Exemplo n.º 1
0
        public ServiceResult <Role> Post([FromBody] Role model)
        {
            ServiceResult <Role> result = null;
            var validatorResult         = validator.Validate(model);

            if (validatorResult.IsValid)
            {
                try
                {
                    result = this.appService.Insert(model);
                }
                catch (Exception ex)
                {
                    result         = new ServiceResult <Role>();
                    result.Errors  = new string[] { ex.Message };
                    result.Success = false;
                }
            }
            else
            {
                result         = new ServiceResult <Role>();
                result.Errors  = validatorResult.GetErrors();
                result.Success = false;
            }

            return(result);
        }
        public void Should_Not_Have_Error_When_Permissions_Is_Not_Unique_But_Exists_In_Deleted_Permissions()
        {
            //Arrange
            var dbContext = _serviceProvider.GetService <IDbContext>();
            var validator = new RoleValidator(dbContext, _translation);

            var model = new RoleModel
            {
                Name        = "Role1",
                Permissions = new List <PermissionModel>
                {
                    new PermissionModel
                    {
                        Id   = 1,
                        Name = "Permission1"
                    },
                    new PermissionModel
                    {
                        Id            = 2,
                        Name          = "Permission1",
                        TrackingState = TrackingState.Deleted
                    }
                }
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldNotContain(x =>
                                           x.ErrorMessage == "Role.Fields.Permissions.Unique");
        }
        public void Should_Not_Have_Error_When_Name_Is_Unique()
        {
            //Arrange
            _serviceProvider.RunScoped <IDbContext>(context =>
            {
                context.Set <Role>().Add(new Role {
                    Name = "ExistingName"
                });
                context.SaveChanges();
            });

            var dbContext = _serviceProvider.GetService <IDbContext>();
            var validator = new RoleValidator(dbContext, _translation);

            var model = new RoleModel
            {
                Name = "NewName"
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldNotContain(x =>
                                           x.ErrorMessage == "Role.Fields.Name.Unique");
        }
        public void RoleValidator_ValidateRole_UniqueCheckIgnoresDeleted()
        {
            var grain         = "app";
            var securableItem = "patientsafety";
            var name          = "admin";

            var existingRole = new Role
            {
                Grain         = grain,
                SecurableItem = securableItem,
                Name          = name,
                IsDeleted     = true
            };

            var mockRoleStore = new Mock <IRoleStore>()
                                .SetupGetRoles(new List <Role> {
                existingRole
            }).Create();
            var mockPermissionStore = new Mock <IPermissionStore>().Create();
            var roleValidator       = new RoleValidator(new RoleService(mockRoleStore, mockPermissionStore));
            var validationResult    = roleValidator.Validate(new Role
            {
                Grain         = grain,
                SecurableItem = securableItem,
                Name          = name
            });

            Assert.True(validationResult.IsValid);
        }
        public void RoleValidator_ValidateRole_ReturnsInvalidIfModelNotValid(string grain, string securableItem,
                                                                             string roleName, int errorCount)
        {
            var existingRole = new Role
            {
                Grain         = "app",
                SecurableItem = "patientsafety",
                Name          = "admin"
            };

            var mockRoleStore = new Mock <IRoleStore>()
                                .SetupGetRoles(new List <Role> {
                existingRole
            }).Create();
            var mockPermissionStore = new Mock <IPermissionStore>().Create();
            var roleValidator       = new RoleValidator(new RoleService(mockRoleStore, mockPermissionStore));
            var validationResult    = roleValidator.Validate(new Role
            {
                Grain         = grain,
                SecurableItem = securableItem,
                Name          = roleName
            });

            Assert.False(validationResult.IsValid);
            Assert.NotNull(validationResult.Errors);
            Assert.Equal(errorCount, validationResult.Errors.Count);
        }
Exemplo n.º 6
0
        public void Should_Have_Error_When_Permissions_Is_Not_Unique()
        {
            //Arrange
            var unitOfWork = _serviceProvider.GetService <IUnitOfWork>();
            var validator  = new RoleValidator(unitOfWork, _localizer);

            var model = new RoleModel
            {
                Name        = "Role1",
                Permissions = new List <PermissionModel>
                {
                    new PermissionModel {
                        Name = "Permission1"
                    },
                    new PermissionModel {
                        Name = "Permission1"
                    }
                }
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldContain(x =>
                                        x.ErrorMessage == "Role.Fields.Permissions.Unique");
        }
Exemplo n.º 7
0
        public void Should_Not_Have_Error_When_Name_Is_Unique()
        {
            //Arrange
            _serviceProvider.RunScoped <IUnitOfWork>(uow =>
            {
                uow.Set <Role>().Add(new Role {
                    Name = "ExistingName"
                });
                uow.SaveChanges();
            });

            var unitOfWork = _serviceProvider.GetService <IUnitOfWork>();
            var validator  = new RoleValidator(unitOfWork, _localizer);

            var model = new RoleModel
            {
                Name = "NewName"
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldNotContain(x =>
                                           x.ErrorMessage == "Role.Fields.Name.Unique");
        }
Exemplo n.º 8
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var validator = new RoleValidator();
            var result    = validator.Validate(this);

            return(result.Errors.Select(item => new ValidationResult(item.ErrorMessage, new[] { item.PropertyName })));
        }
Exemplo n.º 9
0
        public int Save(Role obj, ref ValidationError validationError)
        {
            var validatorResults = _validator.Validate(obj);

            if (!validatorResults.IsValid)
            {
                foreach (var failure in validatorResults.Errors)
                {
                    validationError.Message      = failure.ErrorMessage;
                    validationError.PropertyName = failure.PropertyName;
                    return(0);
                }
            }

            return(Save(obj));
        }
        public void RoleValidator_ValidateRole_ReturnsValid()
        {
            var mockRoleStore       = new Mock <IRoleStore>().SetupGetRoles(new List <Role>()).Create();
            var mockPermissionStore = new Mock <IPermissionStore>().Create();
            var roleValidator       = new RoleValidator(new RoleService(mockRoleStore, mockPermissionStore));
            var validationResult    = roleValidator.Validate(new Role
            {
                Grain         = "app",
                SecurableItem = "patientsafety",
                Name          = "admin"
            });

            Assert.True(validationResult.IsValid);
        }
Exemplo n.º 11
0
        public void Should_Have_Error_When_Name_Is_Empty()
        {
            //Arrange
            var unitOfWork = _serviceProvider.GetService <IUnitOfWork>();
            var validator  = new RoleValidator(unitOfWork, _localizer);

            var model = new RoleModel
            {
                Name = null
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Name.Required");
        }
        public void Should_Have_Error_When_Name_Is_Empty()
        {
            //Arrange
            var dbContext = _serviceProvider.GetService <IDbContext>();
            var validator = new RoleValidator(dbContext, _translation);

            var model = new RoleModel
            {
                Name = null
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldContain(x => x.ErrorMessage == "Role.Fields.Name.Required");
        }
        public void Should_Have_Error_When_Name_Length_More_Than_Maximum()
        {
            //Arrange
            var dbContext = _serviceProvider.GetService <IDbContext>();
            var validator = new RoleValidator(dbContext, _translation);

            var model = new RoleModel
            {
                Name = new string('A', 51)
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldContain(x =>
                                        x.ErrorMessage == "Role.Fields.Name.MaximumLength");
        }
Exemplo n.º 14
0
        public void Should_Have_Error_When_Name_Length_More_Than_Maximum()
        {
            //Arrange
            var unitOfWork = _serviceProvider.GetService <IUnitOfWork>();
            var validator  = new RoleValidator(unitOfWork, _localizer);

            var model = new RoleModel
            {
                Name = new string('A', 51)
            };

            //Act
            var result = validator.Validate(model);

            //Assert
            result.Errors.ShouldContain(x =>
                                        x.ErrorMessage == "Role.Fields.Name.MaximumLength");
        }
Exemplo n.º 15
0
        public SaveResult <RoleEntryModel> Save(RoleDTO roleDTO, DateTime dateStamp)
        {
            ModelValidationResult validationResult = roleValidator.Validate(roleDTO);
            bool           success = false;
            RoleEntryModel model   = null;

            if (validationResult.IsValid)
            {
                success = true;
                Update(roleDTO, dateStamp);
                Db.SaveChanges();
                model = roleEntryDataProvider.Get(roleDTO.Role_PK);
            }

            return(new SaveResult <RoleEntryModel>
            {
                Success = success,
                Message = validationResult.IsValid ? "Data successfully updated." : "Validation error occured.",
                Model = model,
                ValidationResult = validationResult
            });
        }
Exemplo n.º 16
0
        public async Task <Result> InsertRole(RoleEdit role)
        {
            var validator = new RoleValidator(true);
            var result    = validator.Validate(role).GetResult();

            if (!result.Success)
            {
                return(result);
            }

            var entity = MapModelToEntity(role);
            await _context.Roles.AddAsync(entity);

            await _context.SaveChangesAsync();

            role.Id = entity.Id;

            await UpdateUseCases(role);

            result.Tag = role;

            return(result);
        }
Exemplo n.º 17
0
        public async Task <string> CreateRole(RoleDTO roleDTO)
        {
            var role = _mapper.Map <RoleDTO, Role>(roleDTO);

            RoleValidator validator = new RoleValidator();

            ValidationResult results = validator.Validate(role);

            if (!results.IsValid)
            {
                foreach (var failure in results.Errors)
                {
                    string error = ("Property " + failure.PropertyName + " failed validation. Error was: " + failure.ErrorMessage);
                    return(error);
                }
                return("Error");
            }
            else
            {
                await _eFUnitOfWork.RoleManager.CreateAsync(role);

                return("Роль успішно добавлено!");
            }
        }
Exemplo n.º 18
0
        public async Task <Result> UpdateRole(RoleEdit role)
        {
            var validator = new RoleValidator(false);
            var result    = validator.Validate(role).GetResult();

            if (!result.Success)
            {
                return(result);
            }

            var entity = await _context.Roles.FindAsync(role.Id);

            if (entity == null)
            {
                return(new Result());
            }

            entity = MapModelToEntity(role, entity);
            await _context.SaveChangesAsync();

            await UpdateUseCases(role);

            return(result);
        }
Exemplo n.º 19
0
        public RoleModule(ISiteService _siteService,
            IRoleService _roleService)
            : base("/role")
        {
            RoleValidator roleValidator = new RoleValidator();

            Get["/list"] = x =>
            {
                ViewBag.SiteId = Request.Query.siteId;
                ViewBag.SiteList = _siteService.GetAllSite();
                if (!String.IsNullOrEmpty(Request.Query.siteId))
                {
                    return View["Role/List", _roleService.GetAllBySiteId(new Guid(Request.Query.siteId))];
                }
                else
                {
                    return View["Role/List",new List<Role>()];
                }
            };

            Get["/add"] = x =>
            {
                ViewBag.SiteId = Request.Query.siteId;
                ViewBag.SiteList = _siteService.GetAllSite();
                return View["Role/Add", new Role()];
            };

            Post["/add"] = x =>
            {
                ViewBag.SiteId = Request.Query.siteId;
                ViewBag.SiteList = _siteService.GetAllSite();
                ViewBag.Errored = true;

                var role = this.Bind<Role>();
                ValidationResult results = roleValidator.Validate(role);
                if (!results.IsValid)
                {
                    ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", results.Errors);
                }
                else if (_roleService.CreateRole(role))
                {
                    ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.success, "成功信息", "添加成功");
                }
                else
                {
                    ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", "未知错误,请联系管理员");
                }
                return View["Role/Add", role];
            };

            Get["/edit/{id}"] = x =>
            {
                ViewBag.SiteList = _siteService.GetAllSite();

                var model = _roleService.GetByAutoId(x.id);

                return View["Role/Edit", model];
            };

            Post["/edit/{id}"] = x =>
            {
                ViewBag.SiteList = _siteService.GetAllSite();
                ViewBag.Errored = true;

                var role = this.Bind<Role>();
                ValidationResult results = roleValidator.Validate(role);
                if (!results.IsValid)
                {
                    ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", results.Errors);
                }
                else if (_roleService.ModifyRole(role))
                {
                    ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.success, "成功信息", "修改成功");
                }
                else
                {
                    ViewBag.ErrorMsg = HtmlUtils.GetCharisma_Alert(Charisma_AlertType.error, "错误信息", "未知错误,请联系管理员");
                }
                return View["Role/Edit", role];
            };

            Get["/delete/{id}"] = x =>
            {
                var model = _roleService.GetByAutoId((int)x.id);
                _roleService.DeleteRole(model.ID);
                return Response.AsRedirect("/role/list?siteId=" + model.ID.ToString());
            };

            Post["/delete"] = x =>
            {
                var result = new NotyResult();
                Guid[] ids;
                try
                {
                    ids = RequestResultUtil.GetIdsByGuid(Request.Form.id);
                }
                catch
                {
                    Guid strongid = new Guid(Request.Form.id);
                    ids = new Guid[1];
                    ids[0] = strongid;
                }

                var list = (ids ?? new Guid[0]);

                if (list.Length == 0)
                {
                    result.code = NotyType.warning.ToString();
                    result.msg = "你没有选择!";
                }
                else if (_roleService.DeleteByIds(ids))
                {
                    result.code = NotyType.success.ToString();
                    result.msg = "删除成功!";
                }
                else
                {
                    result.code = NotyType.error.ToString();
                    result.msg = "删除失败!请联系管理员!";
                }
                return this.Response.AsJson<NotyResult>(result);
            };

            Get["/vieworder"] = x =>
            {
                var id = new Guid(Request.Query.siteId);
                return View["Role/ViewOrder", _roleService.GetAllBySiteId(id)];
            };

            Post["/saveorder"] = x =>
            {
                var result = new NotyResult();
                Guid[] ids = RequestResultUtil.GetIdsByGuid(Request.Form.ids);
                var list = (ids ?? new Guid[0]);

                if (list.Length == 0)
                {
                    result.code = NotyType.warning.ToString();
                    result.msg = "你没有选择!";
                }
                else if (_roleService.SetOrderByIds(ids))
                {
                    result.code = NotyType.success.ToString();
                    result.msg = "排序成功";
                }
                else
                {
                    result.code = NotyType.error.ToString();
                    result.msg = "排序失败!请联系管理员!";
                }
                return this.Response.AsJson<NotyResult>(result);
            };
        }