예제 #1
0
        public async Task <Tuple <Pet, string> > CreatePet(PetDto petDto, int ownerId)
        {
            var pet = new Pet
            {
                Name        = petDto.Name,
                Race        = petDto.Race,
                Age         = petDto.Age,
                Size        = petDto.Size,
                Description = petDto.Description,
                Photos      = petDto.Photos,
                PetOwnerId  = ownerId,
                DateCreated = DateTime.UtcNow
            };

            try
            {
                _dbContext.Add(pet);
                await _dbContext.SaveChangesAsync();

                return(new Tuple <Pet, string>(pet, "success"));
            }
            catch (DbUpdateException e)
            {
                return(new Tuple <Pet, string>(null, $"error: {e.InnerException.Message}"));
            }
        }
예제 #2
0
        public IHttpActionResult PutPetDto(int id, PetDto petDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != petDto.PetID)
            {
                return(BadRequest());
            }

            db.Entry(petDto).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PetDtoExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #3
0
        public async Task <IDataResult <string> > Add(PetDto dto)
        {
            var postData = JsonConvert.SerializeObject(dto);

            var content = new StringContent(postData, Encoding.UTF8, ContentTypes.JSON);

            var token = _httpContextAccessor.HttpContext.Session.GetString("token");

            if (string.IsNullOrEmpty(token))
            {
                return(new DataResult <string>("Unauthorized.", false, System.Net.HttpStatusCode.NotFound));
            }

            _httpClient.AddJwtTokenToHeader(token);

            var response = await _httpClient.PostAsync("", content);

            if (response.IsSuccessStatusCode)
            {
                return(new DataResult <string>(await response.Content.ReadAsStringAsync(), true, System.Net.HttpStatusCode.OK));
            }
            else
            {
                return(new DataResult <string>(await response.Content.ReadAsStringAsync(), false, System.Net.HttpStatusCode.NotFound));
            }
        }
예제 #4
0
 /// <summary>
 ///     Status201Created + URI read new object
 /// </summary>
 /// <param name="oPet"></param>
 /// <returns></returns>
 private CreatedAtActionResult CreatedLocation201(PetDto oPet)
 {
     return(CreatedAtAction(
                nameof(ReadOneAsync),
                new { petName = oPet.Name },
                oPet));
 }
예제 #5
0
        public async Task <IActionResult> GetPetDetails(int id)
        {
            var userId = _claimsCompat.ExtractFirstIdClaim(HttpContext.User);

            // Just request all for the user while waiting for improvements on Core data access
            // logic.
            var request = new DataAccessRequest <IPet>
            {
                UserId = userId,
                // TODO: when capable swap to something that'd enable specifying the exact
                //       entity to access.
                Strategy = DataAccessRequest <IPet> .AcquisitionStrategy.All
            };
            var port = new BasicPresenter <GenericDataResponse <IPet> >();

            var success = await _getPetDataUseCase.Handle(request, port);

            if (!success)
            {
                return(BadRequest());
            }

            // search for the requested Id:
            var pet = port.Response.Result.FirstOrDefault(p => p.Id == id);

            return((pet != null) ? new OkObjectResult(PetDto.From(pet)) : BadRequest());
        }
예제 #6
0
        public async Task <IResult> Update(PetDto dto)
        {
            if (dto.PetId <= 0)
            {
                return(new ErrorResult());
            }

            var postData = JsonConvert.SerializeObject(dto);

            var content = new StringContent(postData, Encoding.UTF8, ContentTypes.JSON);

            var token = _httpContextAccessor.HttpContext.Session.GetString("token");

            if (string.IsNullOrEmpty(token))
            {
                return(new ErrorResult("Unauthorized."));
            }

            _httpClient.AddJwtTokenToHeader(token);

            var response = await _httpClient.PutAsync("", content);

            if (response.IsSuccessStatusCode)
            {
                return(new Result());
            }
            else
            {
                return(new ErrorResult(await response.Content.ReadAsStringAsync()));
            }
        }
예제 #7
0
 public Pet Map(PetDto dto)
 {
     return(new Pet
     {
         Name = dto.Name,
         Type = dto.Type ?? PetType.Other
     });
 }
예제 #8
0
        public async Task <IActionResult> Add()
        {
            var dto = new PetDto();

            await GenerateViewBags(dto);

            return(View("AddOrUpdate", dto));
        }
예제 #9
0
        public void AddPet(PetDto petDto)
        {
            Mapper.Initialize(config => config.CreateMap <PetDto, Pet>());
            var pet = Mapper.Map <PetDto, Pet>(petDto);

            dataBase.PetRepository.Create(pet);
            dataBase.Save();
        }
예제 #10
0
        public void Create(PetDto petDto)
        {
            var pet = _mapper.Map <Pet>(petDto);

            _unitOfWork.Pets.Create(pet);

            _unitOfWork.Save();
        }
예제 #11
0
        public void Post([FromBody] PetViewModel pet)
        {
            PetDto petDto = new PetDto()
            {
                Name = pet.Name, OwnerId = pet.OwnerId
            };

            ownerService.AddPet(petDto);
        }
예제 #12
0
        public static async Task <HttpResponseMessage> Create(PetDto petDto)
        {
            if (petDto == null)
            {
                throw new System.ArgumentNullException(nameof(petDto));
            }

            return(await Client.PostAsJsonAsync(BaseUrl, petDto));
        }
예제 #13
0
 public static DeletePetResponse Map(this PetDto petDto)
 {
     return(new DeletePetResponse()
     {
         Name = petDto.Name,
         Description = petDto.Description,
         Price = petDto.Price
     });
 }
예제 #14
0
        public async Task <IActionResult> Post([FromBody] PetDto model)
        {
            var pet = await _petsRepository.InsertPetAsync(AutoMapper.Mapper.Map <Pet>(model));

            var petToReturn = AutoMapper.Mapper.Map <PetDto>(pet);

            petToReturn.PopulateLinks(_urlHelper);

            return(CreatedAtRoute("GetPetById", new { id = petToReturn.Id }, petToReturn));
        }
        public ActionResult DeletePet(PetDto model) //Argument
        {
            if (model != null)
            {
                _pet.DeletePetById(model.Id);
                return(RedirectToAction("Index"));
            }

            return(NotFound("Pet ID not found."));
        }
예제 #16
0
        public IHttpActionResult GetPetDto(int id)
        {
            PetDto petDto = db.PetDtoes.Find(id);

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

            return(Ok(petDto));
        }
예제 #17
0
        public IHttpActionResult PostPetDto(PetDto petDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.PetDtoes.Add(petDto);
            db.SaveChanges();

            return(CreatedAtRoute("DefaultApi", new { id = petDto.PetID }, petDto));
        }
예제 #18
0
        public async Task <IActionResult> CreateAsync([FromBody] PetDto aPet)
        {
            try
            {
                var createdPet = await _manager.Create(Map(aPet));

                return(CreatedLocation201(ToView(createdPet)));
            }
            catch (System.Exception e)
            {
                return(InvalidResponseFactory(StatusCode(StatusCodes.Status405MethodNotAllowed, e.Message)));
            }
        }
예제 #19
0
        public IHttpActionResult DeletePetDto(int id)
        {
            PetDto petDto = db.PetDtoes.Find(id);

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

            db.PetDtoes.Remove(petDto);
            db.SaveChanges();

            return(Ok(petDto));
        }
예제 #20
0
        private async Task DeletePet(PetDto pet)
        {
            if (KutyAppClientContext.IsLoggedIn)
            {
                await EnvironmentApi.DeletePetAsync(pet.Id);
                await LoadMyPetsAsync();
            }
            else
            {
                await PageDialogService.DisplayAlertAsync("warning", "csak online lehet torolni", "OK");

                //await PetRepository.DeleteDogAsync(pet.Id);
            }
        }
예제 #21
0
        public int AddPetToShelter(PetDto newPet)
        {
            var newPetEntity = new Entities.PetEntity()
            {
                MedicalCondition = newPet.MedicalCondition,
                Name             = newPet.Name,
                Photo            = newPet.Photo,
                Race             = newPet.Race,
                ShelterId        = newPet.ShelterId
            };

            _dataStore.AddPet(newPetEntity);
            return(newPetEntity.Id);
        }
        //Update
        public async Task UpdateAsync(Guid id, PetDto pet)
        {
            const string sql = "UPDATE Pet SET Name = @Name, Description = @Description, Type = @Type WHERE Id = @Id;";

            var parameters = new DynamicParameters();

            parameters.Add("@Id", id);
            parameters.Add("@Name", pet.Name);
            parameters.Add("@Description", pet.Description);
            parameters.Add("@Type", pet.Type);

            using var connection = _connectionFactory.Connection();
            await connection.ExecuteAsync(sql, parameters, commandType : CommandType.Text);
        }
예제 #23
0
        public async Task <IActionResult> Put(long id, [FromBody] PetDto model)
        {
            if (!(await CheckPetExistsById(id)))
            {
                return(NotFound());
            }

            if (model.Id == 0)
            {
                model.Id = id;
            }

            await _petsRepository.UpdatePetAsync(AutoMapper.Mapper.Map <Pet>(model));

            return(Ok());
        }
        //Add
        public async Task <Pet> AddAsync(PetDto pet)
        {
            Pet newPet = new Pet()
            {
                Id          = Guid.NewGuid(),
                Name        = pet.Name,
                Description = pet.Description,
                Type        = pet.Type
            };

            using var connection = _connectionFactory.Connection();
            connection.Open();
            await connection.InsertAsync(newPet);

            return(newPet);
        }
예제 #25
0
        public async Task <IActionResult> Update(PetDto dto)
        {
            var result = await _petApiService.Update(dto);

            if (result.Success)
            {
                Alert("Güncelleme işlemi başarılı.");
                return(RedirectToAction("Update", dto.PetId));
            }
            else
            {
                await GenerateViewBags(dto);

                Alert("Güncelleme işlemi başarısız.: " + result.Message);
                return(View("AddOrUpdate", dto));
            }
        }
예제 #26
0
        public async Task <IActionResult> CreateAsync([FromBody] PetDto aPet)
        {
            try
            {
                var createdPet = await _manager.Create(Map(aPet));

                return(CreatedLocation201(ToView(createdPet)));
            }
            catch (System.DuplicateWaitObjectException e)
            {
                return(_invalidResponseFactory.Response(StatusCode(StatusCodes.Status400BadRequest, e.Message)));
            }
            catch (System.Exception e)
            {
                return(_invalidResponseFactory.Response(StatusCode(StatusCodes.Status500InternalServerError, e.Message)));
            }
        }
예제 #27
0
        public async Task <IActionResult> UpdateAsync([FromBody] PetDto aPet)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var updatedPet = await _manager.Replace(Map(aPet));

                return(Ok(ToView(updatedPet)));
            }
            catch (NotFoundException ex)
            {
                return(InvalidResponseFactory(NotFound(ex.Message)));
            }
        }
        public ActionResult DeleteConfirm(int id)
        {
            string url = "petdata/findpet/" + id;
            HttpResponseMessage response = client.GetAsync(url).Result;

            //Can catch the status code (200 OK, 301 REDIRECT), etc.
            //Debug.WriteLine(response.StatusCode);
            if (response.IsSuccessStatusCode)
            {
                //Put data into pet data transfer object
                PetDto SelectedPet = response.Content.ReadAsAsync <PetDto>().Result;
                return(View(SelectedPet));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
        // GET: Pet/Details/2
        public ActionResult Details(int id)
        {
            ShowPet             ViewModel = new ShowPet();
            string              url       = "petdata/findpet/" + id;
            HttpResponseMessage response  = client.GetAsync(url).Result;

            //Can catch the status code (200 OK, 301 REDIRECT), etc.

            if (response.IsSuccessStatusCode)
            {
                //Put data into pet data transfer object
                PetDto SelectedPet = response.Content.ReadAsAsync <PetDto>().Result;
                ViewModel.Pet = SelectedPet;

                return(View(ViewModel));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
예제 #30
0
        public async Task <IActionResult> PostPet([FromBody] PetDto petDto)
        {
            var username = User.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value;

            var owner = await _repository.GetOwnerByUserName(username);

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

            var result = await _repository.CreatePet(petDto, owner.Id);

            if (result.Item1 != null)
            {
                return(Ok(new { id = result.Item1.Id, Name = result.Item1.Name }));
            }
            else
            {
                return(BadRequest(new { message = $"error creating user: {result.Item2}" }));
            }
        }