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

viernes, 28 de junio de 2019

SQL - Obtener día hábil anterior.

SELECT DATEADD(DAY, CASE (DATEPART(WEEKDAY, GETDATE()) + @@DATEFIRST) % 7
         WHEN 1 THEN -2
         WHEN 2 THEN -3
         ELSE -1
        END, DATEDIFF(DAY, 0, GETDATE()));

lunes, 18 de marzo de 2019

C# - Encriptar una seccion del web.config

 
La encriptación se debe hacer dentro del servidor, no en ambiente de desarrollo.


INICIO + R
CMD (Como Administrador)

BUSCAR RUTA (CON CMD)
C:\Windows\Microsoft.NET\Framework64\v4.0.30319

EJECUTAR ASPNET_REGIIS

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -pef "connectionStrings" C:\inetpub\wwwroot\ItauCorpancaLeaOperWebVs2017

-pef encripta
-pdf desencripta


C:\inetpub\wwwroot\ItauCorpancaLeaOperWebVs2017 --> es la ruta del sitio web dentro del servidor.-

miércoles, 6 de marzo de 2019

Windows - Listar todos los archivos de un directorio (y subdirectorios)


INICIO + R
CMD

Luego con el nombre de la carpeta y cd llegamos al directorio que quremos listar! (cd.. para devolvernos)

y escribimos dir /b /s> c:/Desarrollo/listadoPaginas.txt


  • /b lista solo el directorio actual
  • /s si lo agregamos lista tambien los subdirectorios.-



C:\Desarrollo\ItauCorpBancaVS2017\SFSLeaseOper\LeaOperWeb\LeaseOperWeb\Paginas>dir /b /s> c:/Desarrollo/listadoPaginas.txt


Especial para saber cuales son las paginas que tiene la solución por ejemplo (.aspx)


martes, 27 de noviembre de 2018

SQL - Paginación.-

Ambas van a retornar el mismo conjunto de resultados.-


--SQL 2008
SELECT operacion,estado FROM
(SELECT operacion, estado ,ROW_NUMBER() OVER (ORDER BY operacion) AS Seq
FROM leaseoper..t_contratos) t
WHERE t.Seq BETWEEN 11 AND 15 /*tramo*/


--SQL 2012 EN ADELANTE

SELECT      operacion,estado
FROM        leaseoper..t_contratos
ORDER BY operacion OFFSET 10 /*n° de fila de partida*/ ROWS FETCH NEXT 5 /*cantidad de registros a mostrar*/ ROWS ONLY