Beispiel #1
0
        /// <summary>
        /// Evento que executa thread´s para processar os arquivos que são colocados nas pastas que estão sendo monitoradas pela FileSystemWatcher
        /// </summary>
        /// <param name="fi">Arquivo detectado pela FileSystemWatcher</param>
        private void fsw_OnFileChanged(FileInfo fi)
        {
            try
            {
                int    empresa;
                string arq = fi.FullName.ToLower();

                if (fi.Directory.FullName.ToLower().EndsWith("geral\\temp"))
                {
                    ///
                    /// encerra o UniNFe no arquivo -sair.xml
                    ///
                    var sext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.sair_XML);
                    if (arq.EndsWith(sext.EnvioTXT) || arq.EndsWith(sext.EnvioXML))
                    {
                        File.Delete(fi.FullName);
                        Empresas.ClearLockFiles(false);
                        if (!Components.Propriedade.ExecutandoPeloUniNFe)
                        {
                            if (Components.ServiceProcess.StatusService(Components.Propriedade.ServiceName) == System.ServiceProcess.ServiceControllerStatus.Running)
                            {
                                Components.ServiceProcess.StopService(Components.Propriedade.ServiceName, 40000);
                            }
                        }
                        else
                        {
                            ThreadService.Stop();
                        }
                        Environment.Exit(0);
                        return;
                    }

                    string    ExtRetorno   = null;
                    string    finalArqErro = null;
                    Exception exx          = null;

                    ///
                    /// Atualiza WSDL / Schemas
                    ///
                    var ext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedUpdatewsdl);
                    if (arq.EndsWith(ext.EnvioTXT) || arq.EndsWith(ext.EnvioXML))
                    {
                        #region ---Atualiza WSDL e Schemas

                        File.Delete(fi.FullName);

                        Components.Functions.DeletarArquivo(Components.Propriedade.XMLVersaoWSDLXSD);

                        string cerros = "";
                        try
                        {
                            ConfiguracaoApp.ForceUpdateWSDL(false, ref cerros);

                            if (!string.IsNullOrEmpty(cerros))
                            {
                                throw new Exception(cerros);
                            }

                            string       ExtRet     = (arq.EndsWith(".xml") ? ext.RetornoXML : ext.RetornoTXT);
                            string       arqRetorno = Components.Propriedade.PastaGeralRetorno + "\\" + Components.Functions.ExtrairNomeArq(fi.FullName, null) + ExtRet;
                            const string rst        = "Schemas atualizados com sucesso!!!";

                            if (arq.EndsWith(".xml"))
                            {
                                var xml = new XDocument(new XDeclaration("1.0", "utf-8", null),
                                                        new XElement("UPDT",
                                                                     new XElement("Result", rst)));
                                xml.Save(arqRetorno);
                            }
                            else
                            {
                                File.WriteAllText(arqRetorno, rst);
                            }
                            return;
                        }
                        catch (Exception ex)
                        {
                            ExtRetorno   = (arq.EndsWith(".xml") ? ext.EnvioXML : ext.EnvioTXT);
                            finalArqErro = ext.EnvioXML.Replace(".xml", ".err");
                            exx          = ex;
                        }

                        #endregion ---Atualiza WSDL e Schemas
                    }

                    ///
                    /// restart o UniNFe
                    ///
                    var uext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedRestart);
                    if (arq.EndsWith(uext.EnvioTXT) || arq.EndsWith(uext.EnvioXML))
                    {
                        #region ---Reinicia o UniNFe

                        File.Delete(fi.FullName);
                        try
                        {
                            if (Components.Propriedade.ExecutandoPeloUniNFe)
                            {
                                System.Diagnostics.Process.Start(Components.Propriedade.PastaExecutavel + "\\uninfe.exe", "/restart");
                            }
                            else
                            {
                                Components.ServiceProcess.StopService(Components.Propriedade.ServiceName, 40000);
                                for (int i = 0; i < 10; ++i)
                                {
                                    Thread.Sleep(500);

                                    if (Components.ServiceProcess.StatusService(Components.Propriedade.ServiceName) == System.ServiceProcess.ServiceControllerStatus.Stopped)
                                    {
                                        Components.ServiceProcess.RestartService(Components.Propriedade.ServiceName, 40000);
                                        break;
                                    }
                                }
                            }

                            return;
                        }
                        catch (Exception ex)
                        {
                            ExtRetorno   = (arq.EndsWith(".xml") ? uext.EnvioXML : uext.EnvioTXT);
                            finalArqErro = uext.EnvioXML.Replace(".xml", ".err");
                            exx          = ex;
                        }

                        #endregion ---Reinicia o UniNFe
                    }

                    if (ExtRetorno != null)
                    {
                        try
                        {
                            Service.TFunctions.GravarArqErroServico(fi.FullName, ExtRetorno, finalArqErro, exx);
                        }
                        catch { }
                        return;
                    }

                    ///
                    /// solicitacao de layouts
                    ///
                    var lext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedLayouts);
                    if (arq.EndsWith(lext.EnvioTXT) || arq.EndsWith(lext.EnvioXML))
                    {
                        Service.TaskLayouts l = new Service.TaskLayouts();
                        l.NomeArquivoXML = fi.FullName;
                        l.Execute();
                        return;
                    }
                    empresa = 0; //Vou criar fixo como 0 quando for na pasta geral, pois na pasta geral não tem como detectar qual é a empresa. Wandrey 20/03/2013
                }
                else
                {
                    empresa = LocalizaEmpresa(fi);
                }

                if (empresa >= 0)
                {
                    /*<#8084>
                     * Aqui foi modificado porque a ThreadControl deixou de existir.
                     * E todo o processamento que antes existia na thread control foi deixado apenas no método Run(), que é chamado abaixo
                     *
                     * Marcelo
                     */
                    new ThreadItem(fi, empresa).Run();
                    //</#8084>
                }
                else
                {
                    Auxiliar.WriteLog(fi.FullName + " - Não localizou a empresa.", true);
                }
            }
            catch (Exception ex)
            {
                if (fi.Directory.Name.ToLower().EndsWith("geral\\temp"))
                {
                    Components.Functions.WriteLog(ex.Message + "\r\n" + ex.StackTrace, false, true, "");
                }
                else
                {
                    Auxiliar.WriteLog(ex.Message + "\r\n" + ex.StackTrace, false);
                }
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.Exception.Message + "\r\n" + e.Exception.StackTrace, false);
                if (e.Exception.InnerException != null)
                {
                    Auxiliar.WriteLog(e.Exception.InnerException.Message + "\r\n" + e.Exception.InnerException.StackTrace, false);

                    if (e.Exception.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.StackTrace, false);
                    }

                    if (e.Exception.InnerException.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.InnerException.StackTrace, false);
                    }
                }
#if false
                ///
                /// executando por servico?
                if (Propriedade.ServicoRodando)
                {
                    return;
                }

                if (NFe.UI.uninfeDummy.mainForm == null)
                {
                    return;
                }

                if (NFe.UI.uninfeDummy.mainForm.WindowState != FormWindowState.Minimized &&
                    NFe.UI.uninfeDummy.showError)
                {
                    MetroFramework.MetroMessageBox.Show(NFe.UI.uninfeDummy.mainForm, e.Exception.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
#endif
            });

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.ExceptionObject.ToString(), false);
            });

            //NFe.UI.uninfeDummy.showError = true;
            //Esta deve ser a primeira linha do Main, não coloque nada antes dela. Wandrey 31/07/2009
            Propriedade.AssemblyEXE = Assembly.GetExecutingAssembly();

            bool silencioso = false;
            ConfiguracaoApp.AtualizaWSDL = false;

            if (args.Length >= 1)
            {
                foreach (string param in args)
                {
                    if (param.ToLower().Equals("/silent"))
                    {
                        silencioso = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/updatewsdl"))
                    {
                        ConfiguracaoApp.AtualizaWSDL = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/quit") || param.ToLower().Equals("/restart"))
                    {
                        string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                        int    Id       = System.Diagnostics.Process.GetCurrentProcess().Id;

                        foreach (System.Diagnostics.Process clsProcess in System.Diagnostics.Process.GetProcesses())
                        {
                            if (clsProcess.ProcessName.Equals(procName))
                            {
                                try
                                {
                                    if (param.ToLower().Equals("/quit") ||
                                        (param.ToLower().Equals("/restart") && clsProcess.Id != Id))
                                    {
                                        Empresas.ClearLockFiles(false);
                                        clsProcess.Kill();
                                    }
                                }
                                catch
                                {
                                }
                                if (param.ToLower().Equals("/quit"))
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            Propriedade.TipoAplicativo = (Propriedade.NomeAplicacao.ToLower().StartsWith("uninfe") ? TipoAplicativo.Nfe : TipoAplicativo.Nfse);

#if DEBUG
            NFe.Components.NativeMethods.AllocConsole();
            Console.WriteLine("start....." + Propriedade.NomeAplicacao);
#endif

            bool executando = Aplicacao.AppExecutando(!silencioso, true);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (executando)
            {
                MetroFramework.MetroMessageBox.Show(null,
                                                    "Somente uma instância do " + Propriedade.NomeAplicacao + " pode ser executada.", "",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            if (Empresas.ExisteErroDiretorio)
            {
                MetroFramework.MetroMessageBox.Show(null,
                                                    "Ocorreu um erro ao efetuar a leitura das configurações da empresa. " +
                                                    "Por favor entre na tela de configurações da(s) empresa(s) listada(s) abaixo na aba \"Pastas\" e reconfigure-as.\r\n\r\n" + Empresas.ErroCaminhoDiretorio, "",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            Application.Run(new NFe.UI.Form_Main());

#if DEBUG
            NFe.Components.NativeMethods.FreeConsole();
#endif
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.Exception.Message + "\r\n" + e.Exception.StackTrace, false);
                if (e.Exception.InnerException != null)
                {
                    Auxiliar.WriteLog(e.Exception.InnerException.Message + "\r\n" + e.Exception.InnerException.StackTrace, false);

                    if (e.Exception.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.StackTrace, false);
                    }

                    if (e.Exception.InnerException.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.InnerException.StackTrace, false);
                    }
                }
            });

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.ExceptionObject.ToString(), false);
            });

            //Esta deve ser a primeira linha do Main, não coloque nada antes dela. Wandrey 31/07/2009
            Propriedade.AssemblyEXE = Assembly.GetExecutingAssembly();

            bool silencioso = false;

            //Começar a contar o tempo de execução do aplicativo - Renan 24/06/2015
            ConfiguracaoApp.ExecutionTime = new System.Diagnostics.Stopwatch();
            ConfiguracaoApp.ExecutionTime.Start();

            if (args.Length >= 1)
            {
                foreach (string param in args)
                {
                    if (param.ToLower().Equals("/silent"))
                    {
                        silencioso = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/updatewsdl"))
                    {
                        continue;
                    }
                    if (param.ToLower().Equals("/quit") || param.ToLower().Equals("/restart"))
                    {
                        string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                        int    Id       = System.Diagnostics.Process.GetCurrentProcess().Id;

                        foreach (System.Diagnostics.Process clsProcess in System.Diagnostics.Process.GetProcesses())
                        {
                            if (clsProcess.ProcessName.Equals(procName))
                            {
                                try
                                {
                                    if (param.ToLower().Equals("/quit") ||
                                        (param.ToLower().Equals("/restart") && clsProcess.Id != Id))
                                    {
                                        Empresas.ClearLockFiles(false);
                                        clsProcess.Kill();
                                    }
                                }
                                catch
                                {
                                }
                                if (param.ToLower().Equals("/quit"))
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            Propriedade.TipoAplicativo = TipoAplicativo.Todos;

#if DEBUG
            NFe.Components.NativeMethods.AllocConsole();
            Console.WriteLine("start....." + Propriedade.NomeAplicacao);
#endif

            bool executando = Aplicacao.AppExecutando();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (executando)
            {
                if (!silencioso)
                {
                    MetroFramework.MetroMessageBox.Show(null,
                                                        "Somente uma instância do " + Propriedade.NomeAplicacao + " pode ser executada." + (Empresas.ExisteErroDiretorio ? "\r\nPossíveis erros:\r\n" + Empresas.ErroCaminhoDiretorio : ""), "",
                                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (!silencioso)
                {
                    if (Empresas.ExisteErroDiretorio)
                    {
                        MetroFramework.MetroMessageBox.Show(null,
                                                            "Ocorreu um erro ao efetuar a leitura das configurações da empresa. " +
                                                            "Por favor entre na tela de configurações da(s) empresa(s) listada(s), acesse a aba \"Pastas\" e reconfigure-as.\r\n\r\n" + Empresas.ErroCaminhoDiretorio, "",
                                                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                Application.Run(new NFe.UI.Form_Main());
            }
#if DEBUG
            NFe.Components.NativeMethods.FreeConsole();
#endif
        }
Beispiel #4
0
 private void pararServicosUniNFe()
 {
     ThreadService.Stop();
     Empresas.ClearLockFiles(false);
 }