public HttpStatusCode Update([FromBody] Category category)
        {
            var validationResult = new CategoryValidator(ValidateFor.Update).Validate(category);

            if (!validationResult.IsValid)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = "Data is invalid",
                    Content      = new StringContent(JsonConvert.SerializeObject(validationResult.Errors))
                });
            }

            using (var session = Raven.Instance.Store.OpenSession())
            {
                var cat = session.Load <Category>(category.Id);
                if (cat == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                cat.Name = category.Name;
                session.SaveChanges();
                return(HttpStatusCode.OK);
            }
        }
예제 #2
0
        private void ValidateCategoryProperties(IEnumerable <Category> categories)
        {
            if (categories == null)
            {
                throw new ArgumentNullException(nameof(categories));
            }
            //Validate categories
            var validator = new CategoryValidator();

            foreach (var category in categories)
            {
                validator.ValidateAndThrow(category);
            }

            var groups = categories.GroupBy(x => x.CatalogId);

            foreach (var group in groups)
            {
                LoadDependencies(group, PreloadCategories(group.Key));
                ApplyInheritanceRules(group);

                foreach (var category in group)
                {
                    var validatioResult = _hasPropertyValidator.Validate(category);
                    if (!validatioResult.IsValid)
                    {
                        throw new Exception($"Category properties has validation error: {string.Join(Environment.NewLine, validatioResult.Errors.Select(x => x.ToString()))}");
                    }
                }
            }
        }
예제 #3
0
 public MovieImportService()
 {
     this.categoryService   = new CategoryService();
     this.categoryValidator = new CategoryValidator(categoryService);
     this.movieService      = new MovieService();
     this.movieValidator    = new MovieValidator(movieService);
 }
예제 #4
0
        public static void ImportMovie(MovieDTO movieDto)
        {
            string movieName = movieDto.Name;

            InputDataValidator.ValidateStringMaxLength(movieName, Constants.MaxMovieNameLength);

            float?rating = movieDto.Rating;

            InputDataValidator.ValidateFloatInRange(rating, Constants.MinRatingValue, Constants.MaxRatingValue);

            int releaseYear = movieDto.ReleaseYear;

            MovieValidator.ValidateMovieDoesNotExist(movieName, releaseYear);

            List <string> categories = movieDto.Categories.Select(c => c.Name).ToList();

            CategoryValidator.CheckCategoriesExist(categories);

            string         directorName   = movieDto.DirectorName;
            int            length         = movieDto.Length;
            AgeRestriction ageRestriction = (AgeRestriction)Enum.Parse(typeof(AgeRestriction), movieDto.AgeRestriction);
            string         synopsis       = movieDto.Synopsis;
            string         releaseCountry = movieDto.ReleaseCountry;

            byte[] image = movieDto.Image;


            MovieService.AddMovie(movieName, rating, length, directorName, releaseYear, ageRestriction, synopsis,
                                  releaseCountry, image);
            MovieImportService.AddCategoriesToMovie(movieName, releaseYear, categories);

            Console.WriteLine(string.Format(Constants.ImportSuccessMessages.MoviesAddedSuccess, movieName));
        }
예제 #5
0
        public CategoryManagerTest()
        {
            var testRepo  = new TestCategoryRepository();
            var validator = new CategoryValidator();

            _mng = new CategoryManager(testRepo, validator);
        }
        public void ReturnCategory_WhenValidUser_CallsUpdateCategory()
        {
            var updatedCategory = new Category
            {
                Id          = 1,
                UserId      = 1,
                Description = "Test",
                Code        = "test"
            };

            var result = new Category
            {
                Id = updatedCategory.Id
            };

            var userHelper = A.Fake <IUserHelper>();

            A.CallTo(() => userHelper.MatchingUsers(A <HttpContext> .Ignored, updatedCategory.UserId)).Returns(true);

            var categoryRepository = A.Fake <ICategoryRepository>();

            A.CallTo(() => categoryRepository.CategoryExists(updatedCategory.Id)).Returns(true);
            A.CallTo(() => categoryRepository.GetCategory(updatedCategory.Id)).Returns(result);

            var validator = new CategoryValidator();

            var controller = new CategoriesController(categoryRepository, null, userHelper, validator);

            var response = controller.UpdateCategory(updatedCategory);

            A.CallTo(() => categoryRepository.Update(updatedCategory)).MustHaveHappened();
            Assert.AreEqual(result.Id, response.Value.Id);
        }
        public void ReturnCategory_OnCallToAddCategory()
        {
            var newCategory = new Category
            {
                Description = "Test",
                Code        = "test"
            };

            var result = new Category
            {
                UserId = newCategory.UserId
            };

            var userHelper         = A.Fake <IUserHelper>();
            var categoryRepository = A.Fake <ICategoryRepository>();

            A.CallTo(() => categoryRepository.GetCategory(A <int> .Ignored)).Returns(result);

            var validator  = new CategoryValidator();
            var controller = new CategoriesController(categoryRepository, null, userHelper, validator);

            var response = controller.AddCategory(newCategory);

            A.CallTo(() => categoryRepository.Add(newCategory)).MustHaveHappened();
            Assert.AreEqual(result.UserId, response.Value.UserId);
        }
        public void ReturnBadRequest_WhenCategoryDoesNotExist_OnCallToUpdateCategory()
        {
            var updatedCategory = new Category
            {
                Id          = 1,
                UserId      = 1,
                Description = "Test",
                Code        = "test"
            };

            var userHelper = A.Fake <IUserHelper>();

            A.CallTo(() => userHelper.MatchingUsers(A <HttpContext> .Ignored, updatedCategory.UserId)).Returns(true);

            var categoryRepository = A.Fake <ICategoryRepository>();

            A.CallTo(() => categoryRepository.CategoryExists(updatedCategory.Id)).Returns(false);

            var validator = new CategoryValidator();

            var controller = new CategoriesController(categoryRepository, null, userHelper, validator);

            var response = controller.UpdateCategory(updatedCategory);

            Assert.AreEqual((int)HttpStatusCode.BadRequest, ((BadRequestObjectResult)response.Result).StatusCode);
            Assert.AreEqual($"Category with Id {updatedCategory.Id} does not exist.", ((BadRequestObjectResult)response.Result).Value);
        }
예제 #9
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var validator = new CategoryValidator();
            var result    = validator.Validate(this);

            return(result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName })));
        }
예제 #10
0
        public ActionResult AddCategory(Category p)
        {
            CategoryValidator categoryValidator = new CategoryValidator();
            ValidationResult  results           = categoryValidator.Validate(p);

            if (results.IsValid)
            {
                cm.CategoryAdd(p);
                return(RedirectToAction("GetCatgoryList"));
            }
            else
            {
                foreach (var item in results.Errors)
                {
                    ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
                }
            }
            return(View());

            ////cm.CategoryAddBL(p);
            return(RedirectToAction("GetCatgoryList"));

            {
            }
        }
예제 #11
0
        public Categories1Controller()
        {
            IRepository <Category, int> repo = new CategoryRepository();
            IValidator validator             = new CategoryValidator();

            _mng = new CategoryManager(repo, validator);
        }
예제 #12
0
        private async Task CorrectFlow()
        {
            Category = Builder <Category>
                       .CreateNew()
                       .Build();

            await CategoryValidator.SetValidatorSuccess();
        }
        public AddCategoryViewModel()
        {
            _categoryValidator  = new CategoryValidator();
            _category           = new Category();
            _categoryRepository = new CategoryRepository();

            AddCategoryCommand = new Command(async() => await AddCategory());
        }
 public DeleteCategoryService(
     IDefaultDbContext context,
     CategoryValidator entityValidator,
     DeleteCategorySpecificationsValidator domainValidator
     ) : base(entityValidator, domainValidator)
 {
     Context = context;
 }
예제 #15
0
        public Category(string name, decimal discount)
        {
            Name     = name;
            Discount = discount;

            var validator = new CategoryValidator();

            validator.ValidateAndThrow(this);
        }
예제 #16
0
        private void CategoryValidation(Category category)
        {
            CategoryValidator categoryValidator = new CategoryValidator();
            var result = categoryValidator.Validate(category);

            if (result.Errors.Count > 0)
            {
                throw new ValidationException(result.Errors);
            }
        }
        public static void ImportCategory(CategoryDTО categoryDtо)
        {
            string categoryName = categoryDtо.Name;

            InputDataValidator.ValidateStringMaxLength(categoryName, Constants.MaxCategoryNameLength);
            CategoryValidator.ValidateCategoryDoesNotExist(categoryName);

            CategoryService.AddCategory(categoryName);

            Console.WriteLine(string.Format(Constants.ImportSuccessMessages.CategoryAddedSuccess, categoryName));
        }
예제 #18
0
 public static Category mapModel(Category oldCategory, Category newCategory)
 {
     if (!CategoryValidator.validateCategory(newCategory))
     {
         return(null);
     }
     oldCategory.IDCategory  = newCategory.IDCategory;
     oldCategory.Name        = newCategory.Name;
     oldCategory.Description = newCategory.Description;
     return(oldCategory);
 }
예제 #19
0
        public void CanValidateNameChangedAndNotExists()
        {
            _methodProvider.Setup(p => p.GetMethodUpperName()).Returns("PUT");
            _categoryValidator = new CategoryValidator(_validationService.Object, _methodProvider.Object);

            var result = _categoryValidator.TestValidate(new CategoryDto
            {
                Id   = _categories[1].Id,
                Name = "Food"
            });

            result.ShouldHaveValidationErrorFor(c => c.Name);
        }
예제 #20
0
        public void CanValidateIdExists()
        {
            _methodProvider.Setup(p => p.GetMethodUpperName()).Returns("PUT");
            _categoryValidator = new CategoryValidator(_validationService.Object, _methodProvider.Object);

            var result = _categoryValidator.TestValidate(new CategoryDto
            {
                Id   = Guid.NewGuid(),
                Name = "Beauty"
            });

            result.ShouldHaveValidationErrorFor(c => c.Id);
        }
예제 #21
0
        public async Task Return_Success_When_Category_Is_Updated()
        {
            //Arrange
            var logic = Create();
            //Act
            var result = await logic.Update(Category);

            //Assert
            result.Should()
            .BeSuccess(Category);
            CategoryValidator.Verify(v => v.ValidateAsync(Category, It.IsAny <CancellationToken>()), Times.Once);
            Repository.Verify(r => r.SaveChanges(), Times.Once);
        }
예제 #22
0
        /*[Authorize("Bearer")]*/
        public IActionResult CreateCategory(string name)
        {
            var category = new Domain.Entities.Category(name);

            var validationResult = new CategoryValidator().Validate(category);

            if (!validationResult.IsValid)
            {
                return(BadRequest(validationResult.Errors));
            }

            addCategoryUseCase.Add(category);
            return(new OkObjectResult(category));
        }
예제 #23
0
        public void AddCategoryToXML(String categoryName) //method to add a new category to the XML file
        {
            CategoryValidator validator = new CategoryValidator();

            validator.Validate(categoryName, "category");
            String path       = (Environment.CurrentDirectory + "/categories.xml");
            var    serializer = new XmlSerializer(typeof(List <Category>));

            using (var stream = new StreamWriter("categories.xml"))
            {
                Category category = new Category(categoryName);
                CategoryList.Add(category);
                serializer.Serialize(stream, CategoryList);
            }
        }
        public CategoryDetailsViewModel(int selectedCategoryId)
        {
            _categoryValidator = new CategoryValidator();
            _category          = new Category()
            {
                Id = selectedCategoryId
            };
            _categoryRepository = new CategoryRepository();

            UpdateCategoryCommand = new Command(async() => await UpdateCategory());
            DeleteCategoryCommand = new Command(async() => await DeleteCategory());

            FetchCategoryDetails();
            GetAllProducts();
        }
        public async Task <ResultResponse> Create(string title)
        {
            Category category = new Category(title);

            CategoryValidator validations     = new CategoryValidator();
            ValidationResult  resultValidator = validations.Validate(category);
            ResultResponse    resultResponse  = new ResultResponse(resultValidator);

            if (resultValidator.IsValid)
            {
                await _unitOfWork.categoryRepository.Create(category);
            }

            return(resultResponse);
        }
예제 #26
0
        public async Task <ActionResult <Transaction> > PostTransaction(Transaction transaction)
        {
            CategoryValidator validator = new CategoryValidator();

            if (validator.CategoryIsValid(transaction))
            {
                _context.Transactions.Add(transaction);
                await _context.SaveChangesAsync();

                return(CreatedAtAction("GetTransaction", new { id = transaction.Id }, transaction));
            }

            string errorMessage = validator.Message(transaction.Direction);

            return(BadRequest(new { error = errorMessage }));
        }
예제 #27
0
        public static void AddCategory(Categories categories)
        {
            CategoryValidator categoryValidator = new CategoryValidator();
            var result = categoryValidator.Validate(categories);

            if (result.Errors.Count > 0)
            {
                throw new ValidationException(result.Errors);
            }
            else
            {
                ReadWriteData.WriteDataTest <Categories>(categories, "category");
            }

            FactoryObject.SetCategory();
        }
예제 #28
0
        public async Task Return_Errors_When_Validation_Fails()
        {
            //Arrange
            const string warning = "You cannot update Category";
            var          logic   = Create();
            await CategoryValidator.SetValidatorFailure(warning);

            //Act
            var result = await logic.Update(Category);

            //Assert
            result.Should()
            .BeFailure(warning);
            CategoryValidator.Verify(v => v.ValidateAsync(Category, It.IsAny <CancellationToken>()), Times.Once());
            Repository.Verify(r => r.SaveChanges(), Times.Never);
        }
        public async Task <ResultResponse> Update(CategoryModelRequest request)
        {
            Category category = new Category(request.Title);

            category.Id = request.Id;

            CategoryValidator validations     = new CategoryValidator();
            ValidationResult  resultValidator = validations.Validate(category);
            ResultResponse    resultResponse  = new ResultResponse(resultValidator);

            if (resultValidator.IsValid)
            {
                await _unitOfWork.categoryRepository.Update(category);
            }

            return(resultResponse);
        }
예제 #30
0
        public CategoryValidatorTests()
        {
            _validationService = new Mock <ICategoryValidationService>();
            _methodProvider    = new Mock <IMethodProvider>();

            _categoryValidator = new CategoryValidator(_validationService.Object, _methodProvider.Object);

            _categories = new List <CategoryDto>
            {
                new CategoryDto
                {
                    Id   = Guid.NewGuid(),
                    Name = "Food"
                },
                new CategoryDto
                {
                    Id   = Guid.NewGuid(),
                    Name = "Sport"
                }
            };

            _validationService.Setup(s => s.CategoryExistsAsync(It.IsAny <Guid>(), CancellationToken.None))
            .Returns((Guid id, CancellationToken token) =>
                     Task.FromResult(_categories.Any(c => c.Id == id)));

            _validationService.Setup(s => s.CategoryIdNotExistsAsync(It.IsAny <Guid>(), CancellationToken.None))
            .Returns((Guid id, CancellationToken token) =>
                     Task.FromResult(_categories.All(c => c.Id != id)));

            _validationService.Setup(s => s.CategoryNameNotExistsAsync(It.IsAny <string>(), CancellationToken.None))
            .Returns((string name, CancellationToken token) =>
                     Task.FromResult(_categories.All(c => c.Name != name)));

            _validationService.Setup(s => s.CategoryNameChangedAndNotExistsAsync(It.IsAny <Guid>(),
                                                                                 It.IsAny <string>(), CancellationToken.None))
            .Returns((Guid id, string name, CancellationToken token) =>
            {
                var category = _categories.First(c => c.Id == id);
                if (category.Name == name)
                {
                    return(Task.FromResult(true));
                }

                return(Task.FromResult(_categories.All(c => c.Name != name)));
            });
        }
예제 #31
0
        public HttpResponseMessage CreateCategory([FromBody]Category category)
        {
            var validationResult = new CategoryValidator(ValidateFor.Create).Validate(category);
            if (!validationResult.IsValid)
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = "Data is invalid",
                    Content = new StringContent(JsonConvert.SerializeObject(validationResult.Errors))
                });

            using (var session = Raven.Instance.Store.OpenSession())
            {
                session.Store(category);
                session.SaveChanges();
                var response = this.Request.CreateResponse<Category>(HttpStatusCode.Created, category);

                return response;
            }
        }
예제 #32
0
        public HttpStatusCode Update([FromBody]Category category)
        {
            var validationResult = new CategoryValidator(ValidateFor.Update).Validate(category);
            if (!validationResult.IsValid)
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = "Data is invalid",
                    Content = new StringContent(JsonConvert.SerializeObject(validationResult.Errors))
                });

            using (var session = Raven.Instance.Store.OpenSession())
            {
                var cat = session.Load<Category>(category.Id);
                if (cat == null)
                    return HttpStatusCode.NotFound;

                cat.Name = category.Name;
                session.SaveChanges();
                return HttpStatusCode.OK;
            }
        }
 public CategoryService(ITransactionsProvider db)
 {
     this._db = db;
     this._validator = new CategoryValidator();
 }
 public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
 {
     var validator = new CategoryValidator();
     var result = validator.Validate(this);
     return result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName }));
 }
 public new void Setup()
 {
     _validator = new CategoryValidator(_localizationService, null);
 }