martes, 10 de agosto de 2021

JQUERY copiar por código al portapapeles

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PopUpLupaCliente.aspx.cs" Inherits="LeaseOperWeb.Paginas.PopUpLupaCliente" %>


<!DOCTYPE html>


<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <style type="text/css">

        #textRut {

            width: 85px;

        }


        #textOperacion {

            width: 91px;

        }


        .auto-style1 {

            width: 115px;

        }

    </style>

    <link href="../css/style-css.css" rel="stylesheet" type="text/css" />

    <!--#include file="../Scripts/jquery.includes.htm"-->

    <script>

        $(document).ready(function () {

            defineFormato();

        });


        function defineFormato() {

            $("#txtOperacion").keyup(function () {

                this.value = this.value.replace(/[^0-9\.]/g, '');

            });

            $("#txtRut").keyup(function () {

                this.value = this.value.replace(/[^0-9\.]/g, '');

            });

        }


        function OperacionBlur() {

            if ($("#txtOperacion").val() === '') {

                showMessage('Debe indicar la operación');

                return;

            }

        }


        function RutBlur() {


        }


        function Buscar() {

            try {

                var rut = $("#txtRut").val();

                var nombre = $("#txtNombre").val();

                var operacion = $("#txtOperacion").val();


                var parametros = "{'rut':'" + rut + "','nombre':'" + nombre + "','operacion':'" + operacion + "'}";

                var data = jutils.ajax.serverCall("Buscar", parametros, arguments.callee.name);


                if (data !== "SD") {

                    $('#lblIdCliente').text(data[0]['id_cliente']);


                    var $temp = $("<input>");

                    $("body").append($temp);

                    $temp.val($('#lblIdCliente').text()).select();

                    document.execCommand("copy");

                    $temp.remove();


                    showMessage('Id. Cliente copiado en PortaPapeles');

                }

                else if (data.substring(0, 1) === "*") {

                    showMessage(data);

                    $('#lblIdCliente').text('');

                } else if (data === "SD") {

                    showMessage('No se encontraron datos');

                    $('#lblIdCliente').text('');

                }


            } catch (e) {

                jutils.showError(e, arguments.callee.name);

            }

        }

    </script>

</head>

<body>

    <form id="form1" runat="server">

        <table width="100%" border="0" cellpadding="0" cellspacing="0">

            <tr>

                <td width="10">&nbsp;

                </td>

                <td>

                    <table width="100%" border="0" cellspacing="0" cellpadding="0">

                        <tr>

                            <td>

                                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="borde">

                                    <tr>

                                        <td>

                                            <div class="">

                                                <div class="">

                                                    <div class="">

                                                    </div>

                                                </div>

                                                <div class="">

                                                </div>

                                            </div>

                                        </td>

                                    </tr>

                                </table>

                            </td>

                        </tr>

                        <tr>

                            <td class="">

                                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="caja-datos">

                                    <tr>

                                        <td width="10" rowspan="7"></td>

                                        <td></td>

                                        <td align="right" class="auto-style1">

                                        &nbsp;

                                    </tr>


                                    <tr>

                                        <td width="70px" align="left">Rut:</td>

                                        <td align="left" class="auto-style1">

                                            <input id="txtRut" type="text" maxlength="13" class="caja-datos" onblur="RutBlur()" />

                                        </td>

                                        <td width="90px" align="left">Nombre Cliente:</td>

                                        <td align="left" class="auto-style1">

                                            <input id="txtNombre" type="text" maxlength="100" class="caja-datos"

                                                style="width: 151px" />

                                        </td>

                                        <td class="auto-style1">

                                            <input id="btnBuscar" type="button" value="Buscar" class="btn_buscar" onclick="Buscar()"

                                                title="Buscar ID. Cliente" /></td>

                                        <td align="left" class="auto-style1">&nbsp;<td align="right">

                                        &nbsp;&nbsp;

                                    </tr>


                                    <tr>

                                        <td width="70px" align="left">Operación:</td>

                                        <td align="left" class="auto-style1">

                                            <input id="txtOperacion" type="text" maxlength="20" class="caja-datos" onblur="OperacionBlur()" /></td>

                                        <td width="90px" align="left">&nbsp;</td>

                                        <td align="left" class="auto-style1">&nbsp;</td>

                                        <td class="auto-style1">&nbsp;</td>

                                        <td align="left" class="auto-style1">&nbsp;<td align="right">

                                        &nbsp;

                                    </tr>

                                    <tr>

                                        <td colspan="7" height="10"></td>

                                    </tr>


                                    <tr>

                                        <td colspan="7" height="10">&nbsp;</td>

                                    </tr>


                                    <tr>

                                        <td colspan="7" height="10">&nbsp;</td>

                                    </tr>


                                    <tr>

                                        <td colspan="7" height="10">ID.Cliente:

                                            <label id="lblIdCliente" style="cursor: pointer;"></label>

                                        </td>

                                    </tr>


                                </table>


                            </td>

                            <td width="10" rowspan="3"></td>

                        </tr>

                    </table>

                </td>

            </tr>

            <tr>

                <td>

                    <div class="">

                        <div class="">

                            <div class="">

                            </div>

                        </div>

                    </div>

                </td>

            </tr>

        </table>

    </form>

</body>

</html>


viernes, 10 de julio de 2020

C# - Convertir string en XML



--
.Bc
--

  private XmlDocument ConvierteStringToXml(string xmlString)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.PreserveWhitespace = false;
            xmlDoc.LoadXml(xmlString);

            return xmlDoc;
        }

C# - Convertir Clase en xml (string)


--
.Bc
--
  public string ConvierteListaDeClaseContablidadToXmlString(List<DiarioContabilidad> contabilidadList)
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(List<DiarioContabilidad>));
            var xml = "";

            using (var sww = new StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww))
                {
                    xsSubmit.Serialize(writer, contabilidadList);
                    var a = sww;
                    xml = sww.ToString(); // TU XML STRING
                }
            }
            xml = ReemplazarTagRepetidosContabilidad(xml);
            return xml;
        }

C# - Servicio Web (.asmx ) Asyncrono


--
Framework 4.6.1
--
.asmx
--
[WebMethod]
        public string IntegracionContabilidad(DateTime fecha)
        {
            var dateTimeNow = DateTime.Now.ToString().Replace(" ", "").Replace("-", "").Replace("/", "").Replace(":", "");
            var filePath = "C://IntegracionesContables//IntegracionContabilidad_" + dateTimeNow + ".xml";
            var filePathReturn = "IntegracionContabilidad_" + dateTimeNow + ".xml";

            new IntegracionesContabilidasBc().GetIntegracionContabilidad(fecha, filePath, filePathReturn);
           //este retorno es inmediato (async)
            return filePathReturn;
        }
--
.BC
--
 //Async indica que se hará una llamada asincrona
        public async void GetIntegracionContabilidad(DateTime fecha, string filePath, string filePathReturn)
        {
            //inicializo, e indico que tarea(s) se va(n) a realizar
            var task = GetIc(fecha, filePath, filePathReturn);
            //Inicio la Tarea
            task.Start();
            //Activo el await para retornar control a método que nos invocó (IntegracionContabilidad), con un Delay de un milisegundo para que vuelva de inmediato       
            await Task.Delay(1);
        }

//declarado como Task.
  public Task<string> GetIc(DateTime fecha, string filePath, string filePathReturn)
        {
            return new Task<string>(() =>
            {
                var dt = new IntegracionesContabilidadDac().GetIntegracionContabilidad(fecha);
                var structListClass = MapeoContabilidadDataTableToListClass(dt);

                var xmlString = ConvierteListaDeClaseContablidadToXmlString(structListClass);
                var xmlDoc = ConvierteStringToXml(xmlString);
                xmlDoc.Save(filePath);
                return "OK";
            });
        }

SQL - Eliminar registros duplicados en una tabla SQL



--

WITH FUENTE AS (
SELECT ROW_NUMBER() OVER(PARTITION BY Col1,Col2,Col3 ORDER BY (SELECT NULL)) AS R_ID,Col1,Col2,Col3
  FROM MyTable) DELETE FROM FUENTE WHERE R_ID > 1;


--

ejemplo práctico:


WITH FUENTE AS (
SELECT ROW_NUMBER() OVER(PARTITION BY tipo, num_factura ORDER BY (SELECT NULL)) AS R_ID,tipo, num_factura
  FROM leaseoper..t_facturas_joel_borrar) DELETE FROM FUENTE WHERE R_ID > 1;

lunes, 27 de enero de 2020

C# - No repetir elementos en una lista con estructura de clase

 public List<DiarioContabilidad> MapeoContabilidadXml(DataTable dt)
        {
            var contabilidadList = new List<DiarioContabilidad>();
            var listaCabeceraPrimerCicloFor = new List<String>();
            var cabeceraDelSegundoCicloFor = string.Empty;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i == 0) // para la primera vez!!
                {
                    listaCabeceraPrimerCicloFor.Add(Convert.ToString(dt.Rows[i]["Desc_Comprobante"]));
                }
                if (!listaCabeceraPrimerCicloFor.Contains(cabeceraDelSegundoCicloFor))
                {
                    //para las demas veces!!!
                    listaCabeceraPrimerCicloFor.Add(Convert.ToString(dt.Rows[i]["Desc_Comprobante"]));

                    var cabecera = new DiarioContabilidad();

                    #region RELLENA CABECERA

                    if (IsStringNotNullEmpy(dt.Rows[i]["Num_lote"]))
                        cabecera.NroDiario = Convert.ToString(dt.Rows[i]["Num_lote"]);

                    if (IsStringNotNullEmpy(dt.Rows[i]["Nombre_lote"]))
                        cabecera.Nombre = Convert.ToString(dt.Rows[i]["Nombre_lote"]);

                    if (IsStringNotNullEmpy(dt.Rows[i]["Desc_Comprobante"]))
                        cabecera.DefContable = Convert.ToString(dt.Rows[i]["Desc_Comprobante"]);

                    #endregion

                    var listaDetalle = new List<Lineas>();
                    for (int x = 0; x < dt.Rows.Count; x++)
                    {
                        cabeceraDelSegundoCicloFor = Convert.ToString(dt.Rows[x]["Desc_Comprobante"]);
                        if (listaCabeceraPrimerCicloFor.Contains(cabeceraDelSegundoCicloFor))
                        {
                            var detalle = new Lineas();

                            #region RELLENA DETALLE

                            //solo si tiene la misma Desc_Comprobante (este es el campo agrupador en el SP) relleno el detalle.
                            if (cabecera.DefContable == Convert.ToString(dt.Rows[x]["Desc_Comprobante"]))
                            {
                                if (IsStringNotNullEmpy(dt.Rows[x]["Fecha_Comp"]))
                                    detalle.Fecha = Convert.ToString(dt.Rows[x]["Fecha_Comp"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Num_Comp"]))
                                    detalle.Asiento = Convert.ToString(dt.Rows[x]["Num_Comp"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Empresa"]))
                                    detalle.Empresa = Convert.ToString(dt.Rows[x]["Empresa"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Tipo_Cuenta"]))
                                    detalle.TipoCuenta = Convert.ToString(dt.Rows[x]["Tipo_Cuenta"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Cod_Cuenta_LS"]))
                                    detalle.Cuenta = Convert.ToString(dt.Rows[x]["Cod_Cuenta_LS"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Glosa_Lin_Comp"]))
                                    detalle.Descripcion = Convert.ToString(dt.Rows[x]["Glosa_Lin_Comp"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Dim_Finan1"]))
                                    detalle.CentroCosto = Convert.ToString(dt.Rows[x]["Dim_Finan1"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Dim_Finan_Rut"]))
                                    detalle.RutCliente = Convert.ToString(dt.Rows[x]["Dim_Finan_Rut"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Mto_debe_pesos"]))
                                    detalle.Debito = Convert.ToString(dt.Rows[x]["Mto_debe_pesos"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Mto_Haber_pesos"]))
                                    detalle.Credito = Convert.ToString(dt.Rows[x]["Mto_Haber_pesos"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Divisa"]))
                                    detalle.Divisa = Convert.ToString(dt.Rows[x]["Divisa"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Tipo_Cambio"]))
                                    detalle.TipoCambio = Convert.ToString(dt.Rows[x]["Tipo_Cambio"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Nro_Docto"]))
                                    detalle.Documento = Convert.ToString(dt.Rows[x]["Nro_Docto"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Tipo_Tr_Bco"]))
                                    detalle.TransBancaria = Convert.ToString(dt.Rows[x]["Tipo_Tr_Bco"]);

                                if (IsStringNotNullEmpy(dt.Rows[x]["Ref_Pago"]))
                                    detalle.ReferenciaPago = Convert.ToString(dt.Rows[x]["Ref_Pago"]);

                                #endregion

                                listaDetalle.Add(detalle);
                            }
                            cabeceraDelSegundoCicloFor = Convert.ToString(dt.Rows[x]["Desc_Comprobante"]);
                        }
                    }

                    cabecera.Diario = listaDetalle;
                    /************************Fin Detalle******************************************/
                    if (i == 0)
                    {
                        contabilidadList.Add(cabecera);
                    }
                    else
                    {
                        if (contabilidadList.All(o => o.DefContable.Trim().ToLower() != cabecera.DefContable.Trim().ToLower()))
                        {
                            contabilidadList.Add(cabecera);
                        }
                    }
                }
            }
            var count = contabilidadList.Count;
            return contabilidadList;
        }

jueves, 2 de enero de 2020

C# - Leer archivos CSV desde un directorio dinamico y por columnas..

----------------------------------------------
.ASPX
----------------------------------------------
       function Procesar() {
            var rowCount = $("#grid").getGridParam("reccount");
            if (rowCount > 0) {
                jutils.confirmMessage("¿Desea Procesar?", "Atención", ProcesarConfirmado);
            } else {
                showMessage("No hay filas para ser procesadas", 'Atención');
            }
        }

        function ProcesarConfirmado() {

            mensaje = '';
            var params = "{}";
            jutils.ajax.getJsonData_Async("ProcesaFacturas", params, arguments.callee.name, ProcesaFacturas);
        }

        function ProcesaFacturas(response) {
            if (response.length > 1 && response[0] == 'OK') {
                mensaje = 'El proceso ha finalizado exitosamente. Factura Inicial : ' + response[1] + ', Factura Final : ' + response[2];
                $("#txtInicial").val(response[1]);
                $("#txtFinal").val(response[2]);
                if (response[3] > 0) {
                    mensaje = 'El proceso ha finalizado exitosamente. Factura Inicial : ' + response[1] + ', Factura Final : ' + response[2] + '. Algunos de los registros presentaron problemas. Favor de revisar la lista de Errores. ';
                }
            }
            else {
                mensaje = 'Se ha producido un error al ejecutar el proceso : ' + response[0];
            }
            loadGridPost(mensaje);
        }

----------------------------------------------
.CS
----------------------------------------------
 [WebMethod]
        public static string ProcesaFacturas()
        {
            string[] mensaje;
            int cantErrores = 0;

            var ModoFactura = Convert.ToByte(0);
            var ModoOriginal = 0;

            try
            {
                //1.buscar nombres de .csv en el directorio de destino
                var pathEnternet = new p_parametros_BC().SelDescPparametros(535).Trim(); //codigo para RUTA ENTERNET
                string[] archivosCsv = Directory.GetFiles(pathEnternet, "*.csv");
                var ini = "0";
                var fin = "0";

                //leo los archivos uno por uno
                foreach (string rutaArchivo in archivosCsv)
                {
                    var dt = new DataTable();
                    using (var sr = new StreamReader(rutaArchivo))
                    {
                        string[] columnas = sr.ReadLine().Split(';');
                        //foreach (string header in headers)
                        //{
                        //    //dt.Columns.Add(header);
                        //}
                        var estado = columnas[4].Trim().ToUpper();
                        var factInterno = columnas[0].Trim();
                        var tipo = columnas[2].Trim();

                        switch (tipo)
                        {
                            case "33":      //FACTURA AFECTA
                                tipo = "3";
                                break;
                            case "34":      //FACTURA EXENTA
                                tipo = "3";
                                break;
                        }
                        var numFacSii = sr.ReadLine().Split(';')[3].Trim();
                        if (estado == "EMITIDO")
                        {
                            //LOG
                            new BcFuncionesGenericas().InsertarLog("ProcesarFacturasCsv.aspx", "ProcesaFacturasCsv", "numFactInterno " + factInterno + ",tipo " + tipo + ",", string.Empty, "ProcesaFacturas()", "Inicio procesar CSV:" + rutaArchivo);
                            var retorno = new ProcesarFacturasBc().ProcesarFacturasCsv(Convert.ToInt32(factInterno.Split('-')[1]),
                                 Convert.ToInt16(tipo), Convert.ToInt32(numFacSii), 0);

                            ini = numFacSii;  //JC corregir esta salida en fase de pruebas
                            fin = numFacSii;
                            //LOG
                            new BcFuncionesGenericas().InsertarLog("ProcesarFacturasCsv.aspx", "ProcesaFacturasCsv", "numFactInterno " + factInterno + ",tipo " + tipo + ",", string.Empty, "ProcesaFacturas()", "Fin procesar CSV:" + rutaArchivo);
                        }
                        else
                        {
                            //LOG
                            new BcFuncionesGenericas().InsertarLog("ProcesarFacturasCsv.aspx", "ProcesaFacturasCsv", "numFactInterno " + factInterno + ",tipo " + tipo + ",", string.Empty, "ProcesaFacturas()", "Inicio procesar CSV:" + rutaArchivo);
                            var retorno = new ProcesarFacturasBc().ProcesarFacturasCsv(Convert.ToInt32(factInterno.Split('-')[1]),
                                Convert.ToInt16(tipo), Convert.ToInt32(numFacSii), 0);
                            //LOG
                            new BcFuncionesGenericas().InsertarLog("ProcesarFacturasCsv.aspx", "ProcesaFacturasCsv", "numFactInterno " + factInterno + ",tipo " + tipo + ",", string.Empty, "ProcesaFacturas()", "Fin procesar CSV:" + rutaArchivo);
                            cantErrores++;
                        }
                    }
                }
                mensaje = new string[]
                             {
                                 "OK",
                                 ini,
                                 fin,
                                 Convert.ToString(cantErrores)
                             };

            }
            catch (Exception exc)
            {
                mensaje = new string[]
                             {
                                 exc.Message.ToString().Replace("'", " ").Replace("\"", "").Replace(@"\r", "").Replace("\r\n", "")
                             };

                new BcFuncionesGenericas().InsertarLog("ProcesarFacturasCsv.aspx", "ProcesaFacturasCsv", string.Empty, string.Empty, "ProcesaFacturas()", "Fin proceso completo:");
            }
            return JsonConvert.SerializeObject(mensaje);

        }

martes, 26 de noviembre de 2019

C# - Convertir un Datatable en un XML, con tags ingresador por el programador

Lo que se busca:
<DiarioContabilidad>
  <Diario>
    <NroDiario>0              </NroDiario>
    <Nombre>ITFZLEASOFT    </Nombre>
    <DefContable>Recaudación Caja</DefContable>
    <Lineas>
      <Fecha>23/09/2019</Fecha>
      <Asiento>15026</Asiento>
      <Empresa>ECLE</Empresa>
      <TipoCuenta>Contabilidad</TipoCuenta>
      <Cuenta>110311031002</Cuenta>
      <Descripcion>Pago Cuota 8</Descripcion>
      <CentroCosto>016</CentroCosto>
      <RutCliente>76092069-K </RutCliente>
      <Debito>0,00</Debito>
      <Credito>810767,00</Credito>
      <Divisa>CLP</Divisa>
      <TipoCambio>0</TipoCambio>
      <Documento>0</Documento>
      <TransBancaria>000</TransBancaria>
      <ReferenciaPago>0</ReferenciaPago>
    </Lineas>
    <Lineas>
      <Fecha>23/09/2019</Fecha>
      <Asiento>15026</Asiento>
      <Empresa>ECLE</Empresa>
      <TipoCuenta>Contabilidad</TipoCuenta>
      <Cuenta>110311031002</Cuenta>
      <Descripcion>Pago Cuota 16</Descripcion>
      <CentroCosto>016</CentroCosto>
      <RutCliente>76092069-K </RutCliente>
      <Debito>0,00</Debito>
      <Credito>792988,00</Credito>
      <Divisa>CLP</Divisa>
      <TipoCambio>0</TipoCambio>
      <Documento>0</Documento>
      <TransBancaria>000</TransBancaria>
      <ReferenciaPago>0</ReferenciaPago>
    </Lineas>
   </Diario>
</DiarioContabilidad>



Un sp devuelve la data, en un dataTable, como se consigue:

   public XDocument CreateXmlContabilidad(DataTable dt)
        {
            try
            {
                XDocument voucher = new XDocument(new XDeclaration("1.0", "utf-8", "true"),
                    new XElement("DiarioContabilidad",
                        from cabecera in dt.AsEnumerable()
                        select
                            new XElement("Diario",
                                new XElement("NroDiario", cabecera["Num_lote"]),
                                new XElement("Nombre", cabecera["Nombre_lote"]),
                                new XElement("DefContable", cabecera["Desc_Comprobante"]),
                                from detalle in dt.AsEnumerable()
                                select
                                    new XElement("Lineas",
                                        new XElement("Fecha", detalle["Fecha_Comp"]),
                                        new XElement("Asiento", detalle["Num_Comp"]),
                                        new XElement("Empresa", detalle["Empresa"]),
                                        new XElement("TipoCuenta", detalle["Tipo_Cuenta"]),
                                        new XElement("Cuenta", detalle["Cod_Cuenta_LS"]),
                                        new XElement("Descripcion", detalle["Glosa_Lin_Comp"]),
                                        new XElement("CentroCosto", detalle["Dim_Finan1"]),
                                        new XElement("RutCliente", detalle["Dim_Finan_Rut"]),
                                        new XElement("Debito", detalle["Mto_debe_pesos"]),
                                        new XElement("Credito", detalle["Mto_Haber_pesos"]),
                                        new XElement("Divisa", detalle["Divisa"]),
                                        new XElement("TipoCambio", detalle["Tipo_Cambio"]),
                                        new XElement("Documento", detalle["Nro_Docto"]),
                                        new XElement("TransBancaria", detalle["Tipo_Tr_Bco"]),
                                        new XElement("ReferenciaPago", detalle["Ref_Pago"])))));
                return voucher;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




fuente: https://www.c-sharpcorner.com/blogs/convert-datatable-to-xml-string-using-linq1

jueves, 18 de julio de 2019

C# - Eliminar registros duplicados DATATABLE



    var newDt = dtSelecc.AsEnumerable()
                .GroupBy(x => x.Field<int>("cod_material"))
                .Select(y => y.First())
                .CopyToDataTable();


var newDt                    = Nuevo DataTable sin columnas repetidas
dtSelecc                        = DataTable a evaluar
<int>("cod_material")) = Columna que no puede estar repetido