public ActionResult AddCategory([Bind(Exclude = "Id")] AddCategoryDto model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    ViewBag.Parents         = LoadParents();
                    ViewBag.TypesOfPayments = LoadTypesOfPayments();
                    return(View(model));
                }

                if (_categoryRepository.GetAll().Any(x => x.Title == model.Title))
                {
                    ViewBag.Parents         = LoadParents();
                    ViewBag.TypesOfPayments = LoadTypesOfPayments();
                    ModelState.AddModelError("CustomError", "קטגוריה כבר קיימת");
                    return(View(model));
                }

                Category dto = Mapper.Map <Category>(model);
                _categoryRepository.Add(dto);
                InitState();

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                logger.Error($"AddCategory() {DateTime.Now}");
                logger.Error(ex.Message);
                logger.Error("==============================");
                return(null);
            }
        }
Beispiel #2
0
        public async Task <IActionResult> Create([FromBody] AddCategoryDto dto)
        {
            var model   = this.mapper.Map <AddCategoryModel>(dto);
            var created = await this.categoryService.AddAsync <CategoryDto>(model);

            return(this.Created($"/api/categories/{created.Id}", created));
        }
Beispiel #3
0
        public async Task <IActionResult> AddCategory(AddCategoryDto text, int id)
        {
            var image = await repo2.GetImage(id);

            if (image == null)
            {
                return(BadRequest("Nie odnaleziono zdjęcia."));
            }

            var userId = image.UserId;

            if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }

            var newCategory = new Category
            {
                Name = text.text
            };

            image.Categories.Add(newCategory);

            if (await repo.SaveAll())
            {
                return(Ok(newCategory));
            }

            return(BadRequest("Nie można dodać kategorii."));
        }
Beispiel #4
0
        /// <summary>
        /// 新增分类
        /// </summary>
        /// <returns></returns>
        public async Task AddCategoryAsync(AddCategoryDto addCategoryDto)
        {
            var mapModel = Map <AddCategoryDto, Category>(addCategoryDto);
            await CategoryRespository.InsertAsync(mapModel);

            await CategoryRespository.UnitOfWork.SaveChangesAsync();
        }
Beispiel #5
0
        public async Task <CategoryDto> AddCategoryAsync(AddCategoryDto addCategory)
        {
            var categoryEntity = _unitOfWork.Categories.Add(_mapper.Map <AddCategoryDto, Category>(addCategory));

            await _unitOfWork.CommitAsync();

            return(_mapper.Map <Category, CategoryDto>(categoryEntity));
        }
Beispiel #6
0
        public async Task <bool> AddCategory(AddCategoryDto req)
        {
            await _context.Category.AddAsync(req.Adapt <Category>());

            await _context.SaveChangesAsync();

            return(await Task.FromResult <bool>(true));
        }
 public void PostCategory(AddCategoryDto dto)
 {
     if (dto == null)
     {
         throw new CategoryRequiredException("Category is required");
     }
     categoryService.Add(dto);
     Uow.Commit();
 }
        public async Task <JsonResult> Add(AddCategoryDto model)
        {
            var result = await _categoryAppService.Add(model);

            OutputModel outputModel = new OutputModel();

            outputModel.Data = result;
            return(new JsonResult(outputModel));
        }
Beispiel #9
0
        public async Task <IActionResult> AddCategoryAsync(AddCategoryDto categoryDto)
        {
            var addCategory = await mediator.Send(new CreateCategoryCommand { Name = categoryDto.Name, ParentId = categoryDto.ParentId });

            if (addCategory.Success)
            {
                return(Ok(addCategory.Result));
            }
            return(BadRequest(addCategory.ErrorMessage));
        }
        public async Task <IActionResult> AddCategory([FromBody] AddCategoryDto categoryDto)
        {
            Category category = _mapper.Map <Category>(categoryDto);

            category.User = await _authRepository.GetUser(categoryDto.UserId);

            await _financesRepository.AddCategory(category);

            return(Ok());
        }
Beispiel #11
0
        public async Task <ServiceResult> AddAsync([FromBody] AddCategoryDto add)
        {
            var validation = add.Validation();

            if (validation.Fail)
            {
                return(ServiceResult.Failed(validation.Msg));
            }
            return(await Task.FromResult(await _categorySvc.AddAsync(add)));
        }
        public async Task <ActionResult <Category> > AddCategory(AddCategoryDto model)
        {
            if (ModelState.IsValid)
            {
                var result = await _Repo.AddCategory(model);

                return(Ok());
            }
            return(BadRequest());
        }
        public IActionResult Post([FromBody] AddCategoryDto model)
        {
            if (!ModelState.IsValid)
            {
                NotifyModelStateErrors();
                return(Response(model));
            }

            _categoryService.Add(model);

            return(Response(model));
        }
Beispiel #14
0
        public async Task <int> Add(AddCategoryDto dto)
        {
            Category category = new Category()
            {
                Title = dto.Title
            };

            _repository.Add(category);

            await _unitOfWork.ComplateAysnc();

            return(category.Id);
        }
Beispiel #15
0
        public async Task <Category> AddCategory(AddCategoryDto model)
        {
            if (model == null)
            {
                return(null);
            }
            var Category = _mapper.Map <Category>(model);
            var result   = await _db.Categories.AddAsync(Category);

            await _db.SaveChangesAsync();

            return(Category);
        }
Beispiel #16
0
        public async Task <ServiceResult> AddAsync(AddCategoryDto add)
        {
            var exist = await _categoryRepo.Select.AnyAsync(c => c.Name == add.Name);

            if (exist)
            {
                return(await Task.FromResult(ServiceResult.Failed($"Name:{add.Name} 的文章分类已存在")));
            }
            var entity = Mapper.Map <CategoryEntity>(add);
            await _categoryRepo.InsertAsync(entity);

            return(await Task.FromResult(ServiceResult.Successed("新增文章分类成功")));
        }
 public bool POST(AddCategoryDto Request)
 {
     try
     {
         var category = new CategoryDto();
         category.CategoryId   = Request.Id;
         category.CategoryName = Request.CategoryName;
         return(_categoryBll.AddCategory(category));
     }
     catch (Exception e)
     {
         return("Error");
     }
 }
Beispiel #18
0
        public async Task <ServiceResponse <List <GetCategoryDto> > > AddCategory(AddCategoryDto newCategory)
        {
            ServiceResponse <List <GetCategoryDto> > response = new ServiceResponse <List <GetCategoryDto> >();

            Category dbCategory = _mapper.Map <Category>(newCategory);

            await _context.Categories.AddAsync(dbCategory);

            await _context.SaveChangesAsync();

            response.Data = _context.Categories.Select(c => _mapper.Map <GetCategoryDto>(c)).ToList();

            return(response);
        }
        public async Task <CategoryDto> AddCategoryAsync(AddCategoryDto addCategory)
        {
            if (await _unitOfWork.Categories.GetByNameAsync(addCategory.Name) != null)
            {
                ExceptionHandler.DublicateObject(nameof(Category), nameof(Category.Name));
            }

            var categoryEntity = _unitOfWork.Categories.Add(_mapper.Map <AddCategoryDto, Category>(addCategory));

            categoryEntity.ImageUrl = await _imageService.UploadImageAsync(addCategory.Image);

            await _unitOfWork.CommitAsync();

            return(_mapper.Map <Category, CategoryDto>(categoryEntity));
        }
        public async Task <Category> AddCategory(AddCategoryDto addCategory)
        {
            Category cat = new Category
            {
                CategoryName = addCategory.CategoryName
            };

            using (var context = new DataBaseContext())
            {
                await context.Categories.AddAsync(cat);

                await context.SaveChangesAsync();
            }
            return(cat);
        }
Beispiel #21
0
        public async Task <HttpResponseMessage> Add(string login, string key, string categoryName, Dictionary <string, double> factor = null)
        {
            var uri = BaseUri.Append("add", login);
            var dto = new AddCategoryDto()
            {
                Name   = categoryName,
                Factor = factor
            };
            var content = new StringContent(JsonConvert.SerializeObject(dto));

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("x-functions-key", key);
                return(await httpClient.PostAsync(uri, content));
            }
        }
Beispiel #22
0
        public async Task <HttpResponseMessage> AddCategory(AddCategoryDto req)
        {
            Response <Entities.Entities.Category> httpResponse = new  Response <Entities.Entities.Category>();

            try
            {
                httpResponse.RequestState = true;
                httpResponse.ErrorState   = !await _categoryManager.AddCategory(req);
            }
            catch (Exception ex)
            {
                httpResponse.ErrorState = true;
                httpResponse.ErrorList.Add(ex.Adapt <ApiException>());
            }
            return(httpResponse);
        }
Beispiel #23
0
        public async Task <ActionResult> AddCategory([FromBody] AddCategoryDto viewRequest)
        {
            if (!TryValidateModel(viewRequest))
            {
                return(BadRequest(ValidationHelper.GetModelErrors(ModelState)));
            }

            var request = this._mapper.Map <AddCategoryRequest>(viewRequest);

            request.UserName = HttpContext.User.Identity.Name;
            var command = new AddCategoryCommand {
                Data = request
            };

            return(await Go(command));
        }
        public async Task <HttpResponseMessage> AddCategory(AddCategoryDto req)
        {
            _logger.LogDebug("AddCategory init with", req);
            Response <Entities.Entities.Category> httpResponse = new  Response <Entities.Entities.Category>();

            try
            {
                httpResponse.RequestState = true;
                httpResponse.ErrorState   = !await _categoryManager.AddCategory(req);
            }
            catch (Exception ex)
            {
                _logger.LogError("AddCategory Error", ex);
                httpResponse.ErrorState = true;
                httpResponse.ErrorList.Add(ex.Adapt <ApiException>());
            }
            _logger.LogDebug("AddCategory end with", httpResponse);
            return(httpResponse);
        }
 public async void AddCategory(AddCategoryDto dto)
 {
     await mediator.Send(new AddCategoryCommand { Name = dto.Name });
 }
Beispiel #26
0
        public async Task <ApiResult> AddCategory(AddCategoryDto addCategoryDto)
        {
            await cdyportService.AddCategoryAsync(addCategoryDto);

            return(ApiResult.Success);
        }
Beispiel #27
0
 public async Task AddCategory(AddCategoryDto input)//add category to restaurant
 {
     string userId   = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
     var    category = Category.Create(input.Type, input.RestaurantId, userId);
     await _categoryRepo.AddAsync(category);
 }
Beispiel #28
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(
                 AuthorizationLevel.Function,
                 "post",
                 Route = "categories/add/{login}/")
            ] HttpRequestMessage req,
            string login,
            [Table("ExpensesApp")] CloudTable table,
            [Table("ExpensesApp", "user_{login}", "user_{login}")] UserLogInData entity,
            TraceWriter log)
        {
            if (entity == null)
            {
                log.Info($"AddCategory response: BadRequest - no such user");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "User with given login does not exist"
                           ));
            }


            AddCategoryDto dto = null;

            try
            {
                dto = await req.Content.ReadAsDeserializedJson <AddCategoryDto>();
            }
            catch
            {
                log.Info("AddCategory response: BadRequest - cannot read dto object");
                return(req.CreateResponse(
                           statusCode: HttpStatusCode.BadRequest,
                           value: "Please pass a valid dto object in the request content"));
            }


            var newCategory = new Category()
            {
                Name   = dto.Name,
                Factor = dto.Factor
            };

            var householdId = entity.HouseholdId;
            var retrieveHouseholdOperation = TableOperation.Retrieve <Household>(householdId, householdId);
            var householdResult            = await table.ExecuteAsync(retrieveHouseholdOperation);

            if (householdResult.Result != null)
            {
                var household = householdResult.Result as Household;

                if (newCategory.Factor == null)
                {
                    var members = JsonConvert.DeserializeObject <List <Member> >(household.Members);
                    var factor  = new Dictionary <string, double>();
                    foreach (var member in members)
                    {
                        if (member.Login == login)
                        {
                            factor.Add(member.Login, 100);
                        }
                        else
                        {
                            factor.Add(member.Login, 0);
                        }
                    }
                    newCategory.Factor = factor;
                }

                var categories = JsonConvert.DeserializeObject <List <Category> >(household.CategoriesAggregated);
                categories.Add(newCategory);
                household.CategoriesAggregated = JsonConvert.SerializeObject(categories);
                var updateTableOperation = TableOperation.Replace(household);
                await table.ExecuteAsync(updateTableOperation);
            }
            else
            {
                var retrieveUsersOwnCategories = TableOperation.Retrieve <UserDetails>(householdId, entity.PartitionKey);
                var userDetailsResult          = await table.ExecuteAsync(retrieveUsersOwnCategories);

                if (userDetailsResult.Result != null)
                {
                    var userDetails = userDetailsResult.Result as UserDetails;
                    var categories  = JsonConvert.DeserializeObject <List <Category> >(userDetails.Categories);

                    if (newCategory.Factor == null)
                    {
                        newCategory.Factor = new Dictionary <string, double>()
                        {
                            { login, 100 }
                        };
                    }

                    categories.Add(newCategory);
                    userDetails.Categories = JsonConvert.SerializeObject(categories);
                    var updateTableOperation = TableOperation.Replace(userDetails);
                    await table.ExecuteAsync(updateTableOperation);
                }
                else
                {
                    log.Info($"AddCategory response: InternalServerError - user does not have categories neither in household nor in user detailed info");
                    return(req.CreateResponse(
                               statusCode: HttpStatusCode.InternalServerError,
                               value: "Cannot get categories"
                               ));
                }
            }

            return(req.CreateResponse(HttpStatusCode.OK));
        }
 public async Task <IActionResult> AddCategory([FromForm] AddCategoryDto addCategory)
 {
     return(Ok(await _categoryService.AddCategoryAsync(addCategory)));
 }
Beispiel #30
0
        public CategoryDto Add(AddCategoryDto dto)
        {
            var entity = _categoryDomainService.Add(dto.MapTo <Category>());

            return(entity.MapTo <CategoryDto>());
        }