private void sfdProcCancNFe_FileOk(object sender, CancelEventArgs e)
        {
            ClientEnvironment manager = null;
            Parametro         oParam  = null;


            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                oParam  = Program.GetParametro(Program.empresaSelecionada, manager);


                if (oNFe.codigoSituacao != TipoSituacaoNota.Aprovada &&
                    oNFe.codigoSituacao != TipoSituacaoNota.Impressa &&
                    oNFe.codigoSituacao != TipoSituacaoNota.Cancelada)    // aprovada ou impressa ou cancelada
                {
                    throw new Exception("Somente para notas Aprovadas ou Canceladas!");
                }

                NFeUtils.GeraArquivoProcCancNFe(oNFe, sfdProcCancNFe.FileName, oParam.versaoDados);
                MessageBox.Show("Arquivo gerado com sucesso em : " + sfdProcCancNFe.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                oParam = null;
                Conexao.DisposeManager(manager);
            }
        }
        public FrmInutilizaNota()
        {
            InitializeComponent();
            cbUF.DataSource    = NFeUtils.Listar(typeof(TCodUfIBGE));
            cbUF.DisplayMember = "Value";
            cbUF.ValueMember   = "Key";

            cbTipoAmbiente.DataSource    = NFeUtils.Listar(typeof(TAmb));
            cbTipoAmbiente.DisplayMember = "Value";
            cbTipoAmbiente.ValueMember   = "Key";

            ClientEnvironment manager = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                Parametro oParam = Program.GetParametro(Program.empresaSelecionada, manager);

                cbTipoAmbiente.SelectedValue = Convert.ToInt32(oParam.tipoAmbiente);
                cbUF.SelectedValue           = Convert.ToInt32(oParam.UF);
                tbCNPJ.Text = Program.empresaSelecionada;

                oParam = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conexao.DisposeManager(manager);
            }
        }
        private void btImprime_Click(object sender, EventArgs e)
        {
            ClientEnvironment manager = null;
            Parametro         oParam  = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                oParam  = Program.GetParametro(Program.empresaSelecionada, manager);

                if (oNFe.codigoSituacao == TipoSituacaoNota.Aprovada || oNFe.codigoSituacao == TipoSituacaoNota.Impressa)//aprovada ou impressa
                {
                    NFeUtils.ImprimeDANFe(oNFe, oParam, manager);
                    DoRefresh();
                    MessageBox.Show("Arquivo enviado para servidor de impressão.");
                }
                else
                {
                    MessageBox.Show("Nota não esta aprovada pela SEFAZ");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                oParam = null;
                Conexao.DisposeManager(manager);
            }
        }
 private void FrmServicos_Load(object sender, EventArgs e)
 {
     cbSituacao.DataSource    = NFeUtils.Listar(typeof(TipoSituacaoServico));
     cbSituacao.DisplayMember = "Value";
     cbSituacao.ValueMember   = "Key";
     cbSituacao.Show();
 }
Exemple #5
0
        private void VerificaCertificado()
        {
            //consulta status do servidor
            ClientEnvironment manager = null;
            Parametro         oParam  = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                oParam  = Program.GetParametro(Program.empresaSelecionada, manager);

                if (String.IsNullOrEmpty(oParam.certificado))
                {
                    lbsValidadeCertificado.Text = "Certificado : Nenhum certificado selecionado.";
                }
                else
                {
                    //verificar validade do certificado
                    var oCertificado = Certificado.BuscaNome(oParam.certificado, oParam.usaWService, oParam.tipoBuscaCertificado);

                    lbsValidadeCertificado.Text = "Certificado : " + oCertificado.GetNameInfo(X509NameType.SimpleName, false);

                    if (oCertificado.Verify())
                    {
                        lbsValidadeCertificado.Text += " | Cadeia : OK";
                    }
                    else
                    {
                        lbsValidadeCertificado.Text += " | Cadeia : Erro";
                    }

                    lbsValidadeCertificado.Text += " | Válido até : " + oCertificado.GetExpirationDateString();
                }

                lbsValidadeCertificado.Text += " | Ambiente : " + (oParam.tipoAmbiente == TAmb.Homologacao ? "Homologação" : "Produção");

                //criar arquivo HeartBeat
                //verificar se FuncaoAutomação esta rodando
                if (!Program.empresasHabilitadas.First(em => em.cnpj == Program.empresaSelecionada).AutomacaoHabilitada&& !Program.ServicoHabilitado)
                {
                    foreach (var item in Program.empresasHabilitadas.Where(e => e.habilitada)) //somente habilitadas
                    {
                        NFeUtils.GeraHeartBeat(false, item.cnpj);
                    }
                }

                //exibir se envio de erros esta habilitado
                AtualizarLabelEnviarErros();
            }
            catch
            {
                //silent
            }
            finally
            {
                oParam = null;
                Conexao.DisposeManager(manager);
            }
        }
Exemple #6
0
 private void FrmVisualizaXML_Load(object sender, EventArgs e)
 {
     if (!String.IsNullOrEmpty(xml))
     {
         xmlDoc = new System.Xml.XmlDocument();
         xmlDoc.LoadXml(xml);
         NFeUtils.PopulaTreeView(xmlDoc, tvXmlNota);
     }
 }
Exemple #7
0
        private void DoRefresh()
        {
            if (oSrv != null)
            {
                ClientEnvironment manager = null;
                try
                {
                    manager = Conexao.CreateManager(Program.ConAux);
                    oSrv    = (ServicoPendente)ServicoPendenteDAL.Instance.Find(oSrv.keyString, manager);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Conexao.DisposeManager(manager);
                }

                txLote.Text   = oSrv.numeroLote.ToString();
                txCodSit.Text = oSrv.codigoSituacao.ToString();
                txDatSit.Text = oSrv.dataSituacao.ToString();
                txRecNum.Text = oSrv.numeroRecibo;

                if (oSrv.xmlRecibo != String.Empty)
                {
                    System.Xml.XmlDocument xmlRec = new System.Xml.XmlDocument();
                    xmlRec.LoadXml(oSrv.xmlRecibo);
                    NFeUtils.PopulaTreeView(xmlRec, tvSPeRec, true);
                }
                else
                {
                    tvSPeRec.Nodes.Clear();
                    tvSPeRec.Nodes.Add("Problema ao carregar o arquivo.");
                }

                if (oSrv.xmlRetConsulta != String.Empty)
                {
                    System.Xml.XmlDocument xmlRec = new System.Xml.XmlDocument();
                    xmlRec.LoadXml(oSrv.xmlRetConsulta);
                    NFeUtils.PopulaTreeView(xmlRec, tvSPeCons, true);
                }
                else
                {
                    tvSPeRec.Nodes.Clear();
                    tvSPeRec.Nodes.Add("Problema ao carregar o arquivo.");
                }

                btAtualizarLote.Enabled = true;//(oSrv.codigoSituacao == TipoSituacaoServico.ProblemaNoEnvio);

                btnAbort.Enabled = oSrv.codigoSituacao == TipoSituacaoServico.AguardandoEnvio ||
                                   oSrv.codigoSituacao == TipoSituacaoServico.AguardandoRetornoAprovacao ||
                                   oSrv.codigoSituacao == TipoSituacaoServico.Processado;
            }
        }
        void sfdProcNFe_FileOkCCe(object sender, CancelEventArgs e)
        {
            try
            {
                NFeUtils.GeraArquivoProcEventoNFe(oEvento, sfdProcNFeCCe.FileName, oNFe.versao);

                MessageBox.Show("Arquivo gerado com sucesso em : " + sfdProcNFeCCe.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #9
0
        private void FrmWebService_Load(object sender, EventArgs e)
        {
            cbTipoEmissao.DataSource    = NFeUtils.Listar(typeof(TNFeInfNFeIdeTpEmis));
            cbTipoEmissao.DisplayMember = "Value";
            cbTipoEmissao.ValueMember   = "Key";


            cbTimeOut.DataSource    = NFeUtils.Listar(typeof(Delay));
            cbTimeOut.DisplayMember = "Value";
            cbTimeOut.ValueMember   = "Key";

            cbTipoAmbiente.DataSource    = NFeUtils.Listar(typeof(TAmb));
            cbTipoAmbiente.DisplayMember = "Value";
            cbTipoAmbiente.ValueMember   = "Key";

            cbUf.DataSource    = NFeUtils.Listar(typeof(TCodUfIBGE));
            cbUf.DisplayMember = "Value";
            cbUf.ValueMember   = "Key";

            cbVersaoNFe.DataSource    = NFeUtils.Listar(typeof(VersaoXML));
            cbVersaoNFe.DisplayMember = "Value";
            cbVersaoNFe.ValueMember   = "Key";


            ClientEnvironment manager = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                Parametro oParam = Program.GetParametro(Program.empresaSelecionada, manager);

                cbTipoEmissao.SelectedValue  = Convert.ToInt32(oParam.tipoEmissao);
                cbTipoAmbiente.SelectedValue = Convert.ToInt32(oParam.tipoAmbiente);
                cbTimeOut.SelectedValue      = Convert.ToInt32(oParam.timeout);
                cbUf.SelectedValue           = Convert.ToInt32(oParam.UF);
                cbVersaoNFe.SelectedValue    = Convert.ToInt32(oParam.versao);

                isModified = true;
                oParam     = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conexao.DisposeManager(manager);
            }
        }
Exemple #10
0
        public async Task <NFeSharp.Esquemas.v3_10.retConsSitNFe> NfeConsultaProtocoloAsync(String chaveAcesso)
        {
            if (!NFeUtils.IsChaveAcessoValida(chaveAcesso))
            {
                throw new  ArgumentException("chaveAcesso", "A Chave de Acesso é inválida");
            }

            int    cUF = NFeUtils.PegarCodigoUFChaveAcesso(chaveAcesso);
            String url = this.PegarUrlServico(IdentificadorServicos.NfeConsultaProtocolo, (UnidadesFederativas)cUF, VersaoServico.v3_10, false);
            INfeConsultaProtocoloCliente cliente;

            // Correção para SEFAZ do PR.
            if (cUF == 41)
            {
                cliente = new Proxies.NfeConsulta3Cliente(this.Certificado, url);
            }
            else
            {
                cliente = new Proxies.NfeConsulta2Cliente(this.Certificado, url);
            }


            NFeSharp.Esquemas.v3_10.consSitNFe param = new NFeSharp.Esquemas.v3_10.consSitNFe()
            {
                chNFe = chaveAcesso,
                tpAmb = this.TipoAmbiente
            };

            var msg         = XmlUtils.SerializeToXml <NFeSharp.Esquemas.v3_10.consSitNFe>(param);
            var respostaXml = await cliente.ConsultarProtocoloAsync(cUF.ToString(), "3.10", msg);

            cliente.Close();

            if (respostaXml == null)
            {
                throw new NFeSharpException("A resposta do serviço não foi entendida.");
            }

            return(DeserializeSeguro <NFeSharp.Esquemas.v3_10.retConsSitNFe>(respostaXml));
        }
        private void button5_Click(object sender, EventArgs e)
        {
            ClientEnvironment manager = null;
            Parametro         oParam  = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                oParam  = Program.GetParametro(Program.empresaSelecionada, manager);

                if (oNFe.codigoSituacao == TipoSituacaoNota.Cancelada)
                {
                    //verificar se foi cancelada por evento
                    if (oNFe.CanceladaPorEvento(manager))
                    {
                        #region cancelamento por evento
                        MessageBox.Show("Nota cancelada por evento");
                        //todo : enviar para DANFE.exe XML do evento.
                        #endregion
                    }
                    else
                    {
                        #region cancelamento por webservice
                        //tratar envio de xml para destinatário.
                        String nomeArquivo = oNFe.nProtCancelamento + "_v2.00-procCancNFe.xml";

                        //enviar email para destinatário ?
                        ITNFe oNFeXML = (ITNFe)XMLUtils.CarregaXML_STR(oNFe.xmlNota, oNFe.versao, "TNFe");
                        if (!String.IsNullOrEmpty(oNFeXML.infNFe.dest.email))
                        {
                            if (File.Exists(oParam.pastaImpressao + nomeArquivo.Replace(".xml", ".txt")))
                            {
                                File.Delete(oParam.pastaImpressao + nomeArquivo.Replace(".xml", ".txt"));
                            }

                            //gerar arquivo TXT com o email do destinatário
                            using (StreamWriter oSW = File.CreateText(oParam.pastaImpressao + nomeArquivo.Replace(".xml", ".txt")))
                            {
                                oSW.WriteLine(oNFeXML.infNFe.dest.email);
                                oSW.WriteLine(oNFeXML.infNFe.Id.Replace("NFe", ""));
                                oSW.WriteLine(oNFeXML.infNFe.ide.nNF);
                                oSW.WriteLine(oNFeXML.infNFe.ide.serie);
                                oSW.WriteLine(oNFeXML.infNFe.emit.xNome);
                                oSW.WriteLine(oNFe.nProtCancelamento);
                                oSW.WriteLine(oNFeXML.infNFe.dest.xNome);
                                oSW.Close();
                            }
                            GC.Collect();

                            //gerar arquivo txt com o email do destinatário
                            NFeUtils.GeraArquivoProcCancNFe(oNFe, oParam.pastaImpressao + nomeArquivo, oParam.versaoDados);

                            MessageBox.Show("Arquivo enviado para servidor de impressão.");
                        }
                        else
                        {
                            MessageBox.Show("Não existe email para enviar arquivo.");
                        }
                        oNFeXML = null;
                        #endregion
                    }
                }
                else
                {
                    MessageBox.Show("Nota não esta cancelada");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                oParam = null;
                Conexao.DisposeManager(manager);
            }
        }
        private void DoRefresh()
        {
            ClientEnvironment manager = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);

                oNFe = (NotaFiscal)NotaFiscalDAL.Instance.Find(oNFe.GetKeyString(), manager);


                txChaveNota.Text = oNFe.chaveNota;
                txLote.Text      = oNFe.numeroLote.ToString();
                txCodSit.Text    = oNFe.codigoSituacao.ToString();
                txDatSit.Text    = oNFe.dataSituacao.ToString();
                txDesSit.Text    = oNFe.descricaoSituacao;

                if (!String.IsNullOrEmpty(oNFe.cStat))
                {
                    txcStat.Text = oNFe.cStat;
                }
                if (!String.IsNullOrEmpty(oNFe.xMotivo))
                {
                    txxMotivo.Text = oNFe.xMotivo;
                }
                if (!String.IsNullOrEmpty(oNFe.nProt))
                {
                    txnProt.Text = oNFe.nProt;
                }
                if (!String.IsNullOrEmpty(oNFe.nProtCancelamento))
                {
                    txnProtCanc.Text = oNFe.nProtCancelamento;
                }



                System.Xml.XmlDocument xmlNota = new System.Xml.XmlDocument();
                xmlNota.LoadXml(oNFe.xmlNota);
                NFeUtils.PopulaTreeView(xmlNota, tvXmlNota);
                if (oNFe.codigoSituacao == TipoSituacaoNota.XMLInvalido) //xml invalido
                {
                    tvProcFinal.Visible = false;
                    tbProcFinal.Visible = true;
                    tbProcFinal.Text    = oNFe.xmlProcesso;
                }
                else if (!String.IsNullOrEmpty(oNFe.xmlProcesso))
                {
                    xmlNota.LoadXml(oNFe.xmlProcesso);
                    NFeUtils.PopulaTreeView(xmlNota, tvProcFinal);
                }


                //carregar eventos
                dgvEventos.AutoGenerateColumns = false;
                dgvEventos.DataSource          = oNFe.CarregarEventos(manager);


                System.Xml.XmlDocument xmlCancelamento = new System.Xml.XmlDocument();
                if (!String.IsNullOrEmpty(oNFe.xmlPedidoCancelamento))
                {
                    xmlCancelamento.LoadXml(oNFe.xmlPedidoCancelamento);
                    NFeUtils.PopulaTreeView(xmlCancelamento, tvXmlCancelamento);
                }
                if (!String.IsNullOrEmpty(oNFe.xmlProcessoCancelamento))
                {
                    xmlCancelamento.LoadXml(oNFe.xmlProcessoCancelamento);
                    NFeUtils.PopulaTreeView(xmlCancelamento, tvProcCancelamento);
                }
                xmlCancelamento = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Conexao.DisposeManager(manager);
            }
        }
        private void dgvEventos_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex.Equals(2))
            {
                try
                {
                    FrmVisualizaXML oFrmXML = new FrmVisualizaXML(
                        ((Evento)dgvEventos.Rows[e.RowIndex].DataBoundItem).XMLPedido);
                    oFrmXML.Show();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else if (e.ColumnIndex.Equals(3))
            {
                try
                {
                    FrmVisualizaXML oFrmXML = new FrmVisualizaXML(
                        ((Evento)dgvEventos.Rows[e.RowIndex].DataBoundItem).XMLResposta);
                    oFrmXML.Show();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else if (e.ColumnIndex.Equals(4))
            {
                try
                {
                    oEvento = (Evento)dgvEventos.Rows[e.RowIndex].DataBoundItem;

                    if (oEvento.codigoSituacao != TipoSituacaoEvento.FinalizadoAprovado135 &&
                        oEvento.codigoSituacao != TipoSituacaoEvento.FinalizadoAprovado136 &&
                        oEvento.codigoSituacao != TipoSituacaoEvento.FinalizadoAprovado155)
                    {
                        throw new Exception("Evento não aprovado");
                    }


                    //solicitar usuario local para save
                    sfdProcNFeCCe.Filter = "Arquivo XML|*.xml";
                    sfdProcNFeCCe.Title  = "Salvar arquivo";

                    string sufixo = "";
                    if (oEvento.tpEvento == TEventoInfEventoTpEvento.CartaCorrecao)
                    {
                        sufixo = "_v1.00-procCCe.xml";
                    }
                    else if (oEvento.tpEvento == TEventoInfEventoTpEvento.Cancelamento)
                    {
                        sufixo = "_v1.00-procEventoCancNFe.xml";
                    }
                    else
                    {
                        sufixo = ".xml";
                    }

                    sfdProcNFeCCe.FileName = ((ITEvento)XMLUtils.CarregaXML_STR(oEvento.XMLPedido,
                                                                                oNFe.versao,
                                                                                "TEvento")).infEvento.Id + sufixo;

                    sfdProcNFeCCe.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    oEvento = null;
                }
            }
            else if (e.ColumnIndex.Equals(5))
            {
                //gerar arquivo para danfe.exe
                #region imprimir evento

                ClientEnvironment manager = null;
                Parametro         oParam  = null;

                try
                {
                    manager = Conexao.CreateManager(Program.ConAux);
                    oParam  = Program.GetParametro(Program.empresaSelecionada, manager);
                    oEvento = (Evento)dgvEventos.Rows[e.RowIndex].DataBoundItem;

                    if (oEvento.codigoSituacao != TipoSituacaoEvento.FinalizadoAprovado135 &&
                        oEvento.codigoSituacao != TipoSituacaoEvento.FinalizadoAprovado136 &&
                        oEvento.codigoSituacao != TipoSituacaoEvento.FinalizadoAprovado155)
                    {
                        throw new Exception("Evento não aprovado");
                    }

                    //tratar envio de xml para destinatário.
                    string sufixo = "";
                    if (oEvento.tpEvento == TEventoInfEventoTpEvento.CartaCorrecao)
                    {
                        sufixo = "_v1.00-procCCe.xml";
                    }
                    else if (oEvento.tpEvento == TEventoInfEventoTpEvento.Cancelamento)
                    {
                        sufixo = "_v1.00-procEventoCancNFe.xml";
                    }
                    else
                    {
                        sufixo = ".xml";
                    }

                    String nomeArquivo = ((ITEvento)XMLUtils.CarregaXML_STR(oEvento.XMLPedido,
                                                                            oNFe.versao,
                                                                            "TEvento")).infEvento.Id + sufixo;

                    ITNFe oNFeXML = (ITNFe)
                                    XMLUtils.CarregaXML_STR(oNFe.xmlNota,
                                                            oNFe.versao,
                                                            "TNFe");

                    //salvar TXT com dados complementares
                    if (File.Exists(oParam.pastaImpressao + nomeArquivo.Replace(".xml", ".txt")))
                    {
                        File.Delete(oParam.pastaImpressao + nomeArquivo.Replace(".xml", ".txt"));
                    }

                    //gerar arquivo TXT com o email do destinatário
                    using (StreamWriter oSW = File.CreateText(oParam.pastaImpressao + nomeArquivo.Replace(".xml", ".txt")))
                    {
                        //dados destinatarios
                        oSW.WriteLine(oNFeXML.infNFe.dest.xNome);
                        oSW.WriteLine(oNFeXML.infNFe.dest.enderDest.xLgr + ", " + oNFeXML.infNFe.dest.enderDest.nro);
                        oSW.WriteLine(oNFeXML.infNFe.dest.enderDest.xBairro);
                        oSW.WriteLine(oNFeXML.infNFe.dest.enderDest.CEP);
                        oSW.WriteLine(oNFeXML.infNFe.dest.enderDest.xMun);
                        oSW.WriteLine(oNFeXML.infNFe.dest.enderDest.fone);
                        oSW.WriteLine(oNFeXML.infNFe.dest.enderDest.UF);
                        oSW.WriteLine(oNFeXML.infNFe.dest.IE);

                        //dados emitente
                        oSW.WriteLine(oNFeXML.infNFe.emit.xNome);
                        oSW.WriteLine(oNFeXML.infNFe.emit.enderEmit.xLgr + ", " + oNFeXML.infNFe.emit.enderEmit.nro);
                        oSW.WriteLine(oNFeXML.infNFe.emit.enderEmit.xBairro);
                        oSW.WriteLine(oNFeXML.infNFe.emit.enderEmit.CEP);
                        oSW.WriteLine(oNFeXML.infNFe.emit.enderEmit.xMun);
                        oSW.WriteLine(oNFeXML.infNFe.emit.enderEmit.fone);
                        oSW.WriteLine(oNFeXML.infNFe.emit.enderEmit.UF);
                        oSW.WriteLine(oNFeXML.infNFe.emit.IE);

                        oSW.WriteLine(oNFeXML.infNFe.ide.nNF);
                        oSW.WriteLine(oNFeXML.infNFe.ide.serie);
                        oSW.WriteLine(oNFeXML.infNFe.ide.dEmi);

                        oSW.Close();
                    }
                    GC.Collect();

                    NFeUtils.GeraArquivoProcEventoNFe(oEvento, oParam.pastaImpressao + nomeArquivo, oNFe.versao);

                    MessageBox.Show("Arquivo enviado para servidor de impressão.");

                    oNFeXML = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    oEvento = null;
                    Conexao.DisposeManager(manager);
                    oParam = null;
                }
                #endregion
            }
        }
        private void btInutiliza_Click(object sender, EventArgs e)
        {
            ClientEnvironment manager = null;
            Parametro         oParam  = null;
            FuncaoAutomacao   oFuncao = null;

            try
            {
                manager = Conexao.CreateManager(Program.ConAux);
                oParam  = Program.GetParametro(Program.empresaSelecionada, manager);
                oFuncao = new FuncaoAutomacao(Program.empresaSelecionada, manager, Program.enviarInformacoesSobreErros);

                if (Int32.Parse(tbNotaInicial.Text) > Int32.Parse(tbNotaFinal.Text))
                {
                    throw new Exception("Nota Inicial deve ser menor que Nota Final.");
                }


                //Código da UF + CNPJ + modelo + série + nro inicial e nro final precedida do literal “ID”
                ITInutNFe oInutilizacao = (ITInutNFe)XMLUtils.XMLFactory(oParam.versao, "TInutNFe");

                oInutilizacao.versao       = oParam.versaoDados;
                oInutilizacao.infInut      = (ITInutNFeInfInut)XMLUtils.XMLFactory(oParam.versao, "TInutNFeInfInut");
                oInutilizacao.infInut.ano  = tbAno.Text;
                oInutilizacao.infInut.CNPJ = tbCNPJ.Text;

                oInutilizacao.infInut.cUF = NFeUtils.DefineUF(cbUF.SelectedValue.ToString());

                oInutilizacao.infInut.Id = "ID" + cbUF.SelectedValue.ToString() + tbAno.Text.PadLeft(2, '0') + tbCNPJ.Text + tbMod.Text +
                                           tbSerie.Text.PadLeft(3, '0') + tbNotaInicial.Text.PadLeft(9, '0') + tbNotaFinal.Text.PadLeft(9, '0');

                oInutilizacao.infInut.mod    = oParam.conexao == TipoConexao.NFCe ? TMod.Item65 : TMod.Item55;
                oInutilizacao.infInut.nNFIni = tbNotaInicial.Text;
                oInutilizacao.infInut.nNFFin = tbNotaFinal.Text;
                oInutilizacao.infInut.serie  = tbSerie.Text;

                oInutilizacao.infInut.tpAmb = (TAmb)NFeUtils.DefineEnum(cbTipoAmbiente.SelectedValue.ToString(), typeof(TAmb));
                oInutilizacao.infInut.xJust = tbJust.Text;
                oInutilizacao.infInut.xServ = TInutNFeInfInutXServ.INUTILIZAR;

                String cStat   = String.Empty;
                String xMotivo = String.Empty;

                oFuncao.InutilizaNumeracao(oInutilizacao, ref cStat, ref xMotivo, oParam.versao);


                if (cStat == String.Empty && xMotivo == String.Empty) //recebeu resposta da sefaz
                {
                    throw new Exception("Não foi possível executar Inutilização. Consulte o LOG do sistema.");
                }

                if (cStat != "102")
                {
                    throw new Exception(xMotivo);
                }

                var oRetInut = (ITRetInutNFe)XMLUtils.LoadXMLFile(oParam.pastaRecibo + oInutilizacao.infInut.Id + "-inu.xml", oParam.versao, "TRetInutNFe");

                oInutilizacao = (ITInutNFe)XMLUtils.LoadXMLFile(oParam.pastaRecibo + oInutilizacao.infInut.Id + "-ped-inu.xml", oParam.versao, "TInutNFe");



                Int32 notaInicial = Int32.Parse(oInutilizacao.infInut.nNFIni);
                Int32 notaFinal   = Int32.Parse(oInutilizacao.infInut.nNFFin);

                while (notaInicial <= notaFinal)
                {
                    NotaInutilizada oNota = new NotaInutilizada();
                    oNota.numeroNota = notaInicial.ToString();

                    //setar a serie da nota
                    oNota.serieNota = oInutilizacao.infInut.serie;
                    oNota.data      = DateTime.Today;
                    oNota.empresa   = oParam.empresa;

                    oNota.XMLResposta = XMLUtils.GetXML(oRetInut, oParam.versao);
                    oNota.XMLPedido   = XMLUtils.GetXML(oInutilizacao, oParam.versao);

                    oNota.Save(manager);

                    notaInicial++;
                }

                MessageBox.Show(xMotivo);
            }
            catch (Exception ex)
            {
                if (oFuncao != null)
                {
                    oFuncao.CriaLog(999, "Inutilização de Notas", ex);
                }
                MessageBox.Show(ex.Message);
            }
            finally
            {
                oParam  = null;
                oFuncao = null;
                Conexao.DisposeManager(manager);
            }
        }