public async Task <ActionResult> Descarga(BusquedaExpedienteViewModel datosDescarga) { IExportadorDocumentos <DocumentoRepositorio> exportadorRepositorio = null; IOperacionesRepositorio <DocumentoRepositorio> operacionesRepositorio = null; if (datosDescarga.ArchivosExpediente != null && datosDescarga.ArchivosExpediente.Count > 0) { //1. Nos conectamos al repositorio y bajamos los documentos especificados //Impersonado para Laserfiche using (Impersonator impersonator = new Impersonator("dah.programador01", "AD-HINOJOSA", "Hinojosa2018")) { using (Laserfiche.RepositoryAccess.Session sesion = Laserfiche.RepositoryAccess.Session.Create("SERVERWA", "DA-HINOJOSA")) { exportadorRepositorio = RepositorioDocumentosFactory.CrearExportador(Repositorio.Laserfiche, sesion); operacionesRepositorio = RepositorioDocumentosFactory.CrearOperaciones(Repositorio.Laserfiche, sesion); DocumentoRepositorio[] listaDocumentos = datosDescarga.ArchivosExpediente.Where(w => w.Seleccionado).Select(s => operacionesRepositorio.ObtenerArchivoPorId(s.Identificador)).ToArray(); Guid temporalGuid = Guid.NewGuid(); string rutaTemporal = Server.MapPath("~/" + ConfigurationManager.AppSettings["RutaTemporalDescargas"] + temporalGuid.ToString()); Directory.CreateDirectory(rutaTemporal); await exportadorRepositorio.ExportarAsync(listaDocumentos, rutaTemporal, true); //Borrar los archivos temporales después de descargar var fileInfo = new FileInfo($"{rutaTemporal}.zip"); long byteSize = fileInfo.Length; byte[] fileByteArray = new byte[byteSize]; fileByteArray = System.IO.File.ReadAllBytes($"{rutaTemporal}.zip"); System.IO.File.Delete($"{rutaTemporal}.zip"); System.IO.Directory.Delete($"{rutaTemporal}", true); //Se obtienen datos de pedimento PedimentosSaaiSirView pedimento = null; if (!string.IsNullOrEmpty(datosDescarga.Referencia)) { pedimento = _catalogos.PedimentosSaaiSirViews.FirstOrDefault(f => f.Referencia == datosDescarga.Referencia); pedimento = pedimento ?? await BuscarPedimentoSAAI(datosDescarga, pedimento); if (pedimento != null) { datosDescarga.Aduana = datosDescarga.Aduana ?? pedimento.Aduana; datosDescarga.Año = datosDescarga.Año ?? pedimento.FechaPago.Value.Year.ToString(); datosDescarga.Pedimento = datosDescarga.Pedimento ?? pedimento.Pedimento; datosDescarga.Referencia = datosDescarga.Referencia ?? pedimento.Referencia; } } return(File(fileByteArray, "application/zip", $"{datosDescarga.Año.Substring(2,2)} {datosDescarga.Aduana} {datosDescarga.Pedimento}.zip")); } } } return(HttpNotFound()); }
private static void NewMethod(Laserfiche.RepositoryAccess.Session a, Laserfiche.RepositoryAccess.EntryInfo entryInfor) { if (entryInfor.EntryType == Laserfiche.RepositoryAccess.EntryType.Folder) { var fol = Laserfiche.RepositoryAccess.Folder.GetFolderInfo(entryInfor.Id, a); var enls = new Laserfiche.RepositoryAccess.EntryListingSettings(); var res = fol.OpenFolderListing(enls); for (int j = 1; j <= res.RowCount; j++) { var info = res.GetEntryInfo(j); if (info.EntryType == Laserfiche.RepositoryAccess.EntryType.Document) { var doci = Laserfiche.RepositoryAccess.Document.GetDocumentInfo(info.Id, a); var de = new Laserfiche.DocumentServices.DocumentExporter(); if (doci.IsElectronicDocument) { de.ExportElecDoc(doci, "C:\\DescargarDanfoss\\" + info.Name + "." + doci.Extension); } else { var pr = new Laserfiche.RepositoryAccess.PageRange(1, doci.PageCount); var ps = new Laserfiche.RepositoryAccess.PageSet(pr); string nombre = doci.Name; if (nombre.Contains("*")) { nombre = doci.TemplateName; } de.ExportPdf(doci, ps, Laserfiche.DocumentServices.PdfExportOptions.None, "C:\\DescargarDanfoss\\" + nombre + ".pdf"); } } else if (info.EntryType == Laserfiche.RepositoryAccess.EntryType.Folder) { NewMethod(a, info); } } } }
private void ProcesarSolicitud(Solicituddescargamasiva objetoSolicitud) { //bool conWindows = Convert.ToBoolean(ConfigurationManager.AppSettings["AutenticarLFConWindows"]); //if (!conWindows) //{ // sesion = Laserfiche.RepositoryAccess.Session.Create(server, database, user, password); //} //else //{ sesion = Laserfiche.RepositoryAccess.Session.Create(server, database); //} try { IArchivosAltContext2 archivosAltContext = new ArchivosAltContext2Factory().Create(); List <SqPedimentosSirSaaiReturnModel> lista = archivosAltContext.SqPedimentosSirSaai(objetoSolicitud.FechaInicio.ToString("MM/dd/yyyy"), objetoSolicitud.FechaFin.ToString("MM/dd/yyyy"), Convert.ToInt32(objetoSolicitud.IdCliente), null, 1); IBuscadorDocumentos <DocumentoRepositorio> buscador = new Hinojosa.RepositorioDocumentos.Laserfiche.BuscadorDocumentosLaserficheRepositoryAccess(sesion); IEnumerable <DocumentoRepositorio> documentoRepositorios = buscador.BuscarDocumentosExpediente(lista.Select(s => s.Referencia).ToArray(), null); //Crear carpeta de la solicitud DirectoryInfo directoryInfo = new DirectoryInfo($@"{DirectorioDescargas}{objetoSolicitud.NombreSolicitud}"); if (!directoryInfo.Exists) { directoryInfo.Create(); } //bool nombrePorPedimento = true; IExportadorDocumentos <DocumentoRepositorio> exportador = new Hinojosa.RepositorioDocumentos.Laserfiche.ExportadorDocumentosLaserficheRepositoryAccess(sesion); exportador.Exportar(documentoRepositorios, $@"{DirectorioDescargas}{objetoSolicitud.NombreSolicitud}", true, (d) => { //if (!nombrePorPedimento) //{ // int dr = d.Ruta.IndexOf(d.Referencia); // return d.Ruta.Substring(dr, (d.Ruta.Length - dr) - (d.Ruta.Length - d.Ruta.LastIndexOf("\\"))); //} //else //{ int dr = d.Ruta.IndexOf(d.Referencia); string subcarpeta = d.Ruta.Substring(dr + d.Ruta.Substring(dr).IndexOf("\\")); subcarpeta = subcarpeta.Substring(0, subcarpeta.LastIndexOf("\\")); var datosPedimento = lista.First(f => f.Referencia == d.Referencia); return($"{datosPedimento.FechaPago.Substring(8, 2)}{datosPedimento.Aduana}{datosPedimento.Seccion}{datosPedimento.Patente}{datosPedimento.Pedimento}{subcarpeta}"); // } //return d.Pedimento; }); objetoSolicitud.Procesado = true; objetoSolicitud.FechaProcesado = DateTime.Now; objetoSolicitud.RutaArchivo = DirectorioDescargas + objetoSolicitud.NombreSolicitud + ".zip"; context.SaveChanges(); //Se envía correo al interesado //Ver archivo de configuración ya que ahí se encuentra configurado el correo de salida SmtpClient clienteSmtp = new SmtpClient("smtp.gmail.com", 587); clienteSmtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "da.hinojosa"); clienteSmtp.EnableSsl = true; string remitente = System.Configuration.ConfigurationManager.AppSettings["SMTPRemitente"]; MailMessage correo = new MailMessage(remitente, objetoSolicitud.Notificar); correo.Body = $"Estimado cliente, le notificamos que la descarga de sus expedientes con folio: {objetoSolicitud.NombreSolicitud} se encuentra disponible para su descarga. Puede ingresar al portal de clientes D.A. Hinojosa para realizar la descarga del mismo a través de este link.\r\n\r\nAtt. Grupo Hinojosa"; clienteSmtp.Send(correo); } catch (Exception exc) { Trace.TraceError(exc.ToString()); try { SmtpClient clienteSmtp = new SmtpClient("smtp.gmail.com", 587); clienteSmtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "da.hinojosa"); clienteSmtp.EnableSsl = true; string remitente = System.Configuration.ConfigurationManager.AppSettings["SMTPRemitente"]; MailMessage correo = new MailMessage(remitente, "*****@*****.**"); correo.Body = $"Error en descarga LF: {exc.ToString()} "; clienteSmtp.Send(correo); }catch (Exception e) { } } finally { if (sesion.IsConnected) { sesion.Close(); } } }
// GET: Operacion/DescargaExpedientes/ListadoExpediente/.... public async Task <ActionResult> ListadoExpediente(BusquedaExpedienteViewModel datosBusqueda) { if (!ModelState.IsValid) { ModelState.AddModelError("BúsquedaErronea", "Los parámetros de búsqueda no son correctos"); return(View("Index")); } //La aduana puede ser aduana o aduana/seccion. Para motivos de consulta se separa la aduana de la seccion if (datosBusqueda != null && !string.IsNullOrEmpty(datosBusqueda.Aduana) && datosBusqueda.Aduana.Length > 2) { datosBusqueda.Aduana = datosBusqueda.Aduana.Substring(0, 2); } /*1. Verificamos si se está buscando por referencia o por pedimento. En caso de no contener la referencia, * se realiza la búsqueda por pedimento, aduana y año. Sino vienen estos datos, la búsqueda no aplica. **/ List <PedimentosSaaiSirView> pedimentos = null; if (string.IsNullOrEmpty(datosBusqueda.Referencia)) { if (string.IsNullOrEmpty(datosBusqueda.Aduana) || string.IsNullOrEmpty(datosBusqueda.Año) || string.IsNullOrEmpty(datosBusqueda.Pedimento)) { ModelState.AddModelError("InformacionIncompletaBusqueda", "Se requiere establecer parámetros de búsqueda por referencia o por pedimento inlcuyendo el año y la aduana"); return(View("Index")); } DateTime fechaInicioBusqueda = Convert.ToDateTime($"01/01/{datosBusqueda.Año}"), fechaFinBusqueda = Convert.ToDateTime($"31/12/{datosBusqueda.Año}"); pedimentos = _catalogos.PedimentosSaaiSirViews.AsNoTracking().Where(f => f.Aduana == datosBusqueda.Aduana && f.FechaPago > fechaInicioBusqueda && f.FechaPago < fechaFinBusqueda && f.Pedimento == datosBusqueda.Pedimento).ToList(); } else { pedimentos = _catalogos.PedimentosSaaiSirViews.AsNoTracking().Where(f => f.Referencia == datosBusqueda.Referencia).ToList(); } PedimentosSaaiSirView pedimento = pedimentos.FirstOrDefault(f => f.IdClienteC.Value.ToString() == User.Identity.GetClientId()); //Si no se encontro en SQL (del 2017 hacia atrás) buscar en el histórico del SAAI VFP if (pedimento == null) { pedimento = await BuscarPedimentoSAAI(datosBusqueda, pedimento); } //1.1 Seguridad: Verificar que el usuario tenga acceso a este pedimento mediante el cliente //TODO: Verificar cuando un usuario tenga varios clientes if (pedimento == null || (!User.IsInRole("Administrador") && pedimento.IdClienteP.Value.ToString() != User.Identity.GetClientId())) { ModelState.AddModelError("PedimentoNoEncontrado", "No se encontró el pedimento o la referencia requerida"); return(View("Index")); //return new HttpStatusCodeResult(403); //Forbidden } //2. Se realiza la búsqueda de los documentos del expediente con la interfaz correcta using (Impersonator impersonator = new Impersonator("dah.programador01", "AD-HINOJOSA", "Hinojosa2018")) { using (Laserfiche.RepositoryAccess.Session sesion = Laserfiche.RepositoryAccess.Session.Create("SERVERWA", "DA-HINOJOSA")) { buscadorRepositorio = RepositorioDocumentosFactory.CrearBuscador(Repositorio.Laserfiche, sesion); //await buscadorRepositorio.OpenAsync(); IEnumerable <DocumentoRepositorio> carpetaReferenciaEnumerable = await buscadorRepositorio.BuscarDocumentosExpedienteAsync(new string[] { pedimento.Referencia }, null); DocumentoRepositorio[] documentosRepositorio = carpetaReferenciaEnumerable.ToArray(); //IEnumerable<DocumentoRepositorio> documentos = await documentosRepositorio[0].ExtraerDocumentosAsync(sesion); //3. Se agrega el listado de documentos a la vista datosBusqueda.ArchivosExpediente = documentosRepositorio.Select(documento => new ArchivoExpedienteViewModel() { Nombre = documento.Nombre, Identificador = documento.IdDocumento, Seleccionado = false, SistemaId = documento.Repositorio.ToString() }).ToList(); buscadorRepositorio.Close(); } } datosBusqueda.Aduana = datosBusqueda.Aduana ?? pedimento.Aduana; datosBusqueda.Año = datosBusqueda.Año ?? pedimento.FechaPago.Value.Year.ToString(); datosBusqueda.Pedimento = datosBusqueda.Pedimento ?? pedimento.Pedimento; datosBusqueda.Referencia = datosBusqueda.Referencia ?? pedimento.Referencia; return(View("Index", datosBusqueda)); }