Пример #1
0
        protected override void OnStart(string[] args)
        {
            try
            {
                try
                {
                    //Log.For(this, pastacliente).Info("Iniciado em :" + DateTime.Now.ToString() + " " + ConfigurationManager.AppSettings.Get("CLIENTE"));
                    this.GravarLogEventViewer("Iniciado em :" + DateTime.Now.ToString() + " " + ConfigurationManager.AppSettings.Get("CLIENTE"));
                }
                catch (Exception efs)
                {
                    string          emailEmpresa = ConfigurationManager.AppSettings.Get("EMAIL_ENVIAR_USUARIO").ToString();
                    string          smtp         = ConfigurationManager.AppSettings.Get("EMAIL_ENVIAR_SMTP").ToString();
                    string          porta        = ConfigurationManager.AppSettings.Get("EMAIL_ENVIAR_PORTA").ToString();
                    string          usuario      = ConfigurationManager.AppSettings.Get("EMAIL_ENVIAR_USUARIO").ToString();
                    string          senha        = ConfigurationManager.AppSettings.Get("EMAIL_ENVIAR_SENHA").ToString();
                    string          cliente      = ConfigurationManager.AppSettings.Get("CLIENTE").ToString();
                    string          cnpjcliente  = ConfigurationManager.AppSettings.Get("CNPJ").ToString();
                    RJSOptimusEmail email        = new RJSOptimusEmail(smtp, Convert.ToInt32(porta), usuario, senha);
                    email.From = emailEmpresa;
                    email.To   = "*****@*****.**";
                    //email.CC = "*****@*****.**";
                    email.Subject = "LOG erro";
                    email.Body    = efs.ToString();
                    email.Enviar();
                }


                int IntervaloNFESaidaSend   = Convert.ToInt32(ConfigurationManager.AppSettings.Get("INTERVALO_EXECUCAO_NFESAIDA_SEND")) * 1000;
                int IntervaloNFESaidaReturn = Convert.ToInt32(ConfigurationManager.AppSettings.Get("INTERVALO_EXECUCAO_NFESAIDA_RETURN")) * 1000;
                int IntervaloNFESaidaMail   = Convert.ToInt32(ConfigurationManager.AppSettings.Get("INTERVALO_EXECUCAO_NFESAIDA_MAIL")) * 1000;
                int IntervaloNFEEntrada     = Convert.ToInt32(ConfigurationManager.AppSettings.Get("INTERVALO_EXECUCAO_NFEENTRADA")) * 1000;
                int IntervaloCartaCorrecao  = Convert.ToInt32(ConfigurationManager.AppSettings.Get("INTERVALO_EXECUCAO_CARTACORRECAO")) * 1000;

                #region NFE de saída

                if (ConfigurationManager.AppSettings.Get("PARAR_NFESAIDA_SEND").Equals("FALSE"))
                {
                    tmNFESaidaSend          = new System.Timers.Timer();
                    tmNFESaidaSend.Interval = IntervaloNFESaidaSend;
                    tmNFESaidaSend.Elapsed += new ElapsedEventHandler(OnTimedEventNFESaidaSend);
                    tmNFESaidaSend.Enabled  = true;
                }
                #endregion

                #region NFE de saída retorno
                if (ConfigurationManager.AppSettings.Get("PARAR_NFESAIDA_RETURN").Equals("FALSE"))
                {
                    tmNFESaidaReturn          = new System.Timers.Timer();
                    tmNFESaidaReturn.Interval = IntervaloNFESaidaReturn;
                    tmNFESaidaReturn.Elapsed += new ElapsedEventHandler(OnTimedEventNFESaidaReturn);
                    tmNFESaidaReturn.Enabled  = true;
                }
                #endregion

                #region NFE de entrada
                if (ConfigurationManager.AppSettings.Get("PARAR_NFEENTRADA").Equals("FALSE"))
                {
                    tmNFEEntrada          = new System.Timers.Timer();
                    tmNFEEntrada.Interval = IntervaloNFEEntrada;
                    tmNFEEntrada.Elapsed += new ElapsedEventHandler(OnTimedEventNFEEntrada);
                    tmNFEEntrada.Enabled  = true;
                }
                #endregion

                #region NFE de Saída envio de e-mail
                if (ConfigurationManager.AppSettings.Get("PARAR_NFESAIDA_MAIL").Equals("FALSE"))
                {
                    tmNFESaidaEmail          = new System.Timers.Timer();
                    tmNFESaidaEmail.Interval = IntervaloNFESaidaMail;
                    tmNFESaidaEmail.Elapsed += new ElapsedEventHandler(OnTimedEventNFESaidaMail);
                    tmNFESaidaEmail.Enabled  = true;
                }
                #endregion

                #region Cartao de correção
                if (ConfigurationManager.AppSettings.Get("PARAR_CARTACORRECAO").Equals("FALSE"))
                {
                    tmCartaoCorrecao          = new System.Timers.Timer();
                    tmCartaoCorrecao.Interval = IntervaloCartaCorrecao;
                    tmCartaoCorrecao.Elapsed += new ElapsedEventHandler(OnTimedEventCartaCorrecao);
                    tmCartaoCorrecao.Enabled  = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                this.GravarLogEventViewer(ex.ToString());
                throw ex;
            }
        }
        //public HttpResponseMessage cadastrar(Usuario user)
        public HttpResponseMessage cadastrar(HttpRequestMessage request, [FromBody] Usuario user)
        {
            RetOk retok = new RetOk();

            ConfigAppMembers cf = Util.ConfigApp.getConfig();

            try
            {
                string aa = JsonConvert.SerializeObject(user);
                //if (!string.IsNullOrEmpty(user.email))
                //{
                //Usuario userexiste = Database.UsuarioADO.ChecaEmail(user.email, user.cdapp, cf.cdentifilial, cf.datasource, cf.schema);
                //if (userexiste != null)
                //{
                //    retok.Codigo = "199";
                //    retok.Mensagem = "NOK";
                //}
                //else
                //{
                //    Util.LogUtil.GravaLog(this, "User post: " + aa, cf.Cnpj, Log.TipoLog.info);
                //    int retquery = Database.UsuarioADO.InsertUser(user, cf.datasource, cf.schema);

                //    retok.Codigo = "100";
                //    retok.Mensagem = "OK";
                //    //}
                //}
                //else
                //{
                Util.LogUtil.GravaLog(this, "User post: " + aa, cf.Cnpj, Log.TipoLog.info);

                string pass = string.Empty;

                bool enviarsenha = false;

                if (!string.IsNullOrEmpty(user.email) && user.senha == "CAD123VINICLARK4321")
                {
                    pass = Util.Cripto.CreatePassword(6);

                    user.senha = pass;

                    enviarsenha = true;
                }


                int retquery = Database.UsuarioADO.InsertUser(user, cf.datasource, cf.schema);

                if (enviarsenha)
                {
                    string query = string.Format("SELECT txsmtp,nrportasmtp,txcontaemail,txsenhaemail,stssl,txtemplateemail FROM configapp where cdapp ={0} and cdentifilial = {1}", cf.codapp, cf.cdentifilial);

                    DataSet       dts          = OracleHelper.ExecQuery(query, null, null, ConfigurationManager.AppSettings.Get("conintegracao"));
                    string        smtp         = string.Empty;
                    string        porta        = string.Empty;
                    string        usuario      = string.Empty;
                    string        senha        = string.Empty;
                    bool          EnableSSL    = false;
                    string        templatehtml = string.Empty;
                    StringBuilder txbody       = new StringBuilder();
                    if (dts.Tables.Count > 0)
                    {
                        foreach (DataRow dr in dts.Tables[0].Rows)
                        {
                            smtp         = dr["txsmtp"].ToString();
                            porta        = dr["nrportasmtp"].ToString();
                            usuario      = dr["txcontaemail"].ToString();
                            senha        = dr["txsenhaemail"].ToString();
                            EnableSSL    = dr["stssl"].ToString() == "1";
                            templatehtml = dr["txtemplateemail"].ToString();
                        }
                    }
                    RJSOptimusEmail emailsend = new RJSOptimusEmail(smtp, Convert.ToInt32(porta), usuario, senha, EnableSSL);

                    emailsend.Subject = "Cadastro";
                    emailsend.To      = user.email;
                    emailsend.From    = usuario;

                    if (string.IsNullOrEmpty(templatehtml))
                    {
                        txbody.AppendLine("Segue o seu usuário e senha de acesso.");
                        txbody.AppendLine(string.Format("Usuário: {0}", user.email));
                        txbody.AppendLine(string.Format("Senha:{0}", pass));
                    }
                    else
                    {//todo dar replace
                        txbody.Append(templatehtml);
                    }
                    emailsend.Body = txbody.ToString();
                    emailsend.Enviar();
                }


                retok.Codigo   = "100";
                retok.Mensagem = "OK";
                //}
            }
            catch (Exception e)
            {
                retok.Codigo   = "200";
                retok.Mensagem = "NOK";
                Util.LogUtil.GravaLog(this, "User post: " + e.ToString(), cf.Cnpj, Log.TipoLog.erro);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, retok));
            }


            string json = JsonConvert.SerializeObject(retok);
            var    res  = Request.CreateResponse(HttpStatusCode.OK);

            res.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(res);
        }
Пример #3
0
        public void EnviarEmailCliente()
        {
            WorkFlowServico _WorkFlowServico = new WorkFlowServico("NFESaidaMail");

            _WorkFlowServico.AddEvento("INÍCIO PROCESSO");
            NFEHelper nfh = new NFEHelper();
            DataTable dt  = null;

            try
            {
                //Verificar se a Internet está ativa
                if (RJS.Optimus.Biblioteca.RJSOptimusNetwork.IsConnected())
                {
                    _WorkFlowServico.AddEvento("INÍCIO nfh.NotasFiscaisEnviarEmail()");

                    if (multiplasfiliais.Equals("TRUE"))
                    {
                        dt = nfh.NotaFiscalEnviarEmailFilial(cdentifilial, datasource, schema);
                    }
                    else
                    {
                        dt = nfh.NotaFiscalEnviarEmail(datasource, schema);
                    }

                    _WorkFlowServico.AddEvento("FIM nfh.NotasFiscaisEnviarEmail()");

                    string xml               = string.Empty;
                    string emailCliente      = string.Empty;
                    string pasta             = string.Empty;
                    string chaveNfe          = string.Empty;
                    string TxFileNfe         = string.Empty;
                    string TxFileNfeAut      = string.Empty;
                    int    CdNotaFiscalSaida = 0;

                    foreach (DataRow dtr in dt.Rows)
                    {
                        //DADOS
                        emailCliente      = dtr["TXEMAIL"].ToString();
                        CdNotaFiscalSaida = Convert.ToInt32(dtr["CDNOTAFISCALSAIDA"]);

                        pasta        = dtr["CDENTIFILIAL"].ToString();
                        chaveNfe     = dtr["NRNFECHAVE"].ToString();
                        TxFileNfe    = dtr["TXFILENFE"].ToString();
                        TxFileNfeAut = dtr["TXFILENFEAUT"].ToString();


                        //não enviar para a lista de dominios informado
                        //mktp.extra.com.br
                        if (EnviarParaDominio(emailCliente))
                        {
                            #region Gravar o arquivo na pasta para o PHP Ler
                            _WorkFlowServico.AddEvento("NRNOTA: " + CdNotaFiscalSaida.ToString() + " CHAVE NFE: " + chaveNfe);

                            string NomeDoArquivo = string.Format("{0}\\{1}\\{2}.xml", PastaNfePHP, pasta, chaveNfe);
                            _WorkFlowServico.AddEvento("NomeDoArquivo: " + NomeDoArquivo);
                            string NomeDoArquivoPdf = string.Format("{0}\\{1}\\{2}.pdf", PastaNfePHP, pasta, chaveNfe);
                            _WorkFlowServico.AddEvento("NomeDoArquivoPdf: " + NomeDoArquivoPdf);
                            //Verifica se o arquivo existe
                            if (!System.IO.File.Exists(NomeDoArquivo))
                            {
                                //Montar o XML
                                StringBuilder XML_NFE = new StringBuilder();
                                XML_NFE.AppendLine(TxFileNfe);

                                _WorkFlowServico.AddEvento("PASTA: " + string.Concat(PastaNfePHP, "\\", pasta));

                                //Se não existe o diretorio cria um novo
                                if (!System.IO.Directory.Exists(string.Concat(PastaNfePHP, "\\", pasta)))
                                {
                                    System.IO.Directory.CreateDirectory(string.Concat(PastaNfePHP, "\\", pasta));
                                }

                                //Se existe exclui o arquivo
                                if (System.IO.File.Exists(NomeDoArquivo))
                                {
                                    System.IO.File.Delete(NomeDoArquivo);
                                }

                                _WorkFlowServico.AddEvento("INÍCIO GRAVAÇÃO DO ARQUIVO");
                                _WorkFlowServico.AddEvento("ARQUIVO: " + NomeDoArquivo);
                                StreamWriter sw = new StreamWriter(NomeDoArquivo, false, Encoding.GetEncoding(1252));
                                sw.Write(XML_NFE);
                                sw.Close();

                                _WorkFlowServico.AddEvento("FIM GRAVAÇÃO DO ARQUIVO");
                            }
                            //CARREGAR O XML PARA PEGAR OS DADOS
                            NFE _NFEtrocar = Util.CarregarNfe(NomeDoArquivo);
                            _WorkFlowServico.AddEvento("CARREGA O XML PARA PERGAR OS DADOS:" + NomeDoArquivo);

                            #endregion
                            _WorkFlowServico.AddEvento("INÍCIO DOWNLOAD DO PDF");
                            #region download do pdf
                            bool pdfOK = false;

                            int i = 0;

                            for (i = 1; i < 5; i++)
                            {
                                if (!pdfOK)
                                {
                                    _WorkFlowServico.AddEvento("TENTATIVA Nº:" + i.ToString());
                                    //Log.For(this, PastaLogCliente).Info("TENTATIVA Nº:" + i.ToString());
                                    //gerar o PDF e gravar o PDF
                                    if (i == 1)
                                    {
                                        _WorkFlowServico.AddEvento("URL: " + string.Format(urlDanfe, pasta, chaveNfe, schema));
                                        _WorkFlowServico.AddEvento("ARQUIVO: " + NomeDoArquivoPdf);
                                        //Log.For(this, PastaLogCliente).Info("PDF URL: " + string.Format(urlDanfe, pasta, chaveNfe, cliente));
                                        //Log.For(this, PastaLogCliente).Info("ARQUIVO: " + NomeDoArquivoPdf);
                                    }

                                    if (!System.IO.File.Exists(NomeDoArquivoPdf))//se nao existe faz o download
                                    {
                                        try
                                        {
                                            Util.DownloadFile(string.Format(urlDanfe, pasta, chaveNfe, schema), NomeDoArquivoPdf);
                                            _WorkFlowServico.AddEvento("BAIXOU NA TENTATIVA:" + i.ToString());
                                        }
                                        catch (Exception exw)
                                        {
                                            Util.DownloadFile(string.Format(urlDanfe, pasta, chaveNfe, schema), NomeDoArquivoPdf);
                                            if (!System.IO.File.Exists(NomeDoArquivoPdf))
                                            {
                                                _WorkFlowServico.AddEvento("NAO BAIXOU NA EXECEPTION :" + exw.ToString());
                                            }
                                            else
                                            {
                                                _WorkFlowServico.AddEvento("BAIXOU NA EXECEPTION :" + exw.ToString());
                                            }
                                        }

                                        if (!System.IO.File.Exists(NomeDoArquivoPdf))
                                        {
                                            _WorkFlowServico.AddEvento("NAO CONSEGUIU BAIXAR:" + NomeDoArquivoPdf);
                                        }
                                        else
                                        {
                                            _WorkFlowServico.AddEvento("FIM DOWNLOAD DO PDF TENTATIVA Nº:" + i.ToString());

                                            FileInfo fi = new FileInfo(NomeDoArquivoPdf);
                                            if (fi.Length < 6144)// menor que 6kb
                                            {
                                                if (System.IO.File.Exists(NomeDoArquivoPdf))
                                                {
                                                    System.IO.File.Delete(NomeDoArquivoPdf);
                                                }

                                                Util.DownloadFile(string.Format(urlDanfe, pasta, chaveNfe, schema), NomeDoArquivoPdf);
                                            }
                                            else
                                            {
                                                pdfOK = true;
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion

                            RJSOptimusEmail email = new RJSOptimusEmail(smtp, Convert.ToInt32(porta), usuario, senha, EnableSSL);

                            FileInfo fiPdf = new FileInfo(NomeDoArquivoPdf);
                            #region Envio do email
                            if (fiPdf.Length < 6144)
                            {
                                _WorkFlowServico.AddEvento("ERRO GERAR PDF (TAMANHO):" + NomeDoArquivoPdf);
                                Log.For(this, PastaLogCliente).Error(_WorkFlowServico.FinishWorkFlow());
                                objemailadm.SUBJECT = string.Format("ERRO GERAR PDF (TAMANHO) {0} Cnpj:{1} SCHEMA{2}:.", cliente, cnpjcliente, schema);
                                objemailadm.BODY    = fiPdf.FullName;
                                Util.EnviaEmail(objemailadm, "*****@*****.**");
                            }
                            else
                            {
                                //Enviar o e-mail
                                _WorkFlowServico.AddEvento("INÍCIO ENVIO E-MAIL");
                                if (smtp.Trim() == "smtp.optimuserp.com.br")
                                {
                                    email.From = "*****@*****.**";
                                }
                                else
                                {
                                    email.From = emailEmpresa;
                                }
                                email.From = emailEmpresa;
                                bool EmailClienteValido = true;

                                email.Subject = MsgSubject.Replace("#NRNOTA#", _NFEtrocar.IDE_NNF.ToString()).
                                                Replace("#CHAVE#", _NFEtrocar.IDE_ID).
                                                Replace("#DTEMISSAO#", _NFEtrocar.IDE_DEMI.ToString("dd/MM/yyyy")).
                                                Replace("#SERIE#", _NFEtrocar.IDE_SERIE).
                                                Replace("#RAZAO#", _NFEtrocar.RAZAOSOCIAL).
                                                Replace("#CODPEDIDO#", _NFEtrocar.CODPEDIDO).
                                                Replace("#NMCLIENTE#", _NFEtrocar.DEST_NOME);;

                                //if (Util.ValidarEmail(emailCliente))
                                //{

                                email.To = emailCliente;

                                string BodyTemplate = MsgPattern.ToString();

                                //Pegar do template
                                //se vier o nome do arquivo carrega se nao pega o texto que veio normal
                                if (BodyTemplate.Contains(".html"))
                                {
                                    string pastaTemplate = ConfigurationManager.AppSettings.Get("PASTA_TEMPLATE_HTML").ToString();

                                    string Body = System.IO.File.ReadAllText(pastaTemplate + BodyTemplate);

                                    BodyTemplate = Body;
                                }

                                BodyTemplate = BodyTemplate.Replace("#CNPJ#", Convert.ToUInt64(_NFEtrocar.EMIT_CNPJ).ToString(@"00\.000\.000\/0000\-00"));

                                BodyTemplate = BodyTemplate.Replace("#NRNOTA#", _NFEtrocar.IDE_NNF.ToString()).
                                               Replace("#CHAVE#", _NFEtrocar.IDE_ID).
                                               Replace("#DTEMISSAO#", _NFEtrocar.IDE_DEMI.ToString("dd/MM/yyyy")).
                                               Replace("#SERIE#", _NFEtrocar.IDE_SERIE).
                                               Replace("#RAZAO#", _NFEtrocar.RAZAOSOCIAL).
                                               Replace("#CODPEDIDO#", _NFEtrocar.CODPEDIDO).
                                               Replace("#NMCLIENTE#", _NFEtrocar.DEST_NOME);



                                email.Body = BodyTemplate;

                                _NFEtrocar = null;

                                try
                                {
                                    if (!string.IsNullOrEmpty(emailAdmin))
                                    {
                                        email.ListaEmailsBCC.Add(emailAdmin);
                                    }

                                    if (!string.IsNullOrEmpty(enviarCopiaCliente) && EmailClienteValido)
                                    {
                                        string[] emailscliente = enviarCopiaCliente.Split(';');

                                        foreach (string emailcli in emailscliente)
                                        {
                                            email.ListaEmailsBCC.Add(emailcli);
                                        }
                                    }

                                    email.AddAnexo(new System.Net.Mail.Attachment(NomeDoArquivo));    //XML
                                    email.AddAnexo(new System.Net.Mail.Attachment(NomeDoArquivoPdf)); //PDF
                                    email.IsBodyHtml = true;
                                    email.Enviar();

                                    //Atualiza o status da NFE como e-mail enviado
                                    nfh.NotaFiscalUpdateEmailEnviado(CdNotaFiscalSaida, 3, datasource, schema);//ele tentar enviar 2x

                                    #region Enviar e-mail para transportador

                                    if (EnviarEmailTransportador)
                                    {
                                        _WorkFlowServico.AddEvento("INÍCIO ENVIO E-MAIL TRANSPORTADOR");
                                        List <string> EmailsTransportador = new List <string>();

                                        //Carrega o xml e pega o CNPJ do transportador
                                        string _CNPJ = Util.PegarCNPJTransportador(NomeDoArquivo);

                                        if (!string.IsNullOrEmpty(_CNPJ))
                                        {
                                            //Verifica se ja esta na base antes de buscar o transportador
                                            if (CacheLayer.Exists(_CNPJ))
                                            {
                                                EmailsTransportador = CacheLayer.Get <List <string> >(_CNPJ);
                                                _WorkFlowServico.AddEvento("ACHOU NO CACHE");
                                            }
                                            else
                                            {
                                                NFEHelper nh = new NFEHelper();
                                                //Busca na base os e-mail do transportador
                                                EmailsTransportador = nh.RetornaEmailTransportadora(_CNPJ, datasource, schema);

                                                if (EmailsTransportador.Count > 0)
                                                {
                                                    CacheLayer.Add(EmailsTransportador, _CNPJ);
                                                    _WorkFlowServico.AddEvento("ACHOU OS EMAILS : " + EmailsTransportador.Count.ToString());
                                                }
                                            }

                                            if (EmailsTransportador.Count > 0)
                                            {
                                                try
                                                {
                                                    RJSOptimusEmail emailtransp = new RJSOptimusEmail(smtp, Convert.ToInt32(porta), usuario, senha, EnableSSL);

                                                    if (!string.IsNullOrEmpty(emailAdmin))
                                                    {
                                                        emailtransp.ListaEmailsBCC.Add(emailAdmin);
                                                    }

                                                    if (smtp.Trim() == "smtp.optimuserp.com.br")
                                                    {
                                                        emailtransp.From = "*****@*****.**";
                                                    }
                                                    else
                                                    {
                                                        emailtransp.From = emailEmpresa;
                                                    }

                                                    emailtransp.Subject = MsgSubject;
                                                    emailtransp.Body    = "Nota fiscal eletronica";

                                                    //TODO lista de e-mails
                                                    foreach (string emailtranspenviar in EmailsTransportador)
                                                    {
                                                        //emailtransp.ListaEmailsBCC.Add(emailtranspenviar);
                                                        _WorkFlowServico.AddEvento("EMAIL: " + emailtranspenviar);
                                                        emailtransp.ListaEmailsObj.Add(new System.Net.Mail.MailAddress(emailtranspenviar));
                                                    }

                                                    emailtransp.AddAnexo(new System.Net.Mail.Attachment(NomeDoArquivo));//XML
                                                    emailtransp.IsBodyHtml = true;
                                                    emailtransp.Enviar();
                                                    _WorkFlowServico.AddEvento("FIM ENVIO E-MAIL TRANSPORTADOR");
                                                }
                                                catch (Exception ext)
                                                {
                                                    _WorkFlowServico.AddEvento("ERRO ENVIO E-MAIL TRANSP:" + ext.ToString());
                                                }
                                            }
                                            else
                                            {
                                                _WorkFlowServico.AddEvento("NÃO RETORNOU E-MAIL TRANSP CNPJ: " + _CNPJ);
                                            }
                                        }
                                        else
                                        {
                                            _WorkFlowServico.AddEvento("NÃO ACHOU TRANSP " + NomeDoArquivo);
                                        }
                                    }
                                    #endregion

                                    _WorkFlowServico.AddEvento("FIM ENVIO E-MAIL ");

                                    Log.For(this, PastaLogCliente).Info(_WorkFlowServico.FinishWorkFlow());
                                }
                                catch (Exception exx)
                                {
                                    nfh.NotaFiscalUpdateEmailEnviado(CdNotaFiscalSaida, datasource, schema);

                                    try
                                    {
                                        Log.For(this, PastaLogCliente).Error(_WorkFlowServico.FinishWorkFlow() + Environment.NewLine + exx.ToString());

                                        string chavecache = Cache[CdNotaFiscalSaida.ToString()] as string;

                                        if (string.IsNullOrEmpty(chavecache))
                                        {
                                            Cache.Insert(
                                                CdNotaFiscalSaida.ToString(),
                                                CdNotaFiscalSaida.ToString(),
                                                null,
                                                Cache.NoAbsoluteExpiration,
                                                TimeSpan.FromSeconds(900));

                                            objemailadm.SUBJECT = string.Format("ERRO ENVIAR E-MAIL CLIENTE: {0} Cnpj: {1} E-MAIL CLIENTE: {2} CDNOTAFISCALSAIDA: {3} SCHEMA: {4}.", cliente, cnpjcliente, emailCliente, CdNotaFiscalSaida, schema);
                                            objemailadm.BODY    = exx.ToString();
                                            Util.EnviaEmail(objemailadm, "*****@*****.**");
                                        }
                                    }
                                    catch (Exception exxx)
                                    {
                                        Log.For(this, PastaLogCliente).Error(_WorkFlowServico.FinishWorkFlow() + Environment.NewLine + exxx.ToString());
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            nfh.NotaFiscalUpdateEmailEnviado(CdNotaFiscalSaida, 3, datasource, schema);
                        }//fim tratamento do dominio
                    }
                }
                else
                {
                    //Internet fora do ar
                    _WorkFlowServico.AddEvento("SEM CONEXÃO COM A INTERNET");
                    Log.For(this, PastaLogCliente).Error(_WorkFlowServico.FinishWorkFlow());
                }
            }
            catch (Exception ex)
            {
                try
                {
                    Log.For(this, PastaLogCliente).Error(_WorkFlowServico.FinishWorkFlow() + Environment.NewLine + ex.ToString());

                    objemailadm.SUBJECT = string.Format("ERRO CATCH GERAL ENVIAR E-MAIL. CLIENTE: {0} Cnpj: {1}.", cliente, cnpjcliente);
                    objemailadm.BODY    = _WorkFlowServico.FinishWorkFlow() + Environment.NewLine + ex.ToString();
                    Util.EnviaEmail(objemailadm, "*****@*****.**");
                }
                catch (Exception exs)
                {
                    RJS.Optimus.Biblioteca.RJSOptimusLog.GravaLogEventViewer("RJS.Optimus.Win.Int.Servicos.NFEOptimus", string.Concat(_WorkFlowServico.FinishWorkFlow(), Environment.NewLine, exs.ToString()), System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }
        public HttpResponseMessage EsqueciSenhaByEmail(string email)
        {
            ConfigAppMembers cf    = Util.ConfigApp.getConfig();
            Usuario          user  = new Usuario();
            RetOk            retok = new RetOk();

            try
            {
                user = Database.UsuarioADO.RetornaUsuarioByEmail(email, cf.codapp, cf.cdentifilial, cf.datasource, cf.schema);

                if (string.IsNullOrEmpty(user.email))
                {
                    retok.Codigo   = "200";
                    retok.Mensagem = "NOK";
                }
                else
                {
                    string query = string.Format("SELECT txsmtp,nrportasmtp,txcontaemail,txsenhaemail,stssl,txtemplateemail FROM configapp where cdapp ={0} and cdentifilial = {1}", cf.codapp, cf.cdentifilial);

                    DataSet       dts          = OracleHelper.ExecQuery(query, null, null, ConfigurationManager.AppSettings.Get("conintegracao"));
                    string        smtp         = string.Empty;
                    string        porta        = string.Empty;
                    string        usuario      = string.Empty;
                    string        senha        = string.Empty;
                    bool          EnableSSL    = false;
                    string        templatehtml = string.Empty;
                    StringBuilder txbody       = new StringBuilder();
                    if (dts.Tables.Count > 0)
                    {
                        foreach (DataRow dr in dts.Tables[0].Rows)
                        {
                            smtp         = dr["txsmtp"].ToString();
                            porta        = dr["nrportasmtp"].ToString();
                            usuario      = dr["txcontaemail"].ToString();
                            senha        = dr["txsenhaemail"].ToString();
                            EnableSSL    = dr["stssl"].ToString() == "1";
                            templatehtml = dr["txtemplateemail"].ToString();
                        }
                    }
                    RJSOptimusEmail emailsend = new RJSOptimusEmail(smtp, Convert.ToInt32(porta), usuario, senha, EnableSSL);

                    emailsend.Subject = "Recuperação de senha";
                    emailsend.To      = user.email;
                    emailsend.From    = usuario;

                    if (string.IsNullOrEmpty(templatehtml))
                    {
                        txbody.AppendLine("Você solicitou a sua senha.");
                        txbody.AppendLine(string.Format("Usuário: {0}", email));
                        txbody.AppendLine(string.Format("Senha:{0}", user.senha));
                    }
                    else
                    {//todo dar replace
                        txbody.Append(templatehtml);
                    }
                    emailsend.Body = txbody.ToString();
                    emailsend.Enviar();

                    retok.Codigo   = "100";
                    retok.Mensagem = "OK";
                    retok.dados    = null;
                }
            }
            catch (Exception e)
            {
                Util.LogUtil.GravaLog(this, "getuserByEmail: " + e.ToString(), cf.Cnpj, Log.TipoLog.erro);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, "ERRO"));
            }

            string json = JsonConvert.SerializeObject(retok);
            var    res  = Request.CreateResponse(HttpStatusCode.OK);

            res.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(res);
            //return Request.CreateResponse(HttpStatusCode.OK, user);
        }