Пример #1
0
        /// <summary>
        /// QRコード作成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QRCreate_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title            = "保存先のファイルを選択してください";
            sfd.RestoreDirectory = true;
            sfd.Filter           = "PNGファイル(*.png)|*.png";
            sfd.FileName         = DateTime.Now.ToString("yyyyMMdd_HHmmssfff") + ".png";

            if (string.IsNullOrEmpty(Properties.Settings.Default.QR出力先))
            {
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            }
            else
            {
                sfd.InitialDirectory = Properties.Settings.Default.QR出力先;
            }

            if (sfd.ShowDialog() == true)
            {
                Properties.Settings.Default.QR出力先 = SysIO.Path.GetDirectoryName(sfd.FileName);
                Properties.Settings.Default.Save();
                QrCodeUtil.CreateHBitmap(QRText.Text, sfd.FileName);
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            var path = "D:/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
            var qr   = QrCodeUtil.Encode("Hello World!");

            qr.Save(path);
            Console.WriteLine(QrCodeUtil.Decode(qr));

            path = "D:/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
            QrCodeUtil.Create("中国智造,惠及全球!", path);
            Console.WriteLine(QrCodeUtil.Decode(path));

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
        public bool IsNotaFiscalValida(NotaFiscal notaFiscal, string cscId, string csc, X509Certificate2 certificado)
        {
            var refUri           = "#NFe" + notaFiscal.Identificacao.Chave;
            var digVal           = "";
            var nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";

            var xml = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>",
                                    string.Empty);

            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            try
            {
                string newNodeXml;
                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    var qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal,
                                                           notaFiscal.Identificacao.Ambiente,
                                                           notaFiscal.Identificacao.DataHoraEmissao,
                                                           notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                           notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId,
                                                           csc, notaFiscal.Identificacao.TipoEmissao);

                    newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
                }
                else
                {
                    newNodeXml = node.InnerXml;
                }

                var document = new XmlDocument();
                document.LoadXml(newNodeXml);
                node = document.DocumentElement;

                ValidadorXml.ValidarXml(node.OuterXml, "enviNFe_v4.00.xsd");

                return(true);
            }
            catch (Exception e)
            {
                log.Error(e);
                return(false);
            }
        }
        private static string PreencherQrCode(NotaFiscal notaFiscal, string cscId, string csc, ref string qrCode, string digVal, XmlNode node)
        {
            string newNodeXml;

            if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
            {
                qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario,
                                                   digVal, notaFiscal.Identificacao.Ambiente,
                                                   notaFiscal.Identificacao.DataHoraEmissao,
                                                   notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                   notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F",
                                                                                                         CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
            }
            else
            {
                newNodeXml = node.InnerXml;
            }

            return(newNodeXml);
        }
        // ap.exe should be called from OOBE [Shift] + [F10] command prompt via:

        // powershell -c iwr ap.domain.com -o ap.exe & qr
        // or
        // curl -o ap.exe ap.domain.com & ap

        // curl remarks:
        // -L is used to follow redirects e.g. redirect to https
        // curl -o ap.exe -L ap.domain.com & ap
        static async Task Main(string[] args)
        {
            _logger        = new LogUtil();
            _backendUrl    = ParseCommandlineArgs(args);
            _backendClient = new BackendClient();
            _backendClient.MessageReceived += BackendClient_MessageReceived;
            _backendClient.ResultReceived  += BackendClient_ResultReceived;
            _windowsAutopilotHashService    = new WindowsAutopilotHashService();
            _windowsAutopilotHashService.MessageReceived += WindowsAutopilotHashService_MessageReceived;

            try
            {
                // default Action is IMPORT
                var action = "IMPORT";

                // --erase device deletion request found
                if (_deleteManagedDeviceOnly)
                {
                    _logger.WriteInfo("Identified as device [DELETE] request");
                    action = "DELETE";
                }
                else
                {
                    _logger.WriteInfo("Identified as device [IMPORT] request");

                    // --skip endpoint validation found
                    if (!_skipEndpointsValidation)
                    {
                        var endpointVerificationError = false;
                        if (_endpointsValidationResult = await _backendClient.VerifyEnrollmentEndpoints())
                        {
                            _logger.WriteInfo("All enrollment URLs reachable");
                        }
                        else
                        {
                            if (!_logger.DebugMode)
                            {
                                _logger.WriteInfo("Not all enrollment URLs reachable or system time is wrong!");
                                _logger.WriteInfo($"Use '{Assembly.GetExecutingAssembly().GetName().Name} --connect --verbose' for connectivity test details.");
                                endpointVerificationError = true;
                            }
                            else
                            {
                                _logger.WriteInfo("=> Not all enrollment URLs reachable or system time is wrong!");
                                endpointVerificationError = true;
                            }
                        }
                        // --connect endpoint validation only found
                        if (_endpointsValidationOnly)
                        {
                            if (endpointVerificationError)
                            {
                                Environment.Exit(1);
                            }
                            return;
                        }
                    }

                    // --ignore Autopilot assignment found
                    if (!_ignoreAutopilotAssignment)
                    {
                        try
                        {
                            // is this already a Autopilot device?
                            var rkbase = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                            using (RegistryKey key = rkbase.OpenSubKey(@"SOFTWARE\Microsoft\Provisioning\Diagnostics\AutoPilot"))
                            {
                                if (key != null)
                                {
                                    var tenantId = key.GetValue("CloudAssignedTenantId").ToString();
                                    if (!string.IsNullOrEmpty(tenantId))
                                    {
                                        _logger.WriteInfo("Device is already Autopilot provisioned");
                                        _logger.WriteDebug($"CloudAssignedTenantId: {tenantId}");

                                        var tenantDomain = key.GetValue("CloudAssignedTenantDomain").ToString();
                                        if (!string.IsNullOrEmpty(tenantDomain))
                                        {
                                            if (_logger.DebugMode)
                                            {
                                                _logger.WriteDebug($"CloudAssignedTenantDomain: {tenantDomain}");
                                            }
                                            else
                                            {
                                                _logger.WriteInfo($"Assigned tenant domain: {tenantDomain}");
                                            }
                                        }
                                        return;
                                    }
                                }
                            }
                        }
                        catch (Exception)
                        {
                            _logger.WriteInfo("Couldn't check existing Autopilot assignment, proceeding.");
                        }
                    }
                }

                // main work start now
                _logger.WriteInfo("Fetching system information");
                _systemInformation        = _windowsAutopilotHashService.FetchData();
                _systemInformation.Action = action;

                if (_systemInformation == null)
                {
                    _logger.WriteInfo("No Windows 10/11 operating system, can't fetch data");
                    return;
                }

                if (string.IsNullOrEmpty(_systemInformation.HardwareHash))
                {
                    _logger.WriteInfo("Information couldn't be fetched");
                }
                else
                {
                    _logger.WriteInfo("Information successfully fetched");
                    if (_fetchHardwareDataOnly)
                    {
                        return;
                    }

                    // check if our backend server is reachable
                    if (!_backendClient.IsValidUrl(_backendUrl, out _backendUrl, "HEAD"))
                    {
                        _logger.WriteInfo("Backend URL not reachable");
                        return;
                    }
                    else
                    {
                        _logger.WriteDebug($"Resolved backend URL is {_backendUrl}");
                    }

                    // Safe the info to app service AutopilotManager... result here may be 'not allowed', catched in ResultReceived handler
                    await _backendClient.SaveDataAsync(_systemInformation, _backendUrl);

                    var url         = new Url($"{_backendUrl}/autopilot/{_systemInformation.Id}/save-information");
                    var qrCodeImage = QrCodeUtil.GenerateQrCode(url.ToString());
                    //var qrCodeImage = QrCodeUtil.GenerateQrCode(url.ToString(), 8);

                    var urlNoSelfService         = new Url($"{_backendUrl}/Home/NoSelfService");
                    var qrCodeNoSelfServiceImage = QrCodeUtil.GenerateQrCode(urlNoSelfService.ToString());

                    var form = new QrCodeForm(qrCodeImage, qrCodeNoSelfServiceImage, _systemInformation, _backendClient, _backendUrl, _preCheckErrorMessage, _endpointsValidationResult);
                    form.DisplayData();

                    if (form.DialogResult == DialogResult.Retry)
                    {
                        _logger.WriteDebug("Retry received");

                        string[] arguments = Environment.GetCommandLineArgs();

                        var path            = Assembly.GetExecutingAssembly().Location;
                        var fullPathcommand = $"{path} {string.Join(" ", arguments.Skip(1).ToArray())}";

                        _logger.WriteDebug($"Using command: {fullPathcommand}");
                        _logger.WriteDebug("Starting as external process, debug output will not be received in this command prompt.");
                        _logger.WriteDebug("Start manually (not using Retry button) from this command prompt to receive the debug output again.");

                        using (var p = new Process())
                        {
                            p.StartInfo.UseShellExecute = false;
                            p.StartInfo.FileName        = path;
                            p.StartInfo.Arguments       = string.Join(" ", arguments.Skip(1).ToArray());
                            p.StartInfo.CreateNoWindow  = true;
                            p.Start();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.WriteInfo(ex.ToString());
                _logger.WriteInfo("**************** Closing application, fix and porting try again ****************");
                return;
            }
        }
Пример #6
0
        public void GerarQrCodeNFeEmissãoOffline_ShouldReturnCorrectQrCode()
        {
            string qrCode = QrCodeUtil.GerarQrCodeNFe("53180904585789000140650030000002561000002566", null, "hxbsVs7OyDdBqCepI6VlkUfkspM=", Ambiente.Homologacao, DateTime.ParseExact("2018-09-30T08:56:34-03:00", "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), "65.00", "0.00", "000001", "D32FCA9A-D485-489E-9001-78BCEFF8B198", TipoEmissao.ContigenciaNfce);

            Assert.AreEqual("http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx?p=53180904585789000140650030000002561000002566|2|2|30|65.00|687862735673374f79446442714365704936566c6b55666b73704d3d|1|D1FF4BAE6B32811BE4D534556E4516CC4A421588", qrCode);
        }
Пример #7
0
        public void GerarQrCodeNFeEmissãoOnline_ShouldReturnCorrectQrCode()
        {
            string qrCode = QrCodeUtil.GerarQrCodeNFe("53180904585789000140650030000002561000002566", null, "hxbsVs7OyDdBqCepI6VlkUfkspM=", Ambiente.Homologacao, DateTime.ParseExact("2018-09-30T08:56:34-03:00", "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture), "65.00", "0.00", "000001", "D32FCA9A-D485-489E-9001-78BCEFF8B198", TipoEmissao.Normal);

            Assert.AreEqual("http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx?p=53180904585789000140650030000002561000002566|2|2|1|C1A66513D0CCA30AEA8F5168A8A80B4787530272", qrCode);
        }
        public int EmitirNotaContingencia(NotaFiscal notaFiscal, string cscId, string csc)
        {
            var qrCode = string.Empty;
            string newNodeXml;
            const string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";
            var digVal = string.Empty;

            var config = _configuracaoService.GetConfiguracao();

            notaFiscal.Identificacao.Numero = _configuracaoService.ObterProximoNumeroNotaFiscal(notaFiscal.Identificacao.Modelo);
            notaFiscal.Identificacao.DataHoraEntradaContigencia = config.DataHoraEntradaContingencia;
            notaFiscal.Identificacao.JustificativaContigencia = config.JustificativaContingencia;
            notaFiscal.Identificacao.TipoEmissao = notaFiscal.Identificacao.Modelo == Modelo.Modelo65
                ? TipoEmissao.ContigenciaNfce
                : TipoEmissao.FsDa;
            notaFiscal.CalcularChave();

            X509Certificate2 certificado;

            var certificadoEntity = _certificadoRepository.GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
                certificado = _certificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                    RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            else
                certificado = _certificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);

            if (notaFiscal.Identificacao.Ambiente == Ambiente.Homologacao)
                notaFiscal.Produtos[0].Descricao = "NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";

            var refUri = "#NFe" + notaFiscal.Identificacao.Chave;

            var xml = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>",
                string.Empty);
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
            {
                qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario,
                    digVal, notaFiscal.Identificacao.Ambiente,
                    notaFiscal.Identificacao.DataHoraEmissao,
                    notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                    notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId,
                    csc, notaFiscal.Identificacao.TipoEmissao);

                newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
            }
            else
            {
                newNodeXml = node.InnerXml.Replace("<infNFeSupl><qrCode /></infNFeSupl>", "");
            }

            var document = new XmlDocument();
            document.LoadXml(newNodeXml);
            node = document.DocumentElement;

            if (node == null) throw new ArgumentException("Xml inválido.");

            var lote = (TEnviNFe)XmlUtil.Deserialize<TEnviNFe>(node.OuterXml);
            var nfe = lote.NFe[0];

            //salvar nota PreEnvio aqui
            notaFiscal.Identificacao.Status = Status.CONTINGENCIA;

            var idNotaCopiaSeguranca =  _notaFiscalRepository.SalvarNotaFiscalPendente(notaFiscal,
                XmlUtil.GerarNfeProcXml(nfe, qrCode),
                notaFiscal.Identificacao.Ambiente);

            var notaFiscalEntity =  _notaFiscalRepository.GetNotaFiscalById(idNotaCopiaSeguranca, false);
            notaFiscalEntity.Status = (int)Status.CONTINGENCIA;
            var nfeProcXml = XmlUtil.GerarNfeProcXml(nfe, qrCode);

             _notaFiscalRepository.Salvar(notaFiscalEntity, nfeProcXml);
            notaFiscal.QrCodeUrl = qrCode;
            return idNotaCopiaSeguranca;
        }
Пример #9
0
        public bool IsNotaFiscalValida(NotaFiscal notaFiscal, string cscId, string csc)
        {
            string qrCode = "";

            string refUri           = "#NFe" + notaFiscal.Identificacao.Chave;
            string digVal           = "";
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
            {
                certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                      RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            }
            else
            {
                certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
            }

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);;
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            TNFe   nfe        = null;
            string newNodeXml = string.Empty;

            try
            {
                var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                       notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                       notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                    newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
                }
                else
                {
                    newNodeXml = node.InnerXml;
                }

                var document = new XmlDocument();
                document.LoadXml(newNodeXml);
                node = document.DocumentElement;

                TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);
                nfe = lote.NFe[0];

                ValidadorXml.ValidarXml(node.OuterXml, "enviNFe_v4.00.xsd");

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #10
0
        /** <exception cref="Exception"/>
         * <summary>Responsável pelo envio da Nota Fiscal para a SEFAZ.</summary>
         */
        internal async Task <int> EnviarNotaFiscalAsync(NotaFiscal notaFiscal, string cscId, string csc)
        {
            string           qrCode               = "";
            TNFe             nfe                  = null;
            string           newNodeXml           = string.Empty;
            int              idNotaCopiaSeguranca = 0;
            NotaFiscalEntity notaFiscalEntity     = null;

            string refUri           = "#NFe" + notaFiscal.Identificacao.Chave;
            string digVal           = "";
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            certificado = EscolherCertificado(certificadoEntity);

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            try
            {
                var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

                if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
                {
                    //NFC-e tem QrCode obrigatório
                    qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                       notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                       notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                    newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
                }
                else
                {
                    newNodeXml = node.InnerXml;
                }

                var document = new XmlDocument();
                document.LoadXml(newNodeXml);
                node = document.DocumentElement;

                TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);
                nfe = lote.NFe[0];

                var servico = ServiceFactory.GetService(notaFiscal.Identificacao.Modelo, notaFiscal.Identificacao.Ambiente, Factory.Servico.AUTORIZACAO, codigoUF, certificado);
                var client  = (NFeAutorizacao4.NFeAutorizacao4SoapClient)servico.SoapClient;

                //salvar nota PreEnvio aqui
                notaFiscal.Identificacao.Status = NFe.Repository.Status.PENDENTE;

                var notaFiscalService = new NotaFiscalService();

                idNotaCopiaSeguranca = await notaFiscalService.SalvarNotaFiscalPendenteAsync(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente);

                XmlNode     result  = client.nfeAutorizacaoLote(node);
                TRetEnviNFe retorno = (TRetEnviNFe)XmlUtil.Deserialize <TRetEnviNFe>(result.OuterXml);
                XmlSchemas.NfeAutorizacao.Retorno.TProtNFe protocolo = (XmlSchemas.NfeAutorizacao.Retorno.TProtNFe)retorno.Item; //existem dois valores possíveis de retorno (esse aqui só vale para lote com 1 nota)

                if (protocolo.infProt.cStat.Equals("100"))
                {
                    notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false);

                    notaFiscalEntity.Status          = (int)Status.ENVIADA;
                    notaFiscalEntity.DataAutorizacao = DateTime.ParseExact(protocolo.infProt.dhRecbto, "yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture);

                    notaFiscalEntity.Protocolo = protocolo.infProt.nProt;
                    string xmlNFeProc = XmlUtil.GerarNfeProcXml(nfe, qrCode, protocolo);

                    await notaFiscalService.SalvarAsync(notaFiscalEntity, xmlNFeProc);
                }
                else
                {
                    if (protocolo.infProt.xMotivo.Contains("Duplicidade"))
                    {
                        notaFiscalEntity = await CorrigirNotaDuplicada(notaFiscal, qrCode, nFeNamespaceName, certificado, nfe, idNotaCopiaSeguranca, notaFiscalEntity);
                    }
                    else
                    {
                        //Nota continua com status pendente nesse caso
                        XmlUtil.SalvarXmlNFeComErro(notaFiscal, node);
                        string mensagem = string.Concat("O xml informado é inválido de acordo com o validar da SEFAZ. Nota Fiscal não enviada!", "\n", protocolo.infProt.xMotivo);
                        throw new ArgumentException(mensagem);
                    }
                }

                notaFiscal.QrCodeUrl            = qrCode;
                notaFiscal.Identificacao.Status = Status.ENVIADA;
                notaFiscal.DhAutorizacao        = notaFiscalEntity.DataAutorizacao.ToString("dd/MM/yyyy HH:mm:ss");
                notaFiscal.DataHoraAutorização  = notaFiscalEntity.DataAutorizacao;
                notaFiscal.ProtocoloAutorizacao = notaFiscalEntity.Protocolo;
                return(idNotaCopiaSeguranca);
            }
            catch (Exception e)
            {
                var codigoUF = notaFiscal.Identificacao.UF;
                var ambiente = notaFiscal.Identificacao.Ambiente;

                if (e.InnerException is WebException)
                {
                    throw new Exception("Serviço indisponível ou sem conexão com a internet.", e.InnerException);
                }

                try
                {
                    notaFiscalEntity = await VerificarSeNotaFoiEnviada(notaFiscal, cscId, csc, qrCode, nfe, idNotaCopiaSeguranca, notaFiscalEntity, nFeNamespaceName, certificado);
                }
                catch (Exception retornoConsultaException)
                {
                    EscreverLogErro(e);
                    EscreverLogErro(retornoConsultaException);
                    XmlUtil.SalvarXmlNFeComErro(notaFiscal, node);
                    throw retornoConsultaException;
                }

                notaFiscal.QrCodeUrl            = qrCode;
                notaFiscal.Identificacao.Status = Status.ENVIADA;
                notaFiscal.DhAutorizacao        = notaFiscalEntity.DataAutorizacao.ToString("dd/MM/yyyy HH:mm:ss");
                notaFiscal.DataHoraAutorização  = notaFiscalEntity.DataAutorizacao;
                notaFiscal.ProtocoloAutorizacao = notaFiscalEntity.Protocolo;
                return(idNotaCopiaSeguranca);
            }
        }
        internal async Task <int> EnviarNotaContingencia(NotaFiscal notaFiscal, string cscId, string csc)
        {
            TNFe   nfe              = null;
            string qrCode           = string.Empty;
            string newNodeXml       = string.Empty;
            string nFeNamespaceName = "http://www.portalfiscal.inf.br/nfe";
            string digVal           = string.Empty;

            int idNotaCopiaSeguranca = 0;

            var config = ConfiguracaoService.GetConfiguracao();

            notaFiscal.Identificacao.DataHoraEntradaContigencia = config.DataHoraEntradaContingencia;
            notaFiscal.Identificacao.JustificativaContigencia   = config.JustificativaContingencia;
            notaFiscal.Identificacao.TipoEmissao = notaFiscal.Identificacao.Modelo == Modelo.Modelo65 ? TipoEmissao.ContigenciaNfce : TipoEmissao.FsDa;
            notaFiscal.CalcularChave();

            X509Certificate2 certificado;

            var certificadoEntity = new CertificadoRepository(new NFeContext()).GetCertificado();

            if (!string.IsNullOrWhiteSpace(certificadoEntity.Caminho))
            {
                certificado = CertificateManager.GetCertificateByPath(certificadoEntity.Caminho,
                                                                      RijndaelManagedEncryption.DecryptRijndael(certificadoEntity.Senha));
            }
            else
            {
                certificado = CertificateManager.GetCertificateBySerialNumber(certificadoEntity.NumeroSerial, false);
            }

            if (notaFiscal.Identificacao.Ambiente == Domain.Services.Identificacao.Ambiente.Homologacao)
            {
                notaFiscal.Produtos[0].Descricao = "NOTA FISCAL EMITIDA EM AMBIENTE DE HOMOLOGACAO - SEM VALOR FISCAL";
            }

            var refUri = "#NFe" + notaFiscal.Identificacao.Chave;

            var     xml  = Regex.Replace(XmlUtil.GerarXmlLoteNFe(notaFiscal, nFeNamespaceName), "<motDesICMS>1</motDesICMS>", string.Empty);
            XmlNode node = AssinaturaDigital.AssinarLoteComUmaNota(xml, refUri, certificado, ref digVal);

            var codigoUF = (CodigoUfIbge)Enum.Parse(typeof(CodigoUfIbge), notaFiscal.Emitente.Endereco.UF);

            if (notaFiscal.Identificacao.Modelo == Modelo.Modelo65)
            {
                qrCode = QrCodeUtil.GerarQrCodeNFe(notaFiscal.Identificacao.Chave, notaFiscal.Destinatario, digVal, notaFiscal.Identificacao.Ambiente,
                                                   notaFiscal.Identificacao.DataHoraEmissao, notaFiscal.TotalNFe.IcmsTotal.ValorTotalNFe.ToString("F", CultureInfo.InvariantCulture),
                                                   notaFiscal.TotalNFe.IcmsTotal.ValorTotalIcms.ToString("F", CultureInfo.InvariantCulture), cscId, csc, notaFiscal.Identificacao.TipoEmissao);

                newNodeXml = node.InnerXml.Replace("<qrCode />", "<qrCode>" + qrCode + "</qrCode>");
            }
            else
            {
                newNodeXml = node.InnerXml.Replace("<infNFeSupl><qrCode /></infNFeSupl>", "");
            }

            var document = new XmlDocument();

            document.LoadXml(newNodeXml);
            node = document.DocumentElement;

            TEnviNFe lote = (TEnviNFe)XmlUtil.Deserialize <TEnviNFe>(node.OuterXml);

            nfe = lote.NFe[0];

            //salvar nota PreEnvio aqui
            notaFiscal.Identificacao.Status = NFe.Repository.Status.CONTINGENCIA;

            var notaFiscalService = new NotaFiscalService();

            idNotaCopiaSeguranca = await notaFiscalService.SalvarNotaFiscalPendenteAsync(notaFiscal, XmlUtil.GerarNfeProcXml(nfe, qrCode), notaFiscal.Identificacao.Ambiente);

            var notaFiscalEntity = await notaFiscalService.GetNotaFiscalByIdAsync(idNotaCopiaSeguranca, false);

            notaFiscalEntity.Status = (int)Status.CONTINGENCIA;
            string nfeProcXml = XmlUtil.GerarNfeProcXml(nfe, qrCode);

            await notaFiscalService.SalvarAsync(notaFiscalEntity, nfeProcXml);

            notaFiscal.QrCodeUrl = qrCode;
            return(idNotaCopiaSeguranca);
        }