viernes, 13 de septiembre de 2024

C# ASP.NET - Carga de excel multihojas con reconocimiento de cabeceras

 


Ejemplo del excel a cargar.

-------------------------------------------------------------------------------
.aspx que contiene control de carga y el boton cargar.
-------------------------------------------------------------------------------

<%@ Page Title="Carga Contratos Cuotas" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="CargaContratosCuotas.aspx.cs" Inherits="LeaseOperWeb.Paginas.AdmContratos.AdmCtos.CargaContratosCuotas" %>



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

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

    <%--<link href="../../../Style/Site2.css" rel="stylesheet" type="text/css" />--%>

    <script src="../../../Scripts/JSValidadores.js" type="text/javascript"></script>

</asp:Content>

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

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

        <tr>

            <td valign="top" id="td-descrip">

                <!-------------------------------titulo y miga de pan-------------------------->

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

                    <tr>

                        <td>&nbsp;</td>

                    </tr>

                    <tr>

                        <td class="td-titulos">

                            Carga Contratos / Cuotas

                        </td>

                    </tr>

                    <tr>

                        <td>

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

                                <tr>

                                    <td width="40">&nbsp;</td>

                                    <td class="lin-borde">&nbsp;</td>

                                </tr>

                            </table>

                        </td>

                    </tr>

                    <tr>

                        <td class="mig">

                            Administración de Contratos / Carga Contratos / Cuotas

                        </td>

                    </tr>

                </table>

            </td>

        </tr>

        <tr>

            <td valign="top">&nbsp;</td>

        </tr>

        <tr>

            <td valign="top">

                <!---------------------------------Formulario de carga-------------------------------->

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

                    <tr>

                        <td width="10">&nbsp;</td>

                        <td>

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

                                <tr>

                                    <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="modul">

                                                                    <div class="modul_top">

                                                                        <div class="modul_top_right">

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

                                                                                <tr>

                                                                                    <td width="9"></td>

                                                                                    <td class="modul_fd">

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

                                                                                            <tr>

                                                                                                <td class="modul_fd_tit">

                                                                                                    CARGA CONTRATOS / CUOTAS

                                                                                                </td>

                                                                                            </tr>

                                                                                        </table>

                                                                                    </td>

                                                                                    <td width="9"></td>

                                                                                </tr>

                                                                            </table>

                                                                        </div>

                                                                    </div>

                                                                </div>

                                                            </td>

                                                        </tr>

                                                    </table>

                                                </td>

                                            </tr>

                                            <tr>

                                                <td class="modul_bordes">

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

                                                        <tr>

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

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

                                                            <td></td>

                                                        </tr>

                                                        <tr>

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

                                                            <td align="center">

                                                                <asp:RadioButtonList ID="rbCargaOpciones" runat="server" RepeatDirection="Horizontal">

                                                                    <asp:ListItem Text="Carga Contratos" Value="Contratos" Selected="True"></asp:ListItem>

                                                                    <asp:ListItem Text="Carga Cuotas" Value="Cuotas"></asp:ListItem>

                                                                </asp:RadioButtonList>

                                                                <br />

                                                                        

                                                                <!-- Control de carga de archivo Excel -->

                                                                <asp:FileUpload ID="fuExcel" runat="server" AllowMultiple="false" />

                                                                <asp:Label ID="lblFileTypeError" runat="server" Text="Solo se permiten archivos .xlsx" ForeColor="Red" Visible="false"></asp:Label>

                                                                <br />

                                                                <asp:Button ID="btnCargar" runat="server" Text="Cargar Excel" OnClick="btnCargar_Click" CssClass="btn_excel" />


                                                            </td>

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

                                                        </tr>

                                                        <tr>

                                                            <td height="10" align="center">

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


                                                            </td>

                                                        </tr>

                                                        <tr>

                                                            <td height="10" align="right">&nbsp;</td>

                                                        </tr>

                                                    </table>

                                                </td>

                                            </tr>

                                            <tr>

                                                <td>

                                                    <div class="modul_bottom">

                                                        <div class="modul_bottom_right">

                                                            <div class="modul_borde-bottom"></div>

                                                        </div>

                                                    </div>

                                                </td>

                                            </tr>

                                        </table>

                                    </td>

                                </tr>

                            </table>

                        </td>

                        <td width="10">&nbsp;</td>

                    </tr>

                </table>

            </td>

        </tr>

        <tr>

            <td valign="top">&nbsp;</td>

        </tr>

        <tr>

            <td valign="top">&nbsp;</td>

        </tr>

        <tr>

            <td valign="top"></td>

        </tr>

    </table>

</asp:Content>

-------------------------------------------------------------------------------
.cs que contiene la carga, y validacion de solo archivos xlsx.
-------------------------------------------------------------------------------

using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using LeaOperBussinesLayer.BussinesComponents.AdminContract.AdmCtos;
using LeaOperBussinesLayer.BussinesEntities.AdminContract.AdmCtos;
using LeaseOperWeb.Negocio.Comun;

namespace LeaseOperWeb.Paginas.AdmContratos.AdmCtos
{
    public partial class CargaContratosCuotas : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var usuario = (UserSessionObjectBc)Session["UserSessionObjectBc"];
                if (usuario == null)
                {
                    lblResultado.ForeColor = Color.Red;
                    lblResultado.Text = "Se ha perdido la Sesión, ingrese nuevamente al sistema";
                }
            }
        }

        protected void btnCargar_Click(object sender, EventArgs e)
        {
            if (rbCargaOpciones.SelectedValue == "Cuotas")
            {
                CargaCuotas();
            }
            else
            {
                CargaContratos();
            }

        }

        private void CargaContratos()
        {
            lblResultado.Text = "throw new NotImplementedException();";
        }

       protected void CargaCuotas()
{
    // Recuperamos el objeto de sesión del usuario actual
    var usuario = (UserSessionObjectBc)Session["UserSessionObjectBc"];

    // Verificamos si el archivo de Excel ha sido cargado
    if (fuExcel.HasFile)
    {
        // Obtenemos la extensión del archivo y lo convertimos a minúsculas
        string fileExtension = Path.GetExtension(fuExcel.FileName).ToLower();

        // Verificamos que la extensión sea .xlsx (formato de Excel válido)
        if (fileExtension == ".xlsx")
        {
            try
            {
                // Abrimos el archivo Excel usando ExcelPackage
                using (var package = new ExcelPackage(fuExcel.PostedFile.InputStream))
                {
                    List<CargaCuotas> cuotas = new List<CargaCuotas>();  // Lista para almacenar las cuotas cargadas
                    bool errorEncontrado = false;  // Bandera para detectar errores
                    string mensajeError = string.Empty;  // Mensaje de error
                    bool encabezadosProcesados = false;  // Bandera para verificar si se encontraron encabezados

                    // Iteramos sobre cada hoja del archivo Excel
                    foreach (var worksheet in package.Workbook.Worksheets)
                    {
                        // Verificamos si la hoja tiene datos
                        if (worksheet.Dimension != null)
                        {
                            int rowCount = worksheet.Dimension.End.Row;  // Número total de filas en la hoja
                            int colCount = worksheet.Dimension.End.Column;  // Número total de columnas en la hoja

                            int headerRow = 1;  // Fila de encabezado por defecto
                            bool encabezadosEncontrados = false;  // Bandera para detectar si se encontraron los encabezados

                            // Iteramos por cada fila buscando los encabezados
                            for (int row = 1; row <= rowCount; row++)
                            {
                                // Verificamos que los encabezados coincidan con los nombres esperados
                                if (worksheet.Cells[row, 1].Text.Trim() == "Numero Operación" &&
                                    worksheet.Cells[row, 2].Text.Trim() == "Nº Rentas" &&
                                    worksheet.Cells[row, 3].Text.Trim() == "Mes" &&
                                    worksheet.Cells[row, 4].Text.Trim() == "Amort" &&
                                    worksheet.Cells[row, 5].Text.Trim() == "I" &&
                                    worksheet.Cells[row, 6].Text.Trim() == "Valor Cuota" &&
                                    worksheet.Cells[row, 7].Text.Trim() == "Saldo Insoluto")
                                {
                                    headerRow = row;  // Guardamos la fila de los encabezados
                                    encabezadosEncontrados = true;  // Indicamos que los encabezados fueron encontrados
                                    break;  // Salimos del bucle una vez encontrados los encabezados
                                }
                            }

                            // Si no se encontraron encabezados, pasamos a la siguiente hoja
                            if (!encabezadosEncontrados)
                            {
                                continue;
                            }

                            encabezadosProcesados = true;  // Marcamos que al menos una hoja tenía encabezados válidos

                            // Iteramos sobre las filas después de los encabezados para procesar los datos
                            for (int row = headerRow + 1; row <= rowCount; row++)
                            {
                                try
                                {
                                    // Creamos una nueva instancia de CargaCuotas
                                    CargaCuotas cuota = new CargaCuotas();

                                    // Convertimos y asignamos los valores de las celdas a las propiedades de cuota
                                    cuota.NumeroOperacion = string.IsNullOrEmpty(worksheet.Cells[row, 1].Text) ? (decimal?)null : Convert.ToDecimal(worksheet.Cells[row, 1].Text);
                                    cuota.NumeroRentas = string.IsNullOrEmpty(worksheet.Cells[row, 2].Text) ? (int?)null : Convert.ToInt32(worksheet.Cells[row, 2].Text);
                                    cuota.Mes = string.IsNullOrEmpty(worksheet.Cells[row, 3].Text) ? (DateTime?)null : Convert.ToDateTime(worksheet.Cells[row, 3].Text);
                                    cuota.Amort = string.IsNullOrEmpty(worksheet.Cells[row, 4].Text) ? (decimal?)null : ParseDecimal(ConvertirComaADecimal(worksheet.Cells[row, 4].Text));
                                    cuota.Interes = string.IsNullOrEmpty(worksheet.Cells[row, 5].Text) ? (decimal?)null : ParseDecimal(ConvertirComaADecimal(worksheet.Cells[row, 5].Text));
                                    cuota.ValorCuota = string.IsNullOrEmpty(worksheet.Cells[row, 6].Text) ? (decimal?)null : ParseDecimal(ConvertirComaADecimal(worksheet.Cells[row, 6].Text));
                                    cuota.SaldoInsoluto = string.IsNullOrEmpty(worksheet.Cells[row, 7].Text) ? (decimal?)null : ParseDecimal(ConvertirComaADecimal(worksheet.Cells[row, 7].Text));

                                    // Asignamos datos adicionales sobre la carga
                                    cuota.NombreExcel = fuExcel.FileName;  // Nombre del archivo cargado
                                    cuota.NombreHoja = worksheet.Name;  // Nombre de la hoja actual
                                    cuota.UsuarioCarga = usuario.CodPersonal;  // Usuario que está cargando los datos
                                    cuota.Estado = true;  // Estado de la cuota (puede ser usado para controlar si es válida)

                                    // Agregamos la cuota a la lista
                                    cuotas.Add(cuota);
                                }
                                catch (FormatException ex)  // Captura errores de formato
                                {
                                    mensajeError = $"Error en la hoja '{worksheet.Name}', fila {row}. Datos inválidos: {ex.Message}.";
                                    errorEncontrado = true;  // Marcamos que hubo un error
                                    break;  // Salimos del bucle al encontrar el error
                                }
                                catch (Exception ex)  // Captura otros errores
                                {
                                    mensajeError = $"Error inesperado en la hoja '{worksheet.Name}', fila {row}: {ex.Message}.";
                                    errorEncontrado = true;  // Marcamos que hubo un error
                                    break;  // Salimos del bucle al encontrar el error
                                }
                            }

                            // Si hubo un error, salimos del bucle que procesa las hojas
                            if (errorEncontrado)
                            {
                                break;
                            }
                        }
                    }

                    // Si se encontró un error, mostramos el mensaje de error
                    if (errorEncontrado)
                    {
                        lblFileTypeError.Text = mensajeError;
                        lblFileTypeError.Visible = true;
                    }
                    // Si no se procesaron encabezados, mostramos un mensaje de advertencia
                    else if (!encabezadosProcesados)
                    {
                        lblFileTypeError.Text = "No se encontraron encabezados válidos en ninguna hoja del archivo.";
                        lblFileTypeError.Visible = true;
                    }
                    // Si se procesaron correctamente las cuotas, las insertamos en la base de datos
                    else if (cuotas.Count > 0)
                    {
                        try
                        {
                            // Insertamos las cuotas en la base de datos
                            CargaContratosCuotasBc bc = new CargaContratosCuotasBc();
                            var idCarga = Guid.NewGuid();  // Generamos un ID único para la carga
                            bc.InsertarCuotas(cuotas, idCarga);  // Insertamos las cuotas
                            lblFileTypeError.Text = "Datos insertados correctamente.";
                            lblFileTypeError.Visible = true;
                        }
                        catch (Exception ex)  // Captura errores al insertar en la base de datos
                        {
                            lblFileTypeError.Text = "Error al insertar los datos en la base de datos: " + ex.Message;
                            lblFileTypeError.Visible = true;
                        }
                    }
                    // Si no se encontraron datos válidos, mostramos un mensaje de advertencia
                    else
                    {
                        lblFileTypeError.Text = "No se encontraron datos válidos en el archivo.";
                        lblFileTypeError.Visible = true;
                    }
                }
            }
            catch (Exception ex)  // Captura errores generales al procesar el archivo
            {
                lblFileTypeError.Text = "Error al procesar el archivo: " + ex.Message;
                lblFileTypeError.Visible = true;
            }
        }
        else
        {
            // Mostramos un mensaje si el archivo no es de tipo .xlsx
            lblFileTypeError.Text = "Solo se permiten archivos .xlsx";
            lblFileTypeError.Visible = true;
        }
    }
}



        private string ConvertirComaADecimal(string texto)
        {
            if (string.IsNullOrEmpty(texto))
                return texto;

            texto = texto.Replace(".", "");
            return texto.Replace(",", ".");
        }
        
        private decimal ParseDecimal(string value)
        {
            // Limpia cualquier espacio en blanco
            value = value.Trim();

            // Si el valor contiene solo "-", lo tomamos como 0
            if (value == "-")
            {
                return 0.00M;
            }

            // Reemplaza la coma por un punto decimal si existe
            value = value.Replace(",", ".");

            // Verifica si es un número válido con formato decimal
            if (decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal result))
            {
                return result;
            }

            throw new FormatException($"El valor '{value}' no se pudo convertir a decimal.");
        }
    }
}

-------------------------------------------------------------------------------
.cs capa de negocio que contiene el ciclo de carga
-------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LeaOperBussinesLayer.BussinesEntities.AdminContract.AdmCtos;
using LeaOperBussinesLayer.DataAcessComponent.AdminContract.AdmCtos;

namespace LeaOperBussinesLayer.BussinesComponents.AdminContract.AdmCtos
{
    public class CargaContratosCuotasBc
    {
        public void InsertarCuotas(List<CargaCuotas> cuotas, Guid idCarga )
        {
            CargaContratosCuotasDac dac = new CargaContratosCuotasDac();
            foreach (var cuota in cuotas)
            {
                dac.InsertarCuota(cuota, idCarga);
            }
        }
    }
}

-------------------------------------------------------------------------------
.cs capa de datos
-------------------------------------------------------------------------------

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using LeaOperBussinesLayer.BussinesEntities.AdminContract.AdmCtos;

public class CargaContratosCuotasDac
{
    public void InsertarCuota(CargaCuotas cuota, Guid idCarga)
    {
        string query = @"INSERT INTO carga_cuotas_temp 
                    (id_carga, numero_operacion, numero_rentas, mes, amort, i, valor_cuota, saldo_insoluto, nombre_excel, nombre_hoja, usuario_carga, estado) 
                 VALUES 
                    (@idCarga,@NumeroOperacion, @NumeroRentas, @Mes, @Amort, @Interes, @ValorCuota, @SaldoInsoluto, @NombreExcel, @NombreHoja, @UsuarioCarga, @Estado)";

        string connectionString = ConfigurationManager.ConnectionStrings["LeaseOper"].ConnectionString;

        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    command.CommandType = CommandType.Text;

                    command.Parameters.AddWithValue("@idCarga", idCarga);
                    command.Parameters.Add("@NumeroOperacion", SqlDbType.Decimal).Value = (object)cuota.NumeroOperacion ?? DBNull.Value;
                    command.Parameters.Add("@NumeroRentas", SqlDbType.Int).Value = (object)cuota.NumeroRentas ?? DBNull.Value;
                    command.Parameters.Add("@Mes", SqlDbType.DateTime).Value = (object)cuota.Mes ?? DBNull.Value;
                    command.Parameters.Add("@Amort", SqlDbType.Decimal).Value = (object)cuota.Amort ?? DBNull.Value;
                    command.Parameters.Add("@Interes", SqlDbType.Decimal).Value = (object)cuota.Interes ?? DBNull.Value;
                    command.Parameters.Add("@ValorCuota", SqlDbType.Decimal).Value = (object)cuota.ValorCuota ?? DBNull.Value;
                    command.Parameters.Add("@SaldoInsoluto", SqlDbType.Decimal).Value = (object)cuota.SaldoInsoluto ?? DBNull.Value;
                    command.Parameters.Add("@NombreExcel", SqlDbType.VarChar, 1000).Value = (object)cuota.NombreExcel ?? DBNull.Value;
                    command.Parameters.Add("@NombreHoja", SqlDbType.VarChar, 1000).Value = (object)cuota.NombreHoja ?? DBNull.Value;
                    command.Parameters.Add("@UsuarioCarga", SqlDbType.Int).Value = (object)cuota.UsuarioCarga ?? DBNull.Value;
                    command.Parameters.Add("@Estado", SqlDbType.Bit).Value = (object)cuota.Estado ?? DBNull.Value;

                    connection.Open();
                    command.ExecuteNonQuery();
                }
            }
        }
        catch (Exception ex)
        {
           
            throw new ApplicationException("Error al insertar la cuota en la base de datos", ex);
        }
    }

}


-------------------------------------------------------------------------------
.cs Clase Carga Cuotas
-------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeaOperBussinesLayer.BussinesEntities.AdminContract.AdmCtos
{
    public class CargaCuotas
    {
        public decimal? NumeroOperacion { get; set; }
        public int? NumeroRentas { get; set; }
        public DateTime? Mes { get; set; }
        public decimal? Amort { get; set; }
        public decimal? Interes { get; set; }
        public decimal? ValorCuota { get; set; }
        public decimal? SaldoInsoluto { get; set; }
        public string NombreExcel { get; set; }
        public string NombreHoja { get; set; }
        public int UsuarioCarga { get; set; }
        public bool Estado { get; set; }
    }
}


-------------------------------------------------------------------------------
.SQL Creación de tabla 
-------------------------------------------------------------------------------

USE [leaseoper]
GO


/****** Object:  Table [dbo].[carga_cuotas_temp]    Script Date: 11/09/2024 17:26:33 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[carga_cuotas_temp]') AND type IN (N'U'))
DROP TABLE [dbo].[carga_cuotas_temp]
GO

/****** Object:  Table [dbo].[carga_cuotas_temp]    Script Date: 11/09/2024 17:26:33 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[carga_cuotas_temp](
[id_carga]  [UNIQUEIDENTIFIER] NOT NULL, 
[numero_operacion] [NUMERIC](20, 0) NULL,
[numero_rentas] [INT] NULL,
[mes] [DATETIME] NULL,
[amort] [NUMERIC](20, 4) NULL,
[i] [NUMERIC](20, 4) NULL,
[valor_cuota] [NUMERIC](20, 4) NULL,
[saldo_insoluto] [NUMERIC](20, 4) NULL,
[nombre_excel] [VARCHAR](1000) NULL,
[nombre_hoja] [VARCHAR](1000) NULL,
[usuario_carga] [INT] NULL,
[fecha_carga] [DATETIME] NULL,
[estado] [BIT] NULL)

ALTER TABLE [dbo].[carga_cuotas_temp] ADD  DEFAULT (GETDATE()) FOR [fecha_carga]
GO

CREATE NONCLUSTERED INDEX IX_carga_cuotas_temp_id_carga ON [dbo].[carga_cuotas_temp] ([id_carga])

CREATE NONCLUSTERED INDEX IX_carga_cuotas_temp_numero_operacion ON [dbo].[carga_cuotas_temp] ([numero_operacion])

CREATE NONCLUSTERED INDEX IX_carga_cuotas_temp_usuario_carga ON [dbo].[carga_cuotas_temp] ([usuario_carga])



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>