public IActionResult Post([FromBody] Person value)
        {
            if (personRepository.Add(value))
            {
                return(Ok());
            }

            return(BadRequest());
        }
Beispiel #2
0
        public HttpResponseMessage PostPerson(Person person)
        {
            person = databasePlaceholder.Add(person);
            string apiName = WebApiConfig.DEFAULT_ROUTE_NAME;
            //this.Request.SetConfiguration(new HttpConfiguration());
            var response =
                this.Request.CreateResponse <Person>(HttpStatusCode.Created, person);
            string uri = Url.Link(apiName, new { id = person.id, controller = "person" });

            response.Headers.Location = new Uri(uri);
            return(response);
        }
 public int AddStudent(Person person)
 {
     using (TransactionScope tran = new TransactionScope()) {
         Persons.Add(person);
         Students.Add(new Student()
         {
             Id = person.Id
         });
         // Complete();
         tran.Complete();
         return(person.Id);
     }
 }
Beispiel #4
0
        public Person Add(string firstName,
                          string lastName,
                          string surName,
                          Genders gender,
                          DateTime?birthDate,
                          string snils,
                          string email,
                          string phone,
                          string registrationAddress,
                          string factAddress,
                          string otherPhones)
        {
            var person = _personFactory.Create(firstName,
                                               lastName,
                                               surName,
                                               gender,
                                               birthDate,
                                               snils,
                                               email,
                                               phone,
                                               registrationAddress,
                                               factAddress,
                                               otherPhones);

            _personRepository.Add(person);

            return(person);
        }
Beispiel #5
0
        public bool Create(Person entity)
        {
            Random rnd = new Random();

            entity.Id = Convert.ToString(rnd.Next(10000, 99999));

            var personas = _personRepository.GetAll().ToList().SkipWhile(s => s.Id == entity.Id); //Evita a si mismo

            if (entity.Rol == "Catador")
            {
                if (personBll.ValidateCatador(entity).StartsWith("Error"))
                {
                    return(false);
                }
            }

            if (personBll.ValidatePersona(entity, personas).StartsWith("Error"))
            {
                return(false);
            }

            try
            {
                _personRepository.Add(entity);
                _unitOfWork.Commit();
            }
            catch (Exception ex)
            {
                return(false);
            }
            return(true);
        }
Beispiel #6
0
        public void Add(PersonViewModel personViewModel)
        {
            var config = _configuration.GetValue <string>("Config:AtletaBase64");


            personViewModel.Password = Divers.GenerateMD5(personViewModel.Password);

            if (personViewModel.Picture == "")
            {
                personViewModel.Picture = Divers.Base64ToImage(config, "PERSON");
            }
            else
            {
                personViewModel.Picture = Divers.Base64ToImage(personViewModel.Picture, "PERSON");
            }

            Person _person = _mapper.Map <Person>(personViewModel);

            _personRepository.Add(_person);

            foreach (var item in personViewModel.ProfileType)
            {
                PersonProfile _personProfile = new PersonProfile
                {
                    PersonId    = _person.Id,
                    ProfileType = (ProfileType)int.Parse(item)
                };

                _personProfileRepository.Add(_personProfile);
            }

            //var registerCommand = _mapper.Map<RegisterNewCustomerCommand>(personViewModel);
            //Bus.SendCommand(registerCommand);
        }
Beispiel #7
0
 public Person Register(Person person)
 {
     person.Password     = new ToPasswordRepository().Md5(person.Password);
     person.IsValid      = true;
     person.PersonTypeID = 1;
     return(_personRepository.Add(person));
 }
Beispiel #8
0
        public async Task Handle(CreatePersonCommand command, UnitOfWork uow)
        {
            IPersonRepository personRepository = PersonRepositoryFactory.Create(uow.Context);
            var person = new Person(command.Name, command.Email);

            personRepository.Add(person);
        }
Beispiel #9
0
        public async Task <IActionResult> Info(Person personDto)
        {
            var Pfr = await _pfrRepository.Get(personDto.Snils);

            PostgreSQL.Entities.Person personDb;
            if (Pfr == null)
            {
                var personEntitiesDb = _mapper.Map <PostgreSQL.Entities.Person>(personDto);
                await _personRepository.Add(personEntitiesDb);

                personDb = await _personRepository.Get(personEntitiesDb.LastName);

                var personDbId = personDb.PersonId;
                await _pfrRepository.Add(new PostgreSQL.Entities.PFR {
                    Snils = personDto.Snils, PersonId = personDbId
                });
            }

            Pfr = await _pfrRepository.Get(personDto.Snils);

            personDb = await _personRepository.GetById(Pfr.PersonId);

            var newPfr                = _mapper.Map <PFR>(Pfr);
            var newPerson             = _mapper.Map <Person>(personDb);
            Tuple <Person, PFR> tuple = new Tuple <Person, PFR>(newPerson, newPfr);

            return(View(tuple));
        }
        public void DeleteTest()
        {
            var p1 = new Person()
            {
                FirstName = "Person1_First", LastName = "Delete", Email = "*****@*****.**", CreatedOn = DateTime.UtcNow
            };
            Person added;

            using (_context = new AllTheSameDbContext())
            {
                using (_personRepository = new PersonRepository(_context))
                {
                    //add so we can delete
                    added = _personRepository.Add(p1);

                    Assert.IsNotNull(added);
                    Assert.IsTrue((p1.FirstName == added.FirstName && (p1.LastName == added.LastName)));
                }
            }

            using (_context = new AllTheSameDbContext())
            {
                using (_personRepository = new PersonRepository(_context))
                {
                    //now delete
                    var deleted = _personRepository.Delete(added);
                    //_context.SaveChanges();

                    Assert.IsNotNull(deleted);
                }
            }
        }
        public async Task <Guid> Execute(PersonAddRequest person)
        {
            var entity = mapper.Map <Person>(person);
            await personRepository.Add(entity);

            return(entity.Id);
        }
Beispiel #12
0
        public Task <bool> Handle(RegisterNewPersonCommand message, CancellationToken cancellationToken)
        {
            //se nao for válido
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.FromResult(false));
            }

            var person = new Person(Guid.NewGuid(), message.Name, message.Email, message.Password, DateTime.Now, message.Active);

            if (_personRepository.GetByEmail(person.Email) != null)
            {
                Bus.RaiseEvent(new DomainNotification(message.MessageType, "O e-mail desta pessoa já está sendo usado!"));
                return(Task.FromResult(false));
            }

            _personRepository.Add(person);

            if (Commit())
            {
                //Bus.RaiseEvent(new PersonRegisteredEvent(person.Id, person.Name, person.Email, person.Password, person.DtRegister, person.Active));
            }

            return(Task.FromResult(true));
        }
        public async Task <IActionResult> Create([FromBody] Person person)
        {
            _logger.LogDebug("Starting save");

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var jsSkill = new Skill
            {
                Name = "Test Skill 1"
            };

            var personSkill = new PersonSkill
            {
                Skill = jsSkill
            };

            _personRepository.Add(new Person {
                LastName  = person.LastName,
                FirstName = person.FirstName,
                Skills    = new Collection <PersonSkill> {
                    personSkill
                }
            });

            await _personRepository.SaveChangesAsync();

            _logger.LogDebug("Finished save");

            return(CreatedAtAction(nameof(Get), new { id = person.LastName }, person));
        }
        public async Task <ResponseModel> Post(PersonModel model)
        {
            //TODO: Integrate

            var errorMsg = _message.Find(MessageKey.AddUserFail);

            try
            {   //This can be placed in a separate validator class
                if (!ModelState.IsValid)
                {
                    return(new ResponseModel(false, errorMsg));
                }
                var dataModel = _mapper.Map(model);

                dataModel.TaskName = "CreatePerson";
                dataModel.TaskId   = Guid.NewGuid();

                var personId = await _personRepository.Add(dataModel);

                if (personId != 0)
                {
                    return(new ResponseModel(true));
                }

                _logger.Error(errorMsg);
                return(new ResponseModel(false, errorMsg));
            }
            catch (Exception ex)
            {
                _logger.Error(ex.ToString());
                return(new ResponseModel(false, _message.Find(MessageKey.AddUserFail)));
            }
        }
        /// <inheritdoc />
        public void FileReader(string file)
        {
            StreamReader reader = null;

            try
            {
                // Clear the repository.
                _personRepository.RemoveAll();

                reader = new StreamReader(file);
                string strline;

                while ((strline = reader.ReadLine()) != null)
                {
                    var    values = strline.Split(',').Select(p => p.Trim()).ToList();
                    Person person = new PersonBuilder().WithFirstName(values[1]).WithLastName(values[0]).Build();
                    _personRepository.Add(person);

                    _logger.WriteLog("Person: " + person.LastName + ", " + person.FirstName + " successfully read from file.");
                }
            }
            catch (Exception exception)
            {
                _logger.WriteLog("An exception occurred in method 'FileReader' from 'FileHandling'. ", exception);
                throw;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
        public Domain.Entities.Person Add(Domain.Entities.Person entity)
        {
            if (!entity.IsValid())
            {
                return(entity);
            }

            var newPersonCpf = entity.Documents.FirstOrDefault(x => x.DocumentTypeId == Domain.Enum.EDocumentType.CPF);

            if (newPersonCpf == null)
            {
                entity.AddError($"CPF não encontrado - Pessoa a ser cadastrada: {entity.FirstName} {entity.MiddleName} {entity.LastName} ");
                return(entity);
            }

            //TODO - validate all documents, in a later moment
            if (_personRepository.GetByCPF(newPersonCpf.DocumentNumber) != null)
            {
                entity.AddError($"CPF {newPersonCpf.DocumentNumber} já cadastrado");
                return(entity);
            }

            _personRepository.Add(entity);

            return(entity);
        }
Beispiel #17
0
        public async Task <int> CreateNew(PersonInput input)
        {
            try
            {
                var person = new Person
                {
                    Name   = input.Name,
                    Images = input.Files.Select(x => new ImageAttachment
                    {
                        Name = x.FileName,
                        ImageAttachmentTypeId = ImageTypes.Person
                    }).ToList()
                };
                peopleRepo.Add(person);
                peopleRepo.Save();

                await filesService.Upload(input.Files, $"{nameof(ImageTypes.Person)}/{person.Id}");

                return(person.Id);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "exception when saving new Person");
                throw;
            }
        }
        public IActionResult Appointment(Person model)
        {
            if (ModelState.IsValid)
            {
                Person nwePerson = new Person
                {
                    Name             = model.Name,
                    PhoneNo          = model.PhoneNo,
                    Email            = model.Email,
                    BirthDate        = model.BirthDate,
                    Gender           = model.Gender,
                    BloodGroup       = model.BloodGroup,
                    PresentAddress   = model.PresentAddress,
                    PermanentAddress = model.PermanentAddress,
                    Password         = model.Password,
                    IUser            = 1,
                    IDate            = DateTime.Now
                };

                _personRepository.Add(nwePerson);
                return(RedirectToAction("Index"));
                //return RedirectToAction("details", new { id = newEmployee.EmpId });
            }


            return(View());
        }
Beispiel #19
0
        public void Add(PersonViewModel person)
        {
            Person p = _Mapper.Map <Person>(person);

            _PersonRepository.Add(p);
            _PersonRepository.Save();
        }
Beispiel #20
0
        public void Handle(AddPersonCommand command)
        {
            if (!command.IsValid())
            {
                NotifyValidationErrors(command);
                return;
            }

            var address = new Address(command.Adress.PostalCode, command.Adress.City, command.Adress.State,
                                      command.Adress.Country, command.Adress.NeighborHood, command.Adress.Street,
                                      command.Adress.Complement, command.Adress.Number);

            var person = new Person(command.Name, address);

            // if exists bussiness validation, you should validate here!


            _personRepository.Add(person);


            if (Commit())
            {
                _mediatorHandler.RaiseEvent(new AddPersonEvent(person.Id, person.Name));
            }
        }
Beispiel #21
0
        public ICommandResult Handle(UserRegisterCommand command)
        {
            var commandResult = new UserRegisterCommandResult();

            if (!(_validationService.Validate(command)))
            {
                return(commandResult);
            }

            //Validações de coisas que não vão em repositório
            if (!(command.HasValidEmail() & command.HasValidPassword()))
            {
                return(commandResult);
            }

            //Validações de coisas que vão em repositório
            if (!(command.HasUniqueUserEmail(_personRepository)))
            {
                return(commandResult);
            }

            //Gera nova entidade
            var person = new Person(Guid.NewGuid(), command.Name, command.DocumentNumber, phoneNumber: command.PhoneNumber, email: command.Email,
                                    password: _passwordService.Encrypt(command.Password), serialKey: Guid.NewGuid().ToString().Replace("-", ""));

            //Adiciona as entidades ao repositório
            var personAdded = _personRepository.Add(person);

            commandResult.SerialKey = personAdded.SerialKey;

            return(commandResult);
        }
Beispiel #22
0
        public async Task <ResultViewModel> Post(
            [FromBody] CreatePersonViewModel personViewModel)
        {
            personViewModel.Validate();

            if (personViewModel.Invalid)
            {
                return(new ResultViewModel
                {
                    Success = false,
                    Message = "Não foi possível cadastrar a pessoa",
                    Data = personViewModel.Notifications
                });
            }

            var person = new Person(
                personViewModel.FirstName,
                personViewModel.LastName,
                personViewModel.Email);


            person.Addresses.Add(personViewModel.Address);

            await _personRepository.Add(person);

            _personRepository.SaveChanges();

            return(new ResultViewModel
            {
                Success = true,
                Message = "Cadastrado com sucesso",
                Data = person,
            });
        }
Beispiel #23
0
        private Person CreateNewPerson()
        {
            var person = new Person();

            _personRepository.Add(person);
            return(person);
        }
Beispiel #24
0
        public async Task <ActionResult <PersonViewModel> > AddPerson(AddViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            if (await _personRepository.CheckEmail(model.Email))
            {
                return(BadRequest("El email ya existe"));
            }



            var person = _mapper.Map <Person>(model);



            var newPerson = await _personRepository.Add(person);

            if (newPerson == null)
            {
                return(BadRequest());
            }

            var newPersonResult = _mapper.Map <PersonViewModel>(newPerson);

            return(CreatedAtAction(nameof(AddPerson), new { id = newPersonResult.IdPerson }, newPersonResult));
        }
Beispiel #25
0
 public void Add(Person person)
 {
     if (_personValidator.Validate(person))
     {
         _personRepository.Add(person);
     }
 }
Beispiel #26
0
        public ActionResult SaveEmployee(PersonAddressViewModel personAddressViewModel)
        {
            if (ModelState.IsValid)
            {
                var Person  = new Person();
                var Address = new Address();

                Person.FirstName = personAddressViewModel.FirstName;
                Person.LastName  = personAddressViewModel.LastName;
                Person.Email     = personAddressViewModel.Email;
                Address.Address1 = personAddressViewModel.Address1;
                Address.Address2 = personAddressViewModel.Address2;
                Address.City     = personAddressViewModel.City;
                Address.State    = personAddressViewModel.State;
                Address.ZipCode  = personAddressViewModel.ZipCode;

                _personRepository.Add(Person);
                _personRepository.Save();

                Address.AddressId = Person.PersonId;
                _addressRepository.Add(Address);
                _addressRepository.Save();
                return(RedirectToAction("EmployeeDetails"));
            }
            else
            {
                return(View("AddAddress", personAddressViewModel));
            }
        }
Beispiel #27
0
        public IActionResult AddPerson([FromBody] Person person)
        {
            _personRepo.Add(person);
            int result = _unitOfWork.SaveAll();

            return(NoContent());
        }
        public ActionResult Post([FromBody] CreatePersonDto personDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }


            var personWithoutAddress = _mapper.Map <PersonWithoutAddressDto>(personDto);
            var personEntity         = _mapper.Map <Person>(personWithoutAddress);

            _personRepository.Add(personEntity);
            if (!_personRepository.Save())
            {
                return(StatusCode(500, "An error occured while making the change"));
            }

            foreach (var address in personDto.Addresses)
            {
                address.PersonID = personEntity.ID;
                var addressEntity = _mapper.Map <Address>(address);
                _addressRepository.Create(addressEntity);
                if (!_addressRepository.Save())
                {
                    return(StatusCode(500, "An error occured while making the change"));
                }
            }

            return(CreatedAtAction("Post", new { id = personEntity.ID }, personEntity));
        }
 public void RegisterNewStudent(Person student)
 {
     if (_personRepository.Find(student.Id) == null)
     {
         _personRepository.Add(student);
     }
 }
Beispiel #30
0
        public async Task <int> Handle(CreatePersonCommand request, CancellationToken cancellationToken)
        {
            var person = _mapper.Map <Person>(request);

            var result = await _personRepository.Add(person);

            return(result);
        }