예제 #1
0
        public void Create_AnyRoleAndAnyExpirationTime_WorksSuccessfully(RoleType role, int minutes)
        {
            //arrange
            User user = new User()
            {
                UserName = "******", Email = "testEmail"
            };
            var key       = "b3ff24525cbdb417dd1f7cbe8c37477d7393f905c873718b8a5222e43testkey";
            var audience  = "testAudience";
            var issuer    = "testIssuer";
            var rolesList = new List <string>()
            {
                role.ToString()
            };
            var userManagerMock = MockUserManager <User>();

            userManagerMock.Setup(um => um.GetRolesAsync(user)).ReturnsAsync(rolesList);
            var sut = new JwtFactory(userManagerMock.Object, key, issuer, audience);

            //act
            var result = sut.Create(user, minutes);

            //assert
            result.Should().NotBeNull();
            result.Should().BeOfType <Jwt>();
            result.Expiration.Should().BeCloseTo(DateTime.UtcNow.AddMinutes(minutes), precision: 60000);
            result.Roles.Should().Contain(role.ToString());
            result.Token.Length.Should().BeGreaterThan(10);
            userManagerMock.Verify(um => um.GetRolesAsync(user), Times.Once);
        }
예제 #2
0
        public async Task DisplayRolesAsync(
            [Summary("The type of roles you want a list of. If left empty, this will default to show all roles")]
            [Example("Admin")]
            [Example("Color")]
            [Example("Game")]
            [Example("Other")]
            RoleType type = RoleType.Last)
        {
            string listDescription = "Here is a list of every ";

            if (type != RoleType.Last)
            {
                listDescription += "`" + type.ToString() + "`";
            }
            listDescription += $" role on `{Context.Guild.Name}`";
            if (type == RoleType.Last)
            {
                listDescription += ", sorted into types:";
            }

            // Declare EmbedBuilder base.
            EmbedBuilder builder = new EmbedBuilder()
                                   .WithColor(Data.COLOR_BOT)
                                   .WithThumbnailUrl(Data.URL_IMAGE_INFINITY_GAMING)
                                   .WithTitle("Roles")
                                   .WithDescription(listDescription);

            // Get the role list fields to the EmbedBuilder.
            builder = Data.AddRoleFields(builder, ((SocketGuildUser)Context.User).GuildPermissions.Administrator, type);

            // Send role list to user and return feedback message.
            await Context.User.SendMessageAsync(embed : builder.Build());

            string feedbackDescription = "I have PMed you a list of the ";

            if (type == RoleType.Last)
            {
                feedbackDescription += "server";
            }
            else
            {
                feedbackDescription += $"`{type.ToString()}`";
            }
            feedbackDescription += " roles.";
            IMessage m = await ReplyAsync(
                embed : new EmbedBuilder()
                .WithTitle("Role list sent")
                .WithDescription(feedbackDescription)
                .WithAutoDeletionFooter()
                .Build());

            // Delete prompt and feedback messages.
            await Task.Delay(Data.MESSAGE_DELETE_DELAY * 1000);

            await Context.Message.DeleteAsync();

            await m.DeleteAsync();
        }
예제 #3
0
        private async Task <string> CreateOrGetRole(RoleType roleType)
        {
            bool roleExists = await roleManager.RoleExistsAsync(roleType.ToString());

            if (!roleExists)
            {
                var role = new IdentityRole
                {
                    Name = roleType.ToString()
                };
                await roleManager.CreateAsync(role);
            }
            return(roleType.ToString());
        }
예제 #4
0
    private IEnumerator CreateRole(RoleType roleType)
    {
        GameObject obj = ResourcesManager.Instance.GetModelPrefab(roleType.ToString());

        obj.name                       = roleType.ToString();
        obj.transform.parent           = this.SelectRoleModelRoot.transform;
        obj.transform.localEulerAngles = new Vector3(0, 180, 0);
        obj.transform.localPosition    = new Vector3(0, -0.6f, 3);
        obj.transform.localScale       = Vector3.one;
        if (roleType == RoleType.Armourer)
        {
            this.RoleModelCreateOver = true;
        }
        yield break;
    }
        public DocumentShare ShareDocument(Guid dlId, Guid usId, string message = "", RoleType linkRole = RoleType.Viewer)
        {
            if (dlId.Equals(Guid.Empty))
            {
                throw new ArgumentException("dlId is required but was an empty Guid", "dlId");
            }
            if (usId.Equals(Guid.Empty))
            {
                throw new ArgumentException("dlId is required but was an empty Guid", "usId");
            }

            switch (linkRole)
            {
            case RoleType.Owner:
            case RoleType.Editor:
                linkRole = RoleType.Editor;
                break;

            default:
                linkRole = RoleType.Viewer;
                break;
            }

            dynamic postData = new ExpandoObject();

            postData.users    = new JObject(new JProperty("id", usId));
            postData.message  = message;
            postData.baseUrl  = ShareUrl;
            postData.isPublic = "true";
            postData.linkRole = linkRole.ToString().ToLower();

            return(HttpHelper.Put <DocumentShare>(VVRestApi.GlobalConfiguration.Routes.DocumentsIdShares, "", GetUrlParts(), this.ClientSecrets, this.ApiTokens, postData, dlId, usId));
        }
        /// <summary>
        /// Creates a link the can be embedded in a web page
        /// </summary>
        public DocumentShare GetDocumentShareLink(Guid dlId, RoleType linkRole)
        {
            if (dlId.Equals(Guid.Empty))
            {
                throw new ArgumentException("dlId is required but was an empty Guid", "dlId");
            }

            switch (linkRole)
            {
            case RoleType.Owner:
            case RoleType.Editor:
                linkRole = RoleType.Editor;
                break;

            default:
                linkRole = RoleType.Viewer;
                break;
            }

            dynamic postData = new ExpandoObject();

            postData.baseUrl  = ShareUrl;
            postData.linkRole = linkRole.ToString().ToLower();

            return(HttpHelper.Post <DocumentShare>(VVRestApi.GlobalConfiguration.Routes.DocumentsIdShares, "", GetUrlParts(), this.ClientSecrets, this.ApiTokens, postData, dlId));
        }
예제 #7
0
 public static SimpleCustomRole Parse(this RoleType role, Team team)
 {
     return(new SimpleCustomRole()
     {
         Role = (role.ToString(), (int)role),
         Team = (team.ToString(), (byte)team)
     });
예제 #8
0
        public ActionResult Login(string username, string password)
        {
            SQLManager manager = new SQLManager();
            RoleType   type    = manager.CheckUser(username, password);

            switch (type)
            {
            case RoleType.Admin:
                HttpCookie adminCookie = GetCookie(username, "Admin");
                Response.Cookies.Add(adminCookie);
                break;

            case RoleType.Teacher:
                HttpCookie teacherCookie = GetCookie(username, "Teacher");
                Response.Cookies.Add(teacherCookie);
                break;

            case RoleType.Student:
                HttpCookie studentCookie = GetCookie(username, "Student");
                Response.Cookies.Add(studentCookie);
                break;

            default:
                break;
            }
            return(Content(type.ToString()));
        }
예제 #9
0
        /// <summary>
        /// Creates a new Role for 1st time install only
        /// </summary>
        /// <param name="username">name of user</param>
        /// <param name="password">password</param>
        /// <param name="role">name of the new role</param>
        /// <param name="type">type of the new role</param>
        public void CreateRole1stTime(string username, string password, string role, RoleType type)
        {
            try
            {
                if (White_Tiger.WhiteTigerService.pref.WindowsAutherication)
                {
                }
                else
                {
                    if ((username != null) && ((password != null)))
                    {
                        this.LoadRoles();

                        if ((roles != null) && (roles.Tables != null) && this.Login(username, password))
                        {
                            object[] vals = new object[rolestable.Length];
                            vals[0] = username;
                            vals[1] = role;
                            vals[2] = type.ToString();
                            roles.Tables[0].Rows.Add(vals);
                            this.UpdateRoles();
                            this.CloseRolesTable();
                            this.LoadRoles();
                        }
                    }
                }
            }

            catch (Exception e)
            {
                program.errorreport(e);
            }
        }
예제 #10
0
        /// <summary>
        /// REturns true if the user is in the given role.
        /// </summary>
        /// <param name="set">The set.</param>
        /// <param name="userId">The user identifier.</param>
        /// <param name="role">The role.</param>
        /// <returns></returns>
        public static bool UserHasRole(this IDbSet <AppUser> set, Guid userId, RoleType role)
        {
            Contract.Requires <ArgumentNullException>(set != null, "set");
            Contract.Requires <ArgumentNullException>(userId != Guid.Empty, "userId");

            return(set.Repo().UserManager.IsInRole(userId, role.ToString()));
        }
        public DocumentShare ShareDocument(Guid dlId, Guid usId, string message = "", RoleType linkRole = RoleType.Viewer)
        {
            if (dlId.Equals(Guid.Empty))
            {
                throw new ArgumentException("dlId is required but was an empty Guid", "dlId");
            }
            if (usId.Equals(Guid.Empty))
            {
                throw new ArgumentException("dlId is required but was an empty Guid", "usId");
            }

            switch (linkRole)
            {
                case RoleType.Owner:
                case RoleType.Editor:
                    linkRole = RoleType.Editor;
                    break;
                default:
                    linkRole = RoleType.Viewer;
                    break;
            }

            dynamic postData = new ExpandoObject();
            postData.users = usId;
            postData.message = message;
            postData.baseUrl = ShareUrl;
            postData.isPublic = "true";
            postData.linkRole = linkRole.ToString().ToLower();

            return HttpHelper.Put<DocumentShare>(VVRestApi.GlobalConfiguration.Routes.DocumentsIdShares, "", GetUrlParts(), this.ClientSecrets, this.ApiTokens, postData, dlId, usId);
        }
예제 #12
0
        public void GetRandom()
        {
            rngRole       = plugin.allowedrngRoles[UnityEngine.Random.Range(0, plugin.allowedrngRoles.Count)];
            rngRoleBoss   = plugin.allowedrngRolesBoss[UnityEngine.Random.Range(0, plugin.allowedrngRolesBoss.Count)];
            plugin.curMod = 0;
            List <ModCategory> curModCategories = new List <ModCategory>();
            int rec = 0;

            for (int i = 0; i < plugin.maxMods; i++)
            {
                rec++;
                ModType modtype = plugin.allowedTypes[UnityEngine.Random.Range(0, plugin.allowedTypes.Count)];
                if (mods[modtype] != ModCategory.NONE && curModCategories.Contains(mods[modtype]))
                {
                    if (rec < 5) //prevent lag
                    {
                        i--;
                    }
                    continue;
                }
                plugin.curMod |= modtype;
                curModCategories.Add(mods[modtype]);
            }
            Log.Debug("curMod: " + plugin.curMod.ToString());
            Log.Debug("rngRole: " + rngRole.ToString());
            Log.Debug("rngRoleBoss: " + rngRoleBoss.ToString());
        }
        public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
        {
            if (!dbContext.MoviesCastMembers.Any())
            {
                var    castMembers = dbContext.CastMembers.Select(x => x.Id).ToList();
                var    movies      = dbContext.Movies.Select(x => x.Id).ToList();
                Random rng         = new Random();

                foreach (var movieId in movies)
                {
                    int numberOfCastMembers = rng.Next(1, 5);
                    foreach (var castMemberId in castMembers.Take(numberOfCastMembers))
                    {
                        RoleType role             = (RoleType)rng.Next(0, 5);
                        var      moviesCastMember = new MoviesCastMember
                        {
                            CastMemberId = castMemberId,
                            MovieId      = movieId,
                            RoleType     = role,
                            RoleName     = role.ToString(),
                        };

                        await dbContext.AddAsync(moviesCastMember);
                    }
                }
            }
        }
예제 #14
0
        public static SingleUserDTO ConvertUserToDTO(User user)
        {
            RoleType      role    = (RoleType)user.Role;
            SingleUserDTO newVDTO = new SingleUserDTO
            {
                Id = user.Id,
                profilePictureUrl = user.ProfilePictureUrl,
                Username          = user.Username,
                Password          = user.Password,
                FirstName         = user.FirstName,
                LastName          = user.LastName,
                Email             = user.Email,
                Description       = user.Description,
                RegistrationDate  = user.RegistrationDate.ToString("dd.mm.yyyy"),
                Role          = role.ToString(),
                Blocked       = user.Blocked,
                UsersVideos   = VideoForUser.ConvertVideoToDTO(user.UserVideos),
                LikedVideos   = SingleVideoDTO.ConvertLikedVideosToDTO(user.LikedVideos),
                UserComments  = CommentForUserDTO.ConvertCommentToDTO(user.UserComments),
                LikedComments = CommentForUserDTO.ConvertCommentToDTO(user.LikedComments),
                Followers     = UserForVideoComment.ConvertFollowers(user.Followers),
                Following     = UserForVideoComment.ConvertFollowers(user.Following)
            };

            return(newVDTO);
        }
 internal EmploymentDetails(Guid employeeId, RoleType roleType, EmploymentType employmentType, DateTime commencementDate)
 {
     Key              = $"{roleType.ToString()}_{employmentType.ToString()}_{commencementDate.ToString("yyyyMMdd")}_{employeeId}";
     RoleType         = roleType;
     EmploymentType   = employmentType;
     CommencementDate = commencementDate;
 }
 public Role(RoleType role)
 {
     this._roleType  = role;
     this._roleName  = role.ToString();
     this._farsiRole = EnumHelper.ToEnumString <RoleType>(role);
     canAssign       = new HashSet <RoleType>();
 }
예제 #17
0
        public static string GetRoleTypeName(RoleType roleType)
        {
            string name = roleType.ToString();

            switch (roleType)
            {
            case RoleType.Defence:
                name = Localization.Get("hero_type_name_def");
                break;

            case RoleType.Offence:
                name = Localization.Get("hero_type_name_atk");
                break;

            case RoleType.Mage:
                name = Localization.Get("hero_type_name_magic");
                break;

            case RoleType.Mighty:
                name = Localization.Get("hero_type_name_all");
                break;

            case RoleType.Support:
                name = Localization.Get("hero_type_name_assist");
                break;

            default:
                break;
            }
            return(name);
        }
예제 #18
0
        public async Task <RegisterDto> Register(RegisterDto model, RoleType role)
        {
            if (!await UserExist(model.Email))
            {
                User user = new User
                {
                    UserName  = model.Email,
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName
                };

                IdentityResult result = _userManager.CreateAsync(user, model.Password).Result;

                if (!result.Succeeded)
                {
                    return(null);
                }
                else
                {
                    await _userManager.AddToRoleAsync(user, role.ToString());
                }

                return(model);
            }

            return(null);
        }
예제 #19
0
        public void Register_EmailIsBuisy_ReturnsNull(RoleType role)
        {
            //arrange
            var model = new RegisterDto()
            {
                FirstName = "test", LastName = "test", Email = "test"
            };
            User findResult      = new User();
            var  jwtFactoryMock  = new Mock <IJwtFactory>();
            var  userManagerMock = MockUserManager <User>();

            userManagerMock.Setup(um => um.FindByEmailAsync(It.IsAny <string>())).ReturnsAsync(findResult);
            var signinManagerMock = MockSignInManager(userManagerMock);

            var sut = new AccountService(signinManagerMock.Object, userManagerMock.Object, jwtFactoryMock.Object);

            //act
            var actresult = sut.Register(model, role).Result;

            //assert
            actresult.Should().BeNull();
            userManagerMock.Verify(um => um.FindByEmailAsync(It.IsAny <string>()), Times.Once);
            userManagerMock.Verify(um => um.CreateAsync(It.IsAny <User>(), It.IsAny <string>()), Times.Never);
            userManagerMock.Verify(um => um.AddToRoleAsync(It.IsAny <User>(), role.ToString()), Times.Never);
        }
예제 #20
0
 public void Lose(RoleType casterRoleType)
 {
     PECommon.Log("你输了");
     SetActive(imgDefeated);
     SetActive(txtDefeated);
     SetText(txtDefeated, casterRoleType.ToString() + "干掉了你");
 }
예제 #21
0
        /// <summary>
        /// Removes the user from role.
        /// </summary>
        /// <param name="set">The set.</param>
        /// <param name="userId">The user identifier.</param>
        /// <param name="role">The role.</param>
        public static void RemoveUserFromRole(this IDbSet <AppUser> set, Guid userId, RoleType role)
        {
            Contract.Requires <ArgumentNullException>(set != null, "set");
            Contract.Requires <ArgumentNullException>(userId != Guid.Empty, "userId");

            set.Repo().UserManager.RemoveFromRole(userId, role.ToString());
        }
예제 #22
0
 public bool HasPermission(RoleType role)
 {
     if (Client != null)
     {
         return(Client.Role.Name == role.ToString().ToLower());
     }
     return(false);
 }
예제 #23
0
 public static string ToDescriptionString(this RoleType val)
 {
     DescriptionAttribute[] attributes = (DescriptionAttribute[])val
                                         .GetType()
                                         .GetField(val.ToString())
                                         .GetCustomAttributes(typeof(DescriptionAttribute), false);
     return(attributes.Length > 0 ? attributes[0].Description : string.Empty);
 }
예제 #24
0
 public static RoleType GetRoleConversion(RoleType currentRole)
 {
     if (RoleConversions.TryGetValue(currentRole.ToString(), out string newRole))
     {
         return(newRole.GetRole());
     }
     return(currentRole);
 }
예제 #25
0
 /// <summary>
 /// 检验当前登录用户的权限
 /// </summary>
 /// <param name="role"></param>
 /// <returns></returns>
 public bool CheckRole(RoleType role)
 {
     AdminUser user = GetUser();
     CommonLoger.Info(role.ToString() + user.RoleType.ToString());
     if (user == null || (int)user.RoleType != (int)role)
         return false;
     else
         return true;
 }
        /// <summary>
        /// 尝试创建用户,并发送注册邮件到用户邮箱
        /// </summary>
        /// <param name="registerUser"></param>
        /// <param name="roleType"></param>
        /// <returns></returns>
        private async Task <ValueTuple <bool, MoUserInfo> > TryCreateUser(MoUserInfoSimple registerUser, RoleType roleType)
        {
            if (registerUser == null)
            {
                throw new ArgumentNullException(nameof(registerUser));
            }

            // 因为我们要考虑到已经入库了但邮箱还未激活的用户(也就是还未完成全部注册流程的用户)可能会重复注册,所以我这里改成这样子
            User user = _uf.UserRepository.GetFirstOrDefault(x => x.Email.Equals(registerUser.UserName, StringComparison.OrdinalIgnoreCase));

            if (user == null)
            {
                using (var trans = _uf.BeginTransaction())
                {
                    try
                    {
                        user = await _uf.UserRepository.CreateUserAsync(registerUser);

                        //_uf.SaveChanges();
                        var role = await _uf.RoleRepository.GetOrAddAsync(roleType);

                        //_uf.SaveChanges();
                        var userToRole = new UserToRole
                        {
                            UserId = user.Id,
                            RoleId = role.Id
                        };

                        await _uf.UserToRoleRepository.InsertAsync(userToRole);

                        await _uf.SaveChangesAsync();

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        this.MsgBox("注册用户失败");
                        return(false, null);
                    }
                }
            }

            var userInfo = new MoUserInfo
            {
                Id         = user.Id,
                UserStatus = (int)user.UserStatus,
                Email      = user.Email,
                HeadPhoto  = user.HeadPhoto,
                UserName   = user.UserName,
                Roles      = roleType.ToString()
            };

            HttpContext.AddUserInfo(userInfo);
            this.MsgBox("注册用户成功,请查看您的邮箱,确认激活!");
            return(true, userInfo);
        }
예제 #27
0
        public static string GetText(this RoleType roleType)
        {
            Type type = roleType.GetType();

            MemberInfo[] memInfo = type.GetMember(roleType.ToString());

            if (memInfo != null && memInfo.Length > 0)
            {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    return(((DescriptionAttribute)attrs[0]).Description);
                }
            }

            return(roleType.ToString());
        }
        public ActionResult Student()
        {
            string   roleName = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).Select(u => u.RoleName).FirstOrDefault();
            RoleType rType    = (RoleType)Enum.Parse(typeof(RoleType), roleName);

            ViewBag.RoleType = rType.ToString();

            return(View());
        }
예제 #29
0
        public ActionResult GetRightTree(string belong, long pId = 0, bool last = true, string chk = "")
        {
            //权限检查
            Helper.IsCheck(HttpContext, belong + "Right", SystemRight.Browse.ToString(), true);

            Result <List <Base_Right> > result = new Result <List <Base_Right> >();
            RoleType roleType = belong.ToEnumReq <RoleType>();

            using (AdminClientProxy proxy = new AdminClientProxy(ProxyEx(Request)))
            {
                result = proxy.LoadRightList(roleType);
            }
            Base_Right right = null;
            var        list  = result.Data;
            var        be    = belong.ToEnumReq <RoleType>();

            switch (be)
            {
            case RoleType.Admin:
                list.Insert(0, Helper.AdminSite);
                break;

            //case RoleType.Tenderer:
            //    break;
            //case RoleType.BiddingAgent:
            //    list.Insert(0, Helper.BiddingAgentSite);
            //    break;
            //case RoleType.Bidder:
            //    break;
            //case RoleType.Exp:
            //    break;
            default:
                right        = Helper.WebSite;
                right.Belong = roleType.ToString();
                list.Insert(0, right);
                break;
            }


            var       first    = list.FirstOrDefault(i => i.Id == pId);
            RightNode rootTree = new RightNode();

            rootTree.checkboxValue = first.Id.ToString();
            rootTree.@checked      = chk == first.Id.ToString();
            rootTree.data          = new { code = first.Code, id = first.Id.ToString() };
            rootTree.name          = first.Name;
            rootTree.spread        = true;

            var tree = createTree(first.Id, list);

            if (!last)
            {
                tree = createTreeNoLast(first.Id, list, chk);
            }
            rootTree.children = tree;
            return(Json(rootTree, JsonRequestBehavior.AllowGet));;
        }
예제 #30
0
        public ActionResult GetRightTree(string belong, long roleId)
        {
            if (belong != "Admin")
            {
                belong = "Owner";
            }
            Result <List <Base_Right> > result = new Result <List <Base_Right> >();
            RoleType roleType = belong.ToEnumReq <RoleType>();

            Result <List <Base_RoleRight> > roleRight = new Result <List <Base_RoleRight> >();
            List <long> roleRightIds = new List <long>();

            using (AdminClientProxy proxy = new AdminClientProxy(ProxyEx(Request)))
            {
                result = proxy.LoadRightList(roleType);
                //获取角色的所有权限
                roleRight = proxy.GetRightByRoleIds(new List <long>()
                {
                    roleId
                });
                if (roleRight.Data != null && roleRight.Data.Any())
                {
                    roleRightIds = roleRight.Data.Select(i => i.RightId).ToList();
                }
            }
            Base_Right right = null;
            var        list  = result.Data;

            switch (roleType)
            {
            case RoleType.Admin:    //管理员
                list.Insert(0, Helper.AdminSite);
                break;

            default:    //业务应用站点,包括(业主,监理,施工,咨询,设计)
                right        = Helper.WebSite;
                right.Belong = roleType.ToString();
                list.Insert(0, right);
                break;
            }


            var       first    = list.FirstOrDefault(i => i.Id == 0);
            RightNode rootTree = new RightNode();

            rootTree.checkboxValue = first.Id.ToString();
            rootTree.@checked      = roleRightIds.Count() > 0;
            rootTree.data          = new { code = first.Code, id = first.Id.ToString() };
            rootTree.name          = first.Name;
            rootTree.spread        = true;

            var tree = createTree(first.Id, list, roleRightIds);

            rootTree.children = tree;
            return(Json(rootTree, JsonRequestBehavior.AllowGet));;
        }
예제 #31
0
 private Vector3 GetPosByRoleType(RoleType _type)
 {
     foreach (Transform item in roleStartPositions)
     {
         if (item.name.IndexOf(_type.ToString()) >= 0)
         {
             return(item.position);
         }
     }
     return(Vector3.zero);
 }
예제 #32
0
        public Role(long levelId, RoleType roleType)
        {
            RoleType = roleType;
            Name     = roleType.ToString();
            NameFa   = roleType.ToString();//roleType.GetDescription();
            switch (roleType)
            {
            case RoleType.AdminCentral:
                CentralOrganizationId = levelId;
                break;

            case RoleType.AdminBranch:
                BranchProvinceId = levelId;
                break;

            default:
                UniversityId = levelId;
                break;
            }
        }
예제 #33
0
        public BasicPersonRole[] GetPeopleWithRoleType (RoleType r, int[] orgId, int[] geoId)   // TODO: Refactor to use ConstructWhereClause
        {
            List<BasicPersonRole> retlist = new List<BasicPersonRole>();
            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();
                string cmd = "SELECT " + personRoleFieldSequence + " WHERE Name= '" + r.ToString()+"'";
                if (orgId.Length > 0)
                    cmd += " AND OrganzationId IN (" + JoinIds(orgId) + ")";
                if (geoId.Length > 0)
                    cmd += " AND GeographyId IN (" + JoinIds(geoId) + ")";

                DbCommand command = GetDbCommand(cmd, connection);

                using (DbDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        retlist.Add(ReadPersonRoleFromDataReader(reader));
                    }
                }
            }
            return retlist.ToArray();
        }
        public List<DocumentShare> ShareDocument(Guid dlId, List<Guid> usIdList, string message = "", RoleType linkRole = RoleType.Viewer)
        {
            if (dlId.Equals(Guid.Empty))
            {
                throw new ArgumentException("dlId is required but was an empty Guid", "dlId");
            }

            switch (linkRole)
            {
                case RoleType.Owner:
                case RoleType.Editor:
                    linkRole = RoleType.Editor;
                    break;
                default:
                    linkRole = RoleType.Viewer;
                    break;
            }

            var jarray = new JArray();
            foreach (var usId in usIdList)
            {
                jarray.Add(new JObject(new JProperty("id", usId)));
            }

            dynamic postData = new ExpandoObject();
            postData.users = jarray;
            postData.message = message;
            postData.baseUrl = ShareUrl;
            postData.isPublic = "true";
            postData.linkRole = linkRole.ToString().ToLower();

            return HttpHelper.PutListResult<DocumentShare>(VVRestApi.GlobalConfiguration.Routes.DocumentsIdShares, "", GetUrlParts(), this.ClientSecrets, this.ApiTokens, postData, dlId);
        }
        /// <summary>
        /// Adds the given role to both config files and the service def.
        /// </summary>
        /// <param name="role"></param>
        private void AddPythonRoleCore(RoleInfo role, RoleType type)
        {
            Dictionary<string, object> parameters = CreateDefaultParameters(role);

            string scaffoldPath = Path.Combine(Path.Combine(scaffoldingFolderPath, Resources.PythonScaffolding), type.ToString());
            Scaffold.GenerateScaffolding(scaffoldPath, Path.Combine(Paths.RootPath, role.Name), parameters);
        }
예제 #36
0
        /// <summary>
        /// Adds the given role to both config files and the service def.
        /// </summary>
        private void AddRoleCore(String Scaffolding, RoleInfo role, RoleType type)
        {
            Dictionary<string, object> parameters = CreateDefaultParameters(role);
            parameters[ScaffoldParams.NodeModules] = General.GetNodeModulesPath();
            parameters[ScaffoldParams.NodeJsProgramFilesX86] = General.GetWithProgramFilesPath(Resources.NodeProgramFilesFolderName, false);

            string scaffoldPath = Path.Combine(Path.Combine(scaffoldingFolderPath, Scaffolding), type.ToString());
            Scaffold.GenerateScaffolding(scaffoldPath, Path.Combine(Paths.RootPath, role.Name), parameters);
        }
예제 #37
0
		private void InitTestUsers(RoleType currentUserRole)
		{
			IPrincipal user = Substitute.For<IPrincipal>();
			IIdentity identity = Substitute.For<IIdentity>();
			user.Identity.Returns(identity);
			user.Identity.Name.Returns(CurrentUserLogin);
			user.IsInRole(Arg.Is<string>(p => p == currentUserRole.ToString())).Returns(true);
			ViewContext.HttpContext.User.ReturnsForAnyArgs(user);
			Target.SetFakeControllerContext(ViewContext.HttpContext);

			UsersManagement.GetByEmail(CurrentUserLogin).Returns(new User()
			{
				Email = CurrentUserLogin,
				Roles = new Role[] { new Role() { Id = (int)currentUserRole } }
			});
		}
예제 #38
0
    private void GeneratePerson (XmlElement thisNode, RoleType role, Person lead)
    {
        XmlElement officerNode = thisNode.OwnerDocument.CreateElement("OFFICER");
        thisNode.AppendChild(officerNode);

        officerNode.SetAttribute("personid", lead.PersonId.ToString());
        officerNode.SetAttribute("type", role.ToString());
        if (localCall)
        {
            officerNode.SetAttribute("email", lead.PartyEmail);
            officerNode.SetAttribute("phone", lead.Phone);
            officerNode.InnerText = lead.Name;
        }
        else
        {
            officerNode.SetAttribute("email", "*****@*****.**");
            officerNode.SetAttribute("phone", "12345678");
            officerNode.InnerText = "Hidden for remote call(" + lead.PersonId.ToString() + ")";
        }
    }
예제 #39
0
        /// <summary>
        /// Adds the given role to both config files and the service def.
        /// </summary>
        /// <param name="role"></param>
        private void AddRoleCore(RoleInfo role, RoleType type)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters[ScaffoldParams.Role] = role;
            parameters[ScaffoldParams.Components] = Components;
            parameters[ScaffoldParams.RoleName] = role.Name;
            parameters[ScaffoldParams.InstancesCount] = role.InstanceCount;
            parameters[ScaffoldParams.Port] = Components.GetNextPort();
            parameters[ScaffoldParams.Paths] = Paths;
            parameters[ScaffoldParams.NodeModules] = General.GetNodeModulesPath();

            string scaffoldPath = Path.Combine(Path.Combine(scaffoldingFolderPath, Resources.NodeScaffolding), type.ToString());
            Scaffold.GenerateScaffolding(scaffoldPath, Path.Combine(Paths.RootPath, role.Name), parameters);
        }
예제 #40
0
        /// <summary>
        /// Create group if it's not existed
        /// </summary>
        /// <param name="collGroup"></param>
        /// <param name="groupName"></param>
        /// <param name="oWebsite"></param>
        /// <param name="clientContext"></param>
        /// <param name="roleType"></param>
        /// <param name="users"></param>
        private static void CreateGroup(GroupCollection collGroup, string groupName, Web oWebsite, ClientContext clientContext, RoleType roleType, List<FieldUserValue> users)
        {
            try
            {
                Group grp = collGroup.Where(g => g.Title == groupName).FirstOrDefault();
                oWebsite.BreakRoleInheritance(true, false);
                if (grp == null)
                {
                    GroupCreationInformation groupCreationInfo = new GroupCreationInformation();
                    groupCreationInfo.Title = groupName;
                    groupCreationInfo.Description = "Use this group to grant people " + roleType.ToString() + " permissions to the SharePoint site: " + oWebsite.Title;
                    grp = oWebsite.SiteGroups.Add(groupCreationInfo);
                    //clientContext.Load(grp);
                    //clientContext.ExecuteQuery();
                }
                // grant role to group
                RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(clientContext);
                RoleDefinition oRoleDefinition = oWebsite.RoleDefinitions.GetByType(roleType);
                collRoleDefinitionBinding.Add(oRoleDefinition);
                oWebsite.RoleAssignments.Add(grp, collRoleDefinitionBinding);
                clientContext.Load(grp, group => group.Title);
                clientContext.Load(oRoleDefinition, role => role.Name);
                clientContext.ExecuteQuery();

                // Add users to newly created group or existing group
                AddUsertoGroup(grp, clientContext, users);
            }
            catch (Exception e)
            {
                Console.Write(e.Message);

            }
        }
예제 #41
0
 public static string GetPlayerKey(RoleType roleType, string keyPostfix)
 {
     return string.Format("{0}_{1}", roleType.ToString().ToLower(), keyPostfix);
 }
예제 #42
0
        public int CreateRole (int personId, RoleType roleType, int organizationId, int nodeId)
        {
            using (DbConnection connection = GetMySqlDbConnection())
            {
                connection.Open();

                DbCommand command = GetDbCommand("CreatePersonRole", connection);
                command.CommandType = CommandType.StoredProcedure;

                AddParameterWithName(command, "personId", personId);
                AddParameterWithName(command, "personRoleType", roleType.ToString());
                AddParameterWithName(command, "organizationId", organizationId);
                AddParameterWithName(command, "geographyId", nodeId);

                return Convert.ToInt32(command.ExecuteScalar());
            }
        }
예제 #43
0
		private void InitTestUser(RoleType currentUserRole, string login)
		{
			IPrincipal user = Substitute.For<IPrincipal>();
			IIdentity identity = Substitute.For<IIdentity>();
			user.Identity.Returns(identity);
			user.Identity.Name.Returns(login);
			user.IsInRole(Arg.Is<string>(p => p == currentUserRole.ToString())).Returns(true);
			ViewContext.HttpContext.User.ReturnsForAnyArgs(user);
			Target.SetFakeControllerContext(ViewContext.HttpContext);
		}