Exemple #1
0
 public void stmp_SendCompletedRGD(object sender, AsyncCompletedEventArgs e)
 {
     if (e.Cancelled)
     {
         mensagem = "Email sending cancelled!";
         VO.LogErro logErro = new VO.LogErro();
         logErro.crg          = 0;
         logErro.descricao    = "Erro ao tentar enviar os relatórios da pressão diários";
         logErro.data         = DateTime.Now;
         logErro.maisDetalhes = mensagem;
         LogErroDAO.inserirLogErro(logErro, logErro.crg);
     }
     else if (e.Error != null)
     {
         mensagem = e.Error.Message;
         VO.LogErro logErro = new VO.LogErro();
         logErro.crg          = 0;
         logErro.descricao    = "Erro ao tentar enviar os relatórios da pressão diários";
         logErro.data         = DateTime.Now;
         logErro.maisDetalhes = mensagem;
         LogErroDAO.inserirLogErro(logErro, logErro.crg);
     }
     else
     {
         mensagem = "Email sent sucessfully!";
     }
 }
Exemple #2
0
        private string[] ObterDadosUltimoMudanca()
        {
            try
            {
                string[] retorno = new string[2];
                retorno[0] = UltimosDAO.RetornaUltimoOperador();
                retorno[1] = UltimosDAO.RetornaUltimoResponsavel();
                return(retorno);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao obter dados de Operador e Responsavel";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao obter dados de Operador e Responsavel", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(new string[2] {
                    "", ""
                });
            }
        }
Exemple #3
0
        public static List <Destinatarios> ListaDestinatarios()
        {
            try
            {
                List <Destinatarios> destinatarios = new List <Destinatarios>();
                var path        = Environment.CurrentDirectory + "\\Destinatarios.xml";
                var stream      = new MemoryStream();
                var xmlDocument = new XmlDocument();
                var cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Destinatarios";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument xml = XDocument.Load(stream);

                foreach (XElement x in xml.Element("Destinatarios").Elements())
                {
                    Destinatarios d = new Destinatarios()
                    {
                        id    = int.Parse(x.Attribute("Id").Value),
                        email = x.Attribute("Email").Value
                    };
                    destinatarios.Add(d);
                }
                return(destinatarios);
            }
            catch (Exception er)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao tentar listar destinatários";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = er.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                return(new List <Destinatarios>());
            }
        }
Exemple #4
0
        private string[] ObterDadosFiltro()
        {
            try
            {
                var path        = Environment.CurrentDirectory + "\\Ultimos.xml";
                var stream      = new MemoryStream();
                var xmlDocument = new XmlDocument();
                var cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Ultimo";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument doc     = XDocument.Load(stream);
                var       ult     = doc.Element("Ultimos").Element("ultimo");
                string[]  retorno = new string[5];
                retorno[0] = ult.Element("ValorFiltro").Value;
                retorno[1] = ult.Element("DataInicio").Value;
                retorno[2] = ult.Element("DataFim").Value;
                retorno[3] = ult.Element("Equipamento").Value;
                retorno[4] = ult.Element("QtdeMeses").Value;
                return(retorno);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao obter dados do filtro";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao obter dados do filtro", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(new string[2] {
                    "", ""
                });
            }
        }
Exemple #5
0
        private string[] ObterDadosEmail()
        {
            try
            {
                var path        = Environment.CurrentDirectory + "\\ConfiguracaoEmail.xml";
                var stream      = new MemoryStream();
                var xmlDocument = new XmlDocument();
                var cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Configuracao";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument doc     = XDocument.Load(stream);
                var       config  = doc.Element("ConfiguracaoEmail").Element("Configuracao");
                string[]  retorno = new string[6];
                retorno[0] = config.Element("SMTP").Value;
                retorno[1] = config.Element("De").Value;
                retorno[2] = config.Element("NomeUsuario").Value;
                retorno[3] = config.Element("Senha").Value;
                retorno[4] = config.Element("Porta").Value;
                retorno[5] = config.Element("SSL").Value;
                return(retorno);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao obter dados da Configuração de Email";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao obter dados da Configuração de Email", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(new string[6]);
            }
        }
Exemple #6
0
        private string ObterDadosUltimo()
        {
            try
            {
                return(UltimosDAO.RetornaUltimaLogo());
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao obter dados de Operador e Responsavel";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao obter dados de Operador e Responsavel", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return("");
            }
        }
Exemple #7
0
        public bool AtualizaUltimo(string opcao)
        {
            try
            {
                return(UltimosDAO.SetarUltimaLogo(opcao));
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao atualizar dados de Operador e Responsavel";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao atualizar dados de Operador e Responsavel", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(false);
            }
        }
Exemple #8
0
        private int ObterUltimoEquipamento()
        {
            try
            {
                var path        = Environment.CurrentDirectory + "\\Ultimos.xml";
                var stream      = new MemoryStream();
                var xmlDocument = new XmlDocument();
                var cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Ultimo";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument doc = XDocument.Load(stream);
                var       ult = doc.Element("Ultimos").Element("ultimo");
                return(int.Parse(ult.Element("Equipamento").Value));
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao obter ultimo equipamento";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao obter ultimo equipamento", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(0);
            }
        }
Exemple #9
0
        private void btnImagem_Click(object sender, EventArgs e)
        {
            abrirArquivo.RestoreDirectory = true;
            abrirArquivo.Title            = "Importar Imagem";
            abrirArquivo.Filter           = "JPEG Images(*.jpg)|*.jpg";
            abrirArquivo.DefaultExt       = "jpg";
            abrirArquivo.CheckPathExists  = true;

            var dialogResult = abrirArquivo.ShowDialog(this);

            if (dialogResult == DialogResult.OK)
            {
                try
                {
                    var file = new FileInfo(abrirArquivo.FileName);

                    using (var stream = abrirArquivo.OpenFile())
                        using (var reader = new BinaryReader(stream))
                            imagem = reader.ReadBytes((int)stream.Length);

                    MemoryStream memoryStream = new MemoryStream(imagem);
                    Bitmap       image        = new Bitmap(memoryStream);

                    pictureBox1.Image = image;
                    mudouImagem       = true;
                }
                catch (Exception error)
                {
                    VO.LogErro logErro = new VO.LogErro();
                    logErro.crg          = 0;
                    logErro.descricao    = "Erro ao importar imagem";
                    logErro.data         = DateTime.Now;
                    logErro.maisDetalhes = error.Message;
                    LogErroDAO.inserirLogErro(logErro, 0);

                    MessageBox.Show("Erro ao importar imagem", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Exemple #10
0
        private string ObterUltimaAtualizacao()
        {
            try
            {
                var path        = Environment.CurrentDirectory + "\\Ultimos.xml";
                var stream      = new MemoryStream();
                var xmlDocument = new XmlDocument();
                var cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Ultimo";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument doc = XDocument.Load(stream);
                var       ult = doc.Element("Ultimos").Element("ultimo");
                return(ult.Element("Atualizacao").Value);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao obter a ultima data de atualizacao do Software";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                return("");
            }
        }
Exemple #11
0
        public static bool AddDestinatario(string email, int id)
        {
            try
            {
                string path        = Environment.CurrentDirectory + "\\Destinatarios.xml";
                var    stream      = new MemoryStream();
                var    xmlDocument = new XmlDocument();
                var    cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Destinatarios";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument xml = XDocument.Load(stream);

                XElement x = new XElement("Destinatarios");
                x.Add(new XAttribute("Id", id.ToString()));
                x.Add(new XAttribute("Email", email));
                //XElement xml = XElement.Load("Destinatarios.xml");
                xml.Element("Destinatarios").Add(x);
                xml.Save(path);

                return(true);
            }
            catch (Exception er)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao tentar adicionar destinatário";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = er.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                return(false);
            }
            finally
            {
                var    xmlDoc = new XmlDocument();
                string path   = Environment.CurrentDirectory + "\\Destinatarios.xml";
                try
                {
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(path);
                }
                catch (Exception er)
                {
                    Console.WriteLine(er.Message);
                }

                var cspParams = new CspParameters();
                cspParams.KeyContainerName = "Destinatarios";

                var rsaKey = new RSACryptoServiceProvider(cspParams);

                try
                {
                    Crypto.Encrypt(xmlDoc, "Destinatarios", "Destinatario", rsaKey, "rsaKey");
                    xmlDoc.Save(path);
                }
                catch (Exception er)
                {
                    VO.LogErro logErro = new VO.LogErro();
                    logErro.crg          = 0;
                    logErro.descricao    = "Erro ao tentar encriptografar Destinatarios";
                    logErro.data         = DateTime.Now;
                    logErro.maisDetalhes = er.Message;
                    LogErroDAO.inserirLogErro(logErro, 0);
                }
            }
        }
Exemple #12
0
        public bool AtualizaDadosEmail(string[] dados)
        {
            try
            {
                string path        = Environment.CurrentDirectory + "\\ConfiguracaoEmail.xml";
                var    stream      = new MemoryStream();
                var    xmlDocument = new XmlDocument();
                var    cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Configuracao";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument doc    = XDocument.Load(stream);
                var       config = from ultimo in doc.Element("ConfiguracaoEmail").Elements("Configuracao") select ultimo;

                foreach (var conf in config.Where(x => x.Element("Id").Value.Equals((1).ToString())))
                {
                    conf.Element("SMTP").Value        = dados[0];
                    conf.Element("De").Value          = dados[1];
                    conf.Element("NomeUsuario").Value = dados[2];
                    conf.Element("Senha").Value       = dados[3];
                    conf.Element("Porta").Value       = dados[4];
                    conf.Element("SSL").Value         = dados[5];

                    doc.Save(path);
                }
                return(true);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao atualizar dados da Configuração de Email";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao atualizar dados da Configuração de Email", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(false);
            }
            finally
            {
                var    xmlDoc = new XmlDocument();
                string path   = Environment.CurrentDirectory + "\\ConfiguracaoEmail.xml";
                try
                {
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(path);
                }
                catch (Exception er)
                {
                    Console.WriteLine(er.Message);
                }

                var cspParams = new CspParameters();
                cspParams.KeyContainerName = "Configuracao";

                var rsaKey = new RSACryptoServiceProvider(cspParams);

                try
                {
                    Crypto.Encrypt(xmlDoc, "ConfiguracaoEmail", "Configuracao", rsaKey, "rsaKey");
                    xmlDoc.Save(path);
                }
                catch (Exception er)
                {
                    VO.LogErro logErro = new VO.LogErro();
                    logErro.crg          = 0;
                    logErro.descricao    = "Erro ao tentar encriptografar Configuração de Email";
                    logErro.data         = DateTime.Now;
                    logErro.maisDetalhes = er.Message;
                    LogErroDAO.inserirLogErro(logErro, 0);
                }
            }
        }
Exemple #13
0
        public bool AtualizaUltimoEquipamento(int equipmento)
        {
            try
            {
                string path        = Environment.CurrentDirectory + "\\Ultimos.xml";
                var    stream      = new MemoryStream();
                var    xmlDocument = new XmlDocument();
                var    cspParams   = new CspParameters();

                cspParams.KeyContainerName = "Ultimo";
                var rsaKey = new RSACryptoServiceProvider(cspParams);

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument doc = XDocument.Load(stream);
                var       ult = from ultimo in doc.Element("Ultimos").Elements("ultimo") select ultimo;
                foreach (var ut in ult.Where(x => x.Element("Id").Value.Equals((1).ToString())))
                {
                    ut.Element("Equipamento").Value = equipmento.ToString();
                    doc.Save(path);
                }
                return(true);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao atualizar dados do equipamento";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = error.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                MessageBox.Show("Erro ao atualizar dados do equipamento", "Erro", MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return(false);
            }
            finally
            {
                var    xmlDoc = new XmlDocument();
                string path   = Environment.CurrentDirectory + "\\Ultimos.xml";
                try
                {
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(path);
                }
                catch (Exception er)
                {
                    Console.WriteLine(er.Message);
                }

                var cspParams = new CspParameters();
                cspParams.KeyContainerName = "Ultimo";

                var rsaKey = new RSACryptoServiceProvider(cspParams);

                try
                {
                    Crypto.Encrypt(xmlDoc, "Ultimos", "ultimo", rsaKey, "rsaKey");
                    xmlDoc.Save(path);
                }
                catch (Exception er)
                {
                    VO.LogErro logErro = new VO.LogErro();
                    logErro.crg          = 0;
                    logErro.descricao    = "Erro ao tentar encriptografar Ultimo";
                    logErro.data         = DateTime.Now;
                    logErro.maisDetalhes = er.Message;
                    LogErroDAO.inserirLogErro(logErro, 0);
                }
            }
        }
Exemple #14
0
        private void Receber_Click(object sender, EventArgs e)
        {
            dtgHistorico.Rows.Clear();
            int    numEquipamento = cmbCRG.SelectedIndex + 1;
            string porta          = ConfiguracaoDAO.retornaPorta();
            bool   continua       = false;
            byte   numBytes       = 0;

            try
            {
                t = new Thread(new ThreadStart(carregarAguarde));
                t.Start();
                var srpComm = new SerialPort(porta, 19200, Parity.None, 8, StopBits.One);
                srpComm.DtrEnable       = true;
                srpComm.RtsEnable       = false;
                srpComm.ReadBufferSize  = 50000;
                srpComm.WriteBufferSize = 50000;

                Conexao.srpComm = srpComm;

                if (Conexao.srpComm.IsOpen == false)
                {
                    Conexao.srpComm.Open();
                    Thread.Sleep(100);
                }

                int aux = numEquipamento + 63;
                Conexao.srpComm.Write(((char)19).ToString());
                Thread.Sleep(100);
                Conexao.srpComm.Write(((char)17).ToString());
                Thread.Sleep(100);
                Conexao.srpComm.Write(((char)aux).ToString());
                Thread.Sleep(100);

                if (Conexao.srpComm.BytesToRead != 0)
                {
                    numBytes       = byte.Parse(Conexao.srpComm.BytesToRead.ToString());
                    Conexao.buffer = new byte[numBytes];
                    Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                }
                continua = true;

                if (continua)
                {
                    int contador = 0;

                    switch (Conexao.buffer[0])
                    {
                    case 167:
                        Conexao.srpComm.Write(((char)15).ToString());
                        Thread.Sleep(500);
                        do
                        {
                            if (Conexao.srpComm.BytesToRead != 0)
                            {
                                numBytes       = byte.Parse(Conexao.srpComm.BytesToRead.ToString());
                                Conexao.buffer = new byte[numBytes];
                                Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                            }
                        } while (contador < 3 && Conexao.srpComm.BytesToRead != 0);

                        int checksum = 0;
                        for (int i = 0; i < Conexao.buffer.Length - 2; i++)
                        {
                            checksum ^= Conexao.buffer[i];
                        }

                        if (checksum == Conexao.buffer[Conexao.buffer.Length - 2])
                        {
                            for (int i = 0; i < Conexao.buffer.Length - 2; i++)
                            {
                                VO.Ciclos ciclo = new VO.Ciclos();
                                ciclo.nTrat      = (Conexao.buffer[i] * 256) + Conexao.buffer[i + 1];
                                ciclo.nl         = (Conexao.buffer[i + 2] * 256) + Conexao.buffer[i + 3];
                                ciclo.dataInicio =
                                    Convert.ToDateTime(
                                        string.Concat((Conexao.buffer[i + 7] / 16), (Conexao.buffer[i + 7] % 16)) + "/" +
                                        string.Concat((Conexao.buffer[i + 8] / 16), (Conexao.buffer[i + 8] % 16)) +
                                        "/20" +
                                        string.Concat((Conexao.buffer[i + 9] / 16), (Conexao.buffer[i + 9] % 16)) + " " +
                                        string.Concat((Conexao.buffer[i + 5] / 16), (Conexao.buffer[i + 5] % 16)) + ":" +
                                        string.Concat((Conexao.buffer[i + 4] / 16), (Conexao.buffer[i + 4] % 16)));
                                ciclo.crg = numEquipamento;
                                bool noBanco = CicloDAO.testanoBanco(ciclo);
                                if (!noBanco)
                                {
                                    dtgHistorico.Rows.Add(ciclo.nTrat, ciclo.nl,
                                                          ciclo.dataInicio.ToString("dd/MM/yyyy HH:mm"));
                                }
                                i = i + 9;
                            }
                            t.Abort();
                            Thread.Sleep(100);
                            if (dtgHistorico.Rows.Count == 0)
                            {
                                MessageBox.Show("Não há nenhum histórico novo");
                            }
                            Conexao.srpComm.Close();
                        }
                        else
                        {
                            MessageBox.Show("Erro de checksum.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Conexao.srpComm.Close();
                        }

                        break;

                    case 166:
                        Conexao.srpComm.Write(((char)15).ToString());
                        Thread.Sleep(500);
                        do
                        {
                            if (Conexao.srpComm.BytesToRead != 0)
                            {
                                numBytes       = byte.Parse(Conexao.srpComm.BytesToRead.ToString());
                                Conexao.buffer = new byte[numBytes];
                                Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                            }
                        } while (contador < 3 && Conexao.srpComm.BytesToRead != 0);

                        int checksum1 = 0;
                        for (int i = 0; i < Conexao.buffer.Length - 2; i++)
                        {
                            checksum1 ^= Conexao.buffer[i];
                        }

                        if (checksum1 == Conexao.buffer[Conexao.buffer.Length - 2])
                        {
                            for (int i = 0; i < Conexao.buffer.Length - 2; i++)
                            {
                                VO.Ciclos ciclo = new VO.Ciclos();
                                ciclo.nTrat      = (Conexao.buffer[i] * 256) + Conexao.buffer[i + 1];
                                ciclo.nl         = (Conexao.buffer[i + 2] * 256) + Conexao.buffer[i + 3];
                                ciclo.dataInicio =
                                    Convert.ToDateTime(
                                        string.Concat((Conexao.buffer[i + 7] / 16), (Conexao.buffer[i + 7] % 16)) + "/" +
                                        string.Concat((Conexao.buffer[i + 8] / 16), (Conexao.buffer[i + 8] % 16)) +
                                        "/20" +
                                        string.Concat((Conexao.buffer[i + 9] / 16), (Conexao.buffer[i + 9] % 16)) + " " +
                                        string.Concat((Conexao.buffer[i + 5] / 16), (Conexao.buffer[i + 5] % 16)) + ":" +
                                        string.Concat((Conexao.buffer[i + 4] / 16), (Conexao.buffer[i + 4] % 16)));
                                ciclo.crg = numEquipamento;
                                bool noBanco = CicloDAO.testanoBanco(ciclo);
                                if (!noBanco)
                                {
                                    dtgHistorico.Rows.Add(ciclo.nTrat, ciclo.nl,
                                                          ciclo.dataInicio.ToString("dd/MM/yyyy HH:mm"));
                                }
                                i = i + 9;
                            }
                            t.Abort();
                            Thread.Sleep(100);
                            if (dtgHistorico.Rows.Count == 0)
                            {
                                MessageBox.Show("Não há nenhum histórico novo", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            Conexao.srpComm.Close();
                        }
                        else
                        {
                            MessageBox.Show("Erro de checksum.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            Conexao.srpComm.Close();
                        }
                        break;

                    case 165:
                        t.Abort();
                        Thread.Sleep(100);
                        if (dtgHistorico.Rows.Count > 0)
                        {
                            dtgHistorico.Rows.Clear();
                        }
                        MessageBox.Show("Essa função não está disponivel para esse equipamento.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Conexao.srpComm.Close();
                        break;
                    }
                    inserir.Enabled = true;
                }
            }
            catch (Exception error)
            {
                if (t.IsAlive)
                {
                    t.Abort();
                    Thread.Sleep(100);
                }
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = numEquipamento;
                logErro.data         = DateTime.Now;
                logErro.descricao    = "Erro ao decodificar os dados do histórico, aparelho nº " + numEquipamento;
                logErro.maisDetalhes = error.Message + " " + error.StackTrace;
                LogErroDAO.inserirLogErro(logErro, logErro.crg);
                MessageBox.Show("Erro durante a comunicação com o equipamento", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Exemple #15
0
        private void Email_Click(object sender, EventArgs e)
        {
            FormularioEmail form = new FormularioEmail(this);

            form.ShowDialog(this);
            if (continuarExportandoEmail)
            {
                var crg = 0;

                FileInfo file = new FileInfo(@Environment.CurrentDirectory + "\\CiclosExportados.crg08");
                if (file.Exists)
                {
                    file.Delete();
                }

                var writer = new XmlTextWriter(Environment.CurrentDirectory + "\\CiclosExportados.crg08", null);
                // Gera o XML de cada ciclo
                try
                {
                    writer.Formatting = Formatting.Indented;
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Ciclos");

                    for (int i = 0; i < dtgAndamento.RowCount; i++)
                    {
                        if (dtgAndamento.Rows[i].Cells[0].Value.ToString() == "True")
                        {
                            var id = int.Parse(dtgAndamento.Rows[i].Cells[1].Value.ToString());
                            crg = int.Parse(dtgAndamento.Rows[i].Cells[2].Value.ToString());
                            var ciclo = CicloDAO.buscaCiclo(crg, id);

                            ExportarCiclo(writer, ciclo, i + 1);
                        }
                    }

                    for (int i = 0; i < dtgFinalizados.RowCount; i++)
                    {
                        if (dtgFinalizados.Rows[i].Cells[0].Value.ToString() == "True")
                        {
                            var id = int.Parse(dtgFinalizados.Rows[i].Cells[1].Value.ToString());
                            crg = int.Parse(dtgFinalizados.Rows[i].Cells[2].Value.ToString());
                            var ciclo = CicloDAO.buscaCiclo(crg, id);

                            ExportarCiclo(writer, ciclo, i + 1);
                        }
                    }

                    writer.WriteFullEndElement();
                    writer.WriteEndDocument();
                }
                catch (Exception error)
                {
                    VO.LogErro logErro = new VO.LogErro();
                    logErro.crg       = crg;
                    logErro.descricao = "Erro ao tentar exportar";
                    string dataHora = DateTime.Now.ToString();
                    logErro.data         = DateTime.Now;
                    logErro.maisDetalhes = error.Message;
                    LogErroDAO.inserirLogErro(logErro, logErro.crg);
                    MessageBox.Show("Erro ao tentar exportar por email.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                finally
                {
                    writer.Flush();
                    writer.Close();

                    var xmlDoc = new XmlDocument();

                    try
                    {
                        xmlDoc.PreserveWhitespace = true;
                        xmlDoc.Load(file.Name);
                    }
                    catch (Exception er)
                    {
                        Console.WriteLine(er.Message);
                    }

                    var cspParams = new CspParameters();
                    cspParams.KeyContainerName = "CRG08";

                    var rsaKey = new RSACryptoServiceProvider(cspParams);

                    try
                    {
                        Crypto.Encrypt(xmlDoc, "Ciclo", "Ciclo", rsaKey, "rsaKey");
                        xmlDoc.Save(file.Name);
                    }
                    catch (Exception er)
                    {
                        VO.LogErro logErro = new VO.LogErro();
                        logErro.crg       = crg;
                        logErro.descricao = "Erro ao tentar exportar";
                        string dataHora = DateTime.Now.ToString();
                        logErro.data         = DateTime.Now;
                        logErro.maisDetalhes = er.Message;
                        LogErroDAO.inserirLogErro(logErro, logErro.crg);
                        MessageBox.Show("Erro ao tentar exportar por email.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                    MailMessage          msg = new MailMessage();
                    List <Destinatarios> listaDestinatarios = ListaDestinatarios();
                    string[]             dadosConfiguracao  = ObterDadosEmail();

                    if (listaDestinatarios.Count > 0)
                    {
                        msg.From = new MailAddress(dadosConfiguracao[1]);
                        foreach (var d in listaDestinatarios)
                        {
                            msg.To.Add(new MailAddress(d.email));
                        }
                        msg.Subject = "Envio de Ciclos Exportados pelo CRG 08";
                        msg.Body    = "Ciclo exportado no dia " + DateTime.Today.ToString().Substring(0, 10) +
                                      " do equipamento CRG 08 enviado via software do CRG 08 desenvolvido pela Digisystem Indústria de " +
                                      "Sistema Eletrônico LTDA, e autorizado conforme configuração do usuário no software.";

                        msg.Attachments.Add(new Attachment(@Environment.CurrentDirectory + "\\CiclosExportados.crg08"));

                        SmtpClient smtp = new SmtpClient(dadosConfiguracao[0]);
                        smtp.Port = Convert.ToInt32(dadosConfiguracao[4]);
                        if (int.Parse(dadosConfiguracao[5]) == 1)
                        {
                            smtp.EnableSsl = true;
                        }
                        else
                        {
                            smtp.EnableSsl = false;
                        }
                        smtp.Credentials = new NetworkCredential(dadosConfiguracao[2], dadosConfiguracao[3]);
                        smtp.SendAsync(msg, msg.Subject);
                        smtp.SendCompleted += new SendCompletedEventHandler(stmp_SendCompletedRGD);
                    }
                    MessageBox.Show("O email foi enviado com sucesso!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.None);
                }
            }
        }
Exemple #16
0
        public bool AtualizaCiclo()
        {
            List <string> mensagens = new List <string>();
            //Lista ciclos em Andamento
            List <VO.Ciclos> ciclos = CicloDAO.listaCiclosPorSituacaoAll(0);

            t = new Thread(new ThreadStart(carregarAguarde));
            //this.Enabled = false;

            try
            {
                for (int i = 0; i < ciclos.Count; i++)
                {
                    VO.Ciclos           cic           = ciclos[i];
                    List <ProdutoCiclo> listaProdutos = ProdutoCicloDAO.listaProdutosCiclo(cic);
                    VO.Ciclos           ciclo         = new VO.Ciclos();

                    string porta    = ConfiguracaoDAO.retornaPorta();
                    bool   continua = false;
                    if (!t.IsAlive)
                    {
                        t.Start();
                    }

                    var srpComm = new SerialPort(porta, 19200, Parity.None, 8, StopBits.One);
                    srpComm.DtrEnable       = true;
                    srpComm.RtsEnable       = false;
                    srpComm.ReadBufferSize  = 100000;
                    srpComm.WriteBufferSize = 100000;

                    Conexao.srpComm = srpComm;
                    Conexao.srpComm.Open();
                    Thread.Sleep(100);

                    int numBytes = 0;
                    int aux      = cic.crg + 63;
                    Conexao.srpComm.Write(((char)19).ToString());
                    Thread.Sleep(100);
                    Conexao.srpComm.Write(((char)17).ToString());
                    Thread.Sleep(100);
                    Conexao.srpComm.Write(((char)aux).ToString());
                    Thread.Sleep(100);

                    if (Conexao.srpComm.BytesToRead != 0)
                    {
                        numBytes       = byte.Parse(Conexao.srpComm.BytesToRead.ToString());
                        Conexao.buffer = new byte[numBytes];
                        Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                    }
                    continua = true;
                    if (continua)
                    {
                        // int cont = 0;
                        //Verifica se é aparelho novo ou antigo
                        switch (Conexao.buffer[0])
                        {
                        //Versão nova até 150ºC
                        case 167:
                            string binario = decimalParaBinario(cic.nTrat);
                            numTrat1 = binarioParaDecimal(binario.Substring(0, 8));
                            numTrat2 = binarioParaDecimal(binario.Substring(8, 8));

                            Conexao.srpComm.Write(((char)5).ToString());
                            Thread.Sleep(100);
                            Conexao.srpComm.Write(((char)numTrat1).ToString());
                            Thread.Sleep(100);
                            Conexao.srpComm.Write(((char)numTrat2).ToString());
                            Thread.Sleep(8000);

                            int contador = 0;
                            do
                            {
                                if (Conexao.srpComm.BytesToRead != 0)
                                {
                                    numBytes       = int.Parse(Conexao.srpComm.BytesToRead.ToString());
                                    Conexao.buffer = new byte[numBytes];
                                    Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                                }
                                contador++;
                            } while (Conexao.srpComm.BytesToRead != 0);

                            int checksum = 0;
                            //Verifica se o ciclo ainda está na memória do equipamento
                            if (Conexao.buffer.Length > 2)
                            {
                                for (int j = 0; j < Conexao.buffer.Length - 2; j++)
                                {
                                    checksum ^= Conexao.buffer[j];
                                }
                                if (checksum == Conexao.buffer[Conexao.buffer.Length - 2])
                                {
                                    int aux2 = Conexao.buffer.Length - 10;
                                    cic.numSerie = ((char)Conexao.buffer[aux2]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 1]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 2]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 3]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 4]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 5]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 6]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 7]).ToString();
                                    cic.nTrat = (Conexao.buffer[0] * 256) + Conexao.buffer[1];
                                    string dataInicio =
                                        string.Concat((Conexao.buffer[7] / 16), (Conexao.buffer[7] % 16)) +
                                        "/" +
                                        string.Concat((Conexao.buffer[8] / 16), (Conexao.buffer[8] % 16)) +
                                        "/20" +
                                        string.Concat((Conexao.buffer[9] / 16), (Conexao.buffer[9] % 16)) +
                                        " " +
                                        string.Concat((Conexao.buffer[5] / 16), (Conexao.buffer[5] % 16)) +
                                        ":" +
                                        string.Concat((Conexao.buffer[4] / 16), (Conexao.buffer[4] % 16));
                                    cic.dataInicio = Convert.ToDateTime(dataInicio);
                                    cic.dataColeta = DateTime.Now;

                                    bool retorno = false;


                                    int indiceLeitCiclo = LeiturasCicloDAO.retornaQtdeLeituras(cic.id,
                                                                                               cic.crg);
                                    int indiceLeitTrat = LeiturasTratDAO.retornaQtdeLeituras(cic.id, cic.crg);
                                    retorno = ConexaoBO.EnviaBancodeDados(cic, Conexao.buffer, true,
                                                                          listaProdutos, indiceLeitCiclo, indiceLeitTrat, true);
                                    if (retorno)
                                    {
                                        AtualizaUltimo(cic.operador, cic.responsavel);
                                        mensagens.Add("O ciclo nº " + cic.nTrat + " do aparelho nº " + cic.crg +
                                                      " foi atualizado com sucesso.");
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Erro no checksum.", "Erro", MessageBoxButtons.OK,
                                                    MessageBoxIcon.Information);
                                }
                            }
                            else
                            {
                                mensagens.Add("O ciclo nº " + cic.nTrat + " do aparelho nº " + cic.crg +
                                              " nao está mais na memória do equipamento.");
                            }
                            break;

                        //Versão nova até 102ºC
                        case 166:
                            string binario1 = decimalParaBinario(cic.nTrat);
                            numTrat1 = binarioParaDecimal(binario1.Substring(0, 8));
                            numTrat2 = binarioParaDecimal(binario1.Substring(8, 8));

                            Conexao.srpComm.Write(((char)5).ToString());
                            Thread.Sleep(100);
                            Conexao.srpComm.Write(((char)numTrat1).ToString());
                            Thread.Sleep(100);
                            Conexao.srpComm.Write(((char)numTrat2).ToString());
                            Thread.Sleep(8000);

                            int contador1 = 0;
                            do
                            {
                                if (Conexao.srpComm.BytesToRead != 0)
                                {
                                    numBytes       = int.Parse(Conexao.srpComm.BytesToRead.ToString());
                                    Conexao.buffer = new byte[numBytes];
                                    Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                                }
                                contador1++;
                            } while (Conexao.srpComm.BytesToRead != 0);

                            int checksum1 = 0;
                            //Verifica se o ciclo ainda está na memória do equipamento
                            if (Conexao.buffer.Length > 2)
                            {
                                for (int j = 0; j < Conexao.buffer.Length - 2; j++)
                                {
                                    checksum1 ^= Conexao.buffer[j];
                                }
                                if (checksum1 == Conexao.buffer[Conexao.buffer.Length - 2])
                                {
                                    int aux2 = Conexao.buffer.Length - 10;
                                    ciclo.numSerie = ((char)Conexao.buffer[aux2]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 1]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 2]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 3]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 4]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 5]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 6]).ToString() +
                                                     ((char)Conexao.buffer[aux2 + 7]).ToString();
                                    ciclo.nTrat = (Conexao.buffer[0] * 256) + Conexao.buffer[1];
                                    string dataInicio =
                                        string.Concat((Conexao.buffer[7] / 16), (Conexao.buffer[7] % 16)) +
                                        "/" +
                                        string.Concat((Conexao.buffer[8] / 16), (Conexao.buffer[8] % 16)) +
                                        "/20" +
                                        string.Concat((Conexao.buffer[9] / 16), (Conexao.buffer[9] % 16)) +
                                        " " +
                                        string.Concat((Conexao.buffer[5] / 16), (Conexao.buffer[5] % 16)) +
                                        ":" +
                                        string.Concat((Conexao.buffer[4] / 16), (Conexao.buffer[4] % 16));
                                    ciclo.dataInicio = Convert.ToDateTime(dataInicio);
                                    ciclo.dataColeta = DateTime.Now;

                                    bool retorno = false;


                                    int indiceLeitCiclo = LeiturasCicloDAO.retornaQtdeLeituras(ciclo.id,
                                                                                               ciclo.crg);
                                    int indiceLeitTrat = LeiturasTratDAO.retornaQtdeLeituras(ciclo.id, ciclo.crg);
                                    retorno = ConexaoBO.EnviaBancodeDados(ciclo, Conexao.buffer, true,
                                                                          listaProdutos, indiceLeitCiclo, indiceLeitTrat, false);
                                    if (retorno)
                                    {
                                        AtualizaUltimo(cic.operador, cic.responsavel);
                                        mensagens.Add("O ciclo nº " + cic.nTrat + " do aparelho nº " + cic.crg +
                                                      " foi atualizado com sucesso.");
                                    }
                                }
                                else
                                {
                                    mensagens.Add("Não foi possível atualizar o ciclo nº " + cic.nTrat +
                                                  " do aparelho nº " + cic.crg + ". Erro de Checksum.");
                                }
                            }
                            else
                            {
                                mensagens.Add("O ciclo nº " + cic.nTrat + " do aparelho nº " + cic.crg +
                                              " nao está mais na memória do equipamento.");
                            }
                            break;

                        //Versão antiga até 102ºC apenas
                        case 165:
                            Conexao.srpComm.Write(((char)6).ToString());
                            Thread.Sleep(8000);

                            int cont = 0;
                            do
                            {
                                if (Conexao.srpComm.BytesToRead != 0)
                                {
                                    numBytes       = int.Parse(Conexao.srpComm.BytesToRead.ToString());
                                    Conexao.buffer = new byte[numBytes];
                                    Conexao.srpComm.Read(Conexao.buffer, 0, numBytes);
                                }
                                cont++;
                            } while (Conexao.srpComm.BytesToRead != 0);

                            int chk = 0;
                            for (int j = 0; j < Conexao.buffer.Length - 2; j++)
                            {
                                chk ^= Conexao.buffer[j];
                            }

                            if (((Conexao.buffer[5] * 256) + Conexao.buffer[2]) == cic.nTrat)
                            {
                                if (chk == Conexao.buffer[Conexao.buffer.Length - 2])
                                {
                                    int aux2 = Conexao.buffer.Length - 10;
                                    cic.numSerie = ((char)Conexao.buffer[aux2]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 1]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 2]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 3]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 4]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 5]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 6]).ToString() +
                                                   ((char)Conexao.buffer[aux2 + 7]).ToString();
                                    cic.nTrat = (Conexao.buffer[5] * 256) + Conexao.buffer[2];
                                    string dataInicio =
                                        string.Concat((Conexao.buffer[6] / 16), (Conexao.buffer[6] % 16)) + "/" +
                                        string.Concat((Conexao.buffer[7] / 16), (Conexao.buffer[7] % 16)) + "/20" +
                                        string.Concat((Conexao.buffer[8] / 16), (Conexao.buffer[8] % 16)) + " " +
                                        string.Concat((Conexao.buffer[4] / 16), (Conexao.buffer[4] % 16)) + ":" +
                                        string.Concat((Conexao.buffer[3] / 16), (Conexao.buffer[3] % 16));
                                    cic.dataInicio = Convert.ToDateTime(dataInicio);
                                    cic.dataColeta = DateTime.Now;

                                    bool retorno = false;

                                    int indiceLeitCiclo = LeiturasCicloDAO.retornaQtdeLeituras(cic.id,
                                                                                               cic.crg);
                                    int indiceLeitTrat = LeiturasTratDAO.retornaQtdeLeituras(cic.id,
                                                                                             cic.crg);
                                    retorno = ConexaoBO.EnviaBancodeDadosAntigo(cic, Conexao.buffer, true,
                                                                                listaProdutos, indiceLeitCiclo, indiceLeitTrat);
                                    if (retorno)
                                    {
                                        AtualizaUltimo(cic.operador, cic.responsavel);
                                        mensagens.Add("O ciclo nº " + cic.nTrat + " do aparelho nº " + cic.crg +
                                                      " foi atualizado com sucesso.");
                                    }
                                }
                                else
                                {
                                    mensagens.Add("Não foi possível atualizar o ciclo nº " + cic.nTrat +
                                                  " do aparelho nº " + cic.crg + ". Erro de Checksum.");
                                }
                            }
                            else
                            {
                                mensagens.Add("O ciclo nº " + cic.nTrat + " do aparelho nº " + cic.crg +
                                              " não está mais no histórico.");
                            }


                            break;
                        }
                    }
                    Conexao.srpComm.Close();
                    Thread.Sleep(100);
                }
                t.Abort();

                if (mensagens.Count > 0)
                {
                    StatusAtualizacao frm = new StatusAtualizacao(mensagens);
                    frm.ShowDialog(this);
                }
                return(true);
            }
            catch (Exception error)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao tentar receber o ciclo";
                logErro.maisDetalhes = error.Message + " " + error.StackTrace;
                logErro.data         = DateTime.Now;
                LogErroDAO.inserirLogErro(logErro, logErro.crg);
                t.Abort();
                return(false);
            }
        }
Exemple #17
0
        public static bool EditarDestinatario(Destinatarios destinatario)
        {
            string path      = Environment.CurrentDirectory + "\\Destinatarios.xml";
            var    cspParams = new CspParameters();

            cspParams.KeyContainerName = "Destinatarios";
            var rsaKey = new RSACryptoServiceProvider(cspParams);

            try
            {
                var stream      = new MemoryStream();
                var xmlDocument = new XmlDocument();

                xmlDocument.PreserveWhitespace = true;
                xmlDocument.Load(path);

                Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                xmlDocument.Save(stream);
                stream.Flush();
                stream.Position = 0;

                XDocument xml      = XDocument.Load(stream);
                var       elements = xml.XPathSelectElements("Destinatarios/Destinatarios");
                foreach (var xElement in elements)
                {
                    if (xElement.FirstAttribute.Value == destinatario.id.ToString())
                    {
                        xElement.LastAttribute.Value = destinatario.email;
                    }
                }
                xml.Save(path);
                return(true);
            }
            catch (Exception er)
            {
                VO.LogErro logErro = new VO.LogErro();
                logErro.crg          = 0;
                logErro.descricao    = "Erro ao tentar editar destinatário";
                logErro.data         = DateTime.Now;
                logErro.maisDetalhes = er.Message;
                LogErroDAO.inserirLogErro(logErro, 0);

                return(false);
            }
            finally
            {
                var xmlDoc = new XmlDocument();

                try
                {
                    xmlDoc.PreserveWhitespace = true;
                    xmlDoc.Load(path);
                }
                catch (Exception er)
                {
                    Console.WriteLine(er.Message);
                }

                try
                {
                    Crypto.Encrypt(xmlDoc, "Destinatarios", "Destinatario", rsaKey, "rsaKey");
                    xmlDoc.Save(path);
                }
                catch (Exception er)
                {
                    VO.LogErro logErro = new VO.LogErro();
                    logErro.crg          = 0;
                    logErro.descricao    = "Erro ao tentar encriptografar Destinatarios";
                    logErro.data         = DateTime.Now;
                    logErro.maisDetalhes = er.Message;
                    LogErroDAO.inserirLogErro(logErro, 0);
                }
            }
        }
Exemple #18
0
        private void Arquivo_Click(object sender, EventArgs e)
        {
            var crg = 0;

            if (Exportar.Checked)
            {
                salvarCiclo.RestoreDirectory = true;
                salvarCiclo.Title            = "Exportar Ciclo para...";
                salvarCiclo.Filter           = "crg08 files(*.crg08)|*.crg08";
                salvarCiclo.DefaultExt       = "crg08";
                salvarCiclo.CheckPathExists  = true;

                var dialogResult = salvarCiclo.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    var writer = new XmlTextWriter(salvarCiclo.FileName, null);
                    // Gera o XML de cada ciclo
                    try
                    {
                        writer.Formatting = Formatting.Indented;
                        writer.WriteStartDocument();
                        writer.WriteStartElement("Ciclos");

                        for (int i = 0; i < dtgAndamento.RowCount; i++)
                        {
                            if (dtgAndamento.Rows[i].Cells[0].Value.ToString() == "True")
                            {
                                var id = int.Parse(dtgAndamento.Rows[i].Cells[1].Value.ToString());
                                crg = int.Parse(dtgAndamento.Rows[i].Cells[2].Value.ToString());
                                var ciclo = CicloDAO.buscaCiclo(crg, id);

                                ExportarCiclo(writer, ciclo, i + 1);
                            }
                        }

                        for (int i = 0; i < dtgFinalizados.RowCount; i++)
                        {
                            if (dtgFinalizados.Rows[i].Cells[0].Value.ToString() == "True")
                            {
                                var id = int.Parse(dtgFinalizados.Rows[i].Cells[1].Value.ToString());
                                crg = int.Parse(dtgFinalizados.Rows[i].Cells[2].Value.ToString());
                                var ciclo = CicloDAO.buscaCiclo(crg, id);

                                ExportarCiclo(writer, ciclo, i + 1);
                            }
                        }

                        writer.WriteFullEndElement();
                        writer.WriteEndDocument();
                    }
                    catch (Exception error)
                    {
                        VO.LogErro logErro = new VO.LogErro();
                        logErro.crg       = crg;
                        logErro.descricao = "Erro ao tentar exportar";
                        string dataHora = DateTime.Now.ToString();
                        logErro.data         = DateTime.Now;
                        logErro.maisDetalhes = error.Message;
                        LogErroDAO.inserirLogErro(logErro, logErro.crg);
                        MessageBox.Show("Erro ao tentar exportar.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        writer.Flush();
                        writer.Close();

                        var xmlDoc = new XmlDocument();

                        try
                        {
                            xmlDoc.PreserveWhitespace = true;
                            xmlDoc.Load(salvarCiclo.FileName);
                        }
                        catch (Exception er)
                        {
                            Console.WriteLine(er.Message);
                        }

                        var cspParams = new CspParameters();
                        cspParams.KeyContainerName = "CRG08";

                        var rsaKey = new RSACryptoServiceProvider(cspParams);

                        try
                        {
                            Crypto.Encrypt(xmlDoc, "Ciclo", "Ciclo", rsaKey, "rsaKey");
                            xmlDoc.Save(salvarCiclo.FileName);
                        }
                        catch (Exception er)
                        {
                            VO.LogErro logErro = new VO.LogErro();
                            logErro.crg       = crg;
                            logErro.descricao = "Erro ao tentar exportar";
                            string dataHora = DateTime.Now.ToString();
                            logErro.data         = DateTime.Now;
                            logErro.maisDetalhes = er.Message;
                            LogErroDAO.inserirLogErro(logErro, logErro.crg);
                            MessageBox.Show("Erro ao tentar exportar.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }

                        CarregaCiclos();
                        MessageBox.Show("Ciclo exportado com sucesso!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.None);
                    }
                }
            }
            else
            {
                var listaCiclos     = new List <ImportarCiclo>();
                var importacaoCiclo = new ImportarCiclo();
                var listaLeituras   = new List <LeiturasCiclo>();
                var listaTratamento = new List <LeiturasTrat>();
                var produtosCiclos  = new List <ProdutoCiclo>();
                var tag             = "";
                var stream          = new MemoryStream();
                var xmlDocument     = new XmlDocument();
                var cspParams       = new CspParameters();

                abrirCiclo.RestoreDirectory = true;
                abrirCiclo.Title            = "Importar Ciclo";
                abrirCiclo.Filter           = "crg08 files(*.crg08)|*.crg08";
                abrirCiclo.DefaultExt       = "crg08";
                abrirCiclo.CheckPathExists  = true;
                VO.Ciclos cicloTemp;
                VO.Ciclos cic = new VO.Ciclos();

                var dialogResult = abrirCiclo.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    try
                    {
                        cspParams.KeyContainerName = "CRG08";
                        var rsaKey = new RSACryptoServiceProvider(cspParams);

                        xmlDocument.PreserveWhitespace = true;
                        xmlDocument.Load(abrirCiclo.FileName);

                        Crypto.Decrypt(xmlDocument, rsaKey, "rsaKey");

                        xmlDocument.Save(stream);
                        stream.Flush();
                        stream.Position = 0;

                        // Carrega os dados no Reader para ler
                        var reader = new XmlTextReader(stream);
                        reader.WhitespaceHandling = WhitespaceHandling.None; // Para ignorar espaço em branco

                        // Carrega os dados de um ciclo, verifica se já existe e questiona
                        // o usuário se ele deseja substituir e os próximos ciclos também
                        while ((reader.Read()))
                        {
                            switch (reader.NodeType)
                            {
                            case XmlNodeType.EndElement:
                                if (reader.Name == "Ciclo")
                                {
                                    importacaoCiclo.leiturasCiclo      = listaLeituras;
                                    importacaoCiclo.leiturasTratamento = listaTratamento;
                                    importacaoCiclo.produtosCiclo      = produtosCiclos;
                                    importacaoCiclo.ciclo = cic;
                                    listaCiclos.Add(importacaoCiclo);
                                    importacaoCiclo = new ImportarCiclo();
                                    listaLeituras   = new List <LeiturasCiclo>();
                                    listaTratamento = new List <LeiturasTrat>();
                                    produtosCiclos  = new List <ProdutoCiclo>();
                                    cic             = new VO.Ciclos();
                                }
                                break;

                            case XmlNodeType.Element:
                                tag = reader.Name;

                                if (tag == "LeituraCiclo")
                                {
                                    listaLeituras.Add(CarregaLeiturasCiclo(reader.ReadSubtree()));
                                }
                                else if (tag == "LeituraTratamento")
                                {
                                    listaTratamento.Add(CarregaLeituraTratamento(reader.ReadSubtree()));
                                }
                                else if (tag == "ProdutoCiclo")
                                {
                                    produtosCiclos.Add(CarregaProdutos(reader.ReadSubtree()));
                                }
                                break;

                            case XmlNodeType.Text:

                                switch (tag)
                                {
                                // Cabeçalho
                                case "Id":
                                    cic.id = Convert.ToInt32(reader.Value);
                                    break;

                                case "CRG":
                                    cic.crg = Convert.ToInt32(reader.Value);
                                    break;

                                case "NTrat":
                                    cic.nTrat = Convert.ToInt32(reader.Value);
                                    break;

                                case "NL":
                                    cic.nl = Convert.ToInt32(reader.Value);
                                    break;

                                case "BaseTempo":
                                    cic.baseTempo = Convert.ToInt32(reader.Value);
                                    break;

                                case "NLT":
                                    cic.nlt = Convert.ToInt32(reader.Value);
                                    break;

                                case "DataColeta":
                                    cic.dataColeta = Convert.ToDateTime(reader.Value);
                                    break;

                                case "Descricao":
                                    cic.descricao = reader.Value;
                                    break;

                                case "DataInicio":
                                    cic.dataInicio = Convert.ToDateTime(reader.Value);
                                    break;

                                case "DataFim":
                                    cic.dataFim = Convert.ToDateTime(reader.Value);
                                    break;

                                case "NLIniTrat":
                                    cic.NLIniTrat = Convert.ToInt32(reader.Value);
                                    break;

                                case "TemperaturaControle":
                                    cic.temperaturaControle = Convert.ToSingle(reader.Value);
                                    break;

                                case "TemperaturaTrat":
                                    cic.temperaturaTrat = Convert.ToSingle(reader.Value);
                                    break;

                                case "TempoTrat":
                                    cic.tempoTrat = Convert.ToInt32(reader.Value);
                                    break;

                                case "Responsavel":
                                    cic.responsavel = reader.Value;
                                    break;

                                case "Operador":
                                    cic.operador = reader.Value;
                                    break;

                                case "Situacao":
                                    cic.situacao = Convert.ToInt32(reader.Value);
                                    break;

                                case "NumSerie":
                                    cic.numSerie = reader.Value;
                                    break;

                                case "VersaoEquip":
                                    cic.versaoEquip = reader.Value;
                                    break;

                                case "Histerese":
                                    cic.histerese = Convert.ToInt32(reader.Value);
                                    break;

                                case "TControl":
                                    cic.tControl = Convert.ToInt32(reader.Value);
                                    break;

                                case "NLAntesTrat":
                                    cic.nlAntesTrat = Convert.ToInt32(reader.Value);
                                    break;

                                case "NLPostTrat":
                                    cic.nlPostTrat = Convert.ToInt32(reader.Value);
                                    break;

                                case "Sensor":
                                    cic.sensor = Convert.ToInt32(reader.Value);
                                    break;

                                case "CA":
                                    cic.CA = reader.Value;
                                    break;

                                case "tipoCRG":
                                    cic.tipoCRG = Convert.ToInt32(reader.Value);
                                    break;
                                }
                                break;
                            }
                        }

                        foreach (var ciclo in listaCiclos)
                        {
                            // Verifica se o ciclo está no banco de dados e add em um Obj temporário = cicloTemp
                            cicloTemp = CicloDAO.testaCiclo(ciclo.ciclo);
                            if (cicloTemp != null)
                            {
                                // Se o obj for diferente de nulo...
                                if (MessageBox.Show("O ciclo de nº " + ciclo.ciclo.nTrat +
                                                    " já existe no Banco de Dados. Deseja atualizar?", "Atenção",
                                                    MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                                {
                                    bool retorno = CicloDAO.alteraCiclo(ciclo.ciclo);
                                    if (retorno)
                                    {
                                        ProdutoCicloDAO.DeletaProdutosCiclo(ciclo.ciclo.id, ciclo.ciclo.crg);
                                        for (int i = 0; i < ciclo.produtosCiclo.Count; i++)
                                        {
                                            ciclo.produtosCiclo[i].ciclo = ciclo.ciclo;
                                            ProdutoCicloDAO.inserirProdutoCiclo(ciclo.produtosCiclo[i]);
                                        }
                                        if (ciclo.leiturasCiclo.Count > 0)
                                        {
                                            if (ciclo.ciclo.tipoCRG == 2)
                                            {
                                                LeiturasCicloDAO.inserirLeiturasCiclo150(ciclo.leiturasCiclo, ciclo.ciclo.nl, ciclo.ciclo);
                                            }
                                            else
                                            {
                                                LeiturasCicloDAO.inserirLeiturasCiclo(ciclo.leiturasCiclo, ciclo.ciclo.nl, ciclo.ciclo);
                                            }
                                        }
                                        if (ciclo.leiturasTratamento.Count > 0)
                                        {
                                            if (ciclo.ciclo.tipoCRG == 2)
                                            {
                                                LeiturasTratDAO.inserirLeiturasTratamento150(ciclo.leiturasTratamento, ciclo.ciclo.nlt, ciclo.ciclo);
                                            }
                                            else
                                            {
                                                LeiturasTratDAO.inserirLeiturasTratamento(ciclo.leiturasTratamento, ciclo.ciclo.nlt, ciclo.ciclo);
                                            }
                                        }
                                    }

                                    CarregaCiclos();
                                }
                            }
                            else
                            {
                                // Inclui a ciclo
                                ImportarCiclo(ciclo);
                                CarregaCiclos();
                            }
                        }

                        MessageBox.Show("Importação realizada com sucesso!", "Sucesso", MessageBoxButtons.OK,
                                        MessageBoxIcon.None);
                    }
                    catch (Exception ex)
                    {
                        VO.LogErro logErro = new VO.LogErro();
                        logErro.crg          = crg;
                        logErro.descricao    = "Erro ao tentar importar ciclo";
                        logErro.data         = DateTime.Now;
                        logErro.maisDetalhes = ex.Message;
                        LogErroDAO.inserirLogErro(logErro, logErro.crg);
                        MessageBox.Show("Erro ao tentar importar.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
        }