Example #1
0
        public static void Eliminar_Departamento()
        {
            string        pasta   = ConfigurationManager.AppSettings["pasta"];
            string        caminho = pasta + "departamentos.json";
            string        dados   = "";
            Departamentos depart  = new Departamentos();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                depart.FromJson(dados);
            }
            catch
            {
            }
            string codigo = Valida_Input("Indique o código do departamento a ser eliminado:");

            if (string.IsNullOrEmpty(codigo))
            {
                return;
            }
            // determinar indice do departamento
            var           index = GetDepartamentos().Items.FindIndex(d => d.Codigo.Equals(codigo));
            Departamentos dpts  = GetDepartamentos();

            //delete
            dpts.Items.RemoveAt(index);
            Ficheiro.EscreverFicheiro(caminho, dpts.ToJson());
        }
 public void PutFicheiro(int id, Ficheiro ficheiro)
 {
     ficheiro.ficheiroId = id;
     if (ficheiro.ficheiroId == default(int) || !repository.Update(ficheiro))
     {
         throw new HttpResponseException(HttpStatusCode.NotFound);
     }
 }
        public HttpResponseMessage PostFicheiro(Ficheiro item)
        {
            item = repository.Insert(item);
            var response = Request.CreateResponse<Ficheiro>(HttpStatusCode.Created, item);

            //string uri = Url.Link("DefaultApi", new { id = item.ficheiroId });
            //response.Headers.Location = new Uri(uri);
            return response;
        }
 public FicheiroProxy(Ficheiro f, IContext ctx) : base()
 {
     context              = ctx;
     Nome                 = f.Nome;
     IDArtigo             = f.IDArtigo;
     NomeConferencia      = f.NomeConferencia;
     AnoConferencia       = f.AnoConferencia;
     base.ArtigoAssociado = null;
 }
        protected override Ficheiro Map(IDataRecord record)
        {
            Ficheiro f = new Ficheiro();

            f.Nome            = record.GetString(0);
            f.IDArtigo        = record.GetInt32(1);
            f.NomeConferencia = record.GetString(2);
            f.AnoConferencia  = record.GetInt32(3);
            return(new FicheiroProxy(f, context));
        }
 public void InsertOrUpdate(Ficheiro ficheiro)
 {
     if (ficheiro.ficheiroId == default(int))
     {
         context.Ficheiros.Add(ficheiro);
     }
     else
     {
         context.Entry(ficheiro).State = EntityState.Modified;
     }
 }
 public bool Update(Ficheiro ficheiro)
 {
     try
     {
         context.Entry(ficheiro).State = EntityState.Modified;
         return true;
     }
     catch (Exception ex)
     {
         return false;
     }
 }
Example #8
0
        private static void Formulario_Funcionario()
        {
            string       pasta   = ConfigurationManager.AppSettings["pasta"];
            string       caminho = pasta + "funcionarios.json";
            string       dados   = "";
            Funcionarios fncs    = new Funcionarios();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                fncs.FromJson(dados);
            }
            catch
            {
            }
            //instanciar o objecto
            Funcionario fnc = new Funcionario();

            //perguntar o codigo
            fnc.codigo = Valida_Input("Indique o codigo");
            if (string.IsNullOrEmpty(fnc.codigo))
            {
                return;
            }
            //perguntar o nome
            fnc.nome = Valida_Input("Indique o nome");
            if (string.IsNullOrEmpty(fnc.nome))
            {
                return;
            }
            //perguntar o data nascimento
            string NovoData = Valida_Input("Indique a data de nascimento");

            if (string.IsNullOrEmpty(NovoData))
            {
                return;
            }
            fnc.dataNascimento = DateTime.Parse(NovoData);
            foreach (Departamento d in GetDepartamentos().Items)
            {
                string frase = "{0} - {1}";
                Console.WriteLine(string.Format(frase, d.Codigo, d.Nome));
            }
            string dep = Valida_Input("Indique o departamento:");

            if (string.IsNullOrEmpty(dep))
            {
                return;
            }
            fnc.departamento = GetDepartamentos().FindByCodigo(dep);
            fncs.Items.Add(fnc);
            Ficheiro.EscreverFicheiro(caminho, fncs.ToJson());
        }
        protected override Ficheiro UpdateEntityKey(IDbCommand command, Ficheiro f)
        {
            var nomeUpdateKey            = command.Parameters["@nome"] as SqlParameter;
            var idArtigoUpdateKey        = command.Parameters["@idArtigo"] as SqlParameter;
            var nomeConferenciaUpdateKey = command.Parameters["@nomeConferencia"] as SqlParameter;
            var anoConferenciaUpdateKey  = command.Parameters["@anoConferencia"] as SqlParameter;

            f.Nome            = nomeUpdateKey.Value.ToString();
            f.IDArtigo        = int.Parse(idArtigoUpdateKey.Value.ToString());
            f.NomeConferencia = nomeConferenciaUpdateKey.Value.ToString();
            f.AnoConferencia  = int.Parse(anoConferenciaUpdateKey.Value.ToString());
            return(f);
        }
Example #10
0
 public void imgFundo(Boolean habilita = true)
 {
     if (habilita)
     {
         try
         {
             String localImagem = String.Format("{0}\\{1}", Ficheiro.getLocalExecutavel(), "logo.png");
             BackgroundImage       = new Bitmap(localImagem);
             BackgroundImageLayout = ImageLayout.Center;
         }
         catch (Exception erro)
         {
             Alert.erro("Erro ao carregar a imagem de fundo. " + erro.Message);
         }
     }
 }
Example #11
0
        public static void Editar_Departamento()
        {
            string pasta   = ConfigurationManager.AppSettings["pasta"];
            string caminho = pasta + "departamentos.json";

            foreach (Departamento d in GetDepartamentos().Items)
            {
                string frase = "{0} - {1}";
                Console.WriteLine(string.Format(frase, d.Codigo, d.Nome));
            }
            string codigo = Valida_Input("Indique o departamento:");

            if (string.IsNullOrEmpty(codigo))
            {
                return;
            }
            // determinar indice do departamento
            var           index = GetDepartamentos().Items.FindIndex(d => d.Codigo.Equals(codigo));
            Departamentos dpts  = GetDepartamentos();
            //perguntar o novo codigo
            string NovoCodigo = Valida_Input("Indique o novo codigo");

            if (string.IsNullOrEmpty(NovoCodigo))
            {
                return;
            }
            //recendo o novo código
            dpts.Items[index].Codigo = NovoCodigo;
            //perguntar o novo nome
            string NovoNome = Valida_Input("Indique o novo nome");

            if (string.IsNullOrEmpty(NovoNome))
            {
                return;
            }
            dpts.Items[index].Nome = NovoNome;

            //perguntar novo tipo
            string Novotipo = Valida_Input("Indique o novo tipo (0 - Interno, 1 - Externo");

            if (string.IsNullOrEmpty(Novotipo))
            {
                return;
            }
            dpts.Items[index].Tipo = (TipoDepartamento)int.Parse(Novotipo);
            Ficheiro.EscreverFicheiro(caminho, dpts.ToJson());
        }
Example #12
0
        public static Funcionarios GetFuncionarios()
        {
            string       pasta   = ConfigurationManager.AppSettings["pasta"];
            string       caminho = pasta + "funcionarios.json";
            string       dados   = "";
            Funcionarios dpts    = new Funcionarios();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                dpts.FromJson(dados);
            }
            catch
            {
            }
            return(dpts);
        }
Example #13
0
        public static void Editar_Funcionario()
        {
            string pasta   = ConfigurationManager.AppSettings["pasta"];
            string caminho = pasta + "funcionarios.json";

            foreach (Funcionario f in GetFuncionarios().Items)
            {
                string frase = "{0} - {1}";
                Console.WriteLine(string.Format(frase, f.codigo, f.nome));
            }
            string codigo = Valida_Input("Indique o código do funcionário:");

            if (string.IsNullOrEmpty(codigo))
            {
                return;
            }
            // determinar indice do departamento
            var          index = GetDepartamentos().Items.FindIndex(d => d.Codigo.Equals(codigo));
            Funcionarios funcs = GetFuncionarios();
            //perguntar o novo codigo
            string NovoCodigo = Valida_Input("Indique o novo codigo");

            if (string.IsNullOrEmpty(NovoCodigo))
            {
                return;
            }
            //recendo o novo código
            funcs.Items[index].codigo = NovoCodigo;
            //perguntar o novo nome
            string NovoNome = Valida_Input("Indique o novo nome");

            if (string.IsNullOrEmpty(NovoNome))
            {
                return;
            }
            funcs.Items[index].nome = NovoNome;
            //perguntar nova data nascimento
            string NovoData = Valida_Input("Indique a nova data de nascimento");

            if (string.IsNullOrEmpty(NovoData))
            {
                return;
            }
            funcs.Items[index].dataNascimento = DateTime.Parse(NovoData);
            Ficheiro.EscreverFicheiro(caminho, funcs.ToJson());
        }
Example #14
0
        public static Departamentos GetDepartamentos()
        {
            string        pasta   = ConfigurationManager.AppSettings["pasta"];
            string        caminho = pasta + "departamentos.json";
            string        dados   = "";
            Departamentos dpts    = new Departamentos();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                dpts.FromJson(dados);
            }
            catch
            {
            }
            return(dpts);
        }
Example #15
0
        static void Main(string[] args)
        {
            Individuos individuos     = new Individuos();
            string     pasta          = ConfigurationManager.AppSettings["pasta"];
            string     fileindividuos = pasta + "individuos1.txt";

            //caso o ficheiro não exista o bloco try-catch captura o erro
            try
            {
                string conteudo = Ficheiro.LerFicheiro(fileindividuos);
                if (!String.IsNullOrEmpty(conteudo))
                {
                    individuos.FromJson(conteudo);
                }
            }
            catch (Exception ex)
            {
                //informação de debug
                Debug.Print(ex.Message);
                //informação para o utilizador
                Console.WriteLine(ex.Message);
            }
            string xml             = individuos.ToXML();
            string fileindividuos1 = pasta + "individuos1.xml";

            Ficheiro.EscreverFicheiro(fileindividuos1, xml);

            try
            {
                string conteudo = Ficheiro.LerFicheiro(fileindividuos1);
                if (!String.IsNullOrEmpty(conteudo))
                {
                    individuos.FromXML(conteudo);
                    Console.WriteLine(individuos.Items.Count.ToString());
                }
            }
            catch (Exception ex)
            {
                //informação de debug
                Debug.Print(ex.Message);
                //informação para o utilizador
                Console.WriteLine(ex.Message);
            }
        }
        protected override void InsertParameters(IDbCommand command, Ficheiro f)
        {
            SqlParameter nomeInsertUpdate            = new SqlParameter("@nome", f.Nome);
            SqlParameter idArtigoInsertUpdate        = new SqlParameter("@idArtigo", f.IDArtigo);
            SqlParameter nomeConferenciaInsertUpdate = new SqlParameter("@nomeConferencia", f.NomeConferencia);
            SqlParameter anoConferenciaInsertUpdate  = new SqlParameter("@anoConferencia", f.AnoConferencia);

            /*p1.Direction = ParameterDirection.InputOutput;
             * if (f.IDArtigo != null)
             *  p1.Value = f.IDArtigo;
             * else
             *  p1.Value = DBNull.Value;
             */

            command.Parameters.Add(nomeInsertUpdate);
            command.Parameters.Add(idArtigoInsertUpdate);
            command.Parameters.Add(nomeConferenciaInsertUpdate);
            command.Parameters.Add(anoConferenciaInsertUpdate);
        }
Example #17
0
        public static void Pesquisar_Departamento()
        {
            Console.WriteLine("Indique o nome");
            string pesquisa = Console.ReadLine();

            string        pasta   = ConfigurationManager.AppSettings["pasta"];
            string        caminho = pasta + "departamentos.json";
            string        dados   = "";
            Departamentos dpts    = new Departamentos();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                dpts.FromJson(dados);

                //Query sintax
                // nome exacto
                var resultado = from d in dpts.Items where d.Nome == pesquisa select d;
                foreach (var r in resultado)
                {
                    Console.WriteLine(r.Nome);
                }

                // like nome
                var resultado1 = from d in dpts.Items where d.Nome.Contains(pesquisa) select d;
                //method syntax
                var resultado2 = dpts.Items.Where(d => d.Nome.Contains(pesquisa)).Select(d => d.Codigo);

                var resultado3 = dpts.Items.Where(d => d.Nome.Contains(pesquisa)).Select(d => new { Name = d.Nome, Code = d.Codigo }).ToList();

                foreach (var r in resultado3)
                {
                    Console.WriteLine(r.Code);
                }
                //contagem de departamentos por tipo de departamento
                var resultado4 = dpts.Items.GroupBy(d => d.Tipo).Select(d => new { tipo = d.Key, Contagem = d.Count() });
            }
            catch
            {
            }
        }
Example #18
0
        private static void Formulario_Departamento()
        {
            string        pasta   = ConfigurationManager.AppSettings["pasta"];
            string        caminho = pasta + "departamentos.json";
            string        dados   = "";
            Departamentos dpts    = new Departamentos();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                dpts.FromJson(dados);
            }
            catch
            {
            }
            //instanciar o objecto
            Departamento dpt = new Departamento();

            //perguntar o codigo
            dpt.Codigo = Valida_Input("Indique o codigo");
            if (string.IsNullOrEmpty(dpt.Codigo))
            {
                return;
            }
            //perguntar o nome
            dpt.Nome = Valida_Input("Indique o nome");
            if (string.IsNullOrEmpty(dpt.Nome))
            {
                return;
            }
            //perguntar tipo
            string tipo = Valida_Input("Indique o tipo (0 - Interno, 1 - Externo");

            if (string.IsNullOrEmpty(tipo))
            {
                return;
            }
            dpt.Tipo = (TipoDepartamento)int.Parse(tipo);
            dpts.Items.Add(dpt);
            Ficheiro.EscreverFicheiro(caminho, dpts.ToJson());
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Titulo,Descricao,Observacao,Dono,Local,DateUpload,AreaFK")] Ficheiro ficheiro)
        {
            //verifica se o user tem a conta suspensa
            var user = await _userManager.GetUserAsync(User);

            var util = await _context.Utilizadores.FirstOrDefaultAsync(u => u.Aut == user.Id);

            if (util.Suspenso)
            {
                return(View("Suspenso"));
            }

            if (id != ficheiro.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try{
                    _context.Update(ficheiro);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException) {
                    if (!FicheiroExists(ficheiro.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["AreaFK"] = new SelectList(_context.Areas, "Id", "Nome", ficheiro.AreaFK);
            ViewData["Dono"]   = new SelectList(_context.Utilizadores, "Id", "Nome", ficheiro.Dono);
            return(View(ficheiro));
        }
Example #20
0
        public static void Listar_Departamento()
        {
            string        pasta   = ConfigurationManager.AppSettings["pasta"];
            string        caminho = pasta + "departamentos.json";
            string        dados   = "";
            Departamentos dpts    = new Departamentos();

            try
            {
                dados = Ficheiro.LerFicheiro(caminho);
                dpts.FromJson(dados);

                //Query sintax
                var resultado = from d in dpts.Items select d;
                foreach (var r in resultado)
                {
                    Console.WriteLine(r.Nome);
                }
            }
            catch
            {
            }
        }
 protected override void DeleteParameters(IDbCommand command, Ficheiro f)
 => SelectParameters(command, new Tuple <string, int, string, int>(f.Nome, f.IDArtigo, f.NomeConferencia, f.AnoConferencia));
        public Task<ResultResponse<EnvioFicheiroResult>> Post()
        {
            ResultResponse<EnvioFicheiroResult> resposta = new ResultResponse<EnvioFicheiroResult>();


            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            UserProfile user = null;

            if (WebSecurity.IsAuthenticated)
            {
                user = usersRepository.GetUserByIDIncludeEntidade(WebSecurity.CurrentUserId);
            }
            else
            {
                string username = string.Empty;

                IEnumerable<string> headerVals;
                if (Request.Headers.TryGetValues("Authorization", out headerVals))
                {
                    string authHeader = headerVals.FirstOrDefault();
                    char[] delims = { ' ' };
                    string[] authHeaderTokens = authHeader.Split(new char[] { ' ' });
                    if (authHeaderTokens[0].Contains("Basic"))
                    {
                        string decodedStr = BasicAuthorizeAttribute.DecodeFrom64(authHeaderTokens[1]);
                        string[] unpw = decodedStr.Split(new char[] { ':' });
                        username = unpw[0];
                    }
                    else
                    {
                        if (authHeaderTokens.Length > 1)
                            username = BasicAuthorizeAttribute.DecodeFrom64(authHeaderTokens[1]);
                    }
                }

                user = usersRepository.All.Include("entidade").Single(u => u.UserName == username);
            }

            if (user == null)
            {
                resposta.Success = false;
                resposta.ErrorMessage += "Erro de autenticação.";
            }


            //List<ValorSistema> paramSistema = valoresSistemaRepository.All.Where(v => v.tipologia == "ESTADO_FICHEIRO"
            //                                                                    || v.tipologia == "TIPO_NOTIFICACAO"
            //                                                                    || v.tipologia == "PARAM_PASTA_FICHEIROS").ToList();
            //List<ValorSistema> estadosFicheiro = paramSistema.Where(v => v.tipologia == "ESTADO_FICHEIRO").ToList();
            //List<ValorSistema> tiposNotificao = paramSistema.Where(v => v.tipologia == "TIPO_NOTIFICACAO").ToList();
            //ValorSistema pastaUpload = paramSistema.Where(v => v.tipologia == "PARAM_PASTA_FICHEIROS").Single();

            List<ValorSistema> estadosFicheiro = valoresSistemaRepository.GetPorTipologia("ESTADO_FICHEIRO");
            List<ValorSistema> tiposNotificao = valoresSistemaRepository.GetPorTipologia("TIPO_NOTIFICACAO");
            ValorSistema pastaUpload = valoresSistemaRepository.GetPorTipologia("PARAM_PASTA_FICHEIROS").Single();
            

            var root = pastaUpload.valor;
            //string root = System.Web.HttpContext.Current.Server.MapPath(destination);
            var provider = new MultipartFormDataStreamProvider(root);

            if (resposta.Success == false)
            {
                request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<ResultResponse<EnvioFicheiroResult>>(o =>
                { return resposta; });
            }

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<ResultResponse<EnvioFicheiroResult>>(o =>
                {
                    try
                    {
                        
                        FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                        DateTime dataSubmissao = DateTime.Now;

                        string guid = Guid.NewGuid().ToString();
                        string filePath = provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "");
                        filePath = filePath.Substring(filePath.LastIndexOf('\\') + 1);

                        var filename = Path.GetFileNameWithoutExtension(filePath);
                        var fileExtension = Path.GetExtension(filePath);
                        var newFilename = filename + "_" + dataSubmissao.ToString("yyyyMMddHHmmssfff") + fileExtension;
                        var path = Path.Combine(root, newFilename);
                        File.Move(finfo.FullName, path);


                        Ficheiro newFicheiro = new Ficheiro
                        {
                            nomeFicheiro = filename,
                            localizacao = path,
                            dataUpload = dataSubmissao,
                            dataAlteracao = dataSubmissao,
                            entidadeId = user.entidadeId,
                            estadoId = estadosFicheiro.Where(f => f.valor == "PENDENTE").Single().valorSistemaId,
                            userName = user.UserName
                        };

                        Notificacao notificacao = new Notificacao
                        {
                            dataCriacao = DateTime.Now,
                            entidadeId = user.entidadeId,
                            tipologiaId = tiposNotificao.Where(f => f.valor == "SUCESSO_RECECAO_FICHEIRO").Single().valorSistemaId,
                            mensagem = "Ficheiro '" +filename+ "' recebido com sucesso (via WebService)",
                        };

                        ficheirosRepository.Insert(newFicheiro);

                        Entidade entidade = entidadesRepository.Find((int)notificacao.entidadeId);

                        entidade.notificacoes.Add(notificacao);
                        entidadesRepository.Save();
                        notificacoesRepository.Save();
                        ficheirosRepository.Save();


                        EnvioFicheiroResult resultado = new EnvioFicheiroResult { dataRecepcao = newFicheiro.dataUpload, nomeFicheiro = filePath, seguradora = entidade.nome };

                        resposta.Success = true;
                        resposta.Result = resultado;

                        return resposta;
                    }
                    catch (Exception e)
                    {
                        resposta.Success = false;
                        resposta.ErrorMessage += "Erro na recepção do Ficheiro";
                        resposta.Result = null;
                        
                        return resposta;
                    }
                }
            );
            return task;
        }
 protected override void UpdateParameters(IDbCommand command, Ficheiro f) => InsertParameters(command, f);
 public override Ficheiro Update(Ficheiro entity)
 {
     return(new FicheiroProxy(base.Update(entity), context));
 }
Example #25
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Titulo,Descricao,Observacao,Local,Tipo,DateUpload,Dono,AreaFK")] Ficheiro ficheiro, IFormFile fich)
        {
            if (id != ficheiro.Id)
            {
                return(NotFound());
            }

            // vars. auxiliares
            string caminhoCompleto = "", ficheiroVelho = "";
            bool   haFicheiro = false;

            //coloca na data actual na entrada do ficheiro na base de dados
            ficheiro.DateUpload = DateTime.Now;

            //verifica se o user que está a fazer upload não tem a conta suspensa
            var user = await _userManager.GetUserAsync(User);

            var util = await _context.Utilizadores.FirstOrDefaultAsync(u => u.Aut == user.Id);

            if (util.Suspenso)
            {
                return(View("Suspenso"));
            }

            //relaciona na base de dados o ficheiro ao utilizador que o criou
            ficheiro.Dono = util.Id;

            // se o ficheiro nao existir, retorna para a mesma view de onde foi carregado mas agora com uma mensagem de erro
            if (fich == null)
            {
                ViewBag.bad        = "null";
                ViewData["AreaFK"] = new SelectList(_context.Areas, "Id", "Nome", ficheiro.AreaFK);
                return(View(ficheiro));
            }
            //se o ficheiro existir
            else
            {
                //cria uma string unica para por como nome
                Guid g;
                g = Guid.NewGuid();
                //retira a extenção do ficheiro
                string extensao = Path.GetExtension(fich.FileName).ToLower();
                //concatena a string com a extenção do ficheiro para criar um novo nome
                string nome = g.ToString() + extensao;
                //coloca na variavel o nome completo do ficheiro em questão concatenado com o seu caminho(directorio)
                caminhoCompleto = Path.Combine(_caminho.WebRootPath, "Documentos", nome);
                //na entrada da base de dados, coloca no Local o caminho do ficheiro para futuros downloads e na variavel ficheiroVelho o nome do antigo ficheiro para depois o mesmo ser apagado
                ficheiroVelho  = ficheiro.Local;
                ficheiro.Local = nome;
                //confirma que há ficheiro
                haFicheiro = true;
            }

            if (ModelState.IsValid)
            {
                try {
                    _context.Update(ficheiro);
                    await _context.SaveChangesAsync();

                    if (haFicheiro)
                    {
                        //se há ficheiro, apaga-se o velho e guarda-se o novo
                        System.IO.File.Delete("./wwwroot/Documentos/" + ficheiroVelho);
                        using var stream = new FileStream(caminhoCompleto, FileMode.Create);
                        await fich.CopyToAsync(stream);
                    }
                }
                catch (DbUpdateConcurrencyException) {
                    if (!FicheiroExists(ficheiro.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                catch (Exception) {
                    ViewBag.bad = "erro";
                }
                return(RedirectToAction(nameof(Index)));
            }

            ViewData["Local"]  = ficheiro.Local;
            ViewData["AreaFK"] = new SelectList(_context.Areas, "Id", "Nome", ficheiro.AreaFK);
            return(View(ficheiro));
        }
        public static void processaFicheiro(Ficheiro ficheiro){

            ValorSistemaRepository valoresSistemaRepository = new ValorSistemaRepository();

            //List<ValorSistema> valSistema = valoresSistemaRepository.All.Where(v => v.tipologia == "ESTADO_EVENTO_STAGGING" || v.tipologia == "OPERACAO_EVENTO").ToList();

            //List<ValorSistema> estadosEvento = valSistema.Where(v => v.tipologia == "ESTADO_EVENTO_STAGGING").ToList();
            //List<ValorSistema> operacoesEvento = valSistema.Where(v => v.tipologia == "OPERACAO_EVENTO").ToList();

            List<ValorSistema> estadosEvento = valoresSistemaRepository.GetPorTipologia("ESTADO_EVENTO_STAGGING");
            List<ValorSistema> operacoesEvento = valoresSistemaRepository.GetPorTipologia("OPERACAO_EVENTO");
            List<ValorSistema> tiposErro = valoresSistemaRepository.GetPorTipologia("TIPO_ERRO");
            List<ValorSistema> estadosFicheiro = valoresSistemaRepository.GetPorTipologia("ESTADO_FICHEIRO");

            ReporteOcorrenciasMatricula reporte;

            XmlSerializer serializer = new XmlSerializer(typeof(ReporteOcorrenciasMatricula));
            using (FileStream fileStream = new FileStream(ficheiro.localizacao, FileMode.Open))
            {
                reporte = (ReporteOcorrenciasMatricula)serializer.Deserialize(fileStream);
            }

            if (reporte.Cabecalho.CodigoEstatistico != ficheiro.entidade.codigoEntidade)
            {
                ErroFicheiro erroFicheiro = new ErroFicheiro(){ dataValidacao = DateTime.Now, 
                                                                tipologiaId = tiposErro.Single(e => e.valor == "GENERICO").valorSistemaId,
                                                                descricao = "Ficheiro reportado pela entidade com código '" + ficheiro.entidade.codigoEntidade + "' e com registos relativos à entidade '" + reporte.Cabecalho.CodigoEstatistico + "'.",
                                                                ficheiroId = ficheiro.ficheiroId };

                ErroFicheiroException ex = new ErroFicheiroException();
                ex.errosFicheiro.Add(erroFicheiro);

                throw ex;
            }

            ReporteOcorrenciasFNMPAS reporteOcorrenciasFNMPAS = new ReporteOcorrenciasFNMPAS(reporte);
            reporteOcorrenciasFNMPAS.ordenaOcorrencias();
           

            for (int i = 0; i < reporteOcorrenciasFNMPAS.OcorrenciaOrdenada.Count(); i++)
            {
                ReporteOcorrenciasMatriculaOcorrenciaOrdenada ocorrencia = reporteOcorrenciasFNMPAS.OcorrenciaOrdenada[i];

                //evento Duplicado e esmagado com os novos dados. (C M - stagging/producao) (A - producao/stagging) 
                //Não foi ainda inserido na Base de dados nem houve delete logico do anterior. 
                //Fazer deletes logicos, e inserções após verificações.
                //Anulações podem necessitar logica adicional caso a validação falhe. (duplicar registo em stagging)
                EventoStagging evento = new EventoStagging();
                
                int codigoOperacaoId = 0;
                switch (ocorrencia.CodigoOperacao)
                {
                    case ReporteOcorrenciasMatriculaOcorrenciaCodigoOperacao.C: codigoOperacaoId = operacoesEvento.Where(o=> o.valor =="C").Single().valorSistemaId; break;
                    case ReporteOcorrenciasMatriculaOcorrenciaCodigoOperacao.M: codigoOperacaoId = operacoesEvento.Where(o=> o.valor =="M").Single().valorSistemaId; break;
                    case ReporteOcorrenciasMatriculaOcorrenciaCodigoOperacao.A: codigoOperacaoId = operacoesEvento.Where(o=> o.valor =="A").Single().valorSistemaId; break;
                    default: codigoOperacaoId = operacoesEvento.Where(o => o.valor == "C").Single().valorSistemaId; break;
                }
                evento.esmagaDados(ocorrencia, ficheiro, codigoOperacaoId);

                evento.estadoEventoId = estadosEvento.Where(e => e.valor == "PENDENTE").Single().valorSistemaId;

                ficheiro.eventosStagging.Add(evento);
            }

            //EventoStaggingRepository eventosStaggingRepository = new EventoStaggingRepository();
            //eventosStaggingRepository.InsertOrUpdate(evento);
            //eventosStaggingRepository.Save();
        }
Example #27
0
 private void btnEnviar_Click(object sender, EventArgs e)
 {
     try
     {
         Boolean prossegue = true;
         String  qtEmail   = "";
         relatorio.Prepare();
         prossegue = Valida.verificaObrigatorios(new Object[] { txtTitulo, txtObservacao });
         if (prossegue)
         {
             for (int i = 0; i < email.Count; i++)
             {
                 qtEmail += Convert.ToString(email.ElementAt(i).ds_email);
                 if (i != email.Count - 1)
                 {
                     qtEmail += ";";
                 }
             }
             if (!qtEmail.Equals(""))
             {
                 usuario = Classes.Acesso.cadUsuarioDAO.getUsuario(StaticVariables.cdUsuario);
                 Utilidades.enviaEmail(new String[] { Utilidades.exportaRelPDF(@"C:\TEMP", Ficheiro.retornaNomeArquivo(relatorio.FileName), relatorio) },
                                       usuario.ds_smtp, usuario.nr_porta, usuario.st_ssl, usuario.ds_email, usuario.ds_senha, usuario.ds_email, qtEmail, txtTitulo.Text, txtObservacao.Text);
                 pnEmail.Visible = false;
             }
             else
             {
                 Alert.atencao("É necessário informar pelo menos um e-mail.");
                 txtEmail.Focus();
             }
         }
     }
     catch (Exception erro)
     {
         Alert.erro(String.Format("Erro ao enviar o e-mail: {0}\n{1}", txtEmail.Text, erro.Message));
     }
 }
 public Ficheiro Insert(Ficheiro ficheiro)
 {
     ficheiro.ficheiroId = default(int);
     context.Ficheiros.Add(ficheiro);
     return ficheiro;
 }
Example #29
0
        public static void TrataIndividuos()
        {
            //como estamos colocando em uma outra classe, e utilizando
            //uma interface não precisamos mais da linha abaixo, nós escondemos a complexidade
            //List<Individuo1> lst = new List<Individuo1>();
            Individuos individuos     = new Individuos();
            string     pasta          = ConfigurationManager.AppSettings["pasta"]; // C:\Users\JEMA\OneDrive\Documentos\Nova pasta\\individuos.txt";
            string     fileIndividuos = pasta + "individuo.txt";

            try
            {
                string conteudo = Ficheiro.LerFicheiro(fileIndividuos); //não precisa instanciar o ojeto Ficheiro porque o método é static
                if (!String.IsNullOrEmpty(conteudo))
                {
                    individuos.FromJson(conteudo);//como estamos colocando em uma outra classe, e utilizando
                    //uma interface não precisamos mais da linha abaixo, nós escondemos a complexidade
                    //lst = JsonConvert.DeserializeObject<List<Individuo1>>(conteudo);
                }
            }
            catch (Exception ex)
            {
                //informação no output do debug
                Debug.Print(ex.Message);
                //informação do utilizador
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Seja bem vindo");
            Boolean continuar = false;
            int     contador  = 0;

            do
            {
                Individuo1 obj = Gravar();
                //como estamos colocando em uma outra classe, e utilizando
                //uma interface não precisamos mais da linha abaixo, nós escondemos a complexidade
                //lst.Add(obj);
                individuos.Items.Add(obj);//Items é uma lista
                //Console.WriteLine(obj.NomeCompleto());

                Console.WriteLine("Deseja introduzir outro individuo? 1 - sim, 0 - não");
                string op = Console.ReadLine();
                continuar = (op == "1");
                contador++;
            } while (continuar);

            Console.WriteLine("Foram introduzidos " + contador + " indivíduos");

            //como estamos colocando em uma outra classe, e utilizando
            //uma interface não precisamos mais da linha abaixo, nós escondemos a complexidade
            //string json = JsonConvert.SerializeObject(lst);
            string json = individuos.ToJson();

            //Console.WriteLine(json);

            try
            {
                if (Ficheiro.EscreverFicheiro(fileIndividuos, json))
                {
                    Console.WriteLine("O registro foi criado!");
                }
                else
                {
                    Console.WriteLine("O registro não foi criado.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            //Militar objM = new Militar();
            //objM.CC = "123456789";
            //objM.nif = "9999999";
            //objM.nome = "Sergio";
            //objM.apelido = "Fontes";
            //objM.datanascimento = new DateTime(1976, 8, 25);
            //objM.CM = "342342";
            //objM.Patente = "Mancebo";
            //Console.WriteLine(objM.NomeCompleto());

            //Console.ReadLine();



            /* _______________________________________________________________________
             *                               AULA 16/03/2020
             * _______________________________________________________________________
             * Console.WriteLine("Hello World!");
             *
             * //instanciar uma classe
             * //Individuo obj = new Individuo();
             * //obj.Nome = "Myrella";
             * //obj.Apelido = "Gomes";
             * //obj.DataNascimento = new DateTime(1985, 01, 03);
             *
             * //a partir do momento que temos cosntrutores podemos instanciar desta maneira abaixo ao invés da anterior
             * Individuo obj = new Individuo("Myrella", "Gomes", new DateTime(1985, 01, 03)); //passando argumento por valor
             * Individuo obj1 = new Individuo(apelido: "Gomes", nome: "Myrella", dataNasc: new DateTime(1985, 01, 03));//passando agumento por nome do parametro
             *
             * obj.Empresa.Nome = "Rumos";
             * obj.Empresa.Area = "Formação";
             *
             * obj.MyDebug();
             * string tmp = obj.Imprimir();
             *
             * Console.WriteLine(tmp);
             * Console.ReadLine();//coloca para a aplicação ficar a espera*/
        }
        public ResultResponse<EnvioOcorrenciasResult> Post([FromBody]ReporteOcorrenciasMatricula ocorrencias)
        {
            ResultResponse<EnvioOcorrenciasResult> resposta = new ResultResponse<EnvioOcorrenciasResult>();

            //List<ValorSistema> paramSistema = valoresSistemaRepository.All.Where(v => v.tipologia == "ESTADO_EVENTO_STAGGING"
            //                                                                    || v.tipologia == "OPERACAO_EVENTO"
            //                                                                    || v.tipologia == "PARAM_PASTA_FICHEIROS").ToList();
            //List<ValorSistema> estadosEvento = paramSistema.Where(v => v.tipologia == "ESTADO_EVENTO_STAGGING").ToList();
            //List<ValorSistema> operacoesEvento = paramSistema.Where(v => v.tipologia == "OPERACAO_EVENTO").ToList();
            //ValorSistema pastaUpload = paramSistema.Where(v => v.tipologia == "PARAM_PASTA_FICHEIROS").Single();

            List<ValorSistema> estadosEvento = valoresSistemaRepository.GetPorTipologia("ESTADO_EVENTO_STAGGING");
            List<ValorSistema> operacoesEvento = valoresSistemaRepository.GetPorTipologia("OPERACAO_EVENTO");
            ValorSistema pastaUpload = valoresSistemaRepository.GetPorTipologia("PARAM_PASTA_FICHEIROS").Single();

            
            if (ocorrencias == null || ocorrencias.Ocorrencia == null)
            {
                resposta.Success = false;
                resposta.ErrorMessage = "Erro na recepção de ocorrências. Mensagem mal formada.";
            }

            UserProfile user = null;

            if (WebSecurity.IsAuthenticated)
            {
                user = usersRepository.GetUserByIDIncludeEntidade(WebSecurity.CurrentUserId);
            }
            else
            {
                string username = string.Empty;

                IEnumerable<string> headerVals;
                if (Request.Headers.TryGetValues("Authorization", out headerVals))
                {
                    string authHeader = headerVals.FirstOrDefault();
                    char[] delims = { ' ' };
                    string[] authHeaderTokens = authHeader.Split(new char[] { ' ' });
                    if (authHeaderTokens[0].Contains("Basic"))
                    {
                        string decodedStr = BasicAuthorizeAttribute.DecodeFrom64(authHeaderTokens[1]);
                        string[] unpw = decodedStr.Split(new char[] { ':' });
                        username = unpw[0];
                    }
                    else
                    {
                        if (authHeaderTokens.Length > 1)
                            username = BasicAuthorizeAttribute.DecodeFrom64(authHeaderTokens[1]);
                    }
                }

                user = usersRepository.GetUserByUsernameIncludeEntidade(username);
            }

            if (user == null)
            {
                resposta.Success = false;
                resposta.ErrorMessage += "Erro de autenticação.";
            }

            var root = System.Configuration.ConfigurationManager.AppSettings["FilesUploadDestination"];
            //string root = System.Web.HttpContext.Current.Server.MapPath(destination);
            var provider = new MultipartFormDataStreamProvider(root);

            if (resposta.Success == false)
            {
                return resposta;
            }

            DateTime dataRecepcao = DateTime.Now;

            ReporteOcorrenciasFNMPAS reporteOcorrenciasFNMPAS = new ReporteOcorrenciasFNMPAS(ocorrencias);
            reporteOcorrenciasFNMPAS.ordenaOcorrencias();

            int nrOcorrencias = 0;
            for (int i = 0; i < reporteOcorrenciasFNMPAS.OcorrenciaOrdenada.Count(); i++)
            {
                ReporteOcorrenciasMatriculaOcorrenciaOrdenada ocorrencia = reporteOcorrenciasFNMPAS.OcorrenciaOrdenada[i];

                //evento Duplicado e esmagado com os novos dados. (C M - stagging/producao) (A - producao/stagging) 
                //Não foi ainda inserido na Base de dados nem houve delete logico do anterior. 
                //Fazer deletes logicos, e inserções após verificações.
                //Anulações podem necessitar logica adicional caso a validação falhe. (duplicar registo em stagging)
                EventoStagging evento = new EventoStagging();

                int codigoOperacaoId = 0;
                switch (ocorrencia.CodigoOperacao)
                {
                    case ReporteOcorrenciasMatriculaOcorrenciaCodigoOperacao.C: codigoOperacaoId = operacoesEvento.Where(o => o.valor == "C").Single().valorSistemaId; break;
                    case ReporteOcorrenciasMatriculaOcorrenciaCodigoOperacao.M: codigoOperacaoId = operacoesEvento.Where(o => o.valor == "M").Single().valorSistemaId; break;
                    case ReporteOcorrenciasMatriculaOcorrenciaCodigoOperacao.A: codigoOperacaoId = operacoesEvento.Where(o => o.valor == "A").Single().valorSistemaId; break;
                    default: codigoOperacaoId = operacoesEvento.Where(o => o.valor == "C").Single().valorSistemaId; break;
                }

                Ficheiro ficheiroVirtual = new Ficheiro { dataAlteracao = dataRecepcao, dataUpload = dataRecepcao, entidadeId = user.entidadeId };

                evento.esmagaDados(ocorrencia, ficheiroVirtual, codigoOperacaoId);
                evento.utilizadorReporte = user.UserName;

                evento.estadoEventoId = estadosEvento.Where(e => e.valor == "PENDENTE").Single().valorSistemaId;

                eventosStaggingRepository.InsertOrUpdate(evento);
                nrOcorrencias++;
            }

                eventosStaggingRepository.Save();
                resposta.Success = true;
                resposta.Result = new EnvioOcorrenciasResult { dataRecepcao = dataRecepcao, nrOcorrencias = nrOcorrencias, seguradora = user.entidade.nome };
            
            return resposta;
        }