コード例 #1
0
        public bool FazLogin(int id, string nome, int nivel, int avatar)
        {
            try
            {
                if (this.SessaoIniciada)
                {
                    throw new Exception("Já existe uma sessão iniciada!");
                }

                HttpContext.Current.Response.Cookies["id"].Value       = id.ToString();
                HttpContext.Current.Response.Cookies["nome"].Value     = nome;
                HttpContext.Current.Response.Cookies["nivel"].Value    = nivel.ToString();
                HttpContext.Current.Response.Cookies["avatar"].Value   = avatar.ToString();
                HttpContext.Current.Response.Cookies["unixTime"].Value = Diversos.ObterTempoUnixAtual().ToString();

                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("FazLogin(): " + ex.Message);
                this.LimpaDados();

                return(false);
            }
        }
コード例 #2
0
        public async Task <IActionResult> Download(int id)
        {
            try
            {
                var _arquivoProjeto = _documentoRepository.GetById(id);
                //string sTipo;

                if (_arquivoProjeto.sNomeArquivo == null)
                {
                    return(Content("Arquivo não encontrado"));
                }

                string path   = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\arquivos", _arquivoProjeto.sNomeArquivo);
                var    memory = new MemoryStream();
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;

                return(File(memory, Diversos.GetContentType(path), Path.GetFileName(path)));
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #3
0
        public int Delete(int id)
        {
            try
            {
                var _arquivoProjeto = _arquivoRepository.GetById(id);
                _arquivoRepository.Remove(_arquivoProjeto);
                string sTipo;


                if (_arquivoProjeto.iTipo == 1)
                {
                    sTipo = "INSTITUICAO";
                }
                else
                {
                    sTipo = "PROJETO";
                }

                string path = Diversos.PathArquivo(_arquivoProjeto.sNomebase, sTipo);

                System.IO.File.Delete(path);

                return(1);
            }
            catch (System.Exception)
            {
                return(0);
            }
        }
コード例 #4
0
        private void btEnviar_Click(object sender, EventArgs e)
        {
            MensagemBE mensagem = new MensagemBE();

            mensagem.Destinatario = txtPara.Text;
            mensagem.Remetente    = txtDe.Text;
            mensagem.Assunto      = txtAssunto.Text;
            mensagem.Mensagem     = txtMensagem.Text;

            erro = new List <String>();

            this.Enabled     = false;
            pnStatus.Visible = true;
            pnStatus.Enabled = true;
            lbEnv.Enabled    = true;
            lbQtd.Enabled    = true;

            if (destinatarios.Count() == 0)
            {
                lbQtd.Text = "1 de 1";
                Form.ActiveForm.Refresh();
                AcaoEnviar(mensagem);
            }
            else
            {
                var x = 0;
                foreach (var des in destinatarios)
                {
                    x++;
                    lbQtd.Text = x.ToString() + " de " + destinatarios.Count().ToString();
                    Form.ActiveForm.Refresh();
                    var le = Diversos.SepararTexto(des, ';');
                    if (le.Count() > 0)
                    {
                        mensagem.Destinatario = le[0];
                        if (le.Count() > 1)
                        {
                            mensagem.Assunto = le[1];
                        }
                        AcaoEnviar(mensagem);
                    }
                }
            }

            this.Enabled     = true;
            pnStatus.Visible = false;

            if (erro.Count() > 0)
            {
                erro.Insert(0, "Alguns erros foram encontrados: \n");
                ValidaErros();
            }
            else
            {
                MessageBox.Show("Processo de envio de e-mail concluído com sucesso...");
            }

            this.Enabled = true;
        }
コード例 #5
0
        public async Task <int> UploadAsync(IFormFile file, int IDInstituicaoProjeto, int iTipo)
        {
            if (file == null)
            {
                throw new Exception("File is null");
            }
            if (file.Length == 0)
            {
                throw new Exception("File is empty");
            }

            try
            {
                using (Stream stream = file.OpenReadStream())
                {
                    using (var binaryReader = new BinaryReader(stream))
                    {
                        var      fileContent = binaryReader.ReadBytes((int)file.Length);
                        string   sTipo;
                        string[] aFoto = file.FileName.Split('.');

                        Arquivo _arquivoProjeto = new Arquivo
                        {
                            sNome                = aFoto[0],
                            sNomebase            = IDInstituicaoProjeto + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "." + aFoto[aFoto.Count() - 1],
                            IDInstituicaoProjeto = IDInstituicaoProjeto,
                            iTipo                = iTipo
                        };

                        _arquivoRepository.Add(_arquivoProjeto);

                        if (iTipo == 1)
                        {
                            sTipo = "INSTITUICAO";
                        }
                        else
                        {
                            sTipo = "PROJETO";
                        }

                        await Diversos.SaveImage(file, sTipo, _arquivoProjeto.sNomebase);
                    }
                }

                return(1);
            }
            catch (Exception)
            {
                return(0);
            }
        }
コード例 #6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string query = Request.QueryString["ID"];

            if (!string.IsNullOrEmpty(query) && Diversos.IsNumeric(query))
            {
                ID = Convert.ToInt32(query);
            }

            if (!IsPostBack)
            {
                #region Preenche Infos

                try
                {
                    Maquina maquina = VARS.Maquinas.First(x => x.Id == ID);

                    if (maquina != null)
                    {
                        txtNomeMaquina.Value = maquina.Nome;

                        this.lblNomeMaquina.InnerText = this.Title = "Configurações Avançadas - " + maquina.Nome;

                        txtLimConformeMin.Value = maquina.Classe.Conforme.Min.ToString("0.000");
                        txtLimConformeMax.Value = maquina.Classe.Conforme.Max.ToString("0.000");

                        txtLimClasse2Min.Value    = maquina.Classe.Classe2.Min.ToString("0.000");
                        txtLimClasse2Max.Value    = maquina.Classe.Classe2.Max.ToString("0.000");
                        txtMaxPointsclasse2.Value = maquina.Classe.MaxPontosClasse2.ToString();

                        txtLimClasse3Min.Value    = maquina.Classe.Classe3.Min.ToString("0.000");
                        txtLimClasse3Max.Value    = maquina.Classe.Classe3.Max.ToString("0.000");
                        txtMaxPointsclasse3.Value = maquina.Classe.MaxPontosClasse3.ToString();

                        txtMaxPointsNC.Value        = maquina.Classe.MaxPontosNC.ToString();
                        txtSptempoMaxPointsNC.Value = Convert.ToInt32(maquina.Classe.SpTempoMaxPontosNC.TotalSeconds).ToString();
                    }
                    else
                    {
                        throw new Exception("sem dados lidos para a maquina " + ID);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                #endregion
            }
        }
コード例 #7
0
        public static string GetAlertasProducao(string id, string DtInicio, string DtFim, string Offset)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Offset) || !Diversos.IsNumeric(Offset))
                {
                    Offset = "0";
                }

                Maquina maquina = VARS.Maquinas.First(x => x.Id == Convert.ToInt32(id));

                //Populating a DataTable from database.
                DataTable dt = new DataTable();

                StringBuilder strQuery = new StringBuilder();
                strQuery.Append("SELECT TOP 1000 TipoAlerta.Tipo as 'A', (Alertas.Diametro + @OFFSET) AS 'D', FORMAT(Alertas.DataHora, 'dd/MM/yyyy HH:mm:ss') AS 'T' FROM Alertas ");
                strQuery.Append("INNER JOIN TipoAlerta ON Alertas.IdAlerta = TipoAlerta.Id ");
                strQuery.Append("WHERE Alertas.IdMaquina = @IdMaquina AND Alertas.DataHora BETWEEN @DATA1 AND @DATA2 ");
                strQuery.Append("ORDER BY Alertas.Id");

                if (maquina == null)
                {
                    throw new Exception("máquina não encontrada!");
                }
                else
                {
                    using (SqlConnection sqlConn = new SqlConnection(VARS.ConnectionString))
                        using (SqlCommand sqlCmd = new SqlCommand(strQuery.ToString(), sqlConn))
                        {
                            sqlCmd.Parameters.Add("@IdMaquina", SqlDbType.TinyInt).Value = Convert.ToInt32(id);
                            sqlCmd.Parameters.AddWithValue("@OFFSET", Convert.ToDouble(Offset.Replace(".", ",")));

                            sqlCmd.Parameters.Add("@DATA1", SqlDbType.DateTime).Value = DateTime.Parse(DtInicio);
                            sqlCmd.Parameters.Add("@DATA2", SqlDbType.DateTime).Value = DateTime.Parse(DtFim);

                            using (SqlDataAdapter sda = new SqlDataAdapter(sqlCmd))
                                sda.Fill(dt);
                        }
                }

                return(VARS.ConvertDataTabletoString(dt));
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetAlertasProducao(): " + ex.Message);

                return(string.Empty);
            }
        }
コード例 #8
0
 //[Authorize]
 public int Delete(int iCodigo)
 {
     try
     {
         var _arquivoProjeto = _documentoRepository.GetById(iCodigo);
         _documentoRepository.Remove(_arquivoProjeto);
         string path = Diversos.PathArquivo(_arquivoProjeto.sNomeArquivo);
         System.IO.File.Delete(path);
         return(1);
     }
     catch (System.Exception)
     {
         return(0);
     }
 }
コード例 #9
0
ファイル: VARS.cs プロジェクト: RubenJeronimo94/CTRL_PROD
 public bool InRange(double value, bool incMin, bool incMax)
 {
     if (incMin && incMax)
     {
         return(Diversos.InRange(Math.Round(value, 3), this.Min, this.Max));
     }
     else if (!incMin && incMax)
     {
         return(Math.Round(value, 3) > this.Min && Math.Round(value, 3) <= this.Max);
     }
     else if (incMin && !incMax)
     {
         return(Math.Round(value, 3) >= this.Min && Math.Round(value, 3) < this.Max);
     }
     else
     {
         return(Math.Round(value, 3) > this.Min && Math.Round(value, 3) < this.Max);
     }
 }
コード例 #10
0
        public VarsAuxiliares()
        {
            this.horaDeArranque = Diversos.ObterTempoUnixAtual();

            //Variáveis do LOG da aplicação
            string logDir     = Application.StartupPath + @"\Logs\Log.txt";
            int    logMaxSize = 5120;
            bool   logEnabled = true;

            #region Load configurations from INI File
            try
            {
                using (FicheiroINI ini = new FicheiroINI(iniPath))
                {
                    // Load Database configurations
                    this.DB_CONNECTION_STRING = @"data source=" + ini.RetornaINI("Database", "Address", ".") + @"\" + ini.RetornaINI("Database", "Instance", "SQLEXPRESS") + "; Initial Catalog=" + ini.RetornaINI("Database", "DBName", "CTRL_PROD") + "; MultipleActiveResultSets=True; persist security info=False; UID=" + ini.RetornaINI("Database", "User", "streak") + "; PWD=" + ini.RetornaINI("Database", "Pass", "streak") + ";";

                    this.IpDb = ini.RetornaINI("Database", "Address", ".");

                    #region Log
                    //Log da aplicação
                    logDir     = ini.RetornaINI("AppLog", "logDir", logDir);
                    logMaxSize = Convert.ToInt32(ini.RetornaINI("AppLog", "logMaxSize", Convert.ToString(logMaxSize)));
                    logEnabled = ini.RetornaTrueFalseDeStringFicheiroINI("AppLog", "logEnabled", logEnabled);
                    #endregion

                    // Diversos
                    this.LAST_LOCATION = new Point(Convert.ToInt32(ini.RetornaINI("App", "LocX", "0")), Convert.ToInt32(ini.RetornaINI("App", "Locy", "0")));

                    this.SETTINGS_UPDATE_RATE = Convert.ToInt32(ini.RetornaINI("App", "SETTINGS_UPDATE_RATE", this.SETTINGS_UPDATE_RATE.ToString()));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error Loading Configs", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(0);
            }
            #endregion

            this.LogDebug = new LogFile(logDir, logMaxSize, logEnabled);
        }
コード例 #11
0
        static void Main()
        {
            if (Diversos.PrevineDuplaExecucao(false))
            {
                Environment.Exit(0);
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                SetUnhandledExceptionFilter(ptrToExceptionInfo =>
                {
                    var errorCode = "0x" + Marshal.GetExceptionCode().ToString("x2");
                    return(1);
                });

                //Start application
                Application.Run(Forms.MainForm);
            }
        }
コード例 #12
0
        public async Task <IActionResult> Download(int id, int iTipo)
        {
            try
            {
                var    _arquivoProjeto = _arquivoRepository.GetById(id);
                string sTipo;

                if (_arquivoProjeto.sNome == null)
                {
                    return(Content("Arquivo não encontrado"));
                }

                if (iTipo == 1)
                {
                    sTipo = "INSTITUICAO";
                }
                else
                {
                    sTipo = "PROJETO";
                }

                string path = Diversos.PathArquivo(_arquivoProjeto.sNomebase, sTipo);

                var memory = new MemoryStream();
                using (var stream = new FileStream(path, FileMode.Open))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;
                return(File(memory, Diversos.GetContentType(path), Path.GetFileName(path)));
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #13
0
        public static string GetGraph(string id, string DtInicio, string DtFim, string Offset)
        {
            //Populating a DataTable from database.
            DataTable dt = new DataTable();

            dt.Columns.Add("D", typeof(double));
            //dt.Columns.Add("C", typeof(int));
            dt.Columns.Add("T", typeof(string));

            int maxOfRecords = 1000;

            if (string.IsNullOrWhiteSpace(Offset) || !Diversos.IsNumeric(Offset))
            {
                Offset = "0";
            }

            try
            {
                Maquina maquina = VARS.Maquinas.First(x => x.Id == Convert.ToInt32(id));

                //   int lastSec = -1;

                if (maquina == null)
                {
                    throw new Exception("máquina não encontrada!");
                }
                else
                if (maquina.GraficoPontos.GetPoints(DateTime.Parse(DtInicio), DateTime.Parse(DtFim).AddMinutes(1).AddSeconds(-1), Convert.ToDouble(Offset.Replace(".", ","))))
                {
                    //get stats
                    LAST_SEARCH_STATS.Clear();
                    //get class
                    LAST_CLASS_TABLE.Clear();

                    LAST_CLASS = Classificacoes.Classificacao.Undefined;

                    long numPointsClasse2 = 0;
                    long numPointsClasse3 = 0;
                    long numPointsNC      = 0;

                    Classificacoes.Classificacao lastClass = Classificacoes.Classificacao.Undefined;

                    int increment = (int)Math.Ceiling((double)maquina.GraficoPontos.Pontos.Count / maxOfRecords);

                    for (int i = 0; i < maquina.GraficoPontos.Pontos.Count; i++)
                    {
                        if (i % increment == 0 || (maquina.GraficoPontos.Pontos[i].Classe != Classificacoes.Classificacao.Conforme && maquina.GraficoPontos.Pontos[i].Classe != lastClass))
                        {
                            // dt.Rows.Add(Math.Round(maquina.GraficoPontos.Pontos[i].Value, 3), (int)maquina.GraficoPontos.Pontos[i].Classe, maquina.GraficoPontos.Pontos[i].DataHora.ToString("dd/MM/yyyy HH:mm:ss"));
                            dt.Rows.Add(Math.Round(maquina.GraficoPontos.Pontos[i].Value, 3), maquina.GraficoPontos.Pontos[i].DataHora.ToString("dd/MM/yyyy HH:mm:ss"));
                        }

                        if (LAST_CLASS_TABLE.Count < 1000)
                        {
                            if (maquina.GraficoPontos.Pontos[i].Classe != Classificacoes.Classificacao.Conforme)
                            {
                                if (maquina.GraficoPontos.Pontos[i].Classe != lastClass)
                                {
                                    LAST_CLASS_TABLE.Add(maquina.GraficoPontos.Pontos[i]);
                                }
                            }
                        }
                        lastClass = maquina.GraficoPontos.Pontos[i].Classe;


                        if (maquina.GraficoPontos.Pontos[i].Classe == Classificacoes.Classificacao.Classe2)
                        {
                            numPointsClasse2++;
                        }
                        else if (maquina.GraficoPontos.Pontos[i].Classe == Classificacoes.Classificacao.Classe3)
                        {
                            numPointsClasse3++;
                        }
                        else if (maquina.GraficoPontos.Pontos[i].Classe == Classificacoes.Classificacao.NaoConforme)
                        {
                            numPointsNC++;
                        }
                    }

                    //analise a conformidade da bobine
                    if (numPointsNC > 0 || numPointsClasse3 > maquina.Classe.MaxPontosClasse3 || numPointsClasse2 > maquina.Classe.MaxPontosClasse2)
                    {
                        LAST_CLASS = Classificacoes.Classificacao.NaoConforme;
                    }
                    else if (numPointsClasse3 > 0)
                    {
                        LAST_CLASS = Classificacoes.Classificacao.Classe3;
                    }
                    else if (numPointsClasse2 > 0)
                    {
                        LAST_CLASS = Classificacoes.Classificacao.Classe2;
                    }
                    else
                    {
                        LAST_CLASS = Classificacoes.Classificacao.Conforme;
                    }

                    //get stats
                    double aux = Math.Round(maquina.GraficoPontos.Pontos.Select(x => x.Value).Average(), 3);
                    LAST_SEARCH_STATS.Add(new Maquina.PontosGraph.DataPoint(aux, DateTime.Now, maquina.Classe.GetClassificacao(aux)));
                    LAST_SEARCH_STATS.Add(maquina.GraficoPontos.Minimum);
                    LAST_SEARCH_STATS.Add(maquina.GraficoPontos.Maximum);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetGraph(): " + ex.Message);

                return(string.Empty);
            }

            return(VARS.ConvertDataTabletoString(dt));
        }
コード例 #14
0
        public int GetChangerPassword(string sCNPJ, string password)
        {
            try
            {
                DateTime dDataEnvioHash = conn.Query <DateTime>("SELECT top(1) dDataEnvioHash FROM TB_INSTITUICAO WHERE sCNPJ =@sCNPJ ", new { sCNPJ }).FirstOrDefault();

                if (dDataEnvioHash <= DateTime.Now.AddDays(1))
                {
                    conn.Execute("UPDATE TB_INSTITUICAO SET sSenha=@sSenha,sHash = null,dDataEnvioHash = null WHERE sCNPJ = @sCNPJ ", new { sCNPJ, sSenha = Diversos.GenerateMD5(password) });
                    return(0);
                }
                else
                {
                    return(1);
                }
            }
            catch (Exception)
            {
                return(2);
            }
        }
コード例 #15
0
        public int GetSend(string sCNPJ)
        {
            try
            {
                var config = new ConfigurationBuilder()
                             .SetBasePath(Directory.GetCurrentDirectory())
                             .AddJsonFile("appsettings.json")
                             .Build();

                Instituicao _instituicao = conn.Query <Instituicao>("SELECT top(1) * FROM TB_INSTITUICAO WHERE sCNPJ =@sCNPJ ", new { sCNPJ }).FirstOrDefault();

                // generate a 128-bit salt using a secure PRNG
                byte[] salt = new byte[128 / 8];
                using (var rng = RandomNumberGenerator.Create())
                {
                    rng.GetBytes(salt);
                }

                string sHash = Convert.ToBase64String(KeyDerivation.Pbkdf2(
                                                          password: sCNPJ,
                                                          salt: salt,
                                                          prf: KeyDerivationPrf.HMACSHA1,
                                                          iterationCount: 10000,
                                                          numBytesRequested: 256 / 8));

                string pattern     = @"(?i)[^0-9a-záéíóúàèìòùâêîôûãõç\s]";
                string replacement = "";
                Regex  rgx         = new Regex(pattern);
                string result      = rgx.Replace(sHash, replacement);

                conn.Execute("UPDATE TB_INSTITUICAO SET sHash=@sHash,dDataEnvioHash=GETDATE() WHERE sCNPJ = @sCNPJ ", new { sCNPJ, sHash = result });

                string _body = "";
                _body  = "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>INSTITUIÇÃO</td></tr>";
                _body += "<tr style='=font-weight:bold;'>";
                _body += "<td font-weight:bold'><b>Proponente: </b>" + _instituicao.sProponente + "</td>";
                _body += "<td font-weight:bold'><b>CNPJ: </b>" + _instituicao.sCNPJ + "</td></tr>";

                _body += "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>Não consegue lembrar sua senha? Não tem problema, acontece com todos nós. Para criar uma nova senha, clique no link abaixo:</td></tr>";
                _body += config.GetSection(key: "Config")["sHostChangeSenha"] + result;

                string strBody = "";
                strBody = strBody + "<html>";
                strBody = strBody + "<head>";
                strBody = strBody + "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>";
                strBody = strBody + "<title>Untitled Document</title>";
                strBody = strBody + "</head>";
                strBody = strBody + "<body>";

                strBody = strBody + "<table style='font-family: verdana; font-size: 11px; color: #000000;' width='100%'>";
                strBody = strBody + "<tr align=center><td colspan=2><img src='cid:Imagem1' /></td></tr>";
                strBody = strBody + "<tr align=center><td colspan=2></td></tr>";
                strBody = strBody + "<tr style='=font-weight:bold;' align=center><td colspan=2>PROCURADORIA GERAL DE JUSTIÇA</td></tr>";
                strBody = strBody + "<tr style='=font-weight:bold;' align=center><td colspan=2>MINISTÉRIO PÚBLICO DO ESTADO DO CEARÁ</td></tr>";

                strBody = strBody + "<tr><td font-weight:bold'><p><p></td></tr> ";
                strBody = strBody + _body;
                strBody = strBody + "</table> ";
                strBody = strBody + "<br><br>";
                strBody = strBody + "Esta é uma  mensagem automática enviada pelo sistema. Não precisa responder.";
                strBody = strBody + "</body>";
                strBody = strBody + "</html>";

                Diversos.SendEmail(_instituicao.sEmail, "Mudança de senha FDID", strBody, null, null);

                return(1);
            }
            catch (Exception)
            {
                return(0);
            }
        }
コード例 #16
0
        public void SendEmail(int IDProjeto, int iTipo)
        {
            string _body   = "";
            string strBody = "";

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json")
                         .Build();

            Projeto _projeto = GetById(IDProjeto);

            _body  = "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>INSTITUIÇÃO</td></tr>";
            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'><b>Proponente: </b>" + _projeto.Instituicao.sProponente + "</td>";
            _body += "<td font-weight:bold'><b>CNPJ: </b>" + _projeto.Instituicao.sCNPJ + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'><b>Endereço: </b>" + _projeto.Instituicao.sEndereco + "</td>";
            _body += "<td font-weight:bold'><b>CEP: </b>" + _projeto.Instituicao.sCep + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'><b>Telefone: </b>" + _projeto.Instituicao.sTelefone + "</td>";
            _body += "<td font-weight:bold'<b>Fax: </b>" + _projeto.Instituicao.sFax + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold' colspan=2><b>Municipio: </b>" + _projeto.Instituicao.IDCidade + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'<b>Email: </b>" + _projeto.Instituicao.sEmail + "</td>";
            _body += "<td font-weight:bold'><b>HomePage: </b>" + _projeto.Instituicao.sHomePage + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";

            switch (_projeto.Instituicao.iRegime)
            {
            case 1:
                _body += "<td font-weight:bold'<b>Regime: </b>Direito Público</td>";

                break;

            case 2:
                _body += "<td font-weight:bold'<b>Regime: </b>Direito Privado</td>";

                break;
            }

            switch (_projeto.Instituicao.iEsfera)
            {
            case 1:
                _body += "<td font-weight:bold'<b>Esfera: </b>Federal</td></tr>";
                break;

            case 2:
                _body += "<td font-weight:bold'<b>Esfera: </b>Estadual</td></tr>";
                break;

            case 3:
                _body += "<td font-weight:bold'<b>Esfera: </b>Municipal</td></tr>";
                break;

            case 4:
                _body += "<td font-weight:bold'<b>Esfera: </b>Organização Ambientalista</td></tr>";
                break;

            case 5:
                _body += "<td font-weight:bold'<b>Esfera: </b>Outros</td></tr>";
                break;
            }

            _body += "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>REPRESENTANTE</td></tr>";

            _body += "<td font-weight:bold'><b>Representante: </b>" + _projeto.Instituicao.sRepresentante + "</td>";
            _body += "<td font-weight:bold'><b>Cpf: </b>" + _projeto.Instituicao.sCpfRepresentante + "</td>";
            _body += "<tr><td font-weight:bold'><b>Cargo: </b>" + _projeto.Instituicao.sCargo + "</td>";
            _body += "<td font-weight:bold'><b>Função: </b>" + _projeto.Instituicao.sFuncao + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Rg: </b>" + _projeto.Instituicao.sRG + "</td>";
            _body += "<td font-weight:bold'><b>Órgão Expedidor: </b>" + _projeto.Instituicao.sOrgaoExpedidor + "</td></tr>";
            _body += "<tr><td font-weight:bold' colspan=2><b>Endereço Representante: </b>" + _projeto.Instituicao.sEnderecoRepresentante + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Telefone: </b>" + _projeto.Instituicao.sTelefoneRepresentante + "</td>";
            _body += "<td font-weight:bold'><b>CEP: </b>" + _projeto.Instituicao.sCepRepresentante + "</td></tr>";

            _body += "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>COORDENADOR</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Coordenador: </b>" + _projeto.Instituicao.sCoordenador + "</td>";
            _body += "<td font-weight:bold'><b>Cpf: </b>" + _projeto.Instituicao.sCPFCoordenador + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Telefone: </b>" + _projeto.Instituicao.sTelefoneCoordenador + "</TD>";
            _body += "<td font-weight:bold'><b>Fax: </b>" + _projeto.Instituicao.sFaxCoordenador + "</td></tr>";

            _body += "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>PROJETO</td></tr>";

            _body += "<tr><td font-weight:bold' colspan=2><b>Título: </b>" + _projeto.sTitulo + "</td>";

            _body += "<tr><td font-weight:bold' colspan=2><b>Area </b></td></tr>";

            foreach (int item in _projeto.sArea)
            {
                switch (item)
                {
                case 1:
                    _body += "<tr><td font-weight:bold' colspan=2>Meio Ambiente</td></tr>";
                    break;

                case 2:
                    _body += "<tr><td font-weight:bold' colspan=2>Consumidor</td></tr>";
                    break;

                case 3:
                    _body += "<tr><td font-weight:bold' colspan=2>Defesa da Concorrencia</td></tr>";
                    break;

                case 4:
                    _body += "<tr><td font-weight:bold' colspan=2>Artístico</td></tr>";
                    break;

                case 5:
                    _body += "<tr><td font-weight:bold' colspan=2>Estítico</td></tr>";
                    break;

                case 6:
                    _body += "<tr><td font-weight:bold' colspan=2>Histórico</td></tr>";
                    break;

                case 7:
                    _body += "<tr><td font-weight:bold' colspan=2>Turístico</td></tr>";
                    break;

                case 8:
                    _body += "<tr><td font-weight:bold' colspan=2>Paisagismo</td></tr>";
                    break;

                case 9:
                    _body += "<tr><td font-weight:bold' colspan=2>Direitos Difusos</td></tr>";
                    break;

                case 10:
                    _body += "<tr><td font-weight:bold' colspan=2>Reaparelhamento e Modernização</td></tr>";
                    break;
                }
            }

            _body += "<tr><td font-weight:bold'><b>Município: </b>" + _projeto.IDCidade + "</td>";
            _body += "<tr><b>Número do Processo: </b>" + _projeto.sNoProcesso + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Início: </b>" + _projeto.dDataInicio + "</td>";
            _body += "<td font-weight:bold'><b>Termino: </b>" + _projeto.dDataTermino + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Valor do Projeto: </b>" + _projeto.mValor + "</td>";
            _body += "<td font-weight:bold'><b>Valor da Contrapartida: </b>" + _projeto.mValorContraPartida + "</td></tr>";
            _body += "<tr><td font-weight:bold' colspan=2><b>Resumo: </b>" + _projeto.tResumo + "</td></tr>";

            List <string> _anexos = new List <string>();

            foreach (Arquivo item in _projeto.Arquivo)
            {
                if (item != null)
                {
                    _anexos.Add(Diversos.PathArquivo(item.sNomebase, "PROJETO"));
                }
            }

            strBody = "";
            strBody = strBody + "<html>";
            strBody = strBody + "<head>";
            strBody = strBody + "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>";
            strBody = strBody + "<title>Untitled Document</title>";
            strBody = strBody + "</head>";
            strBody = strBody + "<body>";

            strBody = strBody + "<table style='font-family: verdana; font-size: 11px; color: #000000;' width='100%'>";
            strBody = strBody + "<tr align=center><td colspan=2><img src='cid:Imagem1' /></td></tr>";
            strBody = strBody + "<tr align=center><td colspan=2></td></tr>";
            strBody = strBody + "<tr style='=font-weight:bold;' align=center><td colspan=2>PROCURADORIA GERAL DE JUSTIÇA</td></tr>";
            strBody = strBody + "<tr style='=font-weight:bold;' align=center><td colspan=2>MINISTÉRIO PÚBLICO DO ESTADO DO CEARÁ</td></tr>";

            strBody = strBody + "<tr><td font-weight:bold'><p><p></td></tr> ";
            strBody = strBody + _body;
            strBody = strBody + "</table> ";
            strBody = strBody + "<br><br>";
            strBody = strBody + "<a href='" + config.GetSection(key: "Config")["sSite"] + "'>Clique aqui para visualizar o projeto na íntegra, incluindo arquivos anexados!<a>";
            strBody = strBody + "<br><br>";
            strBody = strBody + "Esta é uma  mensagem automática enviada pelo sistema. Não precisa responder.";
            strBody = strBody + "</body>";
            strBody = strBody + "</html>";

            string sTitulo;

            if (iTipo == 1)
            {
                sTitulo = "[PROJETOS FDID] Novo projeto cadastrado";
            }
            else
            {
                sTitulo = "Atualização do Projetos FDID";
            }

            Diversos.SendEmail(config.GetSection(key: "Config")["sEmailSend"], sTitulo, strBody, _anexos, _projeto.Instituicao.sEmail);
        }
コード例 #17
0
        public void SendEmail(int IDInstituicao)
        {
            string _body   = "";
            string strBody = "";

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json")
                         .Build();

            Instituicao _instituicao = GetById(IDInstituicao);

            _body  = "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>INSTITUIÇÃO</td></tr>";
            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'><b>Proponente: </b>" + _instituicao.sProponente + "</td>";
            _body += "<td font-weight:bold'><b>CNPJ: </b>" + _instituicao.sCNPJ + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'><b>Endereço: </b>" + _instituicao.sEndereco + "</td>";
            _body += "<td font-weight:bold'><b>CEP: </b>" + _instituicao.sCep + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'><b>Telefone: </b>" + _instituicao.sTelefone + "</td>";
            _body += "<td font-weight:bold'<b>Fax: </b>" + _instituicao.sFax + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold' colspan=2><b>Municipio: </b>" + _instituicao.IDCidade + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";
            _body += "<td font-weight:bold'<b>Email: </b>" + _instituicao.sEmail + "</td>";
            _body += "<td font-weight:bold'><b>HomePage: </b>" + _instituicao.sHomePage + "</td></tr>";

            _body += "<tr style='=font-weight:bold;'>";

            switch (_instituicao.iRegime)
            {
            case 1:
                _body += "<td font-weight:bold'<b>Regime: </b>Direito Público</td>";

                break;

            case 2:
                _body += "<td font-weight:bold'<b>Regime: </b>Direito Privado</td>";

                break;
            }

            switch (_instituicao.iEsfera)
            {
            case 1:
                _body += "<td font-weight:bold'<b>Esfera: </b>Federal</td></tr>";
                break;

            case 2:
                _body += "<td font-weight:bold'<b>Esfera: </b>Estadual</td></tr>";
                break;

            case 3:
                _body += "<td font-weight:bold'<b>Esfera: </b>Municipal</td></tr>";
                break;

            case 4:
                _body += "<td font-weight:bold'<b>Esfera: </b>Organização Ambientalista</td></tr>";
                break;

            case 5:
                _body += "<td font-weight:bold'<b>Esfera: </b>Outros</td></tr>";
                break;
            }

            _body += "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>REPRESENTANTE</td></tr>";

            _body += "<td font-weight:bold'><b>Representante: </b>" + _instituicao.sRepresentante + "</td>";
            _body += "<td font-weight:bold'><b>Cpf: </b>" + _instituicao.sCpfRepresentante + "</td>";
            _body += "<tr><td font-weight:bold'><b>Cargo: </b>" + _instituicao.sCargo + "</td>";
            _body += "<td font-weight:bold'><b>Função: </b>" + _instituicao.sFuncao + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Rg: </b>" + _instituicao.sRG + "</td>";
            _body += "<td font-weight:bold'><b>Órgão Expedidor: </b>" + _instituicao.sOrgaoExpedidor + "</td></tr>";
            _body += "<tr><td font-weight:bold' colspan=2><b>Endereço Representante: </b>" + _instituicao.sEnderecoRepresentante + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Telefone: </b>" + _instituicao.sTelefoneRepresentante + "</td>";
            _body += "<td font-weight:bold'><b>CEP: </b>" + _instituicao.sCepRepresentante + "</td></tr>";

            _body += "<tr bgcolor='#D6EFDA'><td colspan=2  style='font-weight:bold'>COORDENADOR</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Coordenador: </b>" + _instituicao.sCoordenador + "</td>";
            _body += "<td font-weight:bold'><b>Cpf: </b>" + _instituicao.sCPFCoordenador + "</td></tr>";
            _body += "<tr><td font-weight:bold'><b>Telefone: </b>" + _instituicao.sTelefoneCoordenador + "</TD>";
            _body += "<td font-weight:bold'><b>Fax: </b>" + _instituicao.sFaxCoordenador + "</td></tr>";

            strBody = "";
            strBody = strBody + "<html>";
            strBody = strBody + "<head>";
            strBody = strBody + "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>";
            strBody = strBody + "<title>Untitled Document</title>";
            strBody = strBody + "</head>";
            strBody = strBody + "<body>";

            strBody = strBody + "<table style='font-family: verdana; font-size: 11px; color: #000000;' width='100%'>";
            strBody = strBody + "<tr align=center><td colspan=2><img src='cid:Imagem1' /></td></tr>";
            strBody = strBody + "<tr align=center><td colspan=2></td></tr>";
            strBody = strBody + "<tr style='=font-weight:bold;' align=center><td colspan=2>PROCURADORIA GERAL DE JUSTIÇA</td></tr>";
            strBody = strBody + "<tr style='=font-weight:bold;' align=center><td colspan=2>MINISTÉRIO PÚBLICO DO ESTADO DO CEARÁ</td></tr>";

            strBody = strBody + "<tr><td font-weight:bold'><p><p></td></tr> ";
            strBody = strBody + _body;
            strBody = strBody + "</table> ";
            strBody = strBody + "<br><br>";
            strBody = strBody + "ATENÇÃO: O cadastro da instituição somente estará completo após a anexação dos arquivos relacionados à documentação comprobatória exigida em edital! ";
            strBody = strBody + "<a href='" + config.GetSection(key: "Config")["sSite"] + "'>Clique AQUI<a>";
            strBody = strBody + " para entrar no sistema e concluir o cadastro anexando os arquivos necessários.";
            strBody = strBody + "<br><br>";
            strBody = strBody + "Esta é uma  mensagem automática enviada pelo sistema. Não precisa responder.";
            strBody = strBody + "</body>";
            strBody = strBody + "</html>";

            Diversos.SendEmail(config.GetSection(key: "Config")["sEmailSend"], "[PROJETOS FDID] Nova instituição cadastrada", strBody, null, _instituicao.sEmail);
        }
コード例 #18
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string query = Request.QueryString["ID"];

            if (!string.IsNullOrEmpty(query) && Diversos.IsNumeric(query))
            {
                ID = Convert.ToInt32(query);
            }
            else
            {
                Response.Redirect("/index.aspx?id=1");
            }



            #region Get Maquinas

            try
            {
                if (VARS.UserSession.SessaoIniciada)
                {
                    if (VARS.Maquinas.Count == 0)
                    {
                        Response.Redirect("/notfound.html");
                    }
                    else
                    if (VARS.Maquinas.Count == 1)
                    {
                        divSelectMaquinas.Style.Add("display", "none");
                    }
                    else
                    {
                        StringBuilder strRadios = new StringBuilder();

                        for (int i = 0; i < VARS.Maquinas.Count; i++)
                        {
                            strRadios.AppendLine("<div class=\"form-check\">");
                            strRadios.AppendLine("<label class=\"form-check-label\">");
                            strRadios.AppendLine("<input type=\"radio\" class=\"form-check-input\" name=\"choice\" value=\"" + VARS.Maquinas[i].Id.ToString() + "\" onclick=\"RadioClick();\"" + (VARS.Maquinas[i].Id == ID ? "checked" : "") + " > ");
                            strRadios.AppendLine(VARS.Maquinas[i].Nome);
                            strRadios.AppendLine("</label>");
                            strRadios.AppendLine("</div>");
                            strRadios.AppendLine("<div class=\"form-check\">");
                            strRadios.AppendLine("&nbsp  &nbsp  &nbsp");
                            strRadios.AppendLine("</div>");
                        }

                        divRadioButtons.InnerHtml = strRadios.ToString();
                    }

                    Maquina maq = VARS.Maquinas.Find(x => x.Id == ID);

                    if (maq != null)
                    {
                        ControloDiametro control = (ControloDiametro)LoadControl("/ControloDiametro.ascx");

                        control.IdLinha = ID;

                        pnlEspacoMaquinas.Controls.Add(control);
                    }
                    else
                    {
                        Response.Redirect("/index.aspx?id=1");
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Page_Load(): " + ex.Message);
            }
            #endregion
        }
コード例 #19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Debug.WriteLine("ConsultarRegistos Page_Load");

            string id = Request.QueryString["ID"];

            if (!string.IsNullOrEmpty(id) && Diversos.IsNumeric(id))
            {
                ID = Convert.ToInt32(id);
            }

            if (this.Maquina == null || this.Maquina.Id != ID)
            {
                Response.Redirect("/notfound.html", true);
            }

            if (!IsPostBack)
            {
                this.Title = "Controlo de Produção - " + this.Maquina.Nome;
                this.lblNomeMaquina.InnerText = this.Maquina.Nome;

                //vai buscar as datas
                try
                {
                    string dtInicio = Request.QueryString["DtInicio"];
                    if (!string.IsNullOrEmpty(dtInicio))
                    {
                        if (!DateTime.TryParse(dtInicio, out dateTimes[0]))
                        {
                            throw new Exception("DtInicio parse error");
                        }
                    }

                    string dtFim = Request.QueryString["DtFim"];
                    if (!string.IsNullOrEmpty(dtFim))
                    {
                        if (!DateTime.TryParse(dtFim, out dateTimes[1]))
                        {
                            throw new Exception("DtFim parse error");
                        }
                    }

                    if (dateTimes[0] == DateTime.MinValue || dateTimes[1] == DateTime.MinValue)
                    {
                        throw new Exception("Datetime == MinValue");
                    }

                    if (dateTimes[0] >= dateTimes[1])
                    {
                        throw new Exception("DtInicio >= DtFim");
                    }

                    string textOfst = Request.QueryString["Offset"];
                    if (string.IsNullOrEmpty(textOfst))
                    {
                        textOfst = "0";
                    }

                    if (Diversos.IsNumeric(textOfst))
                    {
                        double value = Convert.ToDouble(textOfst.Replace(".", ","));

                        if (value != 0)
                        {
                            txtOffset.Value = Convert.ToDouble(textOfst.Replace(".", ",")).ToString("0.000");
                        }
                    }

                    if (Diversos.CheckForInternetConnection())
                    {
                        string dominio = Convert.ToString(SQLHelper.ExecuteScalar("SELECT Value FROM Settings WHERE Id = 1", VARS.ConnectionString));

                        idQrCode.Src = @"https://chart.googleapis.com/chart?chs=190x190&cht=qr&chl=" + dominio +
                                       "ConsultarRegistos.aspx?id=" + id + "%26DtInicio=" + dtInicio + "%26DtFim=" + dtFim + "%26Offset=" + textOfst + "%26key=" +
                                       new GetKeys().Encripta(dtFim + id.ToString() + textOfst.Replace(".", ",") + dtInicio).Replace("+", "X").Replace("=", "Y");;
                        idDisplayQrCode.Style.Add("display", "block");
                    }

                    if (!this.SessaoIniciada)
                    { //se nao tem sessao iniciada esconde o txt do offset e botao de refresh
                        txtOffset.Disabled = true;
                        txtOffset.Style.Add("display", "none");
                        btnRefresh.HRef = "#";
                        btnRefresh.Style.Add("display", "none");
                    }


                    this.OrdUpdateChart = true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Erro ao obter datas: " + ex.Message);

                    dateTimes[0] = DateTime.Today;
                    dateTimes[1] = DateTime.Today.AddDays(1).AddSeconds(-1);
                    //   idQrCode.Style.Add("display", "none");
                }
            }
        }
コード例 #20
0
        protected void btnIniciarSessao_ServerClick(object sender, EventArgs e)
        {
            try
            {
                if (VARS.UserSession.SessaoIniciada)
                {
                    throw new Exception("Já existe uma sessão iniciada!");
                }

                bool sessaoIniciou = false;
                int  idUsr         = 0;

                using (SqlConnection sqlConn = new SqlConnection(VARS.ConnectionString))
                {
                    using (SqlCommand sqlCmd = new SqlCommand("SELECT Id, Nome, Nivel, Avatar FROM UTILIZADORES WHERE Username LIKE @USER AND Password LIKE @PASS AND Id > 0", sqlConn))
                    {
                        sqlCmd.Parameters.Add("@USER", SqlDbType.NVarChar).Value = txtUsername.Value;
                        sqlCmd.Parameters.Add("@PASS", SqlDbType.NVarChar).Value = txtPassword.Value;

                        sqlConn.Open();

                        using (SqlDataReader dr = sqlCmd.ExecuteReader())
                            if (dr.Read())
                            {
                                idUsr         = Convert.ToInt32(dr[0]);
                                sessaoIniciou = VARS.UserSession.FazLogin(idUsr, Diversos.RemoveAcentos(Convert.ToString(dr[1])), Convert.ToInt32(dr[2]), Convert.ToInt32(dr[3]));
                            }
                            else
                            {
                                throw new Exception("Nenhum utilizador encontrado!");
                            }

                        sqlConn.Close();
                    }

                    if (sessaoIniciou)
                    {
                        using (SqlCommand sqlCmd = new SqlCommand("UPDATE UTILIZADORES SET UltimoAcesso = GETDATE() WHERE Id = @ID", sqlConn))
                        {
                            sqlCmd.Parameters.Add("@ID", SqlDbType.BigInt).Value = idUsr;

                            sqlConn.Open();

                            if (sqlCmd.ExecuteNonQuery() != 1)
                            {
                                throw new Exception("Erro ao atualizar datetime acesso em base de dados!");
                            }

                            sqlConn.Close();
                        }
                    }
                }

                if (sessaoIniciou)
                {
                    Response.Redirect("/index.aspx");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("btnLogin_ServerClick(): " + ex.Message);
                lblError.Visible = true;
            }
        }
コード例 #21
0
        protected void btnExportExcel_ServerClick(object sender, EventArgs e)
        {
            try
            {
                ExcelPackage pck = new ExcelPackage();

                List <double> columnWiths = new List <double>()
                {
                    15.43, 17.86, 15.43, 9.29, 13.43, 17.86, 0.83, 12.71, 9.29, 13.43, 11, 0.83, 13.43, 13.71, 15, 16, 0.83, 11, 9.29, 13.43
                };

                DateTime lastDate = DateTime.MinValue.Date;

                int linha   = 8;
                int wsIndex = 0;

                DateTime startDt = DateTime.MinValue;
                DateTime endDt   = DateTime.MinValue;

                foreach (Maquina.PontosGraph.DataPoint ponto in this.Maquina.GraficoPontos.Pontos)
                {
                    ExcelWorksheet ws = null;

                    #region é nova data
                    if (ponto.DataHora.Date != lastDate)
                    {
                        // Faz os cálculos da folha anterior antes de transicionar para a seguinte
                        if (pck.Workbook.Worksheets.Count > 0)
                        {
                            this.DoWorksheetCalcs(pck.Workbook.Worksheets[wsIndex], linha, startDt, endDt);
                        }

                        #region Cria uma nova folha

                        ws      = pck.Workbook.Worksheets.Add(ponto.DataHora.Date.ToString("dd/MM/yyyy"));
                        wsIndex = pck.Workbook.Worksheets.Count - 1;

                        ws.DefaultRowHeight = 15;

                        startDt = ponto.DataHora;

                        // Tamanho das Colunas
                        for (int i = 0; i < columnWiths.Count; i++)
                        {
                            ws.Column(i + 1).Width = columnWiths[i];
                        }


                        var pic = ws.Drawings.AddPicture("QR Code", Diversos.DownloadImagemFromWeb(idQrCode.Src));
                        pic.SetPosition(0, 1, 0, 18);

                        //  qr code
                        var cell = ws.Cells["A11:B12"];
                        cell.Value                     = "Este relatório pode ser consultado acedendo ao QR code acima";
                        cell.Merge                     = true;
                        cell.Style.WrapText            = true;
                        cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

                        //Titulo

                        cell = ws.Cells["C1:T4"];
                        this.SetCellStyle(cell, "Carta de Controlo de Produção", true, 22, ExcelHorizontalAlignment.Center, ExcelVerticalAlignment.Center);
                        cell.Merge = true;

                        //detalhes relatorio
                        cell = ws.Cells["C6:F6"];
                        this.SetCellStyle(cell, "Detalhes do Relatório", true, 12, ExcelHorizontalAlignment.Center, ExcelVerticalAlignment.Center);
                        cell.Merge = true;

                        ws.Cells["C7"].Value  = "Máquina";
                        ws.Cells["C8"].Value  = "Primeiro Registo";
                        ws.Cells["C9"].Value  = "Último Registo";
                        ws.Cells["C10"].Value = "Total Registos";
                        ws.Cells["C11"].Value = "Classificação";

                        cell = ws.Cells["D7:F7"];
                        this.SetCellStyle(cell, Maquina.Nome, true, 11, ExcelHorizontalAlignment.Center, ExcelVerticalAlignment.Center);
                        cell.Merge = true;

                        //calculos classe
                        for (int i = 0; i < 2; i++)
                        {
                            ws.Cells["E" + (8 + i).ToString()].Formula = "=IF(AND(D" + (8 + i).ToString() + " >= O8,D" + (8 + i).ToString() + " <= P8),\"Conforme\", IF(AND(D" + (8 + i).ToString() + " >= O9,D" + (8 + i).ToString() + " < P9),\"Classe 2\", IF(AND(D" + (8 + i).ToString() + " >= O10, D" + (8 + i).ToString() + " < P10),\"Classe 3\",\"Não Conforme\")))";
                            ws.Cells["E" + (8 + i).ToString()].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        }

                        ws.Cells["D11:F11"].Merge = true;

                        cell = ws.Cells["C6:F11"];
                        SetBorderCells(cell, ExcelBorderStyle.Thin);  //border around table
                        cell.Style.Border.BorderAround(ExcelBorderStyle.Medium);


                        //medias moveis
                        cell = ws.Cells["H6:K6"];
                        this.SetCellStyle(cell, "Médias Móveis", true, 12, ExcelHorizontalAlignment.Center);
                        cell.Merge = true;

                        this.SetCellStyle(ws.Cells["I7"], "Valor", true, 12, ExcelHorizontalAlignment.Center);
                        this.SetCellStyle(ws.Cells["J7"], "Classe", true, 12, ExcelHorizontalAlignment.Center);
                        this.SetCellStyle(ws.Cells["K7"], "Hora", true, 12, ExcelHorizontalAlignment.Center);

                        ws.Cells["H8"].Value  = "Valor Médio";
                        ws.Cells["H9"].Value  = "Valor Mínimo";
                        ws.Cells["H10"].Value = "Valor Máximo";
                        ws.Cells["H11"].Value = "Amplitude";

                        //calculos classe
                        for (int i = 0; i < 3; i++)
                        {
                            ws.Cells["J" + (8 + i).ToString()].Formula = "=IF(AND(I" + (8 + i).ToString() + " >= O8,I" + (8 + i).ToString() + " <= P8),\"Conforme\", IF(AND(I" + (8 + i).ToString() + " >= O9,I" + (8 + i).ToString() + " < P9),\"Classe 2\", IF(AND(I" + (8 + i).ToString() + " >= O10, I" + (8 + i).ToString() + " < P10),\"Classe 3\",\"Não Conforme\")))";
                            ws.Cells["J" + (8 + i).ToString()].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        }

                        cell = ws.Cells["H6:K11"];
                        SetBorderCells(cell, ExcelBorderStyle.Thin);  //border around table
                        cell.Style.Border.BorderAround(ExcelBorderStyle.Medium);

                        //Pontos fora de especificacao
                        cell = ws.Cells["M6:P6"];
                        this.SetCellStyle(cell, "Pontos Fora de Especificação", true, 12, ExcelHorizontalAlignment.Center);
                        cell.Merge = true;

                        this.SetCellStyle(ws.Cells["N7"], "Nº Pontos", true, 12, ExcelHorizontalAlignment.Center);
                        this.SetCellStyle(ws.Cells["O7"], "Limite Mínimo", true, 12, ExcelHorizontalAlignment.Center);
                        this.SetCellStyle(ws.Cells["P7"], "Limite Máximo", true, 12, ExcelHorizontalAlignment.Center);

                        ws.Cells["M8"].Value  = "Conforme";
                        ws.Cells["M9"].Value  = "Classe 2";
                        ws.Cells["M10"].Value = "Classe 3";
                        ws.Cells["M11"].Value = "Não Conforme";

                        //limit conform
                        ws.Cells["O8"].Value = Maquina.Classe.Conforme.Min;
                        ws.Cells["P8"].Value = Maquina.Classe.Conforme.Max;

                        //limit CLASSE 2
                        ws.Cells["O9"].Value = Maquina.Classe.Classe2.Min;
                        ws.Cells["P9"].Value = Maquina.Classe.Classe2.Max;

                        //limit CLASS 3
                        ws.Cells["O10"].Value = Maquina.Classe.Classe3.Min;
                        ws.Cells["P10"].Value = Maquina.Classe.Classe3.Max;

                        ////limit NC
                        //this.SetCellStyle(ws.Cells["O11"], "---", false, 11, ExcelHorizontalAlignment.Center);
                        //this.SetCellStyle(ws.Cells["P11"], "---", false, 11, ExcelHorizontalAlignment.Center);

                        cell = ws.Cells["M6:P11"];
                        SetBorderCells(cell, ExcelBorderStyle.Thin);  //border around table
                        cell.Style.Border.BorderAround(ExcelBorderStyle.Medium);

                        //Listagem de valores
                        cell = ws.Cells["R6:T6"];
                        this.SetCellStyle(cell, "Listagem de Pontos", true, 12, ExcelHorizontalAlignment.Center);
                        cell.Merge = true;

                        this.SetCellStyle(ws.Cells["R7"], "Hora", true, 12, ExcelHorizontalAlignment.Center);
                        this.SetCellStyle(ws.Cells["S7"], "Valor", true, 12, ExcelHorizontalAlignment.Center);
                        this.SetCellStyle(ws.Cells["T7"], "Classe", true, 12, ExcelHorizontalAlignment.Center);

                        linha = 8;
                        #endregion
                    }
                    lastDate = ponto.DataHora.Date;
                    #endregion

                    //add a new point

                    ws = pck.Workbook.Worksheets[wsIndex];

                    //data hora
                    var cells = ws.Cells["R" + linha.ToString()];
                    cells.Value = ponto.DataHora;
                    cells.Style.Numberformat.Format = "hh:mm:ss";

                    //VALUE
                    ws.Cells["S" + linha.ToString()].Value = ponto.Value;

                    //CLASSIFICACAO
                    cells         = ws.Cells["T" + linha.ToString()];
                    cells.Formula = "=IF(AND(S" + linha.ToString() + " >= O8,S" + linha.ToString() + " <= P8),\"Conforme\", IF(AND(S" + linha.ToString() + ">= O9,S" + linha.ToString() + "< P9),\"Classe 2\", IF(AND(S" + linha.ToString() + ">= O10, S" + linha.ToString() + "< P10),\"Classe 3\",\"Não Conforme\")))";
                    cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;


                    Color backColor = Color.White;

                    switch (ponto.Classe)
                    {
                    case Classificacoes.Classificacao.Conforme: backColor = Color.PaleGreen; break;

                    case Classificacoes.Classificacao.Classe2: backColor = Color.Yellow; break;

                    case Classificacoes.Classificacao.Classe3: backColor = Color.Orange; break;

                    case Classificacoes.Classificacao.NaoConforme: backColor = Color.Red; break;
                    }

                    if (backColor != Color.White)
                    {
                        this.SetCellsBackcolor(ws.Cells["R" + linha.ToString() + ":T" + linha.ToString()], backColor);
                    }

                    endDt = ponto.DataHora;


                    linha++;
                }

                //obrigatoriamente faz os calculos na ultima folha
                this.DoWorksheetCalcs(pck.Workbook.Worksheets[wsIndex], linha, startDt, endDt);


                #region EXPORT FILE TO CLIENT

                //EXPORT FILE TO CLIENT


                Response.Clear();
                Response.BinaryWrite(pck.GetAsByteArray());
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment;  filename=carta controlo.xlsx");
                Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                Response.End();
                #endregion
            }
            catch (Exception ex)
            {
                Debug.WriteLine("btnExportExcel_ServerClick(): " + ex.Message);
            }
        }
コード例 #22
0
 //public Instituicao GetAuthenticate(string cnpj, string password) => conn.Query<Instituicao>("SELECT * FROM TB_INSTITUICAO WHERE sCNPJ = '82246853000172' AND sSenha='81DC9BDB52D04DC20036DBD8313ED055' ", new { cnpj, password = Diversos.GenerateMD5(password) }).FirstOrDefault();
 public Instituicao GetAuthenticate(string cnpj, string password) => conn.Query <Instituicao>("SELECT * FROM TB_INSTITUICAO WHERE sCNPJ = @cnpj AND sSenha=@sSenha ", new { cnpj, sSenha = Diversos.GenerateMD5(password) }).FirstOrDefault();