public async Task Create(CategoryInputModel model)
        {
            Category category = model.To <Category>();
            await context.Categories.AddAsync(category);

            await context.SaveChangesAsync();
        }
        public CategoryDto CreateCategory(CategoryInputModel category, string slug)
        {
            int nextInt = 0;

            if (CategoryDataProvider.Categories.Count() == 0)
            {
                nextInt = 1;
            }
            else
            {
                nextInt = CategoryDataProvider.Categories.OrderByDescending(c => c.Id).FirstOrDefault().Id + 1;
            }
            var entity = new Category
            {
                Id         = nextInt,
                Name       = category.Name,
                Slug       = slug,
                ModifiedBy = "Admin"
            };

            CategoryDataProvider.Categories.Add(entity);
            return(new CategoryDto
            {
                Id = entity.Id,
                Name = entity.Name,
                Slug = entity.Slug
            });
        }
        public async Task <IActionResult> Edit(int id)
        {
            if (id == 0)
            {
                return(this.CustomNotFound());
            }

            var jobCategory = await this.categoriesService.GetByIdAsync <JobCategoriesViewModel>(id);

            if (jobCategory == null)
            {
                return(this.CustomNotFound());
            }

            var inputModel = new CategoryInputModel
            {
                BaseJobCategoryId = jobCategory.BaseJobCategoryId,
                Description       = jobCategory.Description,
                Id         = jobCategory.Id,
                Name       = jobCategory.Name,
                PictureUrl = jobCategory.PictureUrl,
            };

            return(this.View(inputModel));
        }
示例#4
0
        public async Task <object> Create([FromBody] CategoryInputModel model)
        {
            if (this.User.IsInRole("Admin"))
            {
                try
                {
                    var category = await this.categoryService.Create(model);

                    await this.hubContext.Clients.All.SendAsync("CategoryAdd", category);

                    return(this.Ok(new CreateEditReturnMessage <CategoryViewModel>
                    {
                        Message = "Category created successfully", Data = category
                    }));
                }
                catch (Exception e)
                {
                    return(this.BadRequest(new ReturnMessage {
                        Message = e.Message
                    }));
                }
            }

            return(this.Unauthorized(new ReturnMessage {
                Message = "You are unauthorized!"
            }));
        }
        public async Task <IActionResult> Create(CategoryInputModel categoryInput)
        {
            var existsMatchingCategory = this.categoriesService
                                         .Exists(x => x.Name == categoryInput.Name);

            if (!this.ModelState.IsValid || existsMatchingCategory)
            {
                if (existsMatchingCategory)
                {
                    this.ModelState.AddModelError(MatchingCategoryKey, MatchingCategoryErrorMessage);
                }

                return(this.View(categoryInput));
            }

            var image = await this.cloudinaryService.SaveImageAsync(categoryInput.FormFile);

            await this.categoriesService.AddAsync(categoryInput, image);

            var categoryNameEncoded = HttpUtility.HtmlEncode(categoryInput.Name);

            this.TempData[GlobalConstants.MessageKey] = $"Successfully created category <strong>{categoryNameEncoded}</strong>";

            return(this.RedirectToAction("Index", "Categories", new { area = "Forum" }));
        }
        public async Task <ActionResult> Create([FromBody] CategoryInputModel input)
        {
            if (this.User.Identity.Name == GlobalConstants.AdminName)
            {
                var isCategoryAlreadyExisting = await this.categoriesService.IsCategoryAlreadyExistingAsync(input.Name);

                if (isCategoryAlreadyExisting)
                {
                    return(this.BadRequest(new BadRequestViewModel
                    {
                        Message = Messages.AlreadyExistsCategory,
                    }));
                }

                try
                {
                    await this.categoriesService.CreateAsync(input.Name, input.Picture);

                    return(this.Ok(new
                    {
                        Message = Messages.SuccessfullyAdded,
                    }));
                }
                catch (Exception)
                {
                    return(this.BadRequest(new BadRequestViewModel
                    {
                        Message = Messages.UnknownError,
                    }));
                }
            }

            return(this.Unauthorized());
        }
示例#7
0
        public async Task DoesCategoryCreateAsyncWorksCorrectly()
        {
            var categoryList = new List <Category>();

            var service = this.CreateMockAndConfigureService(categoryList, new List <CategoryRecipe>());

            using FileStream stream = File.OpenRead(TestImageName);
            var file = new FormFile(stream, 0, stream.Length, null, stream.Name)
            {
                Headers     = new HeaderDictionary(),
                ContentType = TestImageContentType,
            };

            var categoryToAdd = new CategoryInputModel
            {
                Name  = TestCategoryName,
                Image = file,
            };

            await service.CreateAsync(categoryToAdd, TestRootPath);

            var count = categoryList.Count();

            Assert.Equal(1, count);
        }
        public async Task <int> CreateAsync(CategoryInputModel inputModel, string rootPath)
        {
            if (this.categoriesRepository.All().Any(x => x.Name == inputModel.Name))
            {
                throw new ArgumentException(ExceptionMessages.CategoryAlreadyExists, inputModel.Name);
            }

            var    imageName = inputModel.Name.ToLower().Replace(" ", "-");
            var    imageUrl  = $"/assets/img/categories/{imageName}.jpg";
            string imagePath = rootPath + imageUrl;

            using (FileStream stream = new FileStream(imagePath, FileMode.Create))
            {
                await inputModel.Image.CopyToAsync(stream);
            }

            var category = new Category
            {
                Name     = inputModel.Name,
                ImageUrl = imageUrl,
            };

            await this.categoriesRepository.AddAsync(category);

            await this.categoriesRepository.SaveChangesAsync();

            return(category.Id);
        }
示例#9
0
        /// <summary>
        /// Add new category
        /// </summary>
        /// <param name="model">Category that should be added</param>
        /// <returns>Action result</returns>
        public async Task <IHttpActionResult> Post(CategoryInputModel model)
        {
            if (model == null)
            {
                return(BadRequest("Model can not be empty."));
            }

            try
            {
                if (ModelState.IsValid)
                {
                    _unitOfWork.Categories.Add(_mapper.Map <Category>(model));
                    await _unitOfWork.Commit();
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch
            {
                return(InternalServerError());
            }

            return(Ok("Category added"));
        }
        /* From teacher:
         *      "Betri leið væri að sækja stærsta Id
         *      og incrementa það þegar verið er að vinna með lista." */
        public Category ToCategory(CategoryInputModel category)
        {
            var entity = Mapper.Map <Category>(category);

            entity.Id = _dataContext.getCategories.Max(c => c.Id) + 1;
            return(entity);
        }
示例#11
0
        public async Task CreateCategoryFailDueToUnauthorizedToken(string email, string password, string username, string categoryName)
        {
            await this.Register(email, password, username);

            var token = await this.Login(email, password);

            this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            var category = new CategoryInputModel
            {
                Name = categoryName
            };

            var json = new StringContent(
                JsonConvert.SerializeObject(category),
                Encoding.UTF8,
                "application/json");

            var response = await this.client.PostAsync(CategoryCreateEndpoint, json);

            var content = JsonConvert.DeserializeObject <ReturnMessage>(await response.Content.ReadAsStringAsync());

            Assert.Equal(StatusCodes.Status401Unauthorized, content.Status);
            Assert.Equal(UnauthorizedError, content.Message);
        }
示例#12
0
        public async Task CreateCategorySuccessfully(string email, string password, string categoryName)
        {
            var token = await this.Login(email, password);

            this.client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            var category = new CategoryInputModel
            {
                Name = categoryName
            };

            var json = new StringContent(
                JsonConvert.SerializeObject(category),
                Encoding.UTF8,
                "application/json");

            var response = await this.client.PostAsync(CategoryCreateEndpoint, json);

            response.EnsureSuccessStatusCode();

            var content = JsonConvert.DeserializeObject <CreateEditReturnMessage <CategoryViewModel> >(await response.Content.ReadAsStringAsync());

            Assert.Equal("Category created successfully", content.Message);
            Assert.Equal(StatusCodes.Status200OK, content.Status);
        }
        public async Task <IActionResult> Create(CategoryInputModel categoryData)
        {
            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState.ToDictionary(x => x.Key, x => x.Value.Errors)));
            }

            var category = new Category
            {
                Name           = categoryData.Name,
                NormalizedName = categoryData.Name.ToUpper(),
                CreatedOn      = DateTime.UtcNow,
                EditedOn       = DateTime.UtcNow,
                IsActive       = true
            };

            try
            {
                await this.categoryService.Create(category);
            }
            catch (Exception e)
            {
                this.logger.LogError(e.Message);
                this.logger.LogInformation(e.StackTrace);
                return(this.BadRequest("An error occurred while trying to create a category!"));
            }

            return(this.Ok("Category created successfully!"));
        }
示例#14
0
        public ActionResult <CategoryViewModel> Post(CategoryInputModel categoryInputModel)
        {
            Category category = MapearCategory(categoryInputModel);
            var      response = _categoryService.save(category);

            return((response.Error == false)? Ok(response.Object):  BadRequest(response.Menssage));
        }
示例#15
0
        public async Task <IHttpActionResult> Post(CategoryInputModel inputModel)
        {
            if (inputModel == null)
            {
                throw new ArgumentException("inputModel can't be null");
            }

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

            var category = new Category()
            {
                Name = inputModel.Name,
            };

            var result = await categoryRepository.SaveAsync(category);

            if (!result)
            {
                throw new OperationCanceledException("Error when saved!");
            }

            return(Ok());
        }
示例#16
0
        public async Task <IHttpActionResult> Put([FromUri] int id, [FromBody] CategoryInputModel inputModel)
        {
            if (inputModel == null)
            {
                throw new ArgumentException("inputModel can't be null");
            }

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

            var category = await categoryRepository.GetByIdAsync(id);

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

            category.Name = inputModel.Name;

            var result = await categoryRepository.SaveAsync(category);

            if (!result)
            {
                throw new OperationCanceledException("Error when saved!");
            }

            return(Ok());
        }
        public CategoryViewModel Category(CategoryInputModel inputModel)
        {
            CategoryViewModel viewModel = new CategoryViewModel();

            //initialize the dropdownlist values
            string ex;
            var    performanceCounterCategories = _performanceMonitorService.CategoryNames(out ex).ToList();

            if (ex == string.Empty)
            {
                var categoryList = performanceCounterCategories.Select(c => new SelectListItem
                {
                    Text  = c.ToString(),
                    Value = c.ToString()
                });

                viewModel.Accessible   = true;
                viewModel.CategoryList = new SelectList(categoryList, "Value", "Text", inputModel.CategoryName);
                return(viewModel);
            }
            else
            {
                _notifier.Error(T("Error: Not able to load the categories. Exception: {0} ", ex));
                viewModel.Accessible = false;
                return(viewModel);
            }
        }
        public int CreateNewCategory(CategoryInputModel category)
        {
            var entity = ToCategory(category);

            _dataContext.getCategories.Add(entity);
            return(entity.Id);
        }
        public async Task <IActionResult> EditPost(string id, [FromBody] CategoryInputModel categoryInput)
        {
            bool isIdCorrect = int.TryParse(id, out int categoryId);

            if (!isIdCorrect)
            {
                return(this.NotFound("Category does not exist!"));
            }

            var category = this.categoryService.GetById(categoryId, true);

            if (category == null)
            {
                return(this.NotFound("Category does not exist!"));
            }

            if (!this.ModelState.IsValid)
            {
                return(this.BadRequest(this.ModelState.ToDictionary(x => x.Key, x => x.Value.Errors)));
            }

            try
            {
                await this.categoryService.Update(category, categoryInput);
            }
            catch (Exception e)
            {
                this.logger.LogError(e.Message);
                this.logger.LogInformation(e.StackTrace);
                return(this.BadRequest("An error occurred while trying to edit category!"));
            }

            return(this.Ok("Successfully edited category!"));
        }
示例#20
0
        public async Task CreateAsync(CategoryInputModel input, string imagePath)
        {
            var category = new Category()
            {
                Name        = input.Name,
                Title       = input.Title,
                Description = input.Description,
            };

            Directory.CreateDirectory($"{imagePath}/categories/");
            foreach (var image in input.Images)
            {
                var extension = Path.GetExtension(image.FileName).TrimStart('.');
                if (!this.allowedExtensions.Any(x => extension.EndsWith(x)))
                {
                    throw new Exception($"Invalid image extension {extension}");
                }

                var dbImage = new Image
                {
                    Extension = extension,
                };
                category.Images.Add(dbImage);
                var physicalPath = $"{imagePath}/categories/{dbImage.Id}.{extension}";
                await using Stream fileStream = new FileStream(physicalPath, FileMode.Create);
                await image.CopyToAsync(fileStream);
            }

            await this.categoriesRepository.AddAsync(category);

            await this.categoriesRepository.SaveChangesAsync();
        }
示例#21
0
        public void UpdateCategoryById(CategoryInputModel body, int id)
        {
            var entity = CategoryDataProvider.Categories.FirstOrDefault(c => c.Id == id);

            //Update props
            entity.Name = body.Name;
            entity.Slug = body.Name.Replace(' ', '-').ToLower();
        }
 public void updateCategoryById(int categoryId, [FromBody] CategoryInputModel inputModel)
 {
     if (!ModelState.IsValid)
     {
         throw new ModelFormatException();
     }
     _categoryService.updateCategoryById(categoryId, inputModel);
 }
示例#23
0
        public IActionResult Create(CategoryInputModel model)
        {
            this.categoryService.Create(model, this.User);

            this.TempData["Message"] = $"Successfully created the {model.Name} category.";

            return(this.Redirect("/Admin/Category/Create"));
        }
        public void UpdateCategoryById(CategoryInputModel category, int categoryId)
        {
            var updateCategory = _dataContext.getCategories.FirstOrDefault(c => c.Id == categoryId);

            updateCategory.Name             = category.Name;
            updateCategory.ParentCategoryId = category.ParentCategoryId;
            updateCategory.Slug             = category.Slug;
        }
示例#25
0
        public async Task Update(int id, CategoryInputModel model)
        {
            Category category = context.Categories.Find(id);

            category.Name = model.Name;
            context.Categories.Update(category);
            await context.SaveChangesAsync();
        }
 public ActionResult <string> createCategory([FromBody] CategoryInputModel inputModel)
 {
     if (!ModelState.IsValid)
     {
         throw new ModelFormatException();
     }
     return(getCategoryById(_categoryService.createCategory(inputModel)));
 }
示例#27
0
 public IActionResult UpdateCategoryById([FromBody] CategoryInputModel body, int id)
 {
     if (!ModelState.IsValid)
     {
         return(BadRequest("Data was not properly formatted."));
     }
     _categoryService.UpdateCategoryById(body, id);
     return(NoContent());
 }
示例#28
0
        public void UpdateCategoryById(CategoryInputModel category, int id)
        {
            var entity = DataProvider.Categories.FirstOrDefault(n => n.Id == id);

            entity.Name         = category.Name;
            entity.Slug         = category.Name.ToLower().Replace(' ', '-');
            entity.ModifiedDate = DateTime.Now;
            entity.ModifiedBy   = "TechnicalRadiationAdmin";
        }
示例#29
0
 public IActionResult EditCategory(int id, [FromBody] CategoryInputModel category)
 {
     if (!ModelState.IsValid)
     {
         throw new InputFormatException("Category input model was not properly formatted.");
     }
     _categoryService.UpdateCategoryById(category, id);
     return(NoContent());
 }
        public ActionResult Create()
        {
            var sections   = this.Data.Sections.All().ProjectTo <SectionConciseViewModel>().ToList();
            var inputModel = new CategoryInputModel {
                Sections = new SelectList(sections, "Id", "Title")
            };

            return(this.View(inputModel));
        }
        public ActionResult Add(CategoryInputModel model)
        {
            if (!this.ModelState.IsValid)
            {
                return this.View(model);
            }

            this.categories.Create(model.Name);

            return this.RedirectToAction("ListCategories", "ListCategories");
        }
示例#32
0
        public ActionResult Destroy([DataSourceRequest]DataSourceRequest request, CategoryInputModel categoryInputModel)
        {
            CategoryViewModel categoryViewModel = null;

            if (this.ModelState.IsValid)
            {
                var category = this.categoryService.DeleteById(categoryInputModel.Id);

                this.fileService.DeleteById(category.ImageId);

                this.categoryService.Update();

                categoryViewModel = this.Mapper.Map<CategoryViewModel>(category);
            }

            return this.Json(new[] { categoryViewModel }.ToDataSourceResult(request, this.ModelState));
        }
示例#33
0
        public ActionResult Create([DataSourceRequest]DataSourceRequest request, CategoryInputModel categoryInputModel)
        {
            CategoryViewModel categoryViewModel = null;

            if (this.ModelState.IsValid)
            {
                var category = this.Mapper.Map<Category>(categoryInputModel);

                // TODO: find a better way to pass the ImageId
                string fileName = categoryInputModel.ImageFileName;
                category.ImageId = Guid.Parse(fileName.Remove(fileName.IndexOf('.')));

                this.categoryService.Add(category);

                categoryViewModel = this.Mapper.Map<CategoryViewModel>(category);
                categoryViewModel.ImageFileName = categoryInputModel.ImageFileName;
            }

            return this.Json(new[] { categoryViewModel }.ToDataSourceResult(request, this.ModelState));
        }
        public ActionResult Add(CategoryInputModel model)
        {
            if (this.ModelState.IsValid)
            {
                var categoryName = this.categories
                    .GetAll()
                    .FirstOrDefault(x => x.Name.ToLower() == model.Name.ToLower());
                if (categoryName == null)
                {
                    var category = this.Mapper.Map<Category>(model);
                    this.categories.Add(category);
                    TempData["Success"] = GlobalConstants.CategoryAddNotify;
                }
                else
                {
                    TempData["Warning"] = GlobalConstants.CategoryExistsNotify;
                }                

                return this.Redirect("/Admin/Categories/Index");
            }

            return this.View(model);
        }