コード例 #1
0
        public async Task <IActionResult> Put(int AnimalId, AnimalDto model)
        {
            try
            {
                var animal = await _repository.GetAnimalAsyncById(AnimalId);

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

                _mapper.Map(model, animal);

                _repository.Update(animal);

                if (await _repository.SaveChangesAsync())
                {
                    return(Created($"/api/marfrig/{model.Id}", model));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, $"Banco de dados falhou {ex.Message}"));
            }

            return(BadRequest());
        }
コード例 #2
0
        private DateTime SetNextVaccinationDate(AnimalDto animal, VaccinationFullDto vaccination)
        {
            var animalYears = DateTime.Now - animal.DateOfBirth;
            var nextDate    = (animalYears < DateTime.Now.AddYears(1) - DateTime.Now) ? (vaccination.VaccinationDate.Date.AddDays(21)) : (vaccination.VaccinationDate.Date.AddYears(1));

            return(nextDate);
        }
コード例 #3
0
 public static void MapUpdate(Animal animal, AnimalDto animalDto)
 {
     animal.Name   = animalDto.Name;
     animal.Sex    = (int)animalDto.Sex;
     animal.KindId = animalDto.KindId;
     animal.CageId = animalDto.CageId;
 }
コード例 #4
0
 public ActionResult Create(AnimalDto animalModel, IFormFile photo)
 {
     try
     {
         string uniqueFileName = null;
         if (photo != null)
         {
             string uploadsFolder = Path.Combine(_env.WebRootPath, "images");
             uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
             string filePath = Path.Combine(uploadsFolder, uniqueFileName);
             using (var fileStream = new FileStream(filePath, FileMode.Create))
             {
                 photo.CopyTo(fileStream);
             }
         }
         string userId = User.Claims.Where(c => c.Type == "UserId").FirstOrDefault().Value;
         var    animal = new Animal
         {
             Name        = animalModel.Name,
             Age         = animalModel.Age,
             Description = animalModel.Description,
             Photo       = uniqueFileName,
             BreedId     = animalModel.BreedId,
             UserId      = Int32.Parse(userId),
         };
         _context.Animal.Add(animal);
         _context.SaveChanges();
         return(RedirectToAction("List"));
     }
     catch
     {
         return(View());
     }
 }
コード例 #5
0
ファイル: IsNewService.cs プロジェクト: yakubovych/PetUA
 public void UpdateIsNewCheckbox(AnimalDto animalDto, Animal model)
 {
     if (animalDto.IsNew && DateTime.Now - model.FoundDate >= DateTime.Now.AddDays(int.Parse(_configuration["DurationAnimalNewStatus"])) - DateTime.Now)
     {
         model.FoundDate = DateTime.Now;
     }
 }
コード例 #6
0
        public IActionResult UpdateAnimal(int id, [FromBody] AnimalDto updatedAnimalInfo)
        {
            if (updatedAnimalInfo == null)
            {
                _logger.LogInformation($"Information needed to update animal. {updatedAnimalInfo} was provided.");
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            // Find the animal to update
            var currentAnimals = _animalInfoRepository.GetAnimals();
            var animalToUpdate = currentAnimals.FirstOrDefault(animal => animal.Id == id);

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

            // Map the new info to animal to be updated and save
            Mapper.Map(updatedAnimalInfo, animalToUpdate);
            if (!_animalInfoRepository.Save())
            {
                return(StatusCode(500));
            }

            return(Ok(animalToUpdate));
        }
コード例 #7
0
        public IActionResult CreateAnimal([FromBody] AnimalDto animal)

        {
            if (animal == null)
            {
                _logger.LogInformation($"No animal for creation. {animal} was provided.");
                return(BadRequest($"No animal for creation. null was provided."));
            }

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

            var newAnimal = Mapper.Map <Entities.Animal>(animal);

            _animalInfoRepository.AddAnimal(newAnimal);

            // If animal is successfully created, map the animal info to Data transfer Object to return
            if (!_animalInfoRepository.Save())
            {
                return(StatusCode(500, $"{newAnimal} was not saved succesfully."));
            }

            var successfullyCreatedAnimal = Mapper.Map <Models.AnimalDto>(newAnimal);

            return(CreatedAtRoute("GetAnimal", new { id = newAnimal.Id }, successfullyCreatedAnimal));
        }
コード例 #8
0
        public AnimalDto InsertAnimal(AnimalDto dto)
        {
            Animal animal = DtoToEntity(dto);

            context.Animals.Add(animal);
            return(EntityToDto(animal));
        }
コード例 #9
0
        public async Task <IEnumerable <AnimalToCareDto> > GetCaringAnimalsArchiveAsync(string email)
        {
            var user = await GetAsync(email);

            var animalsToCare = await _animalToCareRepository.GetAnimalsCaringByUserArchiveAsync(user.Id);

            var animalsToCareDto = new HashSet <AnimalToCareDto>();

            foreach (var toCare in animalsToCare)
            {
                var tmpAnimal = await _animalRepository.GetAsync(toCare.AnimalId);

                var animalDto = new AnimalDto
                {
                    Id          = toCare.Id,
                    Name        = tmpAnimal.Name,
                    User        = await GetAsync(email),
                    YearOfBirth = toCare.Animal.YearOfBirth
                };

                animalsToCareDto.Add(new AnimalToCareDto
                {
                    Id       = toCare.Id,
                    Animal   = animalDto,
                    DateFrom = toCare.DateFrom,
                    DateTo   = toCare.DateTo,
                    IsTaken  = toCare.IsTaken
                });
            }

            return(animalsToCareDto);
        }
コード例 #10
0
ファイル: AnimalService.cs プロジェクト: taneltumanski/Zoo
        public async Task <ValidationResult> AddOrUpdate(AnimalDto animal)
        {
            var validator        = ValidatorFactory.GetValidator <AnimalDto>();
            var validationResult = validator.Validate(animal);

            if (validationResult.IsSuccess)
            {
                // TODO avoid race conditions with transactions
                var existingEntity = await Context.Animals.FindAsync(animal.Id);

                if (existingEntity == null)
                {
                    existingEntity = new Animal();

                    Context.Animals.Add(existingEntity);
                }
                else
                {
                    existingEntity.ModifiedAt = DateTimeOffset.UtcNow;
                }

                existingEntity.Name      = animal.Name;
                existingEntity.BirthDate = animal.BirthDate;
                existingEntity.Specie    = Context.Species.Find(animal.Specie.Id);

                await Context.SaveChangesAsync();

                var updatedDto = GetExpression().Compile()(existingEntity);

                ObservableProvider.OnUpdate(updatedDto, "Animal");
            }

            return(validationResult);
        }
コード例 #11
0
        public async Task Update(AnimalDto entity)
        {
            var animal = await this.unitOfWork.Animals.Get(entity.Id);

            AnimalMapper.MapUpdate(animal, entity);

            await this.unitOfWork.Animals.Update(animal);
        }
コード例 #12
0
 protected override void Because_of()
 {
     var proxy = new CatProxy
     {
         ToConvert = typeof(Cat)
     };
     _animalDto = Mapper.Map<Animal, AnimalDto>(proxy);
 }
コード例 #13
0
        public async Task <IActionResult> CriarAnimal([FromBody] AnimalDto animalDto)
        {
            Animal animal = new Animal(animalDto.Nome);

            _dataContext.Add(animal);
            await _dataContext.SaveChangesAsync();

            return(Ok(animal));
        }
コード例 #14
0
            protected override void Because_of()
            {
                var proxy = new CatProxy
                {
                    ToConvert = typeof(Cat)
                };

                _animalDto = Mapper.Map <Animal, AnimalDto>(proxy);
            }
コード例 #15
0
        public async Task <CreatedData> CreateAnimalAsync(AnimalDto animalDto)
        {
            var animalDbo = _mapper.Map <Animal>(animalDto);

            _dbContext.Animals.Add(animalDbo);

            await _dbContext.SaveChangesAsync();

            return(new CreatedData(animalDbo.AnimalId));
        }
コード例 #16
0
 public static Animal Map(AnimalDto animal)
 {
     return(new Animal
     {
         Id = animal.Id,
         Name = animal.Name,
         Sex = (int)animal.Sex,
         KindId = animal.KindId,
         CageId = animal.CageId,
     });
 }
コード例 #17
0
        public static AnimalDto MapToDto(this Animal model)
        {
            var result = new AnimalDto();

            result.Id      = model.Id;
            result.Name    = model.Name;
            result.Type    = model.Type;
            result.OwnerId = model.OwnerId;

            return(result);
        }
コード例 #18
0
 public static AnimalVm MapAnimalDtoToVm(AnimalDto animalDto)
 {
     return(new AnimalVm
     {
         Birthday = animalDto.Birthday,
         BreedId = animalDto.BreedId,
         BreedName = animalDto.BreedName,
         Id = animalDto.Id,
         Name = animalDto.Name
     });
 }
コード例 #19
0
 private Animal MapAnimalsDtoToModel(AnimalDto animalDto)
 {
     return(new Animal
     {
         Birthday = animalDto.Birthday,
         Breed = _breedsRepository.GetById(animalDto.BreedId),
         Id = animalDto.Id,
         Name = animalDto.Name,
         User = _usersRepository.GetUserById(animalDto.UserId)
     });
 }
コード例 #20
0
        static void Main(string[] args)
        {
            // Console.WriteLine("Hello World!");
            AnimalDto animal = new AnimalDto();

            animal.Name  = "Marry";
            animal.Age   = 19;
            animal.Color = "Colorful";

            System.Console.WriteLine($"Name {animal.Name} age {animal.Age} color {animal.Color}");
            animal.Scream();
        }
コード例 #21
0
        public async Task <IActionResult> Create(AnimalDto animal)
        {
            if (animal.Id == default)
            {
                await this.animalService.Create(animal);
            }
            else
            {
                await this.animalService.Update(animal);
            }

            return(RedirectToAction("Index"));
        }
コード例 #22
0
        public async Task <IActionResult> Patch([FromRoute] int id, [FromBody] AnimalDto dto)
        {
            try
            {
                var result = await _animalService.Update(dto, id).ConfigureAwait(true);

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #23
0
        public AnimalDto UpdateAnimal(AnimalDto dto)
        {
            Animal animal = context.Animals.Find(dto.Id);

            animal.Name        = dto.Name;
            animal.Tattoo      = dto.Tattoo;
            animal.Gender      = dto.Gender;
            animal.DateOfBirth = dto.DateOfBirth;

            context.Entry(animal).State = EntityState.Modified;

            return(EntityToDto(animal));
        }
コード例 #24
0
        public Animal DtoToEntity(AnimalDto dto)
        {
            return(new Animal()
            {
                Id = dto.Id,
                Name = dto.Name,
                Tattoo = dto.Tattoo,
                Gender = dto.Gender,
                DateOfBirth = dto.DateOfBirth,

                Company = context.Companies.Find(dto.CompanyId)
            });
        }
コード例 #25
0
        public IActionResult UpdateAnimal(AnimalDto model)
        {
            var animal = _context.Animal.Where(a => a.Id == model.Id).FirstOrDefault();

            animal.Name        = model.Name;
            animal.Age         = model.Age;
            animal.Description = model.Description;
            animal.Photo       = model.Photo;
            animal.BreedId     = model.BreedId;

            _context.Update(animal);
            _context.SaveChanges();
            return(RedirectToAction("ManageAnimal"));
        }
コード例 #26
0
        public async Task <AnimalDto> Create(AnimalDto dto)
        {
            var animal = new Animal
            {
                Name    = dto.Name,
                Type    = dto.Type,
                OwnerId = dto.OwnerId
            };

            var addedAnimal = _context.Animals.Add(animal).Entity;
            await _context.SaveChangesAsync();

            return(addedAnimal.MapToDto());
        }
コード例 #27
0
        public async Task UpdateAnimalAsync(AnimalDto animalDto)
        {
            var animalDbo = _mapper.Map <Animal>(animalDto);

            var loaded = await _dbContext.Animals
                         .FirstOrDefaultAsync(x => x.AnimalId == animalDbo.AnimalId);

            loaded.AnimalTypeId = animalDbo.AnimalTypeId;
            loaded.DateOfBirth  = animalDbo.DateOfBirth;
            loaded.Gender       = animalDbo.Gender;
            loaded.Name         = animalDbo.Name;

            await _dbContext.SaveChangesAsync();
        }
コード例 #28
0
ファイル: NeedsService.cs プロジェクト: yakubovych/PetUA
        public async Task UpdateAnimalWithNeeds(AnimalDto animal, Animal model)
        {
            if (animal.Needs == null)
            {
                animal.Needs = new HashSet <NeedsDto>();
            }

            _animalNeedsRepository.TryUpdateManyToMany(model.AnimalNeeds, animal.Needs.Select(x => x.Id)
                                                       .Select(x => new AnimalNeeds
            {
                NeedsId  = x,
                AnimalId = animal.Id
            }), x => x.NeedsId);
            await _animalNeedsRepository.SaveAsync();
        }
コード例 #29
0
        public async Task UpdateAnimalWithDefects(AnimalDto animal, Animal model)
        {
            if (animal.Defects == null)
            {
                animal.Defects = new HashSet <DefectDto>();
            }

            _animalDefectRepository.TryUpdateManyToMany(model.AnimalDefects, animal.Defects
                                                        .Select(x => new AnimalDefects
            {
                DefectsId = x.Id,
                AnimalId  = animal.Id,
            }), x => x.DefectsId);
            await _animalDefectRepository.SaveAsync();
        }
コード例 #30
0
ファイル: KeepingService.cs プロジェクト: yakubovych/PetUA
        public async Task UpdateAnimalWithKeepings(AnimalDto animal, Animal model)
        {
            if (animal.Keepings == null)
            {
                animal.Keepings = new HashSet <KeepingDto>();
            }

            _animalKeepingRepository.TryUpdateManyToMany(model.AnimalKeepings, animal.Keepings.Select(x => x.Id)
                                                         .Select(x => new AnimalKeeping
            {
                KeepingId = x,
                AnimalId  = animal.Id,
            }), x => x.KeepingId);
            await _animalKeepingRepository.SaveAsync();
        }
コード例 #31
0
        public void ConvertAnimalToDto()
        {
            var animalDbModel = new Animal()
            {
                Id = 1, Name = "Jack", Owner = new Employee()
                {
                    FirstName = "John", LastName = "Smith", Id = 1, IsMIEmployee = true
                }, Type = EAnimalType.Cat, OwnerId = 1
            };
            var animalDto = new AnimalDto()
            {
                Id = 1, Name = "Jack", OwnerId = 1, Type = EAnimalType.Cat
            };

            Assert.AreEqual(animalDto, animalDbModel.MapToDto());
        }