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);

        }