Beispiel #1
0
        public async Task <ActionResult <IEnumerable <Evento> > > Post(EventoDto model)
        {
            // Abertura de uma nova thread
            try
            {
                var evento = this.mapper.Map <Evento>(model);

                this.repo.Add(evento);

                if (await this.repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{model.id}", this.mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Banco de Dados Falhou {ex.Message}"));
            }

            return(BadRequest());
        }
Beispiel #2
0
        public async Task <IActionResult> Post(EventoDto eventoDto)
        {
            try
            {
                var evento = _mapper.Map <Evento>(eventoDto);
                _repo.Add(evento);

                var eventoDtoMapeado = _mapper.Map <EventoDto>(evento);

                if (await _repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{eventoDto.Id}", eventoDtoMapeado));
                }
            }
            catch (Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Banco de dados falhou :("));
            }

            return(BadRequest());
        }
Beispiel #3
0
        public async Task <EventoDto> AddEventos(EventoDto model)
        {
            try
            {
                var evento = _mapper.Map <Evento>(model);

                _geralPersist.Add <Evento>(evento);

                if (await _geralPersist.SaveChangesAsync())
                {
                    var eventoRetorno = await _eventoPersist.GetEventoByIdAsync(evento.Id, false);

                    return(_mapper.Map <EventoDto>(eventoRetorno));
                }
                return(null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #4
0
        public async Task <IActionResult> Post(EventoDto model)
        {
            try
            {
                //Mapeando o Evento Dto (Dto/mapeamento inverso)
                var evento = _mapper.Map <Evento>(model);
                //mudança de estado
                _repo.Add(evento);

                //salva mudança de estado
                if (await _repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"BD falhou {ex.Message}"));
            }
            return(BadRequest("Falhou"));
        }
Beispiel #5
0
        public async Task <IActionResult> Post(EventoDto model) //rota que vai retornar todos os resultados
        {
            try
            {
                var evento = _mapper.Map <Evento>(model); // mapeamento inverso

                _repository.Add(evento);                  // sem mapper seria o parametro model

                if (await _repository.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Banco de dados Falhou! {ex.Message}"));
            }

            // caso nao retorne alguma exceçao
            return(BadRequest());
        }
        public async Task <IActionResult> Post(EventoDto model)
        {
            try
            {
                var evento = _mapper.Map <Evento>(model);

                _repo.Add(evento);

                if (await _repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError,
                                       $"Banco Dados Falhou {ex.Message}"));
            }

            return(BadRequest());
        }
Beispiel #7
0
        public async Task <Evento> DeclararMotivo(EventoDto eventoDto)
        {
            TimeSpan diaTodo     = new TimeSpan(0, 0, 0);
            var      eventoModel = _mapper.Map <Evento>(eventoDto);

            var eventoDesatualizado = await _repo.DataHorasUltrapassadas(eventoModel);

            if (eventoDesatualizado.Length > 0)
            {
                await ExcluirEventos(eventoDesatualizado);
            }

            if ((eventoModel.DataHora > DateTime.Now) || (eventoModel.DataHora.TimeOfDay == diaTodo && eventoModel.DataHora.Date == DateTime.Today))
            {
                var eventoRepetido = await _repo.EventoRepetido(eventoModel);

                if (eventoRepetido == false)
                {
                    try
                    {
                        _repo.Add(eventoModel);
                        await _repo.SaveChangesAsync();

                        return(eventoModel);
                    }
                    catch (DbConcurrencyException e)
                    {
                        throw new DbConcurrencyException(e.Message);
                    }
                }
                else
                {
                    throw new BusinessException("indisponível");
                }
            }
            else
            {
                throw new BusinessException("DataHora Ultrapassada");
            }
        }
Beispiel #8
0
        //requisição assincrona
        //via corpo e n query
        public async Task <IActionResult> Post(EventoDto model)
        {
            try
            {
                //recebe o dto realiza o mapeamento com evento do dominio e atribui o evento que é a variavel
                var evento = _mapper.Map <Evento>(model);

                _repo.Add(evento);

                if (await _repo.SaveChangeAsync())
                {
                    //se eu conseguir fazer um post vou dar um created
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception ex)
            {
                //VERIFICA ERRO E DEPENDENDO JOGA A INFORMAÇÃO NA TELA
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Banco de Dados Falhou {ex.Message}"));
            }
            return(BadRequest());
        }
Beispiel #9
0
        public async Task <IActionResult> Post(EventoDto model)
        {
            try
            {
                var evento = _mapper.Map <Evento>(model);

                _repository.Add(evento);

                bool result = await _repository.SaveChangesAsync();

                if (result)
                {
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, "Erro ao buscar informações no banco."));
            }

            return(BadRequest());
        }
Beispiel #10
0
        public async Task <IActionResult> Put(int id, EventoDto model)
        {
            try
            {
                var evento = await this.repo.GetEventoAsyncId(id, false);

                if (evento == null)
                {
                    return(NotFound());
                }
                this.mapper.Map(model, evento);
                this.repo.Update(evento);
                if (await this.repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento{model.Id}", this.mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError));
            }
            return(BadRequest());
        }
Beispiel #11
0
        //public ActionResult<IEnumerable<Evento>> Get()//"ActionResult" é padrao do MVC utilizando RAZOR e ja retorna uma View
        public async Task <IActionResult> Post(EventoDto model)
        {
            try
            {
                var evento = _mapper.Map <Evento>(model);

                _repo.Add(evento);

                if (await _repo.SaveChangesAsync())
                {
                    //tou a chamar a rota [HttpGet("{EventoId}")], porque estou a..
                    //..utilizar o Created
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }

            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError,
                                       $"Base de dados falhou {ex.Message}"));
            }
            return(BadRequest());
        }
        public async Task <IActionResult> Post(EventoDto model)
        {
            // if (!ModelState.IsValid)
            // {
            //   return this.StatusCode(StatusCodes.Status400BadRequest, ModelState);
            // }
            try
            {
                var evento = _mapper.Map <Evento>(model);
                _repo.Add(evento);

                if (await _repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception ex)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, $"Banco Dados Falhou: \n {ex}"));
            }

            return(BadRequest("deu ruim"));
        }
Beispiel #13
0
        public EventoDto Modificar(EventoDto dto)
        {
            var evento = _eventoRepositorio.GetById(dto.Id);

            if (evento == null)
            {
                throw new Exception("No se encontro el registro solicitado.");
            }

            evento.Titulo       = dto.Titulo;
            evento.Descripcion  = dto.Descripcion;
            evento.Mail         = dto.Mail;
            evento.TipoEventoId = dto.TipoEventoId;
            evento.Imagen       = dto.Imagen;
            evento.Orante       = dto.Orante;
            evento.Organizacion = dto.Organizacion;
            evento.Telefono     = dto.Telefono;

            _eventoRepositorio.Update(evento);
            Guardar();

            dto.Id = evento.Id;
            return(dto);
        }
Beispiel #14
0
        public async Task <EventoDto> GetDto(int id)
        {
            var evento = await Get(id);

            if (evento != null)
            {
                var paciente = await _pacienteService.Get(evento.PacienteId);

                var voluntarioMedicoId = evento.VoluntarioMedicoId ?? -1;
                var medico             = voluntarioMedicoId != -1 ? await _voluntarioMedicoService.Get(voluntarioMedicoId) : null;

                var eventoDto = new EventoDto
                {
                    Id               = evento.Id,
                    Fecha            = evento.Fecha,
                    NombrePaciente   = paciente.Nombre,
                    ApellidoPaciente = paciente.Apellido,
                    NombreMedico     = medico != null ? medico.Nombre : null,
                    ApellidoMedico   = medico != null ? medico.Apellido : null
                };
                return(eventoDto);
            }
            return(null);
        }
        public EventoDto GetEvento(int eventoId)
        {
            EventoDto evento = new EventoDto();

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44357/api/");

                var response = client.GetAsync($"eventi/{eventoId}");
                response.Wait();

                var result = response.Result;

                if (result.IsSuccessStatusCode)
                {
                    var readTask = result.Content.ReadAsAsync <EventoDto>();
                    readTask.Wait();

                    evento = readTask.Result;
                }
            }

            return(evento);
        }
Beispiel #16
0
        public async Task <IActionResult> Put(int EventoId, EventoDto model)
        {
            try
            {
                var evento = await _repo.GetAllEventoAsyncById(EventoId, false);

                if (evento == null)
                {
                    return(NotFound());
                }
                _mapper.Map(model, evento);

                _repo.Update(evento);
                if (await _repo.SaveChangesAsync())
                {
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Banco de Dados Falhou"));
            }
            return(BadRequest());
        }
Beispiel #17
0
        private async Task <IEnumerable <RetornoCopiarEventoDto> > CopiarEventos(EventoDto eventoDto)
        {
            var mensagens = new List <RetornoCopiarEventoDto>();

            if (eventoDto.TiposCalendarioParaCopiar != null && eventoDto.TiposCalendarioParaCopiar.Any())
            {
                foreach (var tipoCalendario in eventoDto.TiposCalendarioParaCopiar)
                {
                    eventoDto.TipoCalendarioId = tipoCalendario.TipoCalendarioId;
                    try
                    {
                        var eventoParaCopiar = MapearParaEntidade(new Evento(), eventoDto);
                        await servicoEvento.Salvar(eventoParaCopiar);

                        mensagens.Add(new RetornoCopiarEventoDto($"Evento copiado para o calendário: '{tipoCalendario.NomeCalendario}'.", true));
                    }
                    catch (NegocioException nex)
                    {
                        mensagens.Add(new RetornoCopiarEventoDto($"Erro ao copiar para o calendário: '{tipoCalendario.NomeCalendario}'. {nex.Message}"));
                    }
                }
            }
            return(mensagens);
        }
Beispiel #18
0
        public async Task <IActionResult> Put(int eventoId, EventoDto model)
        {
            try
            {
                var evento = await _repo.GetEventoAsyncById(eventoId, false);

                if (evento == null)
                {
                    return(NotFound());
                }
                _mapper.Map(model, evento);

                _repo.Update(evento);
                if (await _repo.SaveChangesAsync())
                {
                    return(Ok(_mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception e)
            {
                return(this.BadRequest(e.Message));
            }
            return(BadRequest());
        }
Beispiel #19
0
        public async Task <IActionResult> Put(int id, EventoDto model)
        {
            try
            {
                var evento = await _repo.GetEventoAsyncById(id);

                if (evento == null)
                {
                    return(NotFound());
                }

                // DELETE EVENTO & REDE SOCIAL IF NECESSARY

                // Creates the lists which will store the respectives datas ids.
                var idLotesList        = new List <int>();
                var idRedesSociaisList = new List <int>();

                // For each item in the given entity (Lotes or RedesSociais) passed through model,
                //we add it to the newly created lists.
                model.Lotes.ForEach(item => idLotesList.Add(item.Id));
                model.RedesSociais.ForEach(item => idRedesSociaisList.Add(item.Id));

                /*
                 * Gets all the data in the given entity which doesn't match the model
                 * (passed through parameter in this function).
                 */
                var lotes = evento.Lotes.Where(
                    lote => !idLotesList.Contains(lote.Id)
                    ).ToArray();

                var redesSociais = evento.RedesSociais.Where(
                    rede => !idRedesSociaisList.Contains(rede.Id)
                    ).ToArray();

                // If there is some data wich is not present in the new update, it must be deleted.
                if (lotes.Length > 0)
                {
                    _repo.DeleteRange(lotes);
                }
                if (redesSociais.Length > 0)
                {
                    _repo.DeleteRange(redesSociais);
                }
                //END OF THE DELETE EVENTO & REDE SOCIAL SECTION

                //Changes the 'evento' according to 'model'
                this._mapper.Map(model, evento);

                _repo.Update(evento);
                if (await _repo.SaveChangesAsync())
                {
                    //Returns the 'evento' mapped according to 'EventoDto'
                    return(Created($"/api/evento/{model.Id}", this._mapper.Map <EventoDto>(evento)));
                }
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Banco de Dados Falhou"));
            }
            return(BadRequest());
        }
Beispiel #20
0
        public async Task <IEnumerable <RetornoCopiarEventoDto> > Criar(EventoDto eventoDto)
        {
            var evento = MapearParaEntidade(new Evento(), eventoDto);

            return(await SalvarEvento(eventoDto, evento));
        }
Beispiel #21
0
        public ActionResult CrearEvento([Bind(Include = "DenunciaId,Fecha,tipoEventoId,CONTESTADO,SOLUCIONADO,REQUERIMIENTOINFORME,observacion,ResIntId")] EventoDto evento)
        {
            DenunciaDto denuncia = new DenunciaDto();

            using (NuevoDbContext context = new NuevoDbContext())
            {
                denuncia = context.Denuncias.Where(x => x.DenunciaId == evento.DenunciaId).FirstOrDefault();
            }
            var esUnEventoVálido            = true;
            var mensajeFechaInvalida1       = "";
            var mensajeFechaInvalida2       = "";
            var mensajeResponsableInvalido  = "";
            var mensajeTipoDeEventoInvalido = "";

            if (evento.Fecha == null)
            {
                mensajeFechaInvalida1 = "La Fecha De Vencimiento es Inválida</br>";
                esUnEventoVálido      = false;
            }
            if (denuncia.FSELLOCIA > evento.Fecha)
            {
                mensajeFechaInvalida2 = "La Fecha de vencimiento no puede ser anterior a la Fecha de Notificación del Reclamo </br>";
                esUnEventoVálido      = false;
            }
            if (evento.ResIntId == null)
            {
                mensajeResponsableInvalido = "Seleccione un Responsable</br>";
                esUnEventoVálido           = false;
            }
            if (!(evento.TipoEventoId > 0))
            {
                mensajeTipoDeEventoInvalido = "Seleccione un Tipo de Evento</br>";
                esUnEventoVálido            = false;
            }

            if (esUnEventoVálido)
            {
                var usuario = System.Web.HttpContext.Current.User.Identity.Name;
                evento.FECHACREACION  = DateTime.Now;
                evento.Deleted        = false;
                evento.CREATIONPERSON = usuario;
                EventoCommandService evc = new EventoCommandService();
                evc.createEvento(evento, usuario);
                return(Json("Evento guardado correctamente"));
            }
            else
            {
                return(Json("<div class='alert alert-danger text-center'>" + mensajeFechaInvalida1 + mensajeFechaInvalida2 + mensajeResponsableInvalido + mensajeTipoDeEventoInvalido + "</div>"));
            }



            //var courier = evc.elEventoEsValido(evento);
            //if (courier.elObjetoEsVálido)
            //{

            //}
            //else {
            //    if (courier.mensajes != null && courier.mensajes.Count > 0)
            //    {
            //        courier.mensajes;
            //    }
            //    else {

            //    }
            //}


            //if (ModelState.IsValid)
            //{
            //    return JavaScript("<script>toastr.success('guardado correctamente')</script>");
            //}
            //else {
            //    return JavaScript("<script>toastr.error('Existe uno o más parámetros inválidos')</script>");
            //}
        }
 public async Task <IActionResult> Criar([FromServices] IComandosEvento comandosEvento, [FromBody] EventoDto eventoDto)
 {
     return(Ok(await comandosEvento.Criar(eventoDto)));
 }
 public async Task <IActionResult> Alterar(long id, [FromBody] EventoDto eventoDto, [FromServices] IComandosEvento comandosEvento)
 {
     return(Ok(await comandosEvento.Alterar(id, eventoDto)));
 }
Beispiel #24
0
        public async Task <IActionResult> Edit(EventoViewModel vm, long?vbEmpresa = null)
        {
            try
            {
                ViewBag.EmpresaId                   = vbEmpresa;
                ViewBag.EventoDuplicado             = false;
                ViewBag.EstablecimientoNoDisponible = false;
                if (!ModelState.IsValid)
                {
                    throw new Exception("Error de validacion no controlado.");
                }

                var dto = new EventoDto()
                {
                    Id                = vm.Id,
                    Cupo              = vm.Cupo,
                    CupoDisponible    = vm.CupoDisponible,
                    Descripcion       = vm.Descripcion,
                    EmpresaId         = vm.EmpresaId,
                    EstablecimientoId = vm.EstablecimientoId,
                    Fecha             = vm.Fecha,
                    Nombre            = vm.Nombre
                };

                // Validar la duplicidad del evento (misma empresa mismo nombre misma fecha mismo establecimiento)
                var existe = await _eventoServicio.Existe(dto);

                if (existe)
                {
                    ViewBag.EventoDuplicado = true;
                    if (!vbEmpresa.HasValue)
                    {
                        vm.Empresas = await _helperEmpresa.PoblarCombo();
                    }
                    vm.Establecimientos = await _helperEstablecimiento.PoblarCombo();

                    throw new Exception("Evento Duplicado.");
                }

                // Validar que el establecimiento tenga una sala disponibles para esa fecha
                var disponible =
                    await _helperSala.ExisteSalaDisponible(vm.EstablecimientoId, vm.Fecha, vm.Id);

                if (!disponible)
                {
                    ViewBag.EstablecimientoNoDisponible = true;
                    if (!vbEmpresa.HasValue)
                    {
                        vm.Empresas = await _helperEmpresa.PoblarCombo();
                    }
                    vm.Establecimientos = await _helperEstablecimiento.PoblarCombo();

                    throw new Exception("El establecimiento no tiene salas disponibles.");
                }

                await _eventoServicio.Modificar(dto);

                return(RedirectToAction(nameof(Index), new { empresaId = vbEmpresa }));
            }
            catch (Exception)
            {
                return(View(vm));
            }
        }
Beispiel #25
0
        public JsonResult Atualizar(EventoDto eventoDto)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions()
                {
                    IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromMinutes(5)
                }))
                {
                    // atualiza o evento
                    eventoBusiness.Atualizar(eventoDto);

                    // insere as medicações
                    if (eventoDto.PacienteDto != null && eventoDto.PacienteDto.MedicacoesDto != null && eventoDto.PacienteDto.MedicacoesDto.Count() > 0)
                    {
                        var dataCadastro = DateTime.Now;
                        foreach (var medicacaoDto in eventoDto.PacienteDto.MedicacoesDto)
                        {
                            medicacaoDto.DataCadastro = dataCadastro;
                            medicacaoDto.Ativo        = true;
                            medicacaoBusiness.Inserir(medicacaoDto);
                        }
                    }

                    // envia o e-mail de confirmação ou cancelamento
                    if (eventoDto.StatusDto != null && eventoDto.StatusDto.Id > 0)
                    {
                        var          path   = string.Empty;
                        StreamReader sr     = null;
                        var          evento = eventoBusiness.Listar(new EventoDto()
                        {
                            Id = eventoDto.Id
                        }).FirstOrDefault();
                        var emailDto = new EmailDto()
                        {
                            Destinatario = evento.PacienteDto.Email, Remetente = "*****@*****.**", Titulo = "Clínica Dra. Cláudia Bertha"
                        };

                        if (eventoDto.StatusDto.Id == StatusDto.EStatus.Confirmada.GetHashCode())
                        {
                            path = System.Web.HttpContext.Current.Server.MapPath("/Views/Shared/_EmailConsultaConfirmada.cshtml");
                            sr   = new StreamReader(path);
                            emailDto.Mensagem = sr.ReadToEnd().Replace("#NOME_PACIENTE#", evento.PacienteDto.Nome).Replace("#DATA_CONSULTA#", evento.DataInicial.ToString("dd/MM/yyyy HH:mm"));
                            emailDto.Assunto  = "Consulta Confirmada";
                        }
                        else if (eventoDto.StatusDto.Id == StatusDto.EStatus.Cancelada.GetHashCode())
                        {
                            path = System.Web.HttpContext.Current.Server.MapPath("/Views/Shared/_EmailConsultaCancelada.cshtml");
                            sr   = new StreamReader(path);
                            emailDto.Mensagem = sr.ReadToEnd().Replace("#NOME_PACIENTE#", evento.PacienteDto.Nome)
                                                .Replace("#DATA_CONSULTA#", evento.DataInicial.ToString("dd/MM/yyyy HH:mm"))
                                                .Replace("#MOTIVO#", evento.MotivoDto.Descricao);
                            emailDto.Assunto = "Consulta Cancelada";
                        }

                        if (sr != null)
                        {
                            sr.Close();
                            emailBusiness.Enviar(emailDto);
                        }
                    }

                    scope.Complete();
                }

                var eventosDto = eventoBusiness.Listar(new EventoDto()
                {
                    DataInicial = DateTime.Now.ToUniversalTime(), DataFinal = DateTime.Now.ToUniversalTime().AddDays(30)
                }).Where(x => x.PacienteDto != null && x.PacienteDto.Id > 0).ToList();

                return(Json(new { Sucesso = true, Erro = false, Mensagem = "Consulta atualizada com sucesso", EventosDto = eventosDto }, JsonRequestBehavior.AllowGet));
            }
            catch (BusinessException ex)
            {
                return(Json(new { Sucesso = false, Erro = ex.ToString(), Mensagem = ex.Message }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(new { Sucesso = false, Erro = ex.ToString(), Mensagem = "Ocorreu um erro ao atualizar consulta. Tente salvar novamente em 5 segundos" }, JsonRequestBehavior.AllowGet));
            }
        }
Beispiel #26
0
        //public async Task<IActionResult> Put(int EventoId, Evento model)
        // Após a criação dos DTOs alteramos para receber o EventoDto.
        public async Task <IActionResult> Put(int EventoId, EventoDto model)
        {
            try
            {
                // Verifica se encontra algum elemento.
                // Aqui eliminamos que seja feito algum Join no banco de dados com Eventos com Palestrantes
                // procuramos saber somente se o evento foi encontrado.
                var evento = await _repo.GetAllEventoAsyncById(EventoId, false);

                // Se não foi encontrado elemento não é atualizado.
                if (evento == null)
                {
                    return(NotFound());
                }

                //

                // → Com esse código estava dando duplicidade ao inserir Lote e Rede Social, ao contrario
                //  do que foi apresentado em aula.

                // ↓ Deletando relacionamento, quando acontece de duplicar o registro de Lotes e Redes Sociais.
                var idLotes        = new List <int>();
                var idRedesSociais = new List <int>();

                // ↓ Verifica quem esta dentro do model dos Lotes.
                model.Lotes.ForEach(item => idLotes.Add(item.Id));
                // ↓ Verifica quem esta dentro do model das RedeSociais.
                model.RedesSociais.ForEach(item => idRedesSociais.Add(item.Id));

                // ↓ Verifica quem está dentro do evento.
                var lotes = evento.Lotes.Where(
                    lote => !idLotes.Contains(lote.Id)
                    ).ToArray();

                var redesSociais = evento.RedesSociais.Where(
                    rede => !idRedesSociais.Contains(rede.Id)
                    ).ToArray();

                // ↓ Verifica se existe algum registro "duplicado" para deletar dos Lotes.
                if (lotes.Length > 0)
                {
                    _repo.DeleteRange(lotes);
                }

                // ↓ Verifica se existe algum registro "duplicado" para deletar das Redes Sociais.
                if (redesSociais.Length > 0)
                {
                    _repo.DeleteRange(redesSociais);
                }

                // Faz o mapeamento recebendo o model e substituindo pelo evento.
                _mapper.Map(model, evento);

                // Caso encontre o elemento segue o código ↓

                // Na atualização do model ele não precisa ser assincrono.
                // Aqui ele muda um estado do EntityFramework.
                // _repo.Update(model);
                // Após o mapeamento faz a atualização dos campos.
                _repo.Update(evento);

                // Na hora de salvar ele precisa ser assincrono (await).
                // Aqui ele salva toda a mudança de estado.
                if (await _repo.SaveChangeAsync())
                {
                    // Aqui utilizamos o status code 201 que foi salvo com sucesso.
                    return(Created($"/api/evento/{model.Id}", _mapper.Map <EventoDto>(evento))); // _mapper.Map<EventoDto>(evento) → retorna fazendo o match entre o evento com EventoDto.
                }
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Banco de dados falhou"));
            }

            // Caso não tenha dado certo o SaveChangeAsync retorna a mensagem de erro BadRequest.
            return(BadRequest());
        }
Beispiel #27
0
        public async Task <IActionResult> Post(EventoDto eventoDto)
        {
            var evento = _mapper.Map <Evento>(eventoDto);

            return(Ok(await _eventoStorer.Save(evento)));
        }
Beispiel #28
0
        public ActionResult Crear(EventoViewDto eventoViewDto, HttpPostedFileBase img)
        {
            if (img != null)
            {
                using (var reader = new BinaryReader(img.InputStream))
                {
                    eventoViewDto.Imagen = reader.ReadBytes(img.ContentLength);
                }
            }
            else
            {
                ViewBag.ErrorEvento = "Ingrese una Imagen para su evento.";
                return(View());
            }


            ViewBag.ListaTipoEvento = _tipoEventoServicio.Get().ToList();

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_eventoServicio.ValidarTitulo(eventoViewDto.Titulo))
                    {
                        if (!_eventoServicio.ValidarFecha(eventoViewDto.FechaEvento))
                        {
                            var evento = new EventoDto
                            {
                                Id           = eventoViewDto.Id,
                                Titulo       = eventoViewDto.Titulo,
                                Descripcion  = eventoViewDto.Descripcion,
                                Mail         = eventoViewDto.Mail,
                                Latitud      = eventoViewDto.Latitud,
                                Longitud     = eventoViewDto.Longitud,
                                TipoEventoId = eventoViewDto.TipoEventoId,
                                Orante       = eventoViewDto.Orante,
                                Organizacion = eventoViewDto.Organizacion,
                                Domicilio    = eventoViewDto.DomicilioCompleto,
                                Telefono     = eventoViewDto.Telefono,
                                Imagen       = eventoViewDto.Imagen
                            };

                            var EventoObj = _eventoServicio.Insertar(evento);

                            //*************************************************************//

                            var fecha = new FechaDto
                            {
                                FechaEvento = eventoViewDto.FechaEvento,
                                HoraInicio  = eventoViewDto.HoraInicio,
                                HoraCierre  = eventoViewDto.HoraFin
                            };

                            var FechaObj = _fechaServicio.Insertar(fecha);

                            //*************************************************************//

                            var fechaEvento = new FechaEventoDto
                            {
                                EventosId = EventoObj.Id,
                                FechaId   = FechaObj.Id
                            };

                            _fechaEventoServicio.Insertar(fechaEvento);

                            //*************************************************************//

                            var entrada = new EntradaDto
                            {
                                Monto      = eventoViewDto.Precio,
                                FechaDesde = DateTime.Now,
                                FechaHasta = DateTime.Now,
                                EventoId   = EventoObj.Id,
                                Cantidad   = 1
                            };

                            _entradaServicio.Insertar(entrada);

                            //*************************************************************//

                            var CreadorEvento = new CreadorEventoDto()
                            {
                                EventoId  = EventoObj.Id,
                                UsuarioId = SessionActiva.UsuarioId,
                                Fecha     = DateTime.Now
                            };

                            _creadorEventoServicio.Insertar(CreadorEvento);

                            //*************************************************************//

                            return(RedirectToAction("ViewEvento", new { id = EventoObj.Id }));
                        }
                        else
                        {
                            ViewBag.ErrorEvento = "Ingresa una fecha valida , anticipacion de 1 dia";
                            return(View());
                        }
                    }
                    else
                    {
                        ViewBag.ErrorEvento = "El Titulo del evento ya esta siendo utilizada.";
                        return(View());
                    }
                }
                catch (Exception e)
                {
                    ViewBag.ErrorEvento = "Ocurrio un error inesperado en el sistema";
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }