public string ChangeStatus()
        {
            string result = "";
            try
            {
                int id = 0;
                int.TryParse(Request["id"], out id);
                byte status = 0;
                byte.TryParse(Request["status"], out status);
                var repo = new RoleRepository();
                var v = repo.GetByID(id);
                if (v != null)
                {
                    v.RecordStatus = status;
                    repo.SaveChanges();
                }
                result = JsonResult(true, Resources.Messages.StatusChanged);
            }
            catch (Exception ex)
            {
                result = JsonResult(false, ex.Message);
            }

            return result;
        }
 public ManageEmployeeDetails()
 {
     InitializeComponent();
     empRepo = new EmployeeRepository();
     roleRepo = new RoleRepository();
     HideControls(false);
 }
示例#3
0
 public AccountController(IUnitOfWork unitOfWork)
     : base(unitOfWork)
 {
     _repository = new UserRepository(unitOfWork);
     _departRepository= new DepartRepository(unitOfWork);
     _roleRepository = new RoleRepository(unitOfWork);
 }
 public static IRepositoryService<Role> Create()
 {
     IDatabaseFactory databaseFactory = new DatabaseFactory();
     IUnitOfWork unitOfWork = new UnitOfWork(databaseFactory);
     IRepository<Role> roleRepository = new RoleRepository(databaseFactory);
     return new RoleEntityService((IRoleRepository)roleRepository, unitOfWork);
 }
示例#5
0
        public override string[] GetRolesForUser(string login)
        {
            string[] role = new string[] { };
            using (IModelRepository<User> _user = new UserRepository())
            {
                try
                {
                    IModelRepository<Role> _role = new RoleRepository();
                    // Get User
                    var user = (from u in _user.Items
                                 where u.Login == login
                                 select u).FirstOrDefault();
                    if (user != null)
                    {
                        // Get role
                        var userRole = _role.Items.FirstOrDefault(x=>x.Id==user.RoleId);

                        if (userRole != null)
                        {
                            role = new string[] { userRole.Name };
                        }
                    }
                }
                catch
                {
                    role = new string[] { };
                }
            }
            return role;
        }
        public void CreateUser()
        {
            var connectionString = ConfigurationManager.AppSettings["localConnection"];
            using (IDbConnection connection = new SqlConnection(connectionString))
            using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            using(var userRepository = new UserDatabaseRepository(connection))
            using (var roleRepository = new RoleRepository(connection))
            {
                // To create a USER you MUST first have already created a ROLE!
                var role = new Role { Name = "User" };
                var createdRole = roleRepository.Create(role, _ => Task.FromResult(0)).Result;

                createdRole.Match(r =>
                {
                    var user = new User
                    {
                        Email = "*****@*****.**",
                        FirstName = "John",
                        LastName = "Doe",
                        Roles = new List<Role> { r },
                        Username = "******"
                    };

                    var created = userRepository.Create(user, _ => Task.FromResult(0)).Result;
                    Assert.True(created.HasValue);
                },
                () =>
                {
                    Assert.True(false, "Role has not been created!");
                });

            }
        }
示例#7
0
 public RBACHelper()
 {
     permissionAssigmentRepository = new PermissionAssigmentRepository();
     userAssigmentRepository = new UserAssigmentRepository();
     userRepository = new UserRepository();
     roleRepository = new RoleRepository();
 }
        public void RoleInheritRelationService_AddRelation_Test()
        {
            var roleId = 3;
            var inheritRoleId = 4;

            //初始化
            var unit = EntityUnitOfWorkFactory.CreateUnitOfWork();
            var roleInheritRelationService = new RoleInheritRelationService(unit);
            var roleRepository = new RoleRepository(unit);

            var role = roleRepository.Get(roleId);
            var inheritRole = roleRepository.Get(inheritRoleId);

            var inheritRoles = roleInheritRelationService.GetInheritRolesOfRole(role, false);
            Assert.IsFalse(inheritRoles.Contains(inheritRole));

            //启动事务进行测试,并不提交
            using (var ts = new TransactionScope())
            {
                roleInheritRelationService.AddRelation(role, inheritRole);
                unit.SaveChanges();

                inheritRoles = roleInheritRelationService.GetInheritRolesOfRole(role, false);
                Assert.IsTrue(inheritRoles.Contains(inheritRole));
            }
        }
示例#9
0
        public void Sould_GetUsersInRole_Return_Succefully()
        {
            var roleRepository = new RoleRepository<MjrAppRole, User>();

            var result = roleRepository.GetUsersInRole("MjrAdmin");

            Assert.IsNotNull(result);
        }
示例#10
0
        public PermissionAssigment(Int32 roleId, Int32 permissionId)
        {
            this.roleId = roleId;
            this.permissionId = permissionId;

            this.roleRepository = new RoleRepository();
            this.permissionRepository = new PermissionRepository();
        }
示例#11
0
        public void RoleRepository_LoadAll()
        {
            RoleRepository roleRepository = new RoleRepository();

            List<Role> roles = roleRepository.LoadAll();

            Assert.AreEqual(12, roles.Count);
        }
示例#12
0
        public UserAssigment(Int32 userId, Int32 roleId)
        {
            this.userId = userId;
            this.roleId = roleId;

            this.userRepository = new UserRepository();
            this.roleRepository = new RoleRepository();
        }
示例#13
0
 public TaskNodeFormModel(int typeid, TaskRepository taskRepositoryrepository, RoleRepository roleRepository)
 {
     WbsTypeId = typeid;
     Repository = taskRepositoryrepository;
     AvailableRoles = roleRepository.FindAll().ToList();
     AvailableNodes = Repository.FindAll().Where(x => x.WbsTypeId == WbsTypeId).ToList();
     Stages = StageRepository.FindStages().ToList();
 }
 public TenantProvisioningService(
         TenantRepository tenantRepository,
         UserRepository userRepository,
         RoleRepository roleRepository)
 {
     this.RoleRepository = roleRepository;
     this.TenantRepository = tenantRepository;
     this.UserRepository = userRepository;
 }
 public AuthorizationService(
         UserRepository userRepository,
         GroupRepository groupRepository,
         RoleRepository roleRepository)
 {
     this.GroupRepository = groupRepository;
     this.RoleRepository = roleRepository;
     this.UserRepository = userRepository;
 }
示例#16
0
        //
        // GET: /Usuario/Edit/5
        public ActionResult Edit(int id)
        {
            Usuario usuario = _Rep.GetById(id);

            RoleRepository _RepRole = new RoleRepository();
            ViewBag.RoleId = new SelectList(_RepRole.GetAll(), "Id", "Nombre",usuario.RoleId);

            return View(usuario);
        }
示例#17
0
        public static void init()
        {
            RoleRepository repo = new RoleRepository();

            repo.Create(new Role { name = "Ejer" });
            repo.Create(new Role { name = "Admin" });
            repo.Create(new Role { name = "Redaktør" });
            repo.Create(new Role { name = "Basis" });
        }
        public void WhenGetAllFromEmptyDatabase_ThenReturnsEmptyCollection()
        {
            var repository = new RoleRepository(new DatabaseFactory());
            IEnumerable<Roles> actual = repository.GetAll();

            Assert.NotNull(actual);
            var actualList = new List<Roles>(actual);
            Assert.Equal(0, actualList.Count);
        }
 public AuthenticationController()
 {
     string connString = ConfigurationManager.ConnectionStrings["OnlineSurveyDbConn"].ToString();
     var dbContext = new OnlineSurveyContext(connString);
     var roleRepo = new RoleRepository(dbContext);
     var userRepo = new UserRepository(dbContext);
     _roleService = new RoleService(roleRepo);
     _userService = new UserService(userRepo);
 }
示例#20
0
        /// <summary>
        /// Initializes a new instance of the RoleService class.
        /// </summary>
        /// <param name="unitOfWork">UnitOfWork information</param>
        public RoleService(UnitOfWork unitOfWork)
        {
            if (unitOfWork == null)
            {
                throw new ArgumentNullException(UnitOfWorkConst);
            }

            this.unitOfWork = unitOfWork;
            this.roleRepository = new RoleRepository(this.unitOfWork);
        }
示例#21
0
 public bool addRole(Role role)
 {
     RoleRepository repository = new RoleRepository();
     if(role != null)
     {
         repository.Add(role);
         return true;
     }
     return false;
 }
示例#22
0
 public ServiceUser(
     UserRepository userRepo,
     RoleRepository roleRepo,
     AuthRepository authRepo,
     UnitOfWork unit)
     : base(unit)
 {
     this.user_repo = userRepo;
     this.role_repo = roleRepo;
     this.auth_repo = authRepo;
 }
示例#23
0
 public SqlDAL()
 {
     DBContext = new AlbumsDBModel();
     _albumRepository = new AlbumRepository(DBContext);
     _roleRepository = new RoleRepository(DBContext);
     _userRepository = new UserRepository(DBContext);
     _commentRepository = new CommentRepository(DBContext);
     _likeRepository = new LikeRepository(DBContext);
     _albumsPhotoRepository = new AlbumsPhotoRepository(DBContext);
     _photoRepository = new PhotoRepository(DBContext);
 }
示例#24
0
 public AppSettingController(IUnitOfWork unitOfWork)
     : base(unitOfWork)
 {
     _departRepository= new DepartRepository(unitOfWork);
     _roleRepository = new RoleRepository(unitOfWork);
     _wbsTaskRepository = new WBSTaskRepository(unitOfWork);
     _taskRepository = new TaskRepository(unitOfWork);
     _categoryRepostitory = new CategoryRepostitory(unitOfWork);
     _stateCategoryRepostitory = new StateCategoryRepostitory(unitOfWork);
     _nodeDocTypeRepository = new NodeDocTypeRepository(unitOfWork);
 }
示例#25
0
        public void RoleRepository_LoadById()
        {
            Int32 roleId = 1;

            RoleRepository roleRepository = new RoleRepository();

            Role role = roleRepository.LoadById(roleId);

            Assert.IsNotNull(role);
            Assert.AreEqual(roleId, role.Id);
        }
示例#26
0
 public static bool IsOptionInUserRoles(IList<UserRole> roles, string option)
 {
     IRepository<Role> repoRole = new RoleRepository();
     foreach (UserRole item in roles)
     {
         if (ConfigurationManager.AppSettings[repoRole.GetById(item.Role.Id).Name].Contains(option))
         {
             return true;
         }
     }
     return false;
 }
 public OperationResult CreateRole(Model.Role model)
 {
     using (IUnitOfWork unitofwork = new EntityFrameworkContext())
     {
         IRoleRepository roleRepository = new RoleRepository(unitofwork);
         if (roleRepository.GetEntity.Count(m => m.RoleName == model.RoleName) <= 0)
         {
             roleRepository.Insert(model);
             unitofwork.Commit();
             return new OperationResult(OperationResultType.Success, "角色添加成功.");
         }
         return new OperationResult(OperationResultType.NoChanged, "角色名已存在.");
     }
 }
        public DonationInformation()
        {
            //dtpDate.MinDate = DateTime.Now;
            this.MaximizeBox = false;
            InitializeComponent();

            dtpEnglishDateType.Format = DateTimePickerFormat.Custom;
            dtpEnglishDateType.CustomFormat = "dd/MM";

            donorRepo = new DonorRepository();
            datetypeRepo = new DateTypeRepository();
            desigRepo = new DesignationRepository();
            employeeRepo = new EmployeeRepository();
            prefixRepo = new PrefixesRepository();
            roleRepo = new RoleRepository();
            serviceNameRepo = new ServiceNameRepository();
            serviceTypeRepo = new ServiceTypeRepository();
            specialDayRepo = new SpecialDayRepository();
            starRepo = new StarsRepository();
            monthsRepo = new MonthsRepository();
            pakshaRepo = new PakshaRepository();
            thithiRepo = new ThidhiRepository();
            monthlyAnnaRepo = new MonthlyAnnaRepository();
            gothramRepo = new GothramsRepository();
            transTypeRepo = new TransactionTypeRepository();
            lstTokenPrint = new List<TokenPrint>();
            stateRepo = new StateRepository();
            lstStates = new List<State>();
            prefixesRepo = new PrefixesRepository();

            bindData();
            btnUpdate.Visible = false;
            btnCancel.Visible = false;

            lblSpecialDay.Visible = false;
            cmbSpecialDay.Visible = false;
            lblMonth.Visible = false;
            cmbMonth.Visible = false;
            lblThithi.Visible = false;
            cmbThithi.Visible = false;
            lblMonthlyAnna.Visible = false;
            cmbMonthlyAnna.Visible = false;
            lblEnglishDatetype.Visible = false;
            dtpEnglishDateType.Visible = false;
            rbdEnglish.Checked = false;
            rbdTelugu.Checked = false;
            lblMonthyAnnaThithi.Visible = false;
            cmbMonthyAnnaThithi.Visible = false;
        }
示例#29
0
        public static void BeforeMembershipScenarios()
        {
            var context = new ShopAnyWareSql();
            var userRepository = new UserRepository(context);
            var roleRepository = new RoleRepository(context);
            var profileRepository = new ProfileRepository(context);
            var membershipRepository = new MembershipRepository();

            var logger = new FakeLogger();
            var emailService = new FakeEmailService();
            ScenarioContext.Current.Set(emailService);

            var membershipService = new MembershipService(logger, emailService, userRepository, roleRepository, profileRepository, membershipRepository);
            ScenarioContext.Current.Set(membershipService);
        }
示例#30
0
        public ActionResult Create(Usuario usuario)
        {
            if (ModelState.IsValid)
            {
                ///Add object to Database
                _Rep.Add(usuario);

                return RedirectToAction("Index");
            }

            RoleRepository _RepRole = new RoleRepository();
            ViewBag.RoleId = new SelectList(_RepRole.GetAll(), "Id", "Nombre");

            return View(usuario);
        }
示例#31
0
 public override string[] GetRolesForUser(string username)
 {
     using (UsersRepository objContext = new UsersRepository())
     {
         var objUser = objContext.GetUserByName(username);
         if (objUser == null)
         {
             return(null);
         }
         else
         {
             var roles = objUser.UserRoles.Select(x => x.RoleID).ToList();
             using (RoleRepository objRole = new RoleRepository())
             {
                 return((from e  in objRole.GetAllRoles() where roles.Contains(e.RoleID) select e.RoleName).ToArray());
             }
         }
     }
 }
示例#32
0
        public async Task EnsureGenericExceptionIsThrownWhenErrorIsUnknown()
        {
            var k8s = Dummy.Of <IKubernetesWrapper>();
            var sut = new RoleRepository(k8s);

            Mock.Get(k8s).Setup(k => k.CreateNamespacedRoleAsync(It.IsAny <V1Role>(),
                                                                 It.IsAny <string>(), null, It.IsAny <CancellationToken>()))
            .Throws(new HttpOperationException
            {
                Response =
                    new HttpResponseMessageWrapper(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.BadGateway
                }, "Unable to communicate")
            });

            var @namespace = "fancyNamespace";

            await Assert.ThrowsAsync <Exception>(() => sut.CreateNamespaceFullAccessRole(@namespace));
        }
示例#33
0
        public virtual async Task <ActionResult> SyncUsers()
        {
            string token = await ADService.GetTokenForApplication();

            if (token == null)
            {
                return(RedirectToAction("SignIn", MVC.Account.Name));
            }

            var result = await ADService.GetUsers();

            IEnumerable <IUser> users = result.CurrentPage.ToList();

            var myId             = CurrentUserId;
            var defaultRole      = RoleRepository.Single(x => x.Name == "User");
            var currentEmployees = EmployeeRepository.Select(x => x.Id);

            var appUsers = users.Where(x => x.GivenName != null).Select(x => new Employee()
            {
                Id                      = x.ObjectId,
                Email                   = x.Mail,
                Role                    = defaultRole,
                Name                    = x.DisplayName,
                PhoneNumber             = x.Mobile,
                IsInitialized           = false,
                VacationMessages        = false,
                RequestMessages         = false,
                MonthlyBirthdayMessages = false,
                DailyBirthdayMessages   = false,
                VacationDays            = 28
            });

            var newUsers = appUsers.Where(x => !currentEmployees.Contains(x.Id));

            EmployeeRepository.AddRange(newUsers);

            EmployeeRepository.Commit();

            return(View(MVC.Admin.Views.EditEmployees, new WorkersViewModel()
            {
                Employees = EmployeeRepository.AsDto()
            }));
        }
示例#34
0
        public bool Delete(string roleID)
        {
            //Guid gRoleID = new Guid(roleID);
            var role = RoleRepository.GetQueryable()
                       .FirstOrDefault(i => i.ROLE_ID == roleID);

            if (role != null)
            {
                Del(RoleSystemRepository, role.AUTH_ROLE_SYSTEM);
                Del(UserRoleRepository, role.AUTH_USER_ROLE);
                RoleRepository.Delete(role);
                RoleRepository.SaveChanges();
            }
            else
            {
                return(false);
            }
            return(true);
        }
示例#35
0
        public static async Task RegisterAdmin()
        {
            using (var roles = new RoleRepository())
            {
                if (await roles.GetRoleByNameAsync("admin") == null)
                {
                    await roles.CreateAsync(new IdentityRole("admin"));
                }

                if (await roles.GetRoleByNameAsync("editor") == null)
                {
                    await roles.CreateAsync(new IdentityRole("editor"));
                }

                if (await roles.GetRoleByNameAsync("author") == null)
                {
                    await roles.CreateAsync(new IdentityRole("author"));
                }

                if (await roles.GetRoleByNameAsync("user") == null)
                {
                    await roles.CreateAsync(new IdentityRole("user"));
                }
            }
            using (var users = new UserRepository())
            {
                var user = await users.GetUserByNameAsync("admin");

                if (user == null)
                {
                    var adminUser = new UserIdentity
                    {
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        DisplayName = "Administrator"
                    };

                    await users.CreateAsync(adminUser, "User@1234");
                }

                await users.AddUserToRoleAsync(user, "admin");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string rid = Request.QueryString["rid"];
                repo = new RoleRepository();
                rr   = new RegistrationRequestRepository();
                RegistrationRequestTable r     = rr.GetRegistrationRequestForRegistrationRequestID(Convert.ToInt64(rid));
                List <RoleTable>         roles = repo.GetAllRoles();
                DetailsView1.DataSource = r;
                DetailsView1.DataBind();

                DropDownList1.DataSource     = roles;
                DropDownList1.DataTextField  = "RoleName";
                DropDownList1.DataValueField = "RoleID";
                DropDownList1.DataBind();
                lblAddSuc.Visible = false;
            }
        }
        public void TestIsAdminIsTrueSaves()
        {
            #region Arrange
            var role = GetValid(9);
            role.IsAdmin = true;
            #endregion Arrange

            #region Act
            RoleRepository.DbContext.BeginTransaction();
            RoleRepository.EnsurePersistent(role);
            RoleRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsTrue(role.IsAdmin);
            Assert.IsFalse(role.IsTransient());
            Assert.IsTrue(role.IsValid());
            #endregion Assert
        }
        public void TestUsersWithEmptyListWillSave()
        {
            #region Arrange
            Role record = GetValid(9);
            #endregion Arrange

            #region Act
            RoleRepository.DbContext.BeginTransaction();
            RoleRepository.EnsurePersistent(record);
            RoleRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.IsNotNull(record.Users);
            Assert.AreEqual(0, record.Users.Count);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }
        public void TestLevelWithMinIntValueSaves()
        {
            #region Arrange
            var record = GetValid(9);
            record.Level = int.MinValue;
            #endregion Arrange

            #region Act
            RoleRepository.DbContext.BeginTransaction();
            RoleRepository.EnsurePersistent(record);
            RoleRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(int.MinValue, record.Level);
            Assert.IsFalse(record.IsTransient());
            Assert.IsTrue(record.IsValid());
            #endregion Assert
        }
示例#40
0
        public JsonResult SelRole(DRelationship _param)
        {
            List <Role> lRoles = RoleRepository.SelRoles(new Role {
            });

            if (_param.FromOID != null)
            {
                DRelationshipRepository.SelRelationship(new DRelationship {
                    Type = CommonConstant.RELATIONSHIP_ROLE, FromOID = _param.FromOID
                }).ForEach(role =>
                {
                    lRoles.FindAll(innerRole => innerRole.OID == role.ToOID).ForEach(filterRole =>
                    {
                        filterRole.IsChecked = true;
                    });
                });
            }
            return(Json(lRoles));
        }
示例#41
0
        public async Task <ISingleResponse <RoleModel> > GetRoleByIDAsync(int roleID)
        {
            Logger.Info(CreateInvokedMethodLog(MethodBase.GetCurrentMethod().ReflectedType.FullName));

            var response = new SingleResponse <RoleModel>();

            try
            {
                var userDetails = await RoleRepository.GetByIDAsync(roleID);

                response.Model = Mapper.Map <RoleModel>(userDetails);
            }
            catch (Exception ex)
            {
                response.SetError(ex, Logger);
            }

            return(response);
        }
示例#42
0
        public async Task Find_GivenUserDoesExist_ExpectMaybeWithUser()
        {
            var options = new DbContextOptionsBuilder <DataContext>()
                          .UseInMemoryDatabase($"DataContext{Guid.NewGuid()}")
                          .Options;

            var mediator = new Mock <IMediator>();

            await using var context = new DataContext(options, mediator.Object);
            var role = new Role(TestVariables.RoleId, "name", new List <Guid>());
            await context.Roles.AddAsync(role);

            await context.SaveEntitiesAsync();

            var roleRepository = new RoleRepository(context);
            var maybe          = await roleRepository.Find(TestVariables.RoleId);

            Assert.True(maybe.HasValue);
        }
        public void TestGetManagementRolesForUserInApplicationReturnsExpectedValue1()
        {
            #region Arrange
            var applicationRoleRepository = FakeRepository <ApplicationRole>();
            RoleService = new RoleService(PermissionRepository, applicationRoleRepository);
            ControllerRecordFakes.FakeApplications(3, ApplicationRepository);
            ControllerRecordFakes.FakeUsers(3, UserRepository);

            var roles = new List <Role>();
            roles.Add(CreateValidEntities.Role(1));
            roles.Add(CreateValidEntities.Role(2));
            roles.Add(CreateValidEntities.Role(3));
            roles.Add(CreateValidEntities.Role(4));
            roles[0].Name = "ManageAll";
            roles[1].Name = "ManageSchool";
            roles[2].Name = "ManageUnit";
            roles[3].Name = "ManageMe"; //Not special
            ControllerRecordFakes.FakeRoles(5, RoleRepository, roles);

            var permissions = new List <Permission>();
            for (int i = 0; i < 6; i++)
            {
                permissions.Add(CreateValidEntities.Permission(i + 1));
                permissions[i].Application = ApplicationRepository.GetNullableById(1);
                permissions[i].User        = UserRepository.GetNullableById(2);
                permissions[i].Role        = RoleRepository.GetNullableById(i + 1);
            }
            ControllerRecordFakes.FakePermissions(6, PermissionRepository, permissions);
            #endregion Arrange

            #region Act
            var result = RoleService.GetManagementRolesForUserInApplication("Name1", "LoginId2");
            #endregion Act

            #region Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(4, result.Count);
            Assert.AreEqual("ManageAll", result.ElementAt(0));
            Assert.AreEqual("ManageSchool", result.ElementAt(1));
            Assert.AreEqual("ManageUnit", result.ElementAt(2));
            Assert.AreEqual("ManageMe", result.ElementAt(3));
            #endregion Assert
        }
        public override bool RoleExists(string roleName)
        {
            if (string.IsNullOrEmpty(roleName))
            {
                return(false);
            }

            Role Role = null;

            Role = RoleRepository.GetAll().FirstOrDefault(Rl => Rl.RoleName == roleName);
            if (Role != null)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public async Task CreateNamespaceFullAccessRole_IncludesCorrectPolicies()
        {
            var k8s = Dummy.Of <IKubernetesWrapper>();
            var sut = new RoleRepository(k8s);

            Mock.Get(k8s).Setup(k => k.CreateNamespacedRoleAsync(It.IsAny <V1Role>(),
                                                                 It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult(new V1Role()));

            var @namespace = "fancyNamespace";

            var result = await sut.CreateNamespaceFullAccessRole(@namespace);


            Moq.Mock.Get(k8s).Verify(s => s.CreateNamespacedRoleAsync(It.Is <V1Role>(r =>
                                                                                     r.Metadata.NamespaceProperty == @namespace &&
                                                                                     r.Rules.Count == 4 &&
                                                                                     r.Rules.Count(rule => rule.Resources.Any(res => res.Contains("namespace"))) == 1), It.Is <string>(n => n == @namespace), It.IsAny <string>(), It.IsAny <CancellationToken>()));
        }
示例#46
0
        private bool FillSolutionComponentFromSchemaName(ICollection <SolutionComponent> result, string schemaName, int?behavior)
        {
            if (!string.IsNullOrEmpty(schemaName) &&
                Guid.TryParse(schemaName, out var roleTemplateId))
            {
                var repository = new RoleRepository(_service);

                var entity = repository.FindRoleByTemplate(roleTemplateId, new ColumnSet(false));

                if (entity != null)
                {
                    FillSolutionComponentInternal(result, entity.Id, behavior);

                    return(true);
                }
            }

            return(false);
        }
        //删除测试,还是对象
        public void Method3()
        {
            var repo  = new UserRepository();
            var repo1 = new RoleRepository();

            var users = new List <SysUser>()
            {
                new SysUser()
                {
                    UserName = "******",
                    Password = "******"
                }
            };

            repo.Insert(users);

            var roles = new List <SysRole>()
            {
                new SysRole()
                {
                    Name        = "管理员3",
                    Description = "管理员3",
                    RoleType    = RoleType.Admin
                }
            };

            repo1.Insert(roles);

            long userId = repo.Entities.FirstOrDefault(o => o.UserName == "user3").Id;
            long roleId = repo1.Entities.FirstOrDefault(o => o.Name == "管理员3").Id;

            var user = repo.Query(userId);
            var role = repo1.Query(roleId);

            user.Roles = new List <SysRole>()
            {
                role
            };
            repo.Update(user);

            user.Roles = null;
            repo.Update(user);
        }
        private static void CleanRoles(RoleRepository repository)
        {
            var entities = repository.GetAllEntities();

            foreach (Role entity in entities)
            {
                using (var db = new ESportDbContext())
                    try
                    {
                        var entityToRemove = db.Role.Attach(entity);
                        db.Role.Remove(entityToRemove);
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw new RepositoryException("Error al eliminar entidad", e);
                    }
            }
        }
        public void TestNameWithLongValueSaves()
        {
            #region Arrange
            var role = GetValid(9);
            role.Name = "x".RepeatTimes(50);
            #endregion Arrange

            #region Act
            RoleRepository.DbContext.BeginTransaction();
            RoleRepository.EnsurePersistent(role);
            RoleRepository.DbContext.CommitTransaction();
            #endregion Act

            #region Assert
            Assert.AreEqual(50, role.Name.Length);
            Assert.IsFalse(role.IsTransient());
            Assert.IsTrue(role.IsValid());
            #endregion Assert
        }
示例#50
0
        public bool Delete(string roleID)
        {
            Guid gRoleID = new Guid(roleID);
            var  role    = RoleRepository.GetQueryable()
                           .FirstOrDefault(i => i.RoleID == gRoleID);

            if (role != null)
            {
                Del(RoleSystemRepository, role.RoleSystems);
                Del(UserRoleRepository, role.UserRoles);
                RoleRepository.Delete(role);
                RoleRepository.SaveChanges();
            }
            else
            {
                return(false);
            }
            return(true);
        }
        public UnitOfWork(ParkingManagementContext parkingManagementContext)
        {
            _parkingManagementContext = parkingManagementContext;
            Registers           = new RegisterRepository(_parkingManagementContext);
            UserRoles           = new RoleRepository(_parkingManagementContext);
            RequestDuationTypes = new RequestDuationTypeRepository(_parkingManagementContext);
            Tower             = new TowerRepository(_parkingManagementContext);
            ParkingSlot       = new ParkingSlotRepository(_parkingManagementContext);
            RequestDetails    = new RequestDetailsRepository(_parkingManagementContext);
            ParkingAllocation = new ParkingAllocationRepository(_parkingManagementContext);
            SurrenderHistory  = new SurrenderHistoryRepository(_parkingManagementContext);
            TowerParkingSlot  = new TowerParkingSlotRepository(_parkingManagementContext);



            TowerBlock         = new TowerBlockRepository(_parkingManagementContext);
            TowerBlockSlot     = new TowerBlockSlotRepository(_parkingManagementContext);
            slotRequestDetails = new SlotRequestDetailsRepository(_parkingManagementContext);
        }
        public async Task <Guid> CreateCharity(CharityCreateDto charityDto)
        {
            User user = new User(Guid.NewGuid(), charityDto.Login.ToLower(), charityDto.Password.ToSHA512(),
                                 LoginType.CHARITABLE_ENTITY, Guid.NewGuid(), true);

            var charitable = this.Mapper.Map <CharitableEntity>(charityDto);

            charitable.Status       = ApproverStatus.PENDING;
            charitable.IsActive     = false;
            charitable.ApproverData = null;
            charitable.Approver     = string.Empty;
            charitable.Id           = Guid.NewGuid();
            charitable.UserId       = user.Id;

            var approval = new Approval()
            {
                Id = Guid.NewGuid(),
                CharitableEntityId = charitable.Id,
                Date    = DateTime.UtcNow.ToBrazilianTimeZone(),
                Message = "Análise Pendente",
                Status  = (int)ApproverStatus.PENDING
            };

            var lstRole = await RoleRepository.GetWhereAsync(r => r.Name.ToLower().Equals("charitable_entity"));

            if (!lstRole.Any())
            {
                throw new Exception("Cannot find role charitable_entity");
            }

            await UserRoleRepository.AddAsync(new UserRole()
            {
                User = user, RoleId = lstRole.First().Id
            });

            await this.Repository.AddAsync(charitable);

            await ApprovalRepository.AddAsync(approval);

            await this.Repository.SaveAsync();

            return(charitable.Id);
        }
        public UserManageController
            (UserRepository userRepository,
            UserManager <Users> userManager

            , UsersRoleRepository usersRoleRepository
            , RoleRepository roleRepository
            , SmsService smsService
            , UsersAccessRepository usersAccessRepository,
            UserOrganizationRepository userOrganizationRepository,
            OrganizationRepository organizationRepository) : base(usersAccessRepository)
        {
            _userRepository             = userRepository;
            _userManager                = userManager;
            _usersRoleRepository        = usersRoleRepository;
            _roleRepository             = roleRepository;
            _smsService                 = smsService;
            _userOrganizationRepository = userOrganizationRepository;
            _organizationRepository     = organizationRepository;
        }
示例#54
0
        public bool UserCheckRole(int userId, int roleId)
        {
            var user = UserRepository.UserGetById(userId);
            var role = RoleRepository.RoleGetById(roleId);

            if (user == null || role == null)
            {
                return(false);
            }

            foreach (Role userRole in user.Roles)
            {
                if (role.Id == userRole.Id)
                {
                    return(true);
                }
            }
            return(false);
        }
示例#55
0
        /// <summary>
        /// 编辑用户角色映射信息
        /// </summary>
        /// <param name="dto">用户角色映射信息输入DTO</param>
        /// <returns>业务操作结果</returns>
        public virtual async Task <OperationResult> UpdateUserRoleMapAsync(TUserRoleMapInputDto dto)
        {
            dto.CheckNotNull("dto");
            dto.ThrowIfTimeInvalid();
            Expression <Func <TUserRoleMap, bool> > predicate = m => m.User.Id.Equals(dto.UserId) && m.Role.Id.Equals(dto.RoleId);

            predicate = predicate.And(GetUserRoleMapUnexpireExpression(dto));
            TUserRoleMap map = (await UserRoleMapRepository.GetByPredicateAsync(predicate)).FirstOrDefault();

            if (map != null && !map.Id.Equals(dto.Id))
            {
                return(new OperationResult(OperationResultType.Error,
                                           "“{0}{1}”存在的时间区间[{2}→{3}]包含当前时间段,不能重复添加"
                                           .FormatWith(map.User.NickName, map.Role.Name, GetTimeString(map.BeginTime), GetTimeString(map.EndTime))));
            }
            if (map == null || !map.Id.Equals(dto.Id))
            {
                map = await UserRoleMapRepository.GetByKeyAsync(dto.Id);
            }
            map = dto.MapTo(map);
            if (!map.User.Id.Equals(dto.UserId))
            {
                TUser user = UserRepository.GetByKey(dto.UserId);
                if (user == null)
                {
                    return(new OperationResult(OperationResultType.QueryNull, "指定编号的用户信息不存在"));
                }
                map.User = user;
            }
            if (!map.Role.Id.Equals(dto.RoleId))
            {
                TRole role = RoleRepository.GetByKey(dto.RoleId);
                if (role == null)
                {
                    return(new OperationResult(OperationResultType.QueryNull, "指定编号的角色信息不存在"));
                }
                map.Role = role;
            }
            await UserRoleMapRepository.UpdateAsync(map);

            return(OperationResult.Success);
        }
示例#56
0
        /// <summary>
        /// Gets the role ID from the user.
        /// </summary>
        /// <returns>Returns an integer for the selected role ID.</returns>
        private static int GetRoleId()
        {
            _roleRepository = new RoleRepository(context);
            int?         roleId = null;
            IList <Role> roles  = _roleRepository.GetList();

            // While the role ID is null, prompt the user to select a role ID
            // from the provided list.
            while (roleId == null)
            {
                ConsoleHelper.OutputBlankLine();

                foreach (Role r in roles)
                {
                    ConsoleHelper.OutputLine("{0}) {1}", roles.IndexOf(r) + 1, r.Name);
                }

                // Get the line number for the selected role.
                string lineNumberInput = ConsoleHelper.ReadInput(
                    "Enter the line number of the role that the artist had on this comic book: ");

                // Attempt to parse the user's input to a line number.
                int lineNumber = 0;
                if (int.TryParse(lineNumberInput, out lineNumber))
                {
                    if (lineNumber > 0 && lineNumber <= roles.Count)
                    {
                        roleId = roles[lineNumber - 1].Id;
                    }
                }

                // If we weren't able to parse the provided line number
                // to an role ID then display an error message.
                if (roleId == null)
                {
                    ConsoleHelper.OutputLine("Sorry, but that wasn't a valid line number.");
                }
            }

            context.Dispose();
            return(roleId.Value);
        }
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            foreach (string rolename in roleNames)
            {
                if (!RoleExists(rolename))
                {
                    throw new ProviderException(String.Format("Role name {0} not found.", rolename));
                }
            }

            foreach (string username in usernames)
            {
                if (username.Contains(","))
                {
                    throw new ArgumentException(String.Format("User names {0} cannot contain commas.", username));
                }
                //is user not exiting //throw exception

                foreach (string rolename in roleNames)
                {
                    if (IsUserInRole(username, rolename))
                    {
                        throw new ProviderException(String.Format("User {0} is already in role {1}.", username, rolename));
                    }
                }
            }
            List <User> Users = UserRepository.GetAll().Where(Usr => usernames.Contains(Usr.Username)).ToList();
            List <Role> Roles = RoleRepository.GetAll().Where(Rl => roleNames.Contains(Rl.RoleName)).ToList();

            foreach (User user in Users)
            {
                foreach (Role role in Roles)
                {
                    if (!user.Roles.Contains(role))
                    {
                        user.Roles.Add(role);
                        UserRepository.SaveOrUpdate(user);
                        RoleRepository.SaveOrUpdate(role);
                    }
                }
            }
        }
示例#58
0
        public string Edit(FormDataCollection form)
        {
            string   retVal    = string.Empty;
            string   operation = form.Get("oper");
            int      id        = ConvertHelper.ToInt32(form.Get("RoleId"));
            RoleInfo info      = null;

            if (!string.IsNullOrEmpty(operation))
            {
                switch (operation)
                {
                case "edit":
                    info = RoleRepository.GetInfo(id);
                    if (info != null)
                    {
                        info.Name        = form.Get("Name");
                        info.Description = form.Get("Description");
                        info.ChangedBy   = UserRepository.GetCurrentUserInfo().UserID;
                        RoleRepository.Update(info);
                    }
                    break;

                case "add":
                    info = new RoleInfo
                    {
                        Name        = form.Get("Name"),
                        Description = form.Get("Description"),
                        CreatedBy   = UserRepository.GetCurrentUserInfo().UserID
                    };
                    RoleRepository.Insert(info);
                    break;

                case "del":
                    RoleRepository.Delete(id, UserRepository.GetCurrentUserInfo().UserID);
                    break;

                default:
                    break;
                }
            }
            return(retVal);
        }
示例#59
0
 public UserContextLoader(
     ApplicationDbContext dbContext,
     UserContext userContext,
     AccountRepository accountRepository,
     RoleRepository roleRepository,
     IHubContext <ForumHub> forumHub,
     SignInManager <DataModels.ApplicationUser> signInManager,
     UserManager <DataModels.ApplicationUser> userManager,
     IHttpContextAccessor httpContextAccessor
     )
 {
     DbContext           = dbContext;
     UserContext         = userContext;
     RoleRepository      = roleRepository;
     AccountRepository   = accountRepository;
     ForumHub            = forumHub;
     SignInManager       = signInManager;
     UserManager         = userManager;
     HttpContextAccessor = httpContextAccessor;
 }
示例#60
0
 public HttpResponseMessage Put(RoleDto dto)
 {
     try
     {
         if (dto != null)
         {
             RoleRepository.Update(dto);
             return(Request.CreateResponse(HttpStatusCode.OK));
         }
         return(Request.CreateResponse(HttpStatusCode.BadRequest));
     }
     catch (ElementNotFoundException e)
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest, e.Message));
     }
     catch (Exception)
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest, "Generic error happened."));
     }
 }