jueves, 26 de octubre de 2023

C# ASP.NET - Subir archivos a carpeta compartida con credenciales.

 .ASPX

<%@ Page Title="Test Carpeta Compartida" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TestCarpetaCompartida.aspx.cs" Inherits="LeaseOperWeb.Paginas.Administracion.TestCarpetaCompartida.TestCarpetaCompartida" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="HeaderContent" runat="server">

    <br /><asp:Label ID="Label1" runat="server" Text="TEST Carpeta Compartida"></asp:Label>

    <br />

    <br />

    <asp:FileUpload ID="fileUpload" runat="server" />

    <asp:Button ID="uploadButton" runat="server" Text="Subir archivo" OnClick="UploadFile" />

    <br />

    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

</asp:Content>



.CS

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LeaOperBussinesLayer.BussinesComponents.Administracion;

namespace LeaseOperWeb.Paginas.Administracion.TestCarpetaCompartida
{
    public partial class TestCarpetaCompartida : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void UploadFile(object sender, EventArgs e)
        {
            string urlCarpetaCompartida = new TesteoBc().GetURLCarpetaCompartida();
            string usernameCarpetaCompartida = new TesteoBc().GetUserCarpetaCompartida();
            string passwordCarpetaCompartida = new TesteoBc().GetPassCarpetaCompartida();


            if (!String.IsNullOrEmpty(urlCarpetaCompartida) || !String.IsNullOrEmpty(usernameCarpetaCompartida) ||
                !String.IsNullOrEmpty(passwordCarpetaCompartida))
            {
                if (fileUpload.HasFile)
                {
                    string fileName = Path.GetFileName(fileUpload.FileName);

                    string filePath =
                        Server.MapPath($"~/Uploads/{fileName}"); // Ruta temporal para guardar el archivo
                    string folderPath = Server.MapPath("~/Uploads");

                    if (!Directory.Exists(folderPath))
                        Directory.CreateDirectory(folderPath);

                    // Eliminar el archivo temporal en caso de que exista previamente
                    if (File.Exists(filePath))
                        File.Delete(filePath);

                    fileUpload.SaveAs(filePath);

                    // string fileName = Path.GetFileName(fileUpload.PostedFile.FileName);
                    string sharedFolderPath = urlCarpetaCompartida;

                    try
                    {
                        using (FileStream fileStream = File.OpenRead(filePath))
                            if (sharedFolderPath != null)
                                using (FileStream destination = File.Create(Path.Combine(sharedFolderPath, fileName)))
                                {
                                    fileStream.CopyTo(destination);
                                }

                        lblMessage.Text = @"Archivo subido exitosamente";
                    }
                    catch (Exception ex)
                    {
                        lblMessage.Text = @"Ha ocurrido un error: " + ex.Message;
                    }
                }
            }
            else
            {
                lblMessage.Text =
                    @"Atención : Revisar paramétros 908-909-910 alguno de esos está vacío";
            }
        }
    }
}

C# ASP .NET - Subir archivos a un FTP

 Agregar control FILEUPLOAD


-.ASPX

<%@ Page Title="Test FTP" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="TestFTP.aspx.cs" Inherits="LeaseOperWeb.Paginas.Administracion.TestFTP.TestFTP" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="HeaderContent" runat="server">

    <br /><asp:Label ID="Label1" runat="server" Text="TEST FTP"></asp:Label>

    <br />

    <br />

    <asp:FileUpload ID="fileUpload" runat="server" />

    <asp:Button ID="uploadButton" runat="server" Text="Subir archivo" OnClick="UploadFile" />

    <br />

    <asp:Label ID="lblMessageConx" runat="server" Text=""></asp:Label>

    <br />

    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

</asp:Content>


.CS

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Security;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using LeaOperBussinesLayer.BussinesComponents.Administracion;


namespace LeaseOperWeb.Paginas.Administracion.TestFTP

{

    public partial class TestFTP : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {


        }


        public void TestConeccionFTP(string ftpServer, string ftpUsername, string ftpPassword)

        {

            /*Test de conexion*/

            try

            {

                // Crear una solicitud de conexión FTP.

                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer);

                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);

                request.Method = WebRequestMethods.Ftp.ListDirectory; // Puedes cambiar este método según tu necesidad.


                // Realizar la conexión y obtener la respuesta.

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();


                // Si llegamos aquí sin excepciones, la conexión fue exitosa.

                lblMessageConx.Text = "Conexión FTP exitosa.";

                response.Close();

            }

            catch (WebException ex)

            {

                lblMessageConx.Text = "Error de conexión FTP: " + ex.Message;

            }

            /*Fin test conexion*/


        }



        protected void UploadFile(object sender, EventArgs e)

        {

            string ftpServer = new TesteoBc().GetURLFTP(); // Reemplaza con tu servidor FTP                                 //ejemplo : ftp://192.168.1.99:21   (IP Y PUERTO)                                            

            string ftpUsername = new TesteoBc().GetUserFTP();// Reemplaza con tu nombre de usuario

            string ftpPassword = new TesteoBc().GetPassFTP(); // Reemplaza con tu contraseña

            string ssl = new TesteoBc().GetSSl(); //reemplaza con ssl  true o false


            if (!String.IsNullOrEmpty(ftpServer) || !String.IsNullOrEmpty(ftpUsername) ||

                !String.IsNullOrEmpty(ftpPassword) || !String.IsNullOrEmpty(ftpUsername))

            {


                TestConeccionFTP(ftpServer, ftpUsername, ftpPassword);


                if (fileUpload.HasFile)

                {

                    string fileName = Path.GetFileName(fileUpload.FileName);


                    try

                    {

                        string filePath =

                            Server.MapPath($"~/Uploads/{fileName}"); // Ruta temporal para guardar el archivo

                        string folderPath = Server.MapPath("~/Uploads");


                        if (!Directory.Exists(folderPath))

                            Directory.CreateDirectory(folderPath);


                        // Eliminar el archivo temporal en caso de que exista previamente

                        if (File.Exists(filePath))

                            File.Delete(filePath);



                        fileUpload.SaveAs(filePath);


                        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServer + "/" + fileName);

                        request.Method = WebRequestMethods.Ftp.UploadFile;

                        request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);


                        // Habilitar SSL implícito

                        if (ssl.Trim().ToLower() == "true")

                            request.EnableSsl = true;


                        using (FileStream fileStream = File.OpenRead(filePath))

                        using (Stream requestStream = request.GetRequestStream())

                        {

                            byte[] buffer = new byte[1024];

                            int bytesRead;


                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)

                            {

                                requestStream.Write(buffer, 0, bytesRead);

                            }

                        }


                        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

                        lblMessage.Text =

                            $"Archivo {fileName} cargado con éxito. Código de respuesta: {response.StatusDescription}";


                        // Eliminar el archivo temporal

                        if (File.Exists(filePath))

                            File.Delete(filePath);


                        response.Close();

                    }

                    catch (Exception ex)

                    {

                        lblMessage.Text = $"Error al cargar el archivo: {ex.Message}";

                        // Eliminar el archivo temporal


                    }

                }

                else

                {

                    lblMessage.Text =

                        "Por favor, selecciona un archivo para cargar o verifica que el archivo no esté vacío";

                }

            }

            else

            {

                lblMessage.Text =

                    @"Atención : Revisar paramétros 904-905-906 alguno de esos está vacío";

            }

        }



    }

}


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

        }