public Response <SubCategoryDto> Save(SubCategoryDto subCategoryDto)
 {
     using (UnitOfWork unitOfWork = new UnitOfWork())
     {
         return(unitOfWork.SubCategories.Save(subCategoryDto, SubCategoryMappers.Instance.MapToSubCategoryDto));
     }
 }
예제 #2
0
        private HttpResponseMessage SaveSubCategory(SubCategoryDto subCategoryDto)
        {
            subCategoryDto.EditUserId = UserId.Value;
            Response <SubCategoryDto> response = subCategoryManager.Save(subCategoryDto);

            return(Request.CreateResponse <Response <SubCategoryDto> >(HttpStatusCode.OK, response));
        }
예제 #3
0
        public IResponseDTO Insert(SubCategoryDto model)
        {
            try
            {
                var Dto = _mapper.Map <SubCategory>(model);
                //  Dto.CreationDate = DateTime.Now;

                var DBmodel = _unitOfWork.SubCategory.Insert(Dto);

                var save = _unitOfWork.Save();

                if (save == "200")
                {
                    var SubCategoryDto = _mapper.Map <SubCategoryDto>(Dto);;
                    _response.Data    = SubCategoryDto;
                    _response.Code    = 200;
                    _response.Message = "OK";
                }
                else
                {
                    _response.Data    = null;
                    _response.Message = save;
                    _response.Code    = 400;
                }
            }
            catch (Exception ex)
            {
                _response.Data    = null;
                _response.Code    = 400;
                _response.Message = ex.Message;
            }
            return(_response);
        }
        public async Task <IActionResult> UpdateSubcategory(SubCategoryDto subCategoryDto)
        {
            if (!await _repo.SubCategoryNameExists("", subCategoryDto.Id))
            {
                return(BadRequest("Subcategory doesn't exists"));
            }

            if (await _repo.SubCategoryNameExists(subCategoryDto.Name.ToLower(), subCategoryDto.Id))
            {
                return(BadRequest("Subcategory with the same name already exists"));
            }

            var subCategoryToUpdate = new SubCategory
            {
                Id     = subCategoryDto.Id,
                Name   = subCategoryDto.Name,
                Active = subCategoryDto.Active
            };

            if (await _repo.UpdateSubcategory(subCategoryToUpdate))
            {
                return(Ok());
            }

            return(BadRequest("Unable to update"));
        }
예제 #5
0
        public bool Validate(SubCategoryDto request)
        {
            if (_context.Categories.Find(request.CategoryId) == null)
            {
                throw new EntityNotFoundException("Category with id: " + request.CategoryId);
            }

            if (_context.SubCategories
                .Include(sc => sc.Category)
                .AsQueryable()
                .Where
                (
                    x =>
                    (x.Name.Trim().ToLower() == request.Name.Trim().ToLower()) &&
                    (x.Category.Id == request.CategoryId)
                )
                .Count()
                != 0
                )
            {
                throw new EntityAlreadyExistsException("Sub Category with name:" + request.Name);
            }

            return(true);
        }
        //[ProducesResponseType(typeof(CategoryDto), 201)]
        //[ProducesResponseType(typeof(CategoryDto), 400)]
        public IActionResult AddSubCategory([FromBody] SubCategoryDto subCategoryDto)
        {
            if (subCategoryDto == null)
            {
                return(BadRequest("categorycreate object was null"));
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            SubCategory toAdd = Mapper.Map <SubCategory>(subCategoryDto);

            _subCategoryRepository.Add(toAdd);

            bool result = _subCategoryRepository.Save();

            if (!result)
            {
                //return new StatusCodeResult(500);
                throw new Exception("something went wrong when adding a new subcategory");
            }

            //return Ok(Mapper.Map<CategoryDto>(toAdd));
            return(CreatedAtRoute("GetSingleSubCategory", new { id = toAdd.Id }, Mapper.Map <SubCategoryDto>(toAdd)));
        }
        public IActionResult UpdateSubCategory(int id, [FromBody] SubCategoryDto subCategoryDto)
        {
            if (subCategoryDto == null)
            {
                return(BadRequest());
            }
            var existingSubCategory = _subCategoryRepository.GetSingleSubCategory(id);

            subCategoryDto.Id = existingSubCategory.Id;
            if (existingSubCategory == null)
            {
                return(NotFound());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Mapper.Map(subCategoryDto, existingSubCategory);

            _subCategoryRepository.Update(existingSubCategory);

            bool result = _subCategoryRepository.Save();

            if (!result)
            {
                //return new StatusCodeResult(500);
                throw new Exception($"something went wrong when updating the subcategory with id: {id}");
            }

            return(Ok(Mapper.Map <SubCategoryDto>(existingSubCategory)));
        }
예제 #8
0
        public IResponseDTO Update(SubCategoryDto model)
        {
            try
            {
                var DbSubCategory = _mapper.Map <SubCategory>(model);
                DbSubCategory.LastEditDate = DateTime.UtcNow.AddHours(2);
                _unitOfWork.SubCategory.Update(DbSubCategory);
                var save = _unitOfWork.Save();

                if (save == "200")
                {
                    _response.Data    = model;
                    _response.Code    = 200;
                    _response.Message = "OK";
                }
                else
                {
                    _response.Data = null;

                    _response.Code    = 400;
                    _response.Message = save;
                }
            }
            catch (Exception ex)
            {
                _response.Data    = null;
                _response.Code    = 400;
                _response.Message = ex.Message;
            }
            return(_response);
        }
예제 #9
0
        public async Task <IActionResult> UpdateSubCategory([FromRoute] int id, [FromBody] SubCategoryDto entityDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != entityDto.Id)
            {
                return(BadRequest());
            }

            var entity = await _repository.GetByIdAsync(entityDto.Id);

            if (entity == null)
            {
                return(NotFound("Sub-category does not exist"));
            }

            _mapper.Map(entityDto, entity);

            try
            {
                _repository.Update(entity);
                await _unitOfWork.SaveAsync();
            }

            catch (Exception)
            {
                throw new Exception("An unexpected error occured. Could not update.");
            }

            return(Ok(_mapper.Map <SubCategoryDto>(entity)));
        }
예제 #10
0
 public IResponseDTO Remove(SubCategoryDto model)
 {
     try
     {
         var DBmodel = _mapper.Map <SubCategory>(model);
         _unitOfWork.SubCategory.Delete(DBmodel);
         var save = _unitOfWork.Save();
         if (save == "200")
         {
             _response.Data    = null;
             _response.Code    = 200;
             _response.Message = "OK";
         }
         else
         {
             _response.Data    = null;
             _response.Message = save;
             _response.Code    = 400;
         }
     }
     catch (Exception ex)
     {
         _response.Data    = null;
         _response.Code    = 400;
         _response.Message = ex.Message;
     }
     return(_response);
 }
예제 #11
0
        public async Task <ApplicationResult <SubCategoryDto> > Get(Guid id)
        {
            try
            {
                //SubCategory subCategory = await _context.SubCategories.FindAsync(id);
                //SubCategoryDto mapSubCategory = _mapper.Map<SubCategoryDto>(subCategory);

                var SubCategoryList = await(from s in _context.SubCategories
                                            join c in _context.Categories on s.CategoryId equals c.Id
                                            select new
                {
                    c.CategoryName,
                    s.Id,
                    s.CategoryId,
                    s.SubCategoryName,
                    s.SubCategoryUrlName,
                    s.CreatedBy,
                    s.CreatedById,
                    s.CreatedDate,
                    s.ModifiedBy,
                    s.ModifiedById,
                    s.ModifiedDate
                }).ToListAsync();
                var selectSubCategory = SubCategoryList.Where(x => x.Id == id).FirstOrDefault();

                SubCategoryDto mapSubCategory = new SubCategoryDto();

                mapSubCategory = new SubCategoryDto
                {
                    Id                 = selectSubCategory.Id,
                    CategoryName       = selectSubCategory.CategoryName,
                    CategoryId         = selectSubCategory.CategoryId,
                    SubCategoryName    = selectSubCategory.SubCategoryName,
                    SubCategoryUrlName = selectSubCategory.SubCategoryUrlName,
                    CreatedBy          = selectSubCategory.CreatedBy,
                    CreatedById        = selectSubCategory.CreatedById,
                    CreatedDate        = selectSubCategory.CreatedDate,
                    ModifiedBy         = selectSubCategory.ModifiedBy,
                    ModifiedById       = selectSubCategory.ModifiedById,
                    ModifiedDate       = selectSubCategory.ModifiedDate
                };


                return(new ApplicationResult <SubCategoryDto>
                {
                    Result = mapSubCategory,
                    Succeeded = true
                });
            }
            catch (Exception e)
            {
                return(new ApplicationResult <SubCategoryDto>
                {
                    Result = new SubCategoryDto(),
                    Succeeded = false,
                    ErrorMessage = e.Message
                });
            }
        }
예제 #12
0
        public HttpResponseMessage FetchSubCategory(int subCategoryId)
        {
            SubCategoryDto subCategoryDto = new SubCategoryDto {
                CrudStatus = CrudStatus.READ, Id = subCategoryId
            };

            return(SaveSubCategory(subCategoryDto));
        }
        private async Task UpdateAsync(SubCategoryDto input)
        {
            if (input.Id != null)
            {
                var subcategory = await _subcategoryRepository.FirstOrDefaultAsync((int)input.Id);

                ObjectMapper.Map(input, subcategory);
            }
        }
예제 #14
0
        public async Task <ActionResult> PostSubCategory(SubCategoryDto subCategoryDto)
        {
            var subCategory = _mapper.Map <SubCategory>(subCategoryDto);
            await _repo.Add(subCategory);

            var subCategoryToReturn = _mapper.Map <SubCategoryDto>(subCategory);

            return(CreatedAtAction("GetSubCategory", new { id = subCategoryToReturn.Id }, subCategoryToReturn));
        }
예제 #15
0
 public void Execute(SubCategoryDto request)
 {
     _context.SubCategories.Add(new SubCategories
     {
         Active      = true,
         DateCreated = DateTime.Now,
         Category    = _context.Categories.Find(request.CategoryId),
         Name        = request.Name
     });
     _context.SaveChanges();
 }
예제 #16
0
        public static SubCategoryViewModel MapFromDto(this SubCategoryDto subCategoryDto)
        {
            SubCategoryViewModel subCategoryViewModel = new SubCategoryViewModel();

            subCategoryViewModel.Id            = subCategoryDto.Id;
            subCategoryViewModel.Name          = subCategoryDto.Name;
            subCategoryViewModel.Categories_Id = subCategoryDto.Categories_Id;
            subCategoryViewModel.PolicyCount   = subCategoryDto.PolicyCount;

            return(subCategoryViewModel);
        }
 public async Task CreateOrUpdateSubCategory(SubCategoryDto input)
 {
     if (input.Id == null)
     {
         await CreateAsync(input);
     }
     else
     {
         await UpdateAsync(input);
     }
 }
예제 #18
0
        public SubCategoryDto CreateSubCategory(SubCategoryDto subCategoryDto)
        {
            var subCategory = _mapper.Map <SubCategory>(subCategoryDto);
            int res         = _repo.Create(subCategory);

            if (res <= 0)
            {
                return(null);
            }
            return(subCategoryDto);
        }
 public async Task <IActionResult> Update([FromBody] SubCategoryDto subcategory)
 {
     try
     {
         return(Ok(await _subCategoryService.Update(subcategory)));
     }
     catch (Exception e)
     {
         _loggerManager.LogError($"Ocurrio un error mientras se modificaba el subcategory: {e}");
         throw new ApiException(AppResources.BadRequest, HttpStatusCode.BadRequest);
     }
 }
예제 #20
0
        public async Task <SubCategoryDto> Update(SubCategoryDto subcategory)
        {
            var entity        = _mapper.Map <SubCategory>(subcategory);
            var modelToUpdate = await _subCategoryRepository.FindByCondition(x => x.Id == entity.Id);

            if (!modelToUpdate.Any())
            {
                throw new ApiException("No se pudo editar la subcategory", HttpStatusCode.NotFound);
            }
            _subCategoryRepository.Update(entity);
            return(_mapper.Map <SubCategoryDto>(entity));
        }
 public async Task <IActionResult> Add([FromBody] SubCategoryDto subcategory)
 {
     try
     {
         subcategory.Id = Guid.NewGuid();
         _subCategoryService.Save(subcategory);
         return(CreatedAtAction(nameof(GetById), new { version = HttpContext.GetRequestedApiVersion().ToString(), id = subcategory.Id }, subcategory));
     }
     catch (Exception e)
     {
         _loggerManager.LogError($"Ocurrio un error cuando se intentaba guardar el subcategory: {e}");
         throw new ApiException(AppResources.BadRequest, HttpStatusCode.BadRequest);
     }
 }
예제 #22
0
        public async Task <IActionResult> PostSubCategory([FromBody] SubCategoryDto subCategoryDto)
        {
            var subCategory = _mapper.Map <SubCategory>(subCategoryDto);

            subCategory.CreatedDate = DateTime.UtcNow;
            await _iSubCategoryRepository.Create(subCategory);

            if (await _iSubCategoryRepository.SaveAll())
            {
                return(Ok(_mapper.Map <SubCategoryDto>(subCategory)));
            }

            throw new Exception("Error adding the category");
        }
예제 #23
0
        public SubCategoryDto AddSubCategory(SubCategoryDto subCategoryDto)
        {
            try
            {
                var subCategory = Mapper.Map <SubCategory>(subCategoryDto);
                _unitOfWork.SubCategory.Insert(subCategory);
                _unitOfWork.Complete();

                return(subCategoryDto);
            }
            catch (Exception)
            {
                return(null);
            }
        }
예제 #24
0
        public bool UpdateSubCategory(SubCategoryDto subCategoryDto)
        {
            try
            {
                var subCategoryNeedUpdate = Mapper.Map <SubCategory>(subCategoryDto);

                _unitOfWork.SubCategory.Update(subCategoryNeedUpdate);
                _unitOfWork.Complete();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public async Task <IActionResult> Delete(Guid id, SubCategoryDto model)
        {
            var errorReturnModel = model;

            if (ModelState.IsValid & id == model.Id)
            {
                var deleteService = await _subCategoryService.Delete(id);

                if (deleteService.Succeeded)
                {
                    return(RedirectToAction("Index"));
                }
                ModelState.AddModelError(string.Empty, deleteService.ErrorMessage);
            }

            return(View(errorReturnModel));
        }
예제 #26
0
        public ActionResult <SubCategoryDto> UpdateSubCategory([FromBody] SubCategoryDto subCategory)
        {
            var subCategoryDto = _subCategoryService.UpdateSubCategory(subCategory);

            if (subCategoryDto == null)
            {
                List <string> errorMessage = new List <string>();
                errorMessage.Add("Đã phát sinh lỗi, vui lòng thử lại");
                return(BadRequest(new ResponseDto(errorMessage, 500, subCategoryDto)));
            }
            List <string> successMessage = new List <string>();

            successMessage.Add("Sửa thông tin thành công");
            var responseDto = new ResponseDto(successMessage, 200, subCategoryDto);

            return(Ok(responseDto));
        }
예제 #27
0
        public async Task <IActionResult> PutSubCategory(int id, SubCategoryDto subCategoryDto)
        {
            if (id != subCategoryDto.Id)
            {
                return(BadRequest());
            }
            var subCategory = _mapper.Map <SubCategory>(subCategoryDto);
            var updated     = await _repo.Update(subCategory);

            if (updated)
            {
                return(Ok("Updated"));
            }
            else
            {
                return(BadRequest("Could not update"));
            }
        }
예제 #28
0
        public async Task <ApplicationResult <List <SubCategoryDto> > > GetSubCategory(Guid id)
        {
            try
            {
                var SubCategoryList = await _context.SubCategories.Where(x => x.CategoryId == id).Include(c => c.Category).ToListAsync();

                List <SubCategoryDto> listSubCategory = new List <SubCategoryDto>();
                foreach (var item in SubCategoryList)
                {
                    SubCategoryDto mapSubCategory = new SubCategoryDto
                    {
                        Id                 = item.Id,
                        CategoryId         = item.CategoryId,
                        CategoryName       = item.Category.CategoryName,
                        SubCategoryName    = item.SubCategoryName,
                        SubCategoryUrlName = item.SubCategoryUrlName,
                        CreatedBy          = item.CreatedBy,
                        CreatedById        = item.CreatedById,
                        CreatedDate        = item.CreatedDate,
                        ModifiedBy         = item.ModifiedBy,
                        ModifiedById       = item.ModifiedById,
                        ModifiedDate       = item.ModifiedDate
                    };
                    listSubCategory.Add(mapSubCategory);
                }


                return(new ApplicationResult <List <SubCategoryDto> >
                {
                    Succeeded = true,
                    Result = listSubCategory
                });
            }
            catch (Exception e)
            {
                return(new ApplicationResult <List <SubCategoryDto> >
                {
                    Succeeded = false,
                    ErrorMessage = e.Message,
                    Result = new List <SubCategoryDto>()
                });
            }
        }
예제 #29
0
        public IEnumerable <SubCategoryDto> Execute(SubCategorySearch request)
        {
            List <SubCategoryDto> subCategoryDtos = new List <SubCategoryDto>();
            var subCategories = _context.SubCategories
                                .Include(sc => sc.Category)
                                .AsQueryable();

            if (request.Id == null)
            {
                if (request.Name != null)
                {
                    subCategories = subCategories.Where(x => x.Name.Trim().ToLower().Contains(request.Name.Trim().ToLower()));
                }

                if (request.CategoryId != null)
                {
                    subCategories = subCategories.Where(x => x.Category.Id == request.CategoryId);
                }
            }
            else
            {
                subCategories = subCategories.Where(x => x.Id == request.Id);
            }

            if (subCategories.Count() == 0)
            {
                throw new EntityNotFoundException($"Subcategories");
            }

            foreach (var subCategory in subCategories)
            {
                var subCategoryDto = new SubCategoryDto
                {
                    Id         = subCategory.Id,
                    Name       = subCategory.Name,
                    CategoryId = subCategory.Category.Id
                };

                subCategoryDtos.Add(subCategoryDto);
            }

            return(subCategoryDtos);
        }
예제 #30
0
        public Guid AddNewSubCategory(NewSubCategoryDto data)
        {
            var categories  = cacheManager.GetOrCreate <List <CategoryDto> >(nameof(Category), () => FetchCategories());
            var hasCategory = categories.Any(f => f.Id == data.CategoryId);

            if (!hasCategory)
            {
                throw new InvalidOperationException("Category not found");
            }
            var sc = new SubCategory
            {
                Id         = Guid.NewGuid(),
                CategoryId = data.CategoryId,
                Created    = DateTime.Now,
                Updated    = DateTime.Now,
                IsActive   = true,
                IsDeleted  = false,
                ImageUrl   = null,
                Name       = data.Name,
                CreatedBy  = claims.Session.Id,
                UpdatedBy  = claims.Session.Id,
            };

            context.SubCategories.Add(sc);
            var resultValue = context.SaveChanges();

            if (resultValue > 0)
            {
                var dto = new SubCategoryDto
                {
                    Id     = sc.Id,
                    ImgUrl = sc.ImageUrl,
                    Name   = sc.Name
                };
                cacheManager.Update <List <SubCategoryDto> >(nameof(SubCategory), (cachedData) =>
                {
                    cachedData.Add(dto);
                });
                return(sc.Id);
            }
            return(Guid.Empty);
        }