private void ReadDatabase()
        {
            string databaseXml = Path.Combine(App.IconLibPath, "database.xml");

            if (!File.Exists(databaseXml))
            {
                DoDatabaseUpdate();
                return;
            }

            Libraries.Clear();

            ProgressDialogResult result = ProgressDialog.ProgressDialog.Execute(
                Owner, "Reading Database", () =>
            {
                ProgressDialog.ProgressDialog.Current.Report("Reading ...");
                XDocument database = XDocument.Load(databaseXml);

                if (!(database.Root is XElement eltLibraries) || eltLibraries.Name != NSIconMaker + "Libraries")
                {
                    return;
                }

                int n = database
                        .Descendants()
                        .Count(d => d.Name.LocalName == "Overlay" || d.Name.LocalName == "Icon");

                ProgressDialog.ProgressDialog.Current.Report(min: 0, max: n, value: 0);

                List <IconLibrary> libraries = new List <IconLibrary>();
                libraries.AddRange(eltLibraries.Elements(NSIconMaker + "Library").Select(eltLibrary => new IconLibrary(eltLibrary)));
                ProgressDialog.ProgressDialog.Current.Arguments.Result = libraries;

                App.WaitForIdle();
            });
Exemple #2
0
        private List <Transaction> GetDataFromExcel(string path, int tickerID)
        {
            List <Transaction> transactions = new List <Transaction>();

            Excel.Application oExcel       = new Excel.Application();
            Excel.Workbook    WB           = oExcel.Workbooks.Open(path);
            Excel.Worksheet   wks          = (Excel.Worksheet)WB.Worksheets[1];
            int totalRows                  = wks.UsedRange.Rows.Count;
            int totalColumns               = wks.UsedRange.Columns.Count;
            ProgressDialogResult resultLog = FTAPExcelTools.ProgressDialog.ProgressDialog.Execute(Application.Current.Windows.OfType <Window>().Where(o => o.Name == "mainWindow").SingleOrDefault(), "Importing Data... plz watting !!", (bw) =>
            {
                for (int i = 2; i <= totalRows; i++)
                {
                    Transaction transaction = new Transaction();
                    transaction.TID         = ((Excel.Range)wks.Cells[i, 1]).Value?.ToString() != null ?
                                              Int32.Parse(((Excel.Range)wks.Cells[i, 1]).Value?.ToString()) : 0;
                    transaction.ItemSet = ((Excel.Range)wks.Cells[i, 2]).Value?.ToString();
                    transaction.Price   = ((Excel.Range)wks.Cells[i, 3]).Value?.ToString() != null ?
                                          Double.Parse(((Excel.Range)wks.Cells[i, 3]).Value?.ToString()) : 0;
                    transaction.TickerID = tickerID;

                    transactions.Add(transaction);
                }
            });

            WB.Close();
            oExcel.Quit();
            return(transactions);
        }
Exemple #3
0
        private void btnGenerar_Click(object sender, RoutedEventArgs e)
        {
            List <ReporteEmpresa> seleccionados = new List <ReporteEmpresa>();

            foreach (ReporteEmpresa item in lista_reporte)
            {
                if (item.Check == true)
                {
                    seleccionados.Add(item);
                }
            }
            if (seleccionados.Count > 0)
            {
                if (txtRutaTodos.Text.Trim().Length > 0)
                {
                    bool procesar = false;
                    bool password = false;
                    if (chkPasswordTodos.IsChecked == true)
                    {
                        if (txtPasswordTodos.Text.Trim().Length >= 3)
                        {
                            procesar = true;
                            password = true;
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("Debe ingresar el password, minimo 3 caracteres.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            procesar = false;
                        }
                    }
                    else
                    {
                        procesar = true;
                    }

                    if (procesar)
                    {
                        string resultado            = string.Empty;
                        string baseLocation         = txtRutaTodos.Text;
                        string txtPasswordString    = txtPasswordTodos.Text;
                        ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () =>
                        {
                            resultado = procesarBackMultiple(seleccionados, password, baseLocation, txtPasswordString);
                        });

                        System.Windows.Forms.MessageBox.Show("Se procesaron los backups.\n" + resultado, "Resumen", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    ///////
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Seleccione una ruta para generar los archivos backups", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Seleccione las empresas para generar los backups", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemple #4
0
 public ProgressDialog(BackgroundWorker bw)
 {
     this.bw = bw;
     this.bw.ProgressChanged    += bw_ProgressChanged;
     this.bw.RunWorkerCompleted += bw_RunWorkerCompleted;
     ProgressDialogResult        = ProgressDialogResult.None;
     InitializeComponent();
 }
Exemple #5
0
        //Evento envio a sunat de comprobantes.
        private void btnEnviar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //Recorrer la grilla para obtener los documentos seleccionados de la grilla.
                List <ReporteRetention> seleccionados = new List <ReporteRetention>();
                foreach (var item in lista_reporte)
                {
                    if (item.Check == true)
                    {
                        seleccionados.Add(item);
                    }
                }
                //If existen los elementos seleccionados.
                if (seleccionados.Count() > 0)
                {
                    string enviados             = string.Empty;
                    ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                        enviados = sendToSunat(seleccionados);
                    });
                    if (enviados.Trim().Length > 0)
                    {
                        CustomDialogWindow obj = new CustomDialogWindow();
                        obj.AdditionalDetailsText = "Los comprobantes enviados correctamente son:\n" + enviados;
                        obj.Buttons       = CustomDialogButtons.OK;
                        obj.Caption       = "Mensaje";
                        obj.DefaultButton = CustomDialogResults.OK;
                        // obj.FooterIcon = CustomDialogIcons.Shield;
                        // obj.FooterText = "This is a secure program";
                        obj.InstructionHeading = "Documentos enviados";
                        obj.InstructionIcon    = CustomDialogIcons.Information;
                        obj.InstructionText    = "Los comprobantes han sido enviados correctamente.";
                        CustomDialogResults objResults = obj.Show();
                    }
                    refrescarGrilla();

                    //string enviados = String.Empty;
                    //Por cada elemento seleccionado se envia a la sunat.

                    /*if (enviados.Length > 0)
                     * {
                     *  System.Windows.Forms.MessageBox.Show("Los siguientes comprobantes han sido enviados correctamente.\n"+enviados,"Mensaje",System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                     * }*/
                    refrescarGrilla();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Debe seleccionar un item");
                }
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
                clsBaseLog.cs_pxRegistarAdd("Enviar retencion sunat" + ex.Message);
            }
        }
Exemple #6
0
        private void btnGenerarUnico_Click(object sender, RoutedEventArgs e)
        {
            clsEntityDatabaseLocal localDB = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(declarante.Cs_pr_Declarant_Id);

            if (txtRutaUnico.Text.Trim().Length > 0)
            {
                bool procesar = false;
                bool password = false;
                if (chkPasswordUnico.IsChecked == true)
                {
                    if (txtPasswordUnico.Text.Trim().Length >= 3)
                    {
                        procesar = true;
                        password = true;
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Debe ingresar el password, minimo 3 caracteres.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        procesar = false;
                    }
                }
                else
                {
                    procesar = true;
                }

                if (procesar)
                {
                    clsBaseConexion cn           = new clsBaseConexion(localDB);
                    string          resultado    = string.Empty;
                    string          baseLocation = txtRutaUnico.Text;
                    // string nameBack = "FEICONTBACKUP_" + declarante.Cs_pr_Ruc + "_" + DateTime.Now.ToString("yyyy") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("dd") + "_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString();
                    string nameBack = "FEICONTBACKUP_" + declarante.Cs_pr_Ruc;

                    string fullName             = baseLocation + "\\" + nameBack + ".BAK";
                    string targetDirectory      = baseLocation + "\\" + nameBack + ".zip";
                    string txtPasswordString    = txtPasswordUnico.Text;
                    ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                        resultado = procesarBackupUnico(localDB.cs_prConexioncadenabasedatos(), password, baseLocation, nameBack, fullName, targetDirectory, txtPasswordString);
                    });
                    if (resultado == "1")
                    {
                        System.Windows.Forms.MessageBox.Show("Se ha generado correctamente el backup.\n", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Se ha producido un error al procesar el backup.\n" + resultado, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                ///////
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Seleccione una ruta para generar el archivo backup", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void btnGenerarResumen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List <Data_Documentos> selected_data_Documentos = new List <Data_Documentos>();
                foreach (var data_Documento in data_Documentos)
                {
                    if (data_Documento.Selectable == true)
                    {
                        selected_data_Documentos.Add(data_Documento);
                    }
                }

                if (selected_data_Documentos.Count() > 0)
                {
                    string enviados     = string.Empty;
                    string noEnviados   = string.Empty;
                    string mensajeFinal = string.Empty;


                    ProgressDialogResult result = ProgressWindow.Execute(padre, "Procesando...", () =>
                    {
                        ProcesarEnvio procesarEnvio = new ProcesarEnvio(data_Usuario);
                        mensajeFinal = procesarEnvio.PostResumen(selected_data_Documentos);
                    });

                    LoadGrid();

                    CustomDialogWindow customDialogWindow = new CustomDialogWindow();
                    customDialogWindow.Buttons            = CustomDialogButtons.OK;
                    customDialogWindow.Caption            = "Mensaje";
                    customDialogWindow.DefaultButton      = CustomDialogResults.OK;
                    customDialogWindow.InstructionHeading = "Resultados de la comunicación de baja";
                    customDialogWindow.InstructionIcon    = CustomDialogIcons.Information;
                    customDialogWindow.InstructionText    = mensajeFinal;
                    CustomDialogResults customDialogResults = customDialogWindow.Show();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Debe seleccionar al menos un documento", "Ninguna selección detectada", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                var msg = string.Concat(ex.InnerException?.Message, ex.Message);
                System.Windows.MessageBox.Show(msg, "Error al enviar el documento a sunat", MessageBoxButton.OK, MessageBoxImage.Error);
                data_Log = new Data_Log()
                {
                    DetalleError   = $"Detalle del error: {msg}",
                    Comentario     = "Error al enviar el documento a sunat desde la interfaz",
                    IdUser_Empresa = data_Usuario.IdUser_Empresa
                };
                data_Log.Create_Log();
            }
        }
Exemple #8
0
        private void meshSmooth_Click(object sender, RoutedEventArgs e)
        {
            ProcessStartInfo start = new ProcessStartInfo();

            string PCLName         = Path.Combine(Path.GetTempPath(), "PCL_smooth.pcd");
            string PCLFilteredName = Path.Combine(Path.GetTempPath(), "PCL_filtered_smooth.pcd");

            start.WorkingDirectory = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
            start.Arguments        = "Smoothing";
            start.Arguments       += " \"" + PCLName + "\"";
            start.Arguments       += " \"" + PCLFilteredName + "\"";
            start.FileName         = "BuildViewCloudFliter.exe";
            start.WindowStyle      = ProcessWindowStyle.Hidden;
            start.CreateNoWindow   = true;


            ProgressDialogResult result = ProgressDialog.Execute(this, "Filtering data", (bw, we) =>
            {
                buildViewControl.model.ExportPcd(PCLName);

                using (Process proc = Process.Start(start))
                {
                    while (!proc.WaitForExit(1000))
                    {
                        if (ProgressDialog.CheckForPendingCancellation(bw, we))
                        {
                            proc.Kill();
                            return;
                        }
                    }
                }

                buildViewControl.model.ImportPcd(PCLFilteredName);
                buildViewControl.Buffers();
            }, ProgressDialogSettings.WithSubLabelAndCancel);

            if (result.OperationFailed)
            {
                System.Windows.MessageBox.Show("Processing failed.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else if (result.Cancelled)
            {
                File.Delete(PCLName);
                System.Windows.MessageBox.Show("Processing canceled successfully.", "Canceled", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                File.Delete(PCLName);
                File.Delete(PCLFilteredName);
                System.Windows.MessageBox.Show("Processing successfully executed.", "Successfull", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
        public ProgressDialog(BackgroundWorker worker, Progress progress)
        {
            this.progress    = progress;
            backgroundWorker = worker;
            backgroundWorker.ProgressChanged +=
                new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
            backgroundWorker.RunWorkerCompleted +=
                new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
            ProgressDialogResult = ProgressDialogResult.None;
            InitializeComponent();

            this.ProgressDialogResult = ProgressDialogResult.None;
        }
Exemple #10
0
        internal static void Execute(Window owner, string label, Action operation, Action <ProgressDialogResult> successOperation, Action <ProgressDialogResult> failureOperation = null, Action <ProgressDialogResult> cancelledOperation = null)
        {
            ProgressDialogResult result = ExecuteInternal(owner, label, operation, null);

            if (result.Cancelled && cancelledOperation != null)
            {
                cancelledOperation(result);
            }
            else if (result.OperationFailed && failureOperation != null)
            {
                failureOperation(result);
            }
            else if (successOperation != null)
            {
                successOperation(result);
            }
        }
Exemple #11
0
        private void btnRestaurar_Click(object sender, RoutedEventArgs e)
        {
            //Buscar todas las empresas y restaurar uno por uno
            List <ReporteEmpresa> seleccionados = new List <ReporteEmpresa>();

            foreach (ReporteEmpresa item in lista_reporte)
            {
                if (item.Check == true)
                {
                    seleccionados.Add(item);
                }
            }
            if (seleccionados.Count > 0)
            {
                if (txtRutaTodos.Text.Trim().Length > 0)
                {
                    string resultado            = string.Empty;
                    string baseLocation         = txtRutaTodos.Text;
                    ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () =>
                    {
                        resultado = procesarBackMultiple(seleccionados, baseLocation);
                    });

                    //System.Windows.Forms.MessageBox.Show("Resumen backups.\n" + resultado, "Resumen", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    CustomDialogWindow obj = new CustomDialogWindow();
                    obj.AdditionalDetailsText = "Resumen de archivos procesados:\n" + resultado;
                    obj.Buttons       = CustomDialogButtons.OK;
                    obj.Caption       = "Mensaje";
                    obj.DefaultButton = CustomDialogResults.OK;
                    // obj.FooterIcon = CustomDialogIcons.Shield;
                    // obj.FooterText = "This is a secure program";
                    obj.InstructionHeading = "Backup procesados";
                    obj.InstructionIcon    = CustomDialogIcons.Information;
                    obj.InstructionText    = "Se han procesado los archivos de la carpeta seleccionada.";
                    CustomDialogResults objResults = obj.Show();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Seleccione las empresas para restaurar los backups", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Exemple #12
0
        private void fileImport_Click(object sender, RoutedEventArgs e)
        {
            if (BrowseFolder())
            {
                ProgressDialogResult result = ProgressDialog.Execute(this, "Importing data", (bw, we) =>
                {
                    buildViewControl.model.ImportCloud(importPath);
                    buildViewControl.Buffers();
                }, ProgressDialogSettings.WithSubLabelAndCancel);

                if (result.OperationFailed)
                {
                    System.Windows.MessageBox.Show("Processing failed.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    System.Windows.MessageBox.Show("Processing successfully executed.", "Successfull", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }
Exemple #13
0
        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs eventArgs)
        {
            label.Text = Resources.String15;

            if (eventArgs.Error != null)
            {
                Progress.AddLog(eventArgs.Error.Message);

                this.ProgressDialogResult = ProgressDialogResult.Failure;
            }
            else if (eventArgs.Cancelled)
            {
                this.ProgressDialogResult = ProgressDialogResult.Failure;
            }
            else
            {
                this.ProgressDialogResult = ProgressDialogResult.Success;
            }

            this.Close();
        }
Exemple #14
0
        /// <summary>
        /// The eventhandler that gets injected in a call in InterpolateAutomatic_Click .
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void autoInterpolate_StartInterpolation(object sender, AutoInterpolationEventArgs e)
        {
            int    interpolatedFrames = 0;
            double result             = 0;

            interpolateMessageShown = false;

            ProgressDialogResult progressResult = ProgressDialog.Execute(this, "Interpolating", (bw, we) => {
                while (framesContainer.CursorIndex + interpolatedFrames < framesContainer.Count - 1 && result < e.ErrorValue)
                {
                    result = interpolationControl.InterpolateManual(framesContainer.CursorIndex + interpolatedFrames, e.ErrorValue);

                    if (result < e.ErrorValue)
                    {
                        interpolatedFrames++;
                        ProgressDialog.ReportWithCancellationCheck(bw, we, interpolatedFrames + " frames interpolated.");
                    }
                }
                ProgressDialog.CheckForPendingCancellation(bw, we);
            }, ProgressDialogSettings.WithSubLabelAndCancel);

            framesContainer.CursorIndex += interpolatedFrames;
            String response = "Interpolated a total of " + interpolatedFrames + " frames";

            if (progressResult.Cancelled)
            {
                response += " before the process was cancelled.";
            }
            else if (result >= e.ErrorValue)
            {
                response += " before the pixel error became too high.";
            }
            else
            {
                response += ".";
            }
            MessageBox.Show(response);
            this.projectstate.Saved = false;
        }
Exemple #15
0
 private void btnRestauracionUnico_Click(object sender, RoutedEventArgs e)
 {
     if (txtRutaUnico.Text.Trim().Length > 0)
     {
         string rutaArchivo           = txtRutaUnico.Text;
         clsEntityDatabaseLocal local = new clsEntityDatabaseLocal().cs_fxObtenerUnoPorDeclaranteId(declarante.Cs_pr_Declarant_Id);
         //clsBaseConexion cn = new clsBaseConexion();
         string cadenaServidor = local.cs_prConexioncadenaservidor();
         clsBaseLog.cs_pxRegistarAdd(cadenaServidor);
         string resultado            = string.Empty;
         ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () =>
         {
             resultado = restaurarUnico(local, cadenaServidor, rutaArchivo);
         });
         if (resultado.Trim().Length <= 0)
         {
             System.Windows.Forms.MessageBox.Show("El backup se ha restaurado correctamente.\n", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             // System.Windows.Forms.MessageBox.Show("Se ha producido un error al procesar el backup.\n", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             CustomDialogWindow obj = new CustomDialogWindow();
             obj.AdditionalDetailsText = resultado;
             obj.Buttons            = CustomDialogButtons.OK;
             obj.Caption            = "Mensaje";
             obj.DefaultButton      = CustomDialogResults.OK;
             obj.InstructionHeading = "Restauración fallida.";
             obj.InstructionIcon    = CustomDialogIcons.Warning;
             obj.InstructionText    = "Se ha producido un error al procesar el backup. Revise los detalles para mayor información";
             CustomDialogResults objResults = obj.Show();
         }
     }
     else
     {
         System.Windows.Forms.MessageBox.Show("Seleccione un archivo para restaurar el backup", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Warning);
     }
 }
        /// <summary>
        /// Evento para validar los documentos listados que falten realizar el proceso
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnValidarArchivos_Click(object sender, RoutedEventArgs e)
        {
            if (lista_reporte.Count > 0)
            {
                verificarDocs = true;
                int count = 0;
                //obtener todos los docs sin validar y por cada uno reload la pagina
                docsValidados = 0;

                foreach (var item in lista_reporte)
                {
                    if (item.EstadoValidar == "4")
                    {
                        count++;
                    }
                }

                if (count > 0)
                {
                    string resultado            = string.Empty;
                    ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                        resultado = validarDocs();
                    });
                    liberarVariableConsulta();
                }
                verificarDocs        = false;
                lblValidaron.Content = "Se validaron " + docsValidados + " documentos de " + count;
                cs_pxCargarDgvComprobanteselectronicos();
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("No existen documentos a validar.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            // btnGrabar.IsEnabled = true;
            // btnExportar.IsEnabled = true;
        }
        //Evento de consulta de ticket.
        private void btnTicket_Click(object sender, RoutedEventArgs e)
        {
            string no_procesados          = "";
            int    cantidad_seleccionados = 0;

            try
            {
                //Recorrer la lista para obtener los elementos seleccionados.
                List <ReporteResumen> seleccionados = new List <ReporteResumen>();
                foreach (var item in lista_reporte)
                {
                    //Recorrer la lista de items
                    if (item.Check == true)
                    {
                        cantidad_seleccionados++;
                        if ((item.EstadoSunatCodigo == "5" || item.EstadoSunatCodigo == "4" || item.EstadoSunatCodigo == "2") && item.Ticket != "")
                        {
                            seleccionados.Add(item);
                        }
                        else
                        {
                            no_procesados += item.Archivo + "\n";
                        }
                    }
                }

                if (cantidad_seleccionados > 0)
                {
                    if (no_procesados.Length > 0)
                    {
                        System.Windows.MessageBox.Show("Los siguientes resumenes de reversion no seran procesados. Verifique ticket de consulta. \n" + no_procesados);
                    }
                    if (seleccionados.Count() > 0)
                    {
                        string resultado            = string.Empty;
                        ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                            resultado = consultaTicket(seleccionados);
                        });

                        refrescarGrilla();

                        if (resultado.Trim().Length > 0)
                        {
                            CustomDialogWindow obj = new CustomDialogWindow();
                            obj.AdditionalDetailsText = "Los siguientes comprobantes se consultaron correctamente:\n" + resultado;
                            obj.Buttons       = CustomDialogButtons.OK;
                            obj.Caption       = "Mensaje";
                            obj.DefaultButton = CustomDialogResults.OK;
                            // obj.FooterIcon = CustomDialogIcons.Shield;
                            // obj.FooterText = "This is a secure program";
                            obj.InstructionHeading = "Documentos consultados ";
                            obj.InstructionIcon    = CustomDialogIcons.Information;
                            obj.InstructionText    = "Los tickets de los documentos enviados fueron consultados correctamente.";
                            CustomDialogResults objResults = obj.Show();
                        }
                    }
                    //Si existen elementos no procesados
                }
                else
                {
                    System.Windows.MessageBox.Show("Seleccione los items a procesar.");
                }
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
                clsBaseLog.cs_pxRegistarAdd("EnvioRA" + ex.ToString());
            }
        }
        //Evento de envio a sunat de la comunicacion de baja.
        private void btnSunat_Click(object sender, RoutedEventArgs e)
        {
            string comentario             = "";
            string procesados             = "";
            string ya_enviados            = "";
            string no_enviados_motivo     = "";
            int    cantidad_seleccionados = 0;

            try
            {
                List <ReporteResumen> seleccionados = new List <ReporteResumen>();
                //Recorrer la lista para obtener los seleccionados.
                foreach (var item in lista_reporte)
                {
                    if (item.Check == true)
                    {   //Si el item fue seleccionado
                        cantidad_seleccionados++;
                        if (item.Ticket != "" || item.Comentario != "")
                        {
                            ya_enviados += " -> " + item.Archivo + " \n";
                        }
                        else
                        {
                            bool validar_motivos_baja = new clsEntityVoidedDocuments(localDB).cs_pxValidarMotivosDeBajaEnItems(item.Id);
                            if (validar_motivos_baja == true)
                            {
                                seleccionados.Add(item);
                            }
                            else
                            {
                                no_enviados_motivo += " -> " + item.Archivo + " \n";
                            }
                        }
                    }
                }
                //SI existen documentos seleccionados.
                if (cantidad_seleccionados > 0)
                {
                    //Mostrar resumen de comprobantes procesados y no procesados.
                    comentario += ya_enviados + no_enviados_motivo;
                    if (comentario.Length > 0)
                    {
                        comentario = "";
                        if (ya_enviados.Length > 0)
                        {
                            comentario += "Ya enviadas:\n" + ya_enviados;
                        }
                        if (no_enviados_motivo.Length > 0)
                        {
                            comentario += "Sin motivos de baja" + no_enviados_motivo;
                        }
                        System.Windows.MessageBox.Show("Los siguientes resumen de reversiones no seran procesados.\n" + comentario, "Mensaje", MessageBoxButton.OK, MessageBoxImage.Information);
                    }

                    //Si existen items selccionados.
                    if (seleccionados.Count > 0)
                    {
                        //string resultado = string.Empty;
                        ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                            procesados = sendToSunat(seleccionados);
                        });

                        refrescarGrilla();
                    }
                    if (procesados.Length > 0)
                    {
                        CustomDialogWindow obj = new CustomDialogWindow();
                        obj.AdditionalDetailsText = "Los siguientes comprobantes fueron enviados correctamente:\n" + procesados;
                        obj.Buttons       = CustomDialogButtons.OK;
                        obj.Caption       = "Mensaje";
                        obj.DefaultButton = CustomDialogResults.OK;
                        // obj.FooterIcon = CustomDialogIcons.Shield;
                        // obj.FooterText = "This is a secure program";
                        obj.InstructionHeading = "Documentos enviados";
                        obj.InstructionIcon    = CustomDialogIcons.Information;
                        obj.InstructionText    = "Los documentos se enviaron correctamente a SUNAT.";
                        CustomDialogResults objResults = obj.Show();

                        // System.Windows.MessageBox.Show("Las siguientes comunicaciones de baja fueron procesadas correctamente.\n" + procesados, "Mensaje", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("Seleccione los items a procesar.", "Mensaje", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
                clsBaseLog.cs_pxRegistarAdd("EnvioRA" + ex.ToString());
            }
        }
 /// <summary>
 /// Evento click para enviar los comprobantes a comunicacion de baja.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btnEnviarSunat_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         string no_procesados = string.Empty;
         //Recorrer las grilla para obtener los elementos seleccionados y alamcenarlos en una lista con los ids de los seleccionados.
         List <string> seleccionados = new List <string>();
         foreach (var item in lista_reporte)
         {
             if (item.Check == true)
             {
                 //Si el comprobante no esta asigando a una comunicacion de baja se guarda como seleccionado
                 if (item.ComunicacionBaja == "")
                 {
                     seleccionados.Add(item.Id);
                 }
                 else
                 {
                     //En caso este asignado ya a una comunicacion de baja entonces asignar a no procesados.
                     no_procesados += item.SerieNumero + "\n";
                 }
             }
         }
         // Si existen comprobantes no procesados porque ya fueron agregados a comunicaion de baja entonces mostrar menaje al usuario.
         if (no_procesados.Trim().Length > 0)
         {
             System.Windows.Forms.MessageBox.Show("Los siguientes comprobantes no sera procesados. Ya fueron agregados a comunicación de baja\n" + no_procesados, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         //Si existen comprobantes seleccionados entonces procesar
         if (seleccionados.Count > 0)
         {
             //Confirmacion para enviar a comunicacion de baja los documentos seleccionados.
             if (System.Windows.Forms.MessageBox.Show("¿Está seguro que desea enviar a comunicación de baja los documentos seleccionados?", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 string resultadoNoAgregados = string.Empty;
                 //
                 ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                     resultadoNoAgregados = ProcesarComunicacionBaja(seleccionados);
                 });
                 if (resultadoNoAgregados.Trim().Length > 0)
                 {   //no se agregaron
                     CustomDialogWindow obj = new CustomDialogWindow();
                     obj.AdditionalDetailsText = "Los comprobantes no agregados son los siguientes:\n" + resultadoNoAgregados;
                     obj.Buttons       = CustomDialogButtons.OK;
                     obj.Caption       = "Mensaje";
                     obj.DefaultButton = CustomDialogResults.OK;
                     // obj.FooterIcon = CustomDialogIcons.Shield;
                     // obj.FooterText = "This is a secure program";
                     obj.InstructionHeading = "Documentos no agregados";
                     obj.InstructionIcon    = CustomDialogIcons.Information;
                     obj.InstructionText    = "Algunos documentos no se agregaron a su comunicacion de baja. Verifique la fecha de emision no mayor a 7 dias.";
                     CustomDialogResults objResults = obj.Show();
                 }
                 else
                 {
                     //Si el resultado es vacio quiere decir que se agregaron todos los comprobantes:
                     System.Windows.Forms.MessageBox.Show("Los documentos se agregaron a su respectiva comunicación de baja.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 }
                 actualizarGrilla();
             }
         }
     }
     catch (Exception ex)
     {
         clsBaseLog.cs_pxRegistarAdd("btnEnviarSunat " + ex.ToString());
     }
 }
Exemple #20
0
        //Evento para enviar los resumenes diarios a la sunat.
        private void btnSunat_Click(object sender, RoutedEventArgs e)
        {
            string no_procesados          = "";
            int    cantidad_seleccionados = 0;

            try
            {
                //Recorrer los elementos de la grilla para obtener los seleccionados.
                List <ReporteResumen> seleccionados = new List <ReporteResumen>();
                foreach (var item in lista_reporte)
                {
                    //Si estan seleccionados
                    if (item.Check == true)
                    {
                        cantidad_seleccionados++;
                        if (item.EstadoSunatCodigo == "2")
                        {
                            seleccionados.Add(item);
                        }
                        else
                        {
                            no_procesados += item.Archivo + "\n";
                        }
                    }
                }
                //Si existen items seleccionados.
                if (cantidad_seleccionados > 0)
                {
                    string procesados = String.Empty;
                    //Si existen items a procesar.
                    if (seleccionados.Count > 0)
                    {
                        ProgressDialogResult result = ProgressWindow.Execute(VentanaPrincipal, "Procesando...", () => {
                            procesados = sendToSunat(seleccionados);
                        });
                    }

                    string comentario = procesados + no_procesados;

                    if (comentario.Trim().Length > 0)
                    {
                        comentario = "";
                        if (procesados.Trim().Length > 0)
                        {
                            comentario += "Documentos procesados correctamente:\n" + procesados;
                        }
                        //En caso existan elementos nno procesados
                        if (no_procesados.Trim().Length > 0)
                        {
                            comentario += "Resumenes no procesados. Estan en proceso o para consulta de ticket:\n" + no_procesados;
                            //System.Windows.Forms.MessageBox.Show("Los siguientes  . \n" + no_procesados);
                        }
                        CustomDialogWindow obj = new CustomDialogWindow();
                        obj.AdditionalDetailsText = comentario;
                        obj.Buttons       = CustomDialogButtons.OK;
                        obj.Caption       = "Mensaje";
                        obj.DefaultButton = CustomDialogResults.OK;
                        // obj.FooterIcon = CustomDialogIcons.Shield;
                        // obj.FooterText = "This is a secure program";
                        obj.InstructionHeading = "Documentos enviados";
                        obj.InstructionIcon    = CustomDialogIcons.Information;
                        if (procesados.Length > 0)
                        {
                            if (no_procesados.Length > 0)
                            {
                                obj.InstructionText = "Existen documentos no procesados. Para mayor informacion vea los detalles.";
                            }
                            else
                            {
                                obj.InstructionText = "Los documentos se enviaron correctamente a SUNAT.";
                            }
                        }
                        else
                        {
                            obj.InstructionText = "Los documentos no fueron procesados.Para mayor informacion vea los detalles.";
                        }

                        CustomDialogResults objResults = obj.Show();
                    }
                    refrescarGrilla();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Debe seleccionar un item");
                }
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
                clsBaseLog.cs_pxRegistarAdd("Envio a sunat resumen diario" + ex.Message);
            }
        }
        private async void btnEnviar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int cantidadAceptados = 0;
                List <Data_Documentos> selected_data_Documentos = new List <Data_Documentos>();
                foreach (var data_Documento in data_Documentos)
                {
                    if (data_Documento.Selectable == true)
                    {
                        selected_data_Documentos.Add(data_Documento);
                    }
                }

                foreach (var selected_data_Documento in selected_data_Documentos)
                {
                    if (selected_data_Documento.EnviadoSunat == true)
                    {
                        cantidadAceptados++;
                    }
                }

                if (selected_data_Documentos.Count() > 0)
                {
                    string enviados     = string.Empty;
                    string noEnviados   = string.Empty;
                    string mensajeFinal = string.Empty;

                    if (cantidadAceptados == 0)
                    {
                        ProgressDialogResult result = ProgressWindow.Execute(padre, "Procesando...", () =>
                        {
                            ProcesarEnvio procesarEnvio = new ProcesarEnvio(data_Usuario);
                            IEnumerable <Data_Documentos> documentosProcesar = selected_data_Documentos.AsEnumerable();
                            Parallel.ForEach(documentosProcesar, (data_Documento) => procesarEnvio.Post(data_Documento));
                        });

                        List <Data_Documentos> selected_data_Documentos_updated = new List <Data_Documentos>();
                        Data_Documentos        documentoUpdated;

                        foreach (var data_Documento in data_Documentos)
                        {
                            if (data_Documento.Selectable == true)
                            {
                                documentoUpdated = new Data_Documentos(data_Documento.IdDocumento);
                                documentoUpdated.Read_Documento();
                                selected_data_Documentos_updated.Add(documentoUpdated);
                            }
                        }

                        foreach (var selected_data_Documento in selected_data_Documentos_updated)
                        {
                            if (selected_data_Documento.EnviadoSunat == true)
                            {
                                enviados += $", {selected_data_Documento.SerieCorrelativo}";
                            }
                            else
                            {
                                noEnviados += $", {selected_data_Documento.SerieCorrelativo}";
                            }
                        }

                        if (string.IsNullOrEmpty(enviados)) //  Ningún enviado, puros rechazados como voz
                        {
                            mensajeFinal = $"No se pudo enviar ningún documento, los documentos rechazados son:\n {noEnviados}";
                        }

                        if (!string.IsNullOrEmpty(enviados) && string.IsNullOrEmpty(noEnviados))    //  Sin ningún documento rechazado
                        {
                            mensajeFinal = $"Se ha enviado a Sunat el(los) documento(s):\n {enviados}";
                        }

                        if (!string.IsNullOrEmpty(enviados) && !string.IsNullOrEmpty(noEnviados))   //  Con al menos un documento rechazado
                        {
                            mensajeFinal = $"Se ha enviado a Sunat el(los) documento(s):\n {enviados} y se han rechazado los siguientes documentos:\n {noEnviados}";
                        }

                        LoadGrid();

                        CustomDialogWindow customDialogWindow = new CustomDialogWindow();
                        customDialogWindow.Buttons            = CustomDialogButtons.OK;
                        customDialogWindow.Caption            = "Mensaje";
                        customDialogWindow.DefaultButton      = CustomDialogResults.OK;
                        customDialogWindow.InstructionHeading = "Resultados del envío a Sunat";
                        customDialogWindow.InstructionIcon    = CustomDialogIcons.Information;
                        customDialogWindow.InstructionText    = mensajeFinal;
                        CustomDialogResults customDialogResults = customDialogWindow.Show();
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("Estimado usuario, está intentando enviar a Sunat uno o varios documentos que ya fueron aceptados, " +
                                                             "sí desea revisar estos documento(s) selecciónelo y pulse descargar.", "Acción no permitida", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Debe seleccionar al menos un documento", "Ninguna selección detectada", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                var msg = string.Concat(ex.InnerException?.Message, ex.Message);
                System.Windows.MessageBox.Show(msg, "Error al enviar el documento a sunat", MessageBoxButton.OK, MessageBoxImage.Error);
                data_Log = new Data_Log()
                {
                    DetalleError   = $"Detalle del error: {msg}",
                    Comentario     = "Error al enviar el documento a sunat desde la interfaz",
                    IdUser_Empresa = data_Usuario.IdUser_Empresa
                };
                data_Log.Create_Log();
            }
        }
Exemple #22
0
        private void ExecuteSitemapGeneration()
        {
            try
            {
                btnRun.Enabled = false;

                if (CheckDestinationExistence() != DialogResult.OK)
                {
                    btnRun.Enabled = true;
                    return;
                }

                filter       = this.Filter;
                fileLocation = this.DestinationFolder;
                culture      = Program.GetUICulture();

                logger = new Logger()
                {
                    OmitDuplicatedLog = true,
                };

                bw = new BackgroundWorker()
                {
                    WorkerReportsProgress      = true,
                    WorkerSupportsCancellation = true,
                };

                generator = new SitemapGenerator(this.URL, this.bw)
                {
                    LastModification     = this.LastModification,
                    ChangeFrequency      = this.ChangeFrequency,
                    Priority             = this.Priority,
                    FileEncoding         = this.Encoding,
                    GenerateHtmlFile     = this.GenerateHtmlFile,
                    GenerateXmlFile      = this.GenerateXmlFile,
                    IncludeNotFoundFiles = this.IncludeNotFoundFiles,
                    Logger         = this.logger,
                    SpecifiedDate  = this.dateTimePicker.Value,
                    PageTitle      = this.PageTitle,
                    FromLocalFiles = this.FromLocalFiles,
                };

                if (FromLocalFiles)
                {
                    PathInfo localPathInfo = new PathInfo(this.URL, this.LocalPath);
                    generator.LocalPathInfo = localPathInfo;
                }

                bw.DoWork += DoSitemapGenerationBackground;
                bw.RunWorkerAsync();

                progressDialog          = new ProgressDialog(bw);
                progressDialog.Progress = this.logger;
                progressDialog.Text     = Resources.String19;

                ProgressDialogResult result = progressDialog.ShowDialog();

                if (result == ProgressDialogResult.Success)
                {
                    if (logger.LogIsEmpty)
                    {
                        ResultDialog resultDialog = new ResultDialog()
                        {
                            Text        = Resources.String9,
                            MainMessage = Resources.String10,
                            Details     = Resources.String12 + Environment.NewLine,
                            Directory   = this.DestinationFolder,
                            Icon        = SystemIcons.Information,
                            Sound       = System.Media.SystemSounds.Asterisk,
                        };

                        resultDialog.ShowDialog();
                    }
                    else
                    {
                        ResultDialog resultDialog = new ResultDialog()
                        {
                            Text        = Resources.String9,
                            MainMessage = Resources.String10,
                            Details     = Resources.String11 + Environment.NewLine + Environment.NewLine + logger.Log,
                            Directory   = this.DestinationFolder,
                            Icon        = SystemIcons.Information,
                            Sound       = System.Media.SystemSounds.Asterisk,
                        };

                        resultDialog.ShowDialog();
                    }
                }
                else if (result == ProgressDialogResult.Failure)
                {
                    ResultDialog resultDialog = new ResultDialog()
                    {
                        Directory   = null,
                        Text        = Resources.String8,
                        MainMessage = Resources.String13,
                        Details     = Resources.String11 + Environment.NewLine + Environment.NewLine + logger.Log,
                        Icon        = SystemIcons.Error,
                        Sound       = System.Media.SystemSounds.Hand,
                    };

                    resultDialog.ShowDialog();
                }
            }
            catch (Exception e)
            {
                ResultDialog resultDialog = new ResultDialog()
                {
                    Directory   = null,
                    Text        = Resources.String8,
                    MainMessage = Resources.String13,
                    Details     = Resources.String11 + Environment.NewLine + Environment.NewLine + e.Message,
                    Icon        = SystemIcons.Hand,
                    Sound       = System.Media.SystemSounds.Hand,
                };

                resultDialog.ShowDialog();
            }
            finally
            {
                btnRun.Enabled = true;
                btnRun.Focus();
            }
        }
Exemple #23
0
        private void btnDescargarXML_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int    documentosSinXML = 0;
                string mensajeFinal     = string.Empty;

                List <Data_Documentos> selected_data_Documentos = new List <Data_Documentos>();
                foreach (var data_Documento in data_Documentos)
                {
                    if (data_Documento.Selectable == true)
                    {
                        selected_data_Documentos.Add(data_Documento);
                    }

                    if (data_Documento.EstadoSunat == "Pendiente")
                    {
                        documentosSinXML++;
                    }
                }

                if (selected_data_Documentos.Count() > 0)
                {
                    if (documentosSinXML > 0)
                    {
                        System.Windows.MessageBox.Show("Ha seleccionado uno o más documentos que aún no se envían a Sunat (Pendiente), por este motivo aún no se ha" +
                                                       " generado su respectivo XML, envíe el(los) documentos y vuelva a intentarlo", "Documento sin XML", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    }
                    else
                    {
                        string pdfsNoEncontrados = string.Empty;
                        string rutaDescarga      = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                        VistaFolderBrowserDialog dialog = new VistaFolderBrowserDialog();
                        dialog.Description            = "Seleccione el directorio donde desea guardar los archivos.";
                        dialog.UseDescriptionForTitle = true;


                        if (!VistaFolderBrowserDialog.IsVistaFolderDialogSupported)
                        {
                            System.Windows.MessageBox.Show("Estimado usuario estas empleando una versión muy antigua de Windows, algunas funciones están restringidas, " +
                                                           "tu documento será descargado en el directorio MIS DOCUMENTOS.", "Algunas funciones no están soportadas en tu sistema operativo",
                                                           MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            var resultado = dialog.ShowDialog();
                            if (resultado.HasValue && resultado.Value)
                            {
                                rutaDescarga = dialog.SelectedPath;

                                ProgressDialogResult result = ProgressWindow.Execute(padre, "Procesando...", () => {
                                    foreach (var selected_data_Documento in selected_data_Documentos)
                                    {
                                        var nombreArchivo =
                                            $"{data_Contribuyente.NroDocumento}-{selected_data_Documento.TipoDocumento}-{selected_data_Documento.SerieCorrelativo}";

                                        if (!Directory.Exists($"{rutaDescarga}\\{nombreArchivo}"))
                                        {
                                            Directory.CreateDirectory($"{rutaDescarga}\\{nombreArchivo}");
                                        }

                                        #region PDF
                                        try
                                        {
                                            if (!File.Exists($"{selected_data_Documento.Ruta}\\{nombreArchivo}\\{nombreArchivo}.pdf"))
                                            {
                                                pdfsNoEncontrados += $"{selected_data_Documento.SerieCorrelativo}, ";
                                            }
                                            else
                                            {
                                                File.Copy($"{selected_data_Documento.Ruta}\\{nombreArchivo}\\{nombreArchivo}.pdf",
                                                          $"{rutaDescarga}\\{nombreArchivo}\\{nombreArchivo}.pdf", true);
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            var msg  = string.Concat(ex.InnerException?.Message, ex.Message);
                                            data_Log = new Data_Log()
                                            {
                                                DetalleError   = $"Detalle del error: {msg}",
                                                Comentario     = "Error al leer o guardar PDF de representación impresa",
                                                IdUser_Empresa = data_Usuario.IdUser_Empresa
                                            };
                                            data_Log.Create_Log();
                                        }
                                        #endregion PDF

                                        DataTable datosDocumento =
                                            readGeneralData.GetDataTable("[dbo].[Query_Scalar_GetXml_Documento]", "@IdDocumento", selected_data_Documento.IdDocumento);
                                        DataRow row = datosDocumento.Rows[0];

                                        File.WriteAllBytes($"{rutaDescarga}\\{nombreArchivo}\\{nombreArchivo}.xml", Convert.FromBase64String(row["XmlFirmado"].ToString()));

                                        if (!string.IsNullOrEmpty(row["CdrSunat"].ToString()))
                                        {
                                            File.WriteAllBytes($"{rutaDescarga}\\{nombreArchivo}\\R-{nombreArchivo}.zip", Convert.FromBase64String(row["CdrSunat"].ToString()));
                                        }

                                        datosDocumento.Clear();
                                    }
                                });

                                if (!string.IsNullOrEmpty(pdfsNoEncontrados))
                                {
                                    mensajeFinal = $"El(los) documento(s) xml fueron guardados en :{dialog.SelectedPath} pero no hemos podido encontrar la" +
                                                   $" representación impresa de los siguientes documentos: {pdfsNoEncontrados}";
                                }
                                else
                                {
                                    mensajeFinal = $"El(los) documento(s) fueron guardados en :{dialog.SelectedPath}";
                                }

                                CustomDialogWindow customDialogWindow = new CustomDialogWindow();
                                customDialogWindow.Buttons            = CustomDialogButtons.OK;
                                customDialogWindow.Caption            = "Detalle";
                                customDialogWindow.DefaultButton      = CustomDialogResults.OK;
                                customDialogWindow.InstructionHeading = "Resultados de la descarga del documento(s)";
                                customDialogWindow.InstructionIcon    = CustomDialogIcons.Information;
                                customDialogWindow.InstructionText    = mensajeFinal;
                                CustomDialogResults customDialogResults = customDialogWindow.Show();

                                LoadGrid();
                            }
                        }
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Debe seleccionar al menos un documento");
                }
            }
            catch (Exception ex)
            {
                var msg = string.Concat(ex.InnerException?.Message, ex.Message);
                System.Windows.MessageBox.Show(msg, "Error al descargar los archivos del documento", MessageBoxButton.OK, MessageBoxImage.Error);
                data_Log = new Data_Log()
                {
                    DetalleError   = $"Detalle del error: {msg}",
                    Comentario     = "Error al descargar los archivos del documento",
                    IdUser_Empresa = data_Usuario.IdUser_Empresa
                };
                data_Log.Create_Log();
            }
        }
Exemple #24
0
        private void AutoDetectLocalSeriesPaths()
        {
            // Try auto find local series paths for series ona ccount
            ProgressDialogResult result = ProgressDialog.Execute(this, "Loading data", () =>
            {
                string seriesFolderPath = AppGlobal.Paths.LocalSeriesDirectory;

                if (string.IsNullOrEmpty(seriesFolderPath))
                {
                    return;
                }

                // Get directory information of series folder
                DirectoryInfo dInfo    = new DirectoryInfo(seriesFolderPath);
                DirectoryInfo[] series = dInfo.GetDirectories();

                try
                {
                    if (AppGlobal.Settings.LocalSeriesPaths == null || AppGlobal.Settings.LocalSeriesPaths.Count > 0)
                    {
                        AppGlobal.Settings.ClearSeriesPaths();
                    }

                    int count = 1;
                    foreach (Show show in AppGlobal.User.Shows)
                    {
                        int pacent = (int)((double)count++ / AppGlobal.User.Shows.Count * 100);
                        ProgressDialog.Current.Report(pacent, "Checking {0}", show.SeriesName);

                        // Look for exact match first
                        DirectoryInfo showDir = series.SingleOrDefault(x => x.Name == show.SeriesName);

                        // Match of how shows are displayed in the list
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name == show.DisplayName);
                        }

                        // Match of names without brackets
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name == show.GetNameWithoutBrackets());
                        }

                        // Match of listed names (the at end)
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name == show.GetListedName());
                        }

                        // Match for ignoring case
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name.ToLower() == show.SeriesName.ToLower());
                        }

                        // Match for ignoring periods
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name.Replace(".", "") == show.SeriesName.Replace(".", ""));
                        }
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name.Replace(".", "") == show.DisplayName.Replace(".", ""));
                        }

                        // Match for ignoring '
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name.Replace("'", "") == show.SeriesName.Replace("'", ""));
                        }
                        if (showDir == null)
                        {
                            showDir = series.SingleOrDefault(x => x.Name.Replace("'", "") == show.DisplayName.Replace("'", ""));
                        }

                        // Check to see if there's a directory for the show
                        if (showDir != null)
                        {
                            show.LocalSeriesPath = showDir.FullName;

                            // Add to settings
                            AppGlobal.Settings.AddSeriesPath(show.Id, showDir.FullName);
                        }

                        Thread.Sleep(100);
                    }

                    AppGlobal.Settings.Save();
                }
                catch (Exception)
                {
                }
            }, ProgressDialogSettings.WithSubLabel);

            if (result.OperationFailed)
            {
                MessageBox.Show("ProgressDialog failed.");
            }
        }
Exemple #25
0
        //Evento de envio de comprobantes a resumen diario
        private void btnEnviarAResumen_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string no_procesado = String.Empty;
                //Recorrer la grilla para buscar los elementos seleccionados
                List <string> seleccionados = new List <string>();
                int           numero        = 0;
                //int ComprobanteSinEstado = 0;
                //int ComprobanteDeBaja = 0;
                foreach (var item in lista_reporte)
                {
                    if (item.Check == true)
                    {
                        numero++;
                        if (item.ResumenDiario.Trim() == "")
                        {
                            seleccionados.Add(item.Id);
                        }
                        else
                        {
                            no_procesado += item.SerieNumero + "\n";
                        }

                        //if (item.EstadoSunat == "DE BAJA") { ComprobanteDeBaja++; }
                        //else { ComprobanteSinEstado++; }
                    }
                }

                //if (ComprobanteDeBaja==0 || ComprobanteSinEstado==0)
                //{
                if (numero > 0)
                {
                    if (no_procesado.Trim().Length > 0)
                    {
                        CustomDialogWindow obj = new CustomDialogWindow();
                        obj.AdditionalDetailsText = "El listado de comprobantes no agregados es el siguiente:\n" + no_procesado;
                        obj.Buttons       = CustomDialogButtons.OK;
                        obj.Caption       = "Mensaje";
                        obj.DefaultButton = CustomDialogResults.OK;
                        // obj.FooterIcon = CustomDialogIcons.Shield;
                        // obj.FooterText = "This is a secure program";
                        obj.InstructionHeading = "Documentos no procesados";
                        obj.InstructionIcon    = CustomDialogIcons.Information;
                        obj.InstructionText    = "Algunos documentos seleccionados no se procesaran debido a que ya fueron agregados a un resumen diario. Si es sustitutorio / rectificatorio debe liberarlos para poder agregarlos al resumen.";
                        CustomDialogResults objResults = obj.Show();
                    }
                    //Si existen seleccionados a procesar
                    if (seleccionados.Count() > 0)
                    {
                        //Confirmacion para agregar.
                        if (System.Windows.Forms.MessageBox.Show("¿Está seguro que desea enviar a resumen diario los documentos seleccionados?", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                        {
                            string resultado            = string.Empty;
                            ProgressDialogResult result = ProgressWindow.Execute(padre, "Procesando...", () => {
                                resultado = SendItemToRc(seleccionados);
                            });
                            if (resultado.Trim().Length > 0)
                            {
                                CustomDialogWindow obj = new CustomDialogWindow();
                                obj.AdditionalDetailsText = "Los comprobantes no agregados son los siguientes:\n" + resultado;
                                obj.Buttons       = CustomDialogButtons.OK;
                                obj.Caption       = "Mensaje";
                                obj.DefaultButton = CustomDialogResults.OK;
                                // obj.FooterIcon = CustomDialogIcons.Shield;
                                // obj.FooterText = "This is a secure program";
                                obj.InstructionHeading = "Documentos no agregados";
                                obj.InstructionIcon    = CustomDialogIcons.Information;
                                obj.InstructionText    = "Algunos documentos no se agregaron a resumen diario. Verifique la fecha de emision no mayor a 7 dias.";
                                CustomDialogResults objResults = obj.Show();
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Todos los documentos se agregaron a su respectivo resumen diario.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }

                            actualizarGrid();
                        }
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Debe seleccionar un item.", "Mensaje", System.Windows.Forms.MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                //}
                //else
                //{
                //    System.Windows.Forms.MessageBox.Show("Debe seleccionar documentos con el mismo estado de SUNAT", "Mensaje", System.Windows.Forms.MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //}
            }
            catch (Exception ex)
            {
                clsBaseMensaje.cs_pxMsgEr("ERR15", ex.Message);
                clsBaseLog.cs_pxRegistarAdd("Enviar comprobantes a resumen diario" + ex.Message);
            }
        }
Exemple #26
0
        void Replace(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(azukiBefore.Text))
            {
                MessageBox.Show(
                    "置換前のテキストが入力されていません。",
                    "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!fileListView.ListValid)
            {
                Progress.Clear();

                Find(sender, e);

                if (Progress.Canceled)
                {
                    // error message has been already shown
                    return;
                }
            }

            if (fileListView.CheckedItems.Count == 0)
            {
                MessageBox.Show(
                    "置換するファイルがありません。",
                    "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (InformAfterTextEmpty && string.IsNullOrEmpty(azukiAfter.Text))
            {
                string msg = "置換後のテキストが入力されていません。置換を実行しますか?\n\n" +
                             string.Format("対象ファイル: {0} 件 ({1} 件中)\nバックアップ: {2}\n正規表現: {3}",
                                           fileListView.CheckedItems.Count, fileListView.Items.Count,
                                           BackupArgs.Enabled ? "する" : "しない",
                                           cbRegex.Checked ? "適用する" : "適用しない");
                DialogResult dr = MessageBox.Show(
                    msg, "確認", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (dr != DialogResult.Yes)
                {
                    return;
                }
            }
            else if (InformBeforeReplace) // 'else if' to avoid inquiring twice in succession
            {
                string msg = "置換を開始します。よろしいですか?\n\n" +
                             string.Format("対象ファイル: {0} 件 ({1} 件中)\nバックアップ: {2}\n正規表現: {3}",
                                           fileListView.CheckedItems.Count, fileListView.Items.Count,
                                           BackupArgs.Enabled ? "する" : "しない",
                                           cbRegex.Checked ? "適用する" : "適用しない");
                DialogResult dr = MessageBox.Show(
                    msg, "確認", MessageBoxButtons.YesNo, MessageBoxIcon.None);
                if (dr != DialogResult.Yes)
                {
                    return;
                }
            }

            btnReplace.Enabled = false;

            int _fileListView_CheckedItems_Count = fileListView.CheckedItems.Count;

            if (!fileListView.ListValid)
            {
                this.Find(sender, e);
                if (!fileListView.ListValid)
                {
                    btnReplace.Enabled = true;
                    return;
                }
            }

            _dirPath        = DirPath;
            _pattern        = Pattern;
            _beforeText     = BeforeText;
            _afterText      = AfterText;
            _inclSubDir     = InclSubDir;
            _regEx          = RegexEnabled;
            _encNumber      = EncNumber;
            _regExMultiline = RegexMultiline;

            // copy of reference is not approved
            _fileListView.ListValid = fileListView.ListValid;
            _fileListView.Items.Clear();
            foreach (ListViewItem item in fileListView.Items)
            {
                _fileListView.Items.Add(item.Clone() as ListViewItem);
            }

            Progress.Clear();

            using (BackgroundWorker bw = new BackgroundWorker())
            {
                bw.WorkerReportsProgress      = true;
                bw.WorkerSupportsCancellation = true;
                bw.DoWork += new DoWorkEventHandler(DoReplaceBkgnd);

                // progress dialog
                progressDialog      = new ProgressDialog(bw, Progress);
                progressDialog.Text = "置換中...";

                bw.RunWorkerAsync();
            }

            ProgressDialogResult result = progressDialog.ShowDialog();

            if (_fileListView != null)
            {
                fileListView.ListValid = _fileListView.ListValid;
                fileListView.Items.Clear();
                foreach (ListViewItem item in _fileListView.Items)
                {
                    fileListView.Items.Add(item.Clone() as ListViewItem);
                }
            }

            if (result == ProgressDialogResult.Success)
            {
                fileListView.ListValid = _fileListView.ListValid;
                fileListView.Items.Clear();
                foreach (ListViewItem item in _fileListView.Items)
                {
                    fileListView.Items.Add(item.Clone() as ListViewItem);
                }
                if (Progress.ErrorOccured)
                {
                    Progress.ErrorDescription = "アクセスできないファイルは無視されました。\n" +
                                                "バックアップエラーだけであれば、置換は行われています。";
                    ErrorDialog dialog = new ErrorDialog(Progress);
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        fileListView.ListValid = true;
                    }
                    else
                    {
                        fileListView.ListValid = false;
                    }
                }

                btnReplace.Enabled = true;
                btnReplace.Focus();

                if (InformAfterReplace)
                {
                    int    fileNum = fileListView.Items[0].Checked ? fileListView.Items.Count : 0;
                    string msg     = "置換が完了しました。\n\n" +
                                     string.Format("置換に成功したファイル: {0} 件\n置換に失敗したファイル: {1} 件",
                                                   _fileListView_CheckedItems_Count - fileListView.CheckedItems.Count,
                                                   fileListView.CheckedItems.Count);
                    MessageBox.Show(msg, "情報", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else if (result == ProgressDialogResult.Failure)
            {
                Progress.ErrorDescription = "置換に失敗しました。";
                ErrorDialog dialog = new ErrorDialog(Progress);
                dialog.ShowDialog();

                btnReplace.Enabled = true;
                btnReplace.Focus();
            }
        }
 private void btnAsignar_click(object sender, RoutedEventArgs e)
 {
     ProgressDialogResult result = ProgressWindow.Execute(padre, "Procesando...", () => {
         AsignarPermisos();
     });
 }
Exemple #28
0
        void Find(object sender, EventArgs e)
        {
            azukiAfter.UpdateNewlineChars();
            azukiBefore.UpdateNewlineChars();

            if (!Directory.Exists(DirPath))
            {
                MessageBox.Show("存在しないフォルダです。", "エラー",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(Pattern))
            {
                MessageBox.Show("フィルタが入力されていません。", "エラー",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (InformBeforeTextEmpty && string.IsNullOrEmpty(BeforeText))
            {
                string msg = "置換前のテキストが入力されていません。検索を実行しますか?\n\n" +
                             string.Format("場所: {0}\nサブフォルダ: {1}\nフィルタ: {2}\n文字コード: {3}\n正規表現: {4}",
                                           tbDirPath.Text, cbSubDir.Checked ? "含める" : "含めない",
                                           tbPattern.Text, comboBoxEnc.SelectedItem.ToString(),
                                           cbRegex.Checked ? "適用する" : "適用しない");
                DialogResult dr = MessageBox.Show(
                    msg, "確認", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
                if (dr != DialogResult.Yes)
                {
                    return;
                }
            }
            else if (InformBeforeSearch) // 'else if' to avoid inquiring twice in succession
            {
                string msg = "検索を開始します。よろしいですか?\n\n" +
                             string.Format("場所: {0}\nサブフォルダ: {1}\nフィルタ: {2}\n文字コード: {3}\n正規表現: {4}",
                                           tbDirPath.Text, cbSubDir.Checked ? "含め" : "含めない",
                                           tbPattern.Text, comboBoxEnc.SelectedItem.ToString(),
                                           cbRegex.Checked ? "適用する" : "適用しない");
                DialogResult dr = MessageBox.Show(
                    msg, "確認", MessageBoxButtons.YesNo, MessageBoxIcon.None);
                if (dr != DialogResult.Yes)
                {
                    return;
                }
            }

            fileListView.AzukiBefore  = azukiBefore;
            fileListView.AzukiAfter   = azukiAfter;
            fileListView.RegexEnabled = RegexEnabled;
            fileListView.RegexOptions = RegexMultiline ? RegexOptions.Multiline : RegexOptions.Singleline;  // do not use |=

            _dirPath        = DirPath;
            _pattern        = Pattern;
            _beforeText     = BeforeText;
            _inclSubDir     = InclSubDir;
            _inclHiddenDir  = InclHiddenDir;
            _inclHiddenFile = InclHiddenFile;
            _regEx          = RegexEnabled;
            _encNumber      = EncNumber;
            _regExMultiline = RegexMultiline;

            btnFind.Enabled = false;
            fileListView.Items.Clear();

            Progress.Clear();

            using (BackgroundWorker bw = new BackgroundWorker())
            {
                bw.WorkerReportsProgress      = true;
                bw.WorkerSupportsCancellation = true;
                bw.DoWork += new DoWorkEventHandler(DoFindBkgnd);

                progressDialog      = new ProgressDialog(bw, Progress);
                progressDialog.Text = "検索中...";

                bw.RunWorkerAsync();
            }

            ProgressDialogResult result = progressDialog.ShowDialog();

            if (result == ProgressDialogResult.Success)
            {
                fileListView.Items.Clear();
                foreach (ListViewItem item in _fileListView.Items)
                {
                    fileListView.Items.Add(item.Clone() as ListViewItem);
                }
                fileListView.ListValid = _fileListView.ListValid;
            }

            btnFind.Enabled = true;

            if (btnReplace.Enabled)
            {
                btnReplace.Focus();
            }
            else
            {
                btnFind.Focus();
            }

            if (Progress.Canceled)
            {
                Progress.ErrorDescription = "処理が中断されました。";
                ErrorDialog dialog = new ErrorDialog(Progress);
                dialog.ShowDialog();
                fileListView.ListValid = false;
            }
            else
            {
                if (Progress.ErrorOccured)
                {
                    Progress.ErrorDescription = "アクセスできないファイルまたはフォルダがありました。" + Environment.NewLine + "または、その他のエラーが発生しました。";
                    ErrorDialog dialog = new ErrorDialog(Progress);
                    dialog.ShowDialog();

                    if (fileListView.Items.Count > 0 &&
                        !string.IsNullOrEmpty(fileListView.Items[0].SubItems[1].Text))
                    {
                        fileListView.ListValid = true;
                    }
                    else
                    {
                        fileListView.ListValid = false;
                    }
                }
                if (InformAfterSearch)
                {
                    int    fileNum = fileListView.Items[0].Checked ? fileListView.Items.Count : 0;
                    string msg     = "検索が完了しました。\n\n" +
                                     string.Format("見つかったファイル: {0} 件", fileNum);
                    MessageBox.Show(msg, "確認", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void btnGenerar_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string no_procesados = string.Empty;
                //Recorrer las grilla para obtener los elementos seleccionados.
                List <string> seleccionados = new List <string>();
                foreach (var item in lista_reporte)
                {
                    if (item.Check == true)
                    {
                        if (item.Reversion == "")
                        {
                            seleccionados.Add(item.Id);
                        }
                        else
                        {
                            no_procesados += item.SerieNumero + "\n";
                        }
                    }
                }
                if (no_procesados.Trim().Length > 0)
                {
                    System.Windows.Forms.MessageBox.Show("Los siguientes comprobantes no sera procesados. Ya fueron agregados a resumen de reversión\n" + no_procesados, "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                if (seleccionados.Count > 0)
                {
                    //Confirmacion para enviar a comunicacion de baja los documentos seleccionados.
                    if (System.Windows.Forms.MessageBox.Show("¿Está seguro que desea enviar a resumen de reversión los documentos seleccionados?", "¿Está seguro?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string resultado            = string.Empty;
                        ProgressDialogResult result = ProgressWindow.Execute(ventanaPrincipal, "Procesando...", () => {
                            resultado = ProcesarReversion(seleccionados);
                        });
                        if (resultado.Trim().Length > 0)
                        { //Se agregaron
                            CustomDialogWindow obj = new CustomDialogWindow();
                            obj.AdditionalDetailsText = "Los comprobantes no agregados son los siguientes:\n" + resultado;
                            obj.Buttons       = CustomDialogButtons.OK;
                            obj.Caption       = "Mensaje";
                            obj.DefaultButton = CustomDialogResults.OK;
                            // obj.FooterIcon = CustomDialogIcons.Shield;
                            // obj.FooterText = "This is a secure program";
                            obj.InstructionHeading = "Documentos no agregados";
                            obj.InstructionIcon    = CustomDialogIcons.Information;
                            obj.InstructionText    = "Algunos documentos no se agregaron a su respectivo resumen de reversión. Verifique el archivo de errores.";
                            CustomDialogResults objResults = obj.Show();
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("Los documentos se agregaron a su respectivo resumen de reversión.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            // System.Windows.Forms.MessageBox.Show("Ocurrio un error al procesar los documentos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        actualizarGrilla();
                    }
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("btnAgregar " + ex.ToString());
            }
        }
Exemple #30
0
        internal ProgressDialogResult Execute(object operation)
        {
            if (operation == null)
            {
                throw new ArgumentNullException("operation");
            }

            ProgressDialogResult result = null;

            _isBusy = true;

            _worker = new BackgroundWorker();
            _worker.WorkerReportsProgress      = true;
            _worker.WorkerSupportsCancellation = true;

            _worker.DoWork +=
                (s, e) => {
                try
                {
                    ProgressDialog.Current = new ProgressDialogContext(s as BackgroundWorker, e as DoWorkEventArgs);

                    if (operation is Action)
                    {
                        ((Action)operation)();
                    }
                    else if (operation is Func <object> )
                    {
                        e.Result = ((Func <object>)operation)();
                    }
                    else
                    {
                        throw new InvalidOperationException("Operation type is not supoorted");
                    }

                    // NOTE: Always do this check in order to avoid default processing after the Cancel button has been pressed.
                    // This call will set the Cancelled flag on the result structure.
                    ProgressDialog.Current.CheckCancellationPending();
                }
                catch (ProgressDialogCancellationExcpetion)
                { }
                catch (Exception ex)
                {
                    if (!ProgressDialog.Current.CheckCancellationPending())
                    {
                        throw ex;
                    }
                }
                finally
                {
                    ProgressDialog.Current = null;
                }
            };

            _worker.RunWorkerCompleted +=
                (s, e) => {
                result = new ProgressDialogResult(e);

                Dispatcher.BeginInvoke(DispatcherPriority.Send, (SendOrPostCallback) delegate {
                    _isBusy = false;
                    Close();
                }, null);
            };

            _worker.ProgressChanged +=
                (s, e) => {
                if (!_worker.CancellationPending)
                {
                    SubLabel          = (e.UserState as string) ?? string.Empty;
                    ProgressBar.Value = e.ProgressPercentage;
                }
            };

            _worker.RunWorkerAsync();

            ShowDialog();

            return(result);
        }