Example #1
0
        public static PSRoleAssignment ToPSRoleAssignment(this RoleAssignment assignment, AuthorizationClient policyClient, ActiveDirectoryClient activeDirectoryClient, bool excludeAssignmentsForDeletedPrincipals = true)
        {
            List <PSRoleDefinition> roleDefinitions = null;

            try
            {
                roleDefinitions = new List <PSRoleDefinition> {
                    policyClient.GetRoleDefinition(assignment.Properties.RoleDefinitionId)
                };
            }
            catch (CloudException ce)
            {
                if (ce.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    //Swallow unauthorized errors on RoleDefinition when displaying RoleAssignments
                    roleDefinitions = new List <PSRoleDefinition>();
                }
                else
                {
                    throw;
                }
            }

            IEnumerable <RoleAssignment> assignments = new List <RoleAssignment> {
                assignment
            };

            return(assignments.ToPSRoleAssignments(roleDefinitions, policyClient, activeDirectoryClient, excludeAssignmentsForDeletedPrincipals).SingleOrDefault());
        }
        private void UpdateMarinRoles(string[] selectedRoles, Marin marinToUpdate)
        {
            if (selectedRoles == null)
            {
                marinToUpdate.Roles = new List <RoleAssignment>();
                return;
            }

            var selectedRolesHS = new HashSet <string>(selectedRoles);
            var instructorRoles = new HashSet <int>(marinToUpdate.Roles.Select(r => r.Role.RoleID));

            foreach (var role in _context.Roles)
            {
                if (selectedRolesHS.Contains(role.RoleID.ToString()))
                {
                    if (!instructorRoles.Contains(role.RoleID))
                    {
                        marinToUpdate.Roles.Add(new RoleAssignment {
                            MarinID = marinToUpdate.ID, RoleID = role.RoleID
                        });
                    }
                }
                else
                {
                    if (instructorRoles.Contains(role.RoleID))
                    {
                        RoleAssignment roleToRemove = marinToUpdate.Roles.SingleOrDefault(i => i.RoleID == role.RoleID);
                        _context.Remove(roleToRemove);
                    }
                }
            }
        }
Example #3
0
        public static void AsignarPermis(ClientContext c)
        {
            try
            {
                Principal      buffet        = c.Web.SiteGroups.GetByName("Buffet");
                RoleDefinition buffetPermiso = c.Web.RoleDefinitions.GetByName("Colaborar");
                RoleDefinitionBindingCollection coleccionBPermisos = new RoleDefinitionBindingCollection(c);
                coleccionBPermisos.Add(buffetPermiso);
                RoleAssignment buffetRoleAssigment = c.Web.RoleAssignments.Add(buffet, coleccionBPermisos);

                Principal      integrantes        = c.Web.SiteGroups.GetByName("Integrantes");
                RoleDefinition integrantesPermiso = c.Web.RoleDefinitions.GetByName("Leer");
                RoleDefinitionBindingCollection coleccionIPermisos = new RoleDefinitionBindingCollection(c);
                coleccionIPermisos.Add(integrantesPermiso);
                RoleAssignment integrantesRoleAssigment = c.Web.RoleAssignments.Add(integrantes, coleccionIPermisos);
                c.ExecuteQuery();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("--- PERMISOS ASIGNADOS ---");
                Console.ResetColor();
            }
            catch (Exception ex) {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("--- ERROR AL ASIGNAR PERMISOS A LOS GRUPOS ---");
                Console.ResetColor();
            }
        }
Example #4
0
        public int Add(RoleAssignmentDto dto)
        {
            int result = -1;

            var entity = new RoleAssignment();

            try
            {
                Mapper.Map(dto, entity);
                _repository.Repository <RoleAssignment>().Insert(entity);
                _repository.Save();

                if (entity != null)
                {
                    result = entity.ID;
                }
            }
            catch (DbEntityValidationException valEx)
            {
                HandleValidationException(valEx);
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw;
            }

            return(result);
        }
Example #5
0
        /// <summary>
        /// Creates new role assignment.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created role assignment object</returns>
        public PSRoleAssignment CreateRoleAssignment(FilterRoleAssignmentsOptions parameters)
        {
            Guid   principalId      = ActiveDirectoryClient.GetObjectId(parameters.ADObjectFilter);
            Guid   roleAssignmentId = RoleAssignmentNames.Count == 0 ? Guid.NewGuid() : RoleAssignmentNames.Dequeue();
            string scope            = parameters.Scope;

            ValidateScope(scope);
            string roleDefinitionId = !string.IsNullOrEmpty(parameters.RoleDefinitionName)
                ? AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, GetSingleRoleDefinitionByName(parameters.RoleDefinitionName, scope).Id)
                : AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, parameters.RoleDefinitionId);

#if !NETSTANDARD
            RoleAssignmentCreateParameters createParameters = new RoleAssignmentCreateParameters
            {
                Properties = new RoleAssignmentProperties
                {
                    PrincipalId      = principalId,
                    RoleDefinitionId = roleDefinitionId
                }
            };

            RoleAssignment assignment = AuthorizationManagementClient.RoleAssignments.Create(parameters.Scope, roleAssignmentId, createParameters).RoleAssignment;
#else
            var createParameters = new RoleAssignmentProperties
            {
                PrincipalId      = principalId.ToString(),
                RoleDefinitionId = roleDefinitionId
            };

            RoleAssignment assignment = AuthorizationManagementClient.RoleAssignments.Create(
                parameters.Scope,
                roleAssignmentId.ToString(), createParameters);
#endif
            return(assignment.ToPSRoleAssignment(this, ActiveDirectoryClient));
        }
Example #6
0
        public void UpdateUserRoles(string[] selectedRoles, User userToUpdate)
        {
            if (selectedRoles == null)
            {
                userToUpdate.RoleAssignments = new List <RoleAssignment>();
                return;
            }

            var selectedRolesHS = new HashSet <string>(selectedRoles);
            var userRoles       = new HashSet <int>
                                      (userToUpdate.RoleAssignments.Select(c => c.RoleID));

            foreach (var role in _context.Roles)
            {
                if (selectedRolesHS.Contains(role.RoleID.ToString()))
                {
                    if (!userRoles.Contains(role.RoleID))
                    {
                        userToUpdate.RoleAssignments.Add(new RoleAssignment {
                            UserID = userToUpdate.ID, RoleID = role.RoleID
                        });
                    }
                }
                else
                {
                    if (userRoles.Contains(role.RoleID))
                    {
                        RoleAssignment roleToRemove = userToUpdate.RoleAssignments.SingleOrDefault(i => i.RoleID == role.RoleID);
                        _context.Remove(roleToRemove);
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// Function to check user full permission on document library
        /// </summary>
        /// <param name="environment">environment identifier</param>
        /// <param name="refreshToken">The refresh token for Client Context</param>
        /// <param name="clientUrl">The client URL for Client Context</param>
        /// <param name="matterName">Document library name</param>
        /// <param name="request">The HTTP request</param>
        /// <returns>A Boolean variable indicating whether user has full permission on the matter</returns>
        public static bool CheckUserFullPermission(ClientContext clientContext, Matter matter)
        {
            bool result = false;

            try
            {
                if (null != clientContext && null != matter)
                {
                    Web            web           = clientContext.Web;
                    List           list          = web.Lists.GetByTitle(matter.Name);
                    Users          userDetails   = GetLoggedInUserDetails(clientContext);
                    Principal      userPrincipal = web.EnsureUser(userDetails.Name);
                    RoleAssignment userRole      = list.RoleAssignments.GetByPrincipal(userPrincipal);
                    clientContext.Load(userRole, userRoleProperties => userRoleProperties.Member, userRoleProperties => userRoleProperties.RoleDefinitionBindings.Include(userRoleDefinition => userRoleDefinition.Name).Where(userRoleDefinitionName => userRoleDefinitionName.Name == ConstantStrings.EditMatterAllowedPermissionLevel));
                    clientContext.ExecuteQuery();
                    if (0 < userRole.RoleDefinitionBindings.Count)
                    {
                        result = true;
                    }
                }
            }
            catch (Exception)
            {
                result = false;
            }
            return(result);
        }
        /// <summary>
        /// Creates new role assignment.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created role assignment object</returns>
        public PSRoleAssignment CreateRoleAssignment(FilterRoleAssignmentsOptions parameters, Guid roleAssignmentId = default(Guid))
        {
            string principalId = ActiveDirectoryClient.GetObjectId(parameters.ADObjectFilter);

            roleAssignmentId = roleAssignmentId == default(Guid) ? Guid.NewGuid() : roleAssignmentId;
            string scope            = parameters.Scope;
            string roleDefinitionId = string.IsNullOrEmpty(parameters.RoleDefinitionName)
                ? AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, parameters.RoleDefinitionId)
                : AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, GetSingleRoleDefinitionByName(parameters.RoleDefinitionName, scope).Id);

            parameters.Description      = string.IsNullOrWhiteSpace(parameters.Description) ? null : parameters.Description;
            parameters.Condition        = string.IsNullOrWhiteSpace(parameters.Condition) ? null : parameters.Condition;
            parameters.ConditionVersion = string.IsNullOrWhiteSpace(parameters.ConditionVersion) ? null : parameters.ConditionVersion;
            var createParameters = new RoleAssignmentCreateParameters
            {
                PrincipalId      = principalId.ToString(),
                RoleDefinitionId = roleDefinitionId,
                CanDelegate      = parameters.CanDelegate,
                Description      = parameters.Description,
                Condition        = parameters.Condition,
                ConditionVersion = parameters.ConditionVersion
            };

            RoleAssignment assignment = AuthorizationManagementClient.RoleAssignments.Create(
                parameters.Scope, roleAssignmentId.ToString(), createParameters);
            var PSRoleAssignment = assignment.ToPSRoleAssignment(this, ActiveDirectoryClient);

            return(PSRoleAssignment);
        }
        public async Task <IActionResult> AssignRole()
        {
            var roleAssignmentModel = new RoleAssisgnmentModel()
            {
                SubscriptionId           = "47ca3602-b986-46de-a99a-e473c26bd588",
                ResourceGroupName        = "AdityaAzureRG",
                StorageAccountName       = "researchstorageacct",
                ContainerName            = "research",
                RoleId                   = "2a2b9908-6ea1-4ae2-8e65-a410df84e7d1",
                ServicePrincipalObjectId = "04f300cc-5632-4820-8fd2-9d36e7efd020",
                RoleAssignmentName       = Guid.NewGuid().ToString()
            };

            var roleAssignmentService = new RoleAssignment(roleAssignmentModel);

            var currentContext = _httpContextAccessor.HttpContext;
            var accesToken     = await currentContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

            var httpResponseMessage = await roleAssignmentService.AssignRole(accesToken);

            var responeFromazureAPi = await httpResponseMessage.Content.ReadAsStringAsync();

            var deserializeResponse = JsonConvert.DeserializeObject(responeFromazureAPi).ToString();

            return(View("AssignRole", deserializeResponse));
        }
        /// <summary>
        /// Function to check user full permission on document library
        /// </summary>
        /// <param name="clientContext"></param>
        /// <param name="matter"></param>
        /// <returns></returns>
        public bool CheckUserFullPermission(ClientContext clientContext, Matter matter)
        {
            bool result = false;

            try
            {
                if (null != matter)
                {
                    Web            web           = clientContext.Web;
                    List           list          = web.Lists.GetByTitle(matter.Name);
                    Users          userDetails   = GetLoggedInUserDetails(clientContext);
                    Principal      userPrincipal = web.EnsureUser(userDetails.Name);
                    RoleAssignment userRole      = list.RoleAssignments.GetByPrincipal(userPrincipal);
                    clientContext.Load(userRole, userRoleProperties => userRoleProperties.Member,
                                       userRoleProperties => userRoleProperties.RoleDefinitionBindings.Include(userRoleDefinition => userRoleDefinition.Name).Where(userRoleDefinitionName => userRoleDefinitionName.Name ==
                                                                                                                                                                    matterSettings.EditMatterAllowedPermissionLevel));
                    clientContext.ExecuteQuery();
                    if (0 < userRole.RoleDefinitionBindings.Count)
                    {
                        result = true;
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                customLogger.LogError(ex, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }
        }
Example #11
0
        public void Can_add_remove_add()
        {
            var accountName = "Account add_remove_add";
            var roleName    = "Role create_role_graph";
            var accountId   = AddAccount(accountName);
            var roleId      = AddRole(roleName);


            var client = GetRepository();
            var role   = client.Roles.Where(x => x.Name == roleName).SingleOrDefault();

            Assert.NotNull(role);

            var account = client.Accounts.Expand("RoleAssignments/Role").Where(x => x.AccountId == accountId).SingleOrDefault();

            Assert.NotNull(account);

            //var newRole = client.Roles.Where(x => x.Name == roleName).SingleOrDefault(); // need to reload role in new repository

            //var roleAssignment = new RoleAssignment { RoleId = roleId, AccountId = accountId};// worked
            var roleAssignment = new RoleAssignment {
                RoleId = role.RoleId, AccountId = accountId, Role = role
            };

            account.RoleAssignments.Add(roleAssignment);
            account.RoleAssignments.Remove(roleAssignment);
            //Deattach here
            account.RoleAssignments.Add(roleAssignment);

            client.UnitOfWork.Commit();

            client  = GetRepository();
            account = client.Accounts.Expand("RoleAssignments/Role").Where(x => x.UserName == accountName).SingleOrDefault();
            Assert.NotNull(account.RoleAssignments.Where(x => x.Role.Name == roleName).SingleOrDefault());
        }
Example #12
0
        public static async Task NewTopSong(DiscordSocketClient discordSocketClient, SocketMessage message)
        {
            var r = new RoleAssignment(discordSocketClient);

            if (r.CheckIfDiscordIdIsLinked(message.Author.Id.ToString()) && message.Content.Count() == 11)
            {
                var scoresaberId = r.GetScoresaberIdWithDiscordId(message.Author.Id.ToString());

                var embedTask = await BeatSaberInfoExtension.GetNewTopSongWithScoresaberId(scoresaberId);

                await message.Channel.SendMessageAsync("", false, embedTask.Build());
            }
            else
            {
                if (message.Content.Length <= 11)
                {
                    await message.Channel.SendMessageAsync("", false,
                                                           EmbedBuilderExtension.NullEmbed("Search failed",
                                                                                           "Search value is not long enough. it should be larger than 3 characters.", null, null)
                                                           .Build());

                    return;
                }

                var username = message.Content.Substring(11);
                var id       = await BeatSaberInfoExtension.GetPlayerIdsWithUsername(username);

                var embedTask = await BeatSaberInfoExtension.GetNewRecentSongWithScoresaberId(id);

                await message.Channel.SendMessageAsync("", false, embedTask.Build());
            }
        }
 public SecurableObjectInfo(List list, RoleAssignment roleAssignment) : this((SecurableObject)list, roleAssignment)
 {
     Type      = SecurableObjectType.Liste;
     Url       = list.RootFolder.ServerRelativeUrl;
     SiteTitle = list.ParentWeb.Title;
     ListTitle = list.Title;
 }
        public void RemoveUncommitedRoleTest()
        {
            ISecurityRepository client = GetClient();

            var account = new Account()
            {
                UserName = "******"
            };
            var role = new Role()
            {
                Name = "testRole"
            };

            var roleAssignment = new RoleAssignment
            {
                Account   = account,
                AccountId = account.AccountId,
                Role      = role,
                RoleId    = role.RoleId
            };

            client.Attach(account);

            // add role
            account.RoleAssignments.Add(roleAssignment);
            Assert.True(client.IsAttachedTo(roleAssignment));

            // remove uncommited role
            account.RoleAssignments.Remove(roleAssignment);
            client.Remove(roleAssignment);
            Assert.False(client.IsAttachedTo(roleAssignment));
        }
        /// <summary>
        /// Creates new role assignment.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created role assignment object</returns>
        public PSRoleAssignment CreateRoleAssignment(FilterRoleAssignmentsOptions parameters)
        {
            Guid   principalId    = ActiveDirectoryClient.GetObjectId(parameters.ADObjectFilter);
            string principalIdStr = null;

            if (principalId == Guid.Empty)
            {
                principalIdStr = ActiveDirectoryClient.GetAdfsObjectId(parameters.ADObjectFilter);
            }
            else
            {
                principalIdStr = principalId.ToString();
            }

            Guid   roleAssignmentId = RoleAssignmentNames.Count == 0 ? Guid.NewGuid() : RoleAssignmentNames.Dequeue();
            string scope            = parameters.Scope;
            string roleDefinitionId = !string.IsNullOrEmpty(parameters.RoleDefinitionName)
                ? AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, GetSingleRoleDefinitionByName(parameters.RoleDefinitionName, scope).Id)
                : AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, parameters.RoleDefinitionId);
            var createProperties = new RoleAssignmentProperties
            {
                PrincipalId      = principalIdStr,
                RoleDefinitionId = roleDefinitionId
            };
            var createParameters = new RoleAssignmentCreateParameters(createProperties);

            RoleAssignment assignment = AuthorizationManagementClient.RoleAssignments.Create(
                parameters.Scope, roleAssignmentId.ToString(), createParameters);

            return(assignment.ToPSRoleAssignment(this, ActiveDirectoryClient));
        }
Example #16
0
        public void CreateRoleAssignment()
        {
            client = Client;
            #region Snippet:CreateRoleAssignment
            // Replace roleDefinitionId with a role definition Id from the definitions returned from the List the role definitions section above
            string definitionIdToAssign = roleDefinitionId;

            // Replace objectId with the service principal object id from the Create/Get credentials section above
            string servicePrincipalObjectId = objectId;

            RoleAssignmentProperties properties        = new RoleAssignmentProperties(definitionIdToAssign, servicePrincipalObjectId);
            RoleAssignment           createdAssignment = client.CreateRoleAssignment(RoleAssignmentScope.Global, properties);

            Console.WriteLine(createdAssignment.Name);
            Console.WriteLine(createdAssignment.Properties.PrincipalId);
            Console.WriteLine(createdAssignment.Properties.RoleDefinitionId);

            RoleAssignment fetchedAssignment = client.GetRoleAssignment(RoleAssignmentScope.Global, createdAssignment.Name);

            Console.WriteLine(fetchedAssignment.Name);
            Console.WriteLine(fetchedAssignment.Properties.PrincipalId);
            Console.WriteLine(fetchedAssignment.Properties.RoleDefinitionId);

            RoleAssignment deletedAssignment = client.DeleteRoleAssignment(RoleAssignmentScope.Global, createdAssignment.Name);

            Console.WriteLine(deletedAssignment.Name);
            Console.WriteLine(deletedAssignment.Properties.PrincipalId);
            Console.WriteLine(deletedAssignment.Properties.RoleDefinitionId);

            #endregion
        }
        public async Task <Response <RoleAssignment> > DeleteAsync(string vaultBaseUrl, string scope, string roleAssignmentName, CancellationToken cancellationToken = default)
        {
            if (vaultBaseUrl == null)
            {
                throw new ArgumentNullException(nameof(vaultBaseUrl));
            }
            if (scope == null)
            {
                throw new ArgumentNullException(nameof(scope));
            }
            if (roleAssignmentName == null)
            {
                throw new ArgumentNullException(nameof(roleAssignmentName));
            }

            using var message = CreateDeleteRequest(vaultBaseUrl, scope, roleAssignmentName);
            await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);

            switch (message.Response.Status)
            {
            case 200:
            {
                RoleAssignment value = default;
                using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);

                value = RoleAssignment.DeserializeRoleAssignment(document.RootElement);
                return(Response.FromValue(value, message.Response));
            }
        /// <summary>
        /// Updates a role assignment.
        /// </summary>
        /// <param name="roleAssignment">The role assignment to update.</param>
        /// <returns>The updated role assignment.</returns>
        public PSRoleAssignment UpdateRoleAssignment(PSRoleAssignment roleAssignment)
        {
            string principalId             = roleAssignment.ObjectId;
            var    roleAssignmentGuidIndex = roleAssignment.RoleAssignmentId.LastIndexOf("/");
            var    roleAssignmentId        = roleAssignmentGuidIndex != -1 ? roleAssignment.RoleAssignmentId.Substring(roleAssignmentGuidIndex + 1) : roleAssignment.RoleAssignmentId;
            string scope            = roleAssignment.Scope;
            string roleDefinitionId = AuthorizationHelper.ConstructFullyQualifiedRoleDefinitionIdFromScopeAndIdAsGuid(scope, roleAssignment.RoleDefinitionId);
            var    Description      = string.IsNullOrWhiteSpace(roleAssignment.Description) ? null : roleAssignment.Description;
            var    Condition        = string.IsNullOrWhiteSpace(roleAssignment.Condition) ? null : roleAssignment.Condition;
            var    ConditionVersion = string.IsNullOrWhiteSpace(roleAssignment.ConditionVersion) ? null : roleAssignment.ConditionVersion;
            var    createParameters = new RoleAssignmentCreateParameters
            {
                PrincipalId      = principalId.ToString(),
                RoleDefinitionId = roleDefinitionId,
                PrincipalType    = roleAssignment.ObjectType,
                CanDelegate      = roleAssignment.CanDelegate,
                Description      = Description,
                Condition        = Condition,
                ConditionVersion = ConditionVersion
            };

            RoleAssignment assignment = AuthorizationManagementClient.RoleAssignments.Create(
                scope, roleAssignmentId, createParameters);
            var PSRoleAssignment = assignment.ToPSRoleAssignment(this, ActiveDirectoryClient);

            return(PSRoleAssignment);
        }
Example #19
0
        public async Task GivePermissions(PermissionAndRole permission)
        {
            ClientContext context = GetSharepointContext(permission.Url);
            List          list    = context.Web.Lists.GetByTitle(permission.ListName);

            context.Load(list);
            await context.ExecuteQueryAsync();

            var item = list.GetItemById(permission.ItemId);

            context.Load(item);
            await context.ExecuteQueryAsync();

            Principal user;

            if (permission.IsGroup)
            {
                user = context.Web.SiteGroups.GetById(permission.Id);
            }
            else
            {
                user = context.Web.SiteUsers.GetById(permission.Id);
                context.Load(user);
                await context.ExecuteQueryAsync();
            }
            RoleDefinition writeDefinition = context.Web.RoleDefinitions.GetByName(permission.roleDefinitionName);
            RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);

            roleDefCollection.Add(writeDefinition);
            RoleAssignment newRoleAssignment = item.RoleAssignments.Add(user, roleDefCollection);
            await context.ExecuteQueryAsync();
        }
Example #20
0
        /// <summary>
        /// Creates new role assignment.
        /// </summary>
        /// <param name="parameters">The create parameters</param>
        /// <returns>The created role assignment object</returns>
        public PSRoleAssignment CreateRoleAssignment(FilterRoleAssignmentsOptions parameters, string subscriptionId)
        {
            Guid   principalId      = ActiveDirectoryClient.GetObjectId(parameters.ADObjectFilter);
            Guid   roleAssignmentId = RoleAssignmentNames.Count == 0 ? Guid.NewGuid() : RoleAssignmentNames.Dequeue();
            string roleDefinitionId = !string.IsNullOrEmpty(parameters.RoleDefinitionName)
                ? AuthorizationHelper.GetRoleDefinitionFullyQualifiedId(subscriptionId, GetRoleRoleDefinition(parameters.RoleDefinitionName).Id)
                : AuthorizationHelper.GetRoleDefinitionFullyQualifiedId(subscriptionId, parameters.RoleDefinitionId);

            RoleAssignmentCreateParameters createParameters = new RoleAssignmentCreateParameters
            {
                Properties = new RoleAssignmentProperties
                {
                    PrincipalId      = principalId,
                    RoleDefinitionId = roleDefinitionId
                }
            };

            RoleAssignment assignment = AuthorizationManagementClient.RoleAssignments.Create(parameters.Scope, roleAssignmentId, createParameters).RoleAssignment;

            IEnumerable <RoleAssignment> assignments = new List <RoleAssignment>()
            {
                assignment
            };

            return(assignments.ToPSRoleAssignments(this, ActiveDirectoryClient).FirstOrDefault());
        }
Example #21
0
        public Task <RoleAssignment> PutRoleAssignment(RoleAssignment roleAssignment)
        {
            var possibleDuplicateRoleAssignment = this.localPolicyStore.RoleAssignments.FirstOrDefault(ra => ra.RoleDefinitionId == roleAssignment.RoleDefinitionId && ra.Scope == roleAssignment.Scope && ra.PrincipalId == roleAssignment.PrincipalId);

            if (possibleDuplicateRoleAssignment != null && roleAssignment.Id != possibleDuplicateRoleAssignment.Id)
            {
                throw new ArgumentException("Can't insert a duplicate role assignment", nameof(roleAssignment));
            }


            lock (this.localPolicyStore)
            {
                roleAssignment.PrincipalType = "User";
                var existingRoleAssigmentIndex = this.localPolicyStore.RoleAssignments.FindIndex(ra => ra.Id == roleAssignment.Id);
                if (existingRoleAssigmentIndex != -1)
                {
                    this.localPolicyStore.RoleAssignments[existingRoleAssigmentIndex] = roleAssignment;
                }
                else
                {
                    this.localPolicyStore.RoleAssignments.Add(roleAssignment);
                }
                this.SavePolicyData();
            }
            return(Task.FromResult(roleAssignment));
        }
        public void CreateRoleAssignment()
        {
            // Replace client with the Instrumented Client.
            client = Client;

            List <RoleDefinition> definitions = client.GetRoleDefinitions(RoleAssignmentScope.Global).ToList();

            _roleDefinitionId = definitions.FirstOrDefault(d => d.RoleName == RoleName).Id;

            // Replace roleDefinitionId with a role definition Id from the definitions returned from GetRoleAssignments.
            string definitionIdToAssign = _roleDefinitionId;

            // Replace objectId with the service principal object id.
            string servicePrincipalObjectId = _objectId;

            #region Snippet:CreateRoleAssignment
            //@@string definitionIdToAssign = "<roleDefinitionId>";
            //@@string servicePrincipalObjectId = "<objectId>";

            RoleAssignmentProperties properties = new RoleAssignmentProperties(definitionIdToAssign, servicePrincipalObjectId);
            //@@RoleAssignment createdAssignment = client.CreateRoleAssignment(RoleAssignmentScope.Global, properties);
            /*@@*/ RoleAssignment createdAssignment = client.CreateRoleAssignment(RoleAssignmentScope.Global, properties, _roleAssignmentId);
            #endregion

            #region Snippet:GetRoleAssignment
            RoleAssignment fetchedAssignment = client.GetRoleAssignment(RoleAssignmentScope.Global, createdAssignment.Name);
            #endregion

            #region Snippet:DeleteRoleAssignment
            RoleAssignment deletedAssignment = client.DeleteRoleAssignment(RoleAssignmentScope.Global, createdAssignment.Name);
            #endregion
        }
Example #23
0
        protected void AddAcrRoleAssignment(string acrName, string acrParameterName, AcsServicePrincipal acsServicePrincipal)
        {
            string acrResourceId = null;

            try
            {
                //Find Acr resourceId first
                var acrQuery   = new ODataQuery <GenericResourceFilter>($"$filter=resourceType eq 'Microsoft.ContainerRegistry/registries' and name eq '{acrName}'");
                var acrObjects = RmClient.Resources.List(acrQuery);
                acrResourceId = acrObjects.First().Id;
            }
            catch (Exception)
            {
                throw new AzPSArgumentException(
                          string.Format(Resources.CouldNotFindSpecifiedAcr, acrName),
                          acrParameterName,
                          string.Format(Resources.CouldNotFindSpecifiedAcr, "*"));
            }

            var            roleId         = GetRoleId("acrpull", acrResourceId);
            RoleAssignment roleAssignment = GetRoleAssignmentWithRoleDefinitionId(roleId);

            if (roleAssignment != null)
            {
                WriteWarning(string.Format(Resources.AcrRoleAssignmentIsAlreadyExist, acrResourceId));
                return;
            }
            var spObjectId = acsServicePrincipal.ObjectId;

            if (spObjectId == null)
            {
                try
                {
                    //Please note string.Equals doesn't work here, while == works.
                    var odataQuery       = new ODataQuery <ServicePrincipal>(sp => sp.AppId == acsServicePrincipal.SpId);
                    var servicePrincipal = GraphClient.ServicePrincipals.List(odataQuery).First();
                    spObjectId = servicePrincipal.ObjectId;
                }
                catch (Exception ex)
                {
                    throw new AzPSInvalidOperationException(
                              string.Format(Resources.CouldNotFindObjectIdForServicePrincipal, acsServicePrincipal.SpId),
                              ex,
                              string.Format(Resources.CouldNotFindObjectIdForServicePrincipal, "*"));
                }
            }
            var success = RetryAction(() =>
                                      AuthClient.RoleAssignments.Create(acrResourceId, Guid.NewGuid().ToString(), new RoleAssignmentCreateParameters()
            {
                Properties = new RoleAssignmentProperties(roleId, spObjectId)
            }), Resources.AddRoleAssignment);

            if (!success)
            {
                throw new AzPSInvalidOperationException(
                          Resources.CouldNotAddAcrRoleAssignment,
                          desensitizedMessage: Resources.CouldNotAddAcrRoleAssignment);
            }
        }
 public SecurableObjectInfo(ListItem listItem, RoleAssignment roleAssignment) : this((SecurableObject)listItem, roleAssignment)
 {
     Type        = SecurableObjectType.Dossier;
     Url         = listItem["FileRef"]?.ToString();
     SiteTitle   = listItem.ParentList.ParentWeb.Title;
     ListTitle   = listItem.ParentList.Title;
     FolderTitle = listItem.DisplayName;
 }
Example #25
0
        public static async Task CreateRoleAssignmentAsync(this RoleAssignment roleAssignment, HttpClient httpClient, JsonSerializerSettings jsonSerializerSettings)
        {
            Console.WriteLine($"Creating RoleAssignment: {JsonConvert.SerializeObject( roleAssignment, Formatting.Indented, jsonSerializerSettings )}");
            var request  = HttpMethod.Post.CreateRequest("roleassignments", JsonConvert.SerializeObject(roleAssignment, jsonSerializerSettings));
            var response = await httpClient.SendAsync(request);

            Console.WriteLine(response.IsSuccessStatusCode ? "succeeded..." : "failed...");
        }
Example #26
0
 static public async Task NotLinkedNames(DiscordSocketClient discordSocketClient, SocketMessage message)
 {
     if (new GuildService(discordSocketClient, 505485680344956928).IsStaffInGuild(message.Author.Id, 505486321595187220))
     {
         var embed = new RoleAssignment(discordSocketClient).GetNotLinkedDiscordNamesInGuildEmbed(505485680344956928);
         await message.Channel.SendMessageAsync(embed);
     }
 }
        public static RoleAssignment CreateRoleAssignment(string userName, string roleName, string sourceAccountName)
        {
            RoleAssignment roleAssignment = new RoleAssignment();

            roleAssignment.UserName          = userName;
            roleAssignment.RoleName          = roleName;
            roleAssignment.SourceAccountName = sourceAccountName;
            return(roleAssignment);
        }
Example #28
0
        public static PSRoleAssignment ToPSRoleAssignment(this RoleAssignment assignment, AuthorizationClient policyClient, ActiveDirectoryClient activeDirectoryClient, string scopeForRoleDefinition = null)
        {
            PSRoleDefinition roleDefinition = null;
            PSADObject       adObject       = null;

            // Get role definition name information by role definition ID
            try
            {
                if (string.IsNullOrEmpty(scopeForRoleDefinition))
                {
                    roleDefinition = policyClient.GetRoleDefinition(assignment.RoleDefinitionId);
                }
                else
                {
                    roleDefinition = policyClient.GetRoleDefinition(assignment.RoleDefinitionId.GetGuidFromId(), scopeForRoleDefinition);
                }
            }
            catch (CloudException ce) when(ce.Response.StatusCode == HttpStatusCode.Unauthorized)
            {
                //Swallow unauthorized errors on RoleDefinition when displaying RoleAssignments
            }

            // Get ab object
            try
            {
                adObject = activeDirectoryClient.GetObjectByObjectId(assignment.PrincipalId);
            }
            catch (Common.MSGraph.Version1_0.DirectoryObjects.Models.OdataErrorException oe)
            {
                if (oe.IsAuthorizationDeniedException() || oe.IsNotFoundException())
                {
                    adObject = new PSADObject()
                    {
                        Id = assignment.PrincipalId, Type = UnknownType
                    };
                }
                //Swallow exceptions when displaying active directive object
            }

            return(new PSRoleAssignment()
            {
                RoleAssignmentName = assignment.Name,
                RoleAssignmentId = assignment.Id,
                Scope = assignment.Scope,
                DisplayName = adObject?.DisplayName,
                SignInName = adObject is PSADUser user ? user.UserPrincipalName : null,
                RoleDefinitionName = roleDefinition?.Name,
                RoleDefinitionId = assignment.RoleDefinitionId.GuidFromFullyQualifiedId(),
                ObjectId = assignment.PrincipalId,
                // Use information from adObject first, assignment.PrincipalType is a cached information
                ObjectType = adObject?.Type ?? assignment.PrincipalType,
                // CanDelegate's value is absent from RoleAssignment
                // CanDelegate = null,
                Description = assignment.Description,
                ConditionVersion = assignment.ConditionVersion,
                Condition = assignment.Condition
            });
Example #29
0
        /// <summary>
        /// Delete element executed.
        /// </summary>
        protected virtual void AddElementCommand_Executed()
        {
            WaitCursor cursor = new WaitCursor();

            try
            {
                // update the default values list first.
                this.UpdateDefaultValuesList();

                using (SelectElementViewModel vm = new SelectElementViewModel(this.ViewModelStore, this.DefaultValues))
                {
                    vm.Title = "Select a role player";

                    if (this.Elements.Count == 1)
                    {
                        if (this.Elements[0] is IDomainModelOwnable)
                        {
                            vm.Title += " of type " + (this.Elements[0] as IDomainModelOwnable).DomainElementTypeDisplayName;
                        }
                    }
                    //vm.Title += " of type " + this.ViewModelStore.GetDomainModelServices(this.Elements[0] as ModelElement).ElementTypeProvider.GetTypeDisplayName(
                    //    this.Elements[0] as ModelElement);

                    cursor.Dispose();
                    cursor = null;

                    bool?result = this.GlobalServiceProvider.Resolve <IUIVisualizerService>().ShowDialog("SelectElementPopup", vm);
                    if (result == true && vm.SelectedElement is ModelElement)
                    {
                        try
                        {
                            using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add new relationship"))
                            {
                                RoleAssignment[] roleAssignments = new RoleAssignment[2];
                                roleAssignments[0] = new RoleAssignment(this.SourceRoleId, this.Elements[0] as ModelElement);
                                roleAssignments[1] = new RoleAssignment(this.TargetRoleId, vm.SelectedElement as ModelElement);
                                this.Store.ElementFactory.CreateElementLink(this.RelationshipDomainClassId, roleAssignments);

                                transaction.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Windows.MessageBox.Show("Error while adding: " + ex.Message);
                        }
                    }
                }
            }
            finally
            {
                if (cursor != null)
                {
                    cursor.Dispose();
                }
            }
            GC.Collect();
        }
        public static SPPermissions ToPermission(this RoleAssignment ra)
        {
            var permission = new SPPermissions(ra.Member);

            foreach (var rd in ra.RoleDefinitionBindings)
            {
                permission.Level.Add(rd.ToPermissionLevel());
            }
            return(permission);
        }
Example #31
0
        static List<RoleAssignment> GetRoleAssigments(List<UserGroupAssignmentsEntity> userGroupAssignments)
        {
            List<RoleAssignment> roleAssignments = new List<RoleAssignment>();

            foreach (UserGroupAssignmentsEntity assignment in userGroupAssignments)
            {
                RoleAssignment roleAssignment = new RoleAssignment();
                roleAssignment.Id = Guid.NewGuid().ToString();
                roleAssignment.PrincipalId = assignment.PartitionKey; // userObjectId;
                roleAssignment.Scope = "/";
                roleAssignment.RoleDefinitionId = assignment.RowKey; // groupObejectId -> role id
                roleAssignment.PrincipalType = "User";

                roleAssignments.Add(roleAssignment);
            }

            return roleAssignments;
        }
        /// <summary>
        /// Adds a proto link to the current element.
        /// </summary>
        /// <param name="protoLink">Proto link representation of the element link that is to be added.</param>
        /// <param name="groupMerger">
        /// Group merger class used to track id mapping, merge errors/warnings and 
        /// postprocess merging by rebuilding reference relationships.
        /// </param>
        public virtual void ModelMerge(ModelProtoLink protoLink, ModelProtoGroupMerger groupMerger)
        {
            if (protoLink.IsTargetIncludedSubmodel && !String.IsNullOrEmpty(protoLink.DomainFilePath))
            {
                // TODO ...
                /*
                string file = protoLink.DomainFilePath;
                IParentModelElement parent = this.GetDomainModelServices().ElementParentProvider.GetParentModelElement(this);
                if (parent == null)
                    throw new System.ArgumentNullException("Parent of element " + this.ToString() + " can not be null");

                string path = parent.DomainFilePath;
                string vModellDirectory = new System.IO.FileInfo(path).DirectoryName;
                string curPath = vModellDirectory + System.IO.Path.DirectorySeparatorChar + path;

                // load model
                using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Set referenced model"))
                {
                    // TODO load.
                    /*
                    global::Tum.VModellXT.VModellXTDocumentData data = global::Tum.VModellXT.VModellXTDocumentData.Instance as global::Tum.VModellXT.VModellXTDocumentData;
                    global::Tum.VModellXT.VModell referenceModel = data.ModelContextVModellXT.LoadInternal(file) as global::Tum.VModellXT.VModell;
                    model.VModell = referenceModel;
                    */
                /*
                    transaction.Commit();
                }

                return;
                */
                return;
            }

            DomainRelationshipInfo linkDomainInfo = null;
            if (protoLink != null)
            {
                linkDomainInfo = this.Partition.DomainDataDirectory.GetDomainRelationship(protoLink.DomainClassId);
            }
            else
            {
                // try getting the linkDomainInfo from name
                DomainClassInfo elementDomainInfo = this.GetDomainClass();
                foreach (DomainRoleInfo info in elementDomainInfo.AllDomainRolesPlayed)
                {
                    if (info.IsSource)
                        if (!this.Store.DomainDataAdvDirectory.IsEmbeddingRelationship(info.DomainRelationship.Id) &&
                            !this.Store.DomainDataAdvDirectory.IsAbstractRelationship(info.DomainRelationship.Id))
                        {
                            if (protoLink.Name == info.DomainRelationship.Name && linkDomainInfo == null)
                            {
                                linkDomainInfo = this.Partition.DomainDataDirectory.GetDomainRelationship(info.DomainRelationship.Id);
                            }
                        }
                }
            }

            if (linkDomainInfo == null)
            {
                groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergeElementLinkDomainTypeMissingId,
                                 ModelValidationViolationType.Error, "Element link can not be created as the corresponding domain type is missing."));
                return;
            }

            ReferenceRelationshipAdvancedInfo advancedInfo = this.Store.DomainDataAdvDirectory.GetRelationshipInfo(linkDomainInfo.Id) as ReferenceRelationshipAdvancedInfo;
            if (advancedInfo == null)
                throw new InvalidOperationException("Relationship advanced info not found for " + linkDomainInfo.Name);

            // see if this element is taking part in this role
            bool bTakesPart = false;

            ModelProtoRolePlayer sourceRolePlayer = protoLink.GetSourceRolePlayer(this.Store.DefaultPartition);
            ModelProtoElement sourceProtoElement = groupMerger.GetElementById(sourceRolePlayer.RolePlayerId);
            System.Guid mappedSourceIdTP = System.Guid.Empty;
            if (sourceProtoElement != null)
            {
                mappedSourceIdTP = groupMerger.GetIdMapping(sourceRolePlayer.RolePlayerId);
                if (mappedSourceIdTP == this.Id)
                    bTakesPart = true;
            }

            if (advancedInfo.PropagatesCopyOnDeniedElement)
            {
                if (!bTakesPart && mappedSourceIdTP == System.Guid.Empty)
                    if (this.Id == sourceRolePlayer.RolePlayerId)
                        bTakesPart = true;
            }

            if (bTakesPart)
            {
                bool bExists = true;
                if (this.Store.ElementDirectory.FindElement(protoLink.ElementId) == null)
                    bExists = false;

                if (bExists && groupMerger.ProtoGroup.Operation == ModelProtoGroupOperation.Move)
                {
                    groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergeElementLinkExistsOnMoveId,
                         ModelValidationViolationType.Error, "Element link exists although the operation = Move."));
                }

                #region Target
                // see if target element was copied
                ModelProtoRolePlayer targetRolePlayer = protoLink.GetTargetRolePlayer(this.Store.DefaultPartition);
                ModelProtoElement targetProtoElement = groupMerger.GetElementById(targetRolePlayer.RolePlayerId);
                Guid mappedTargetId = Guid.Empty;
                if (targetProtoElement != null)
                {
                    mappedTargetId = groupMerger.GetIdMapping(targetRolePlayer.RolePlayerId);
                }

                if (advancedInfo.PropagatesCopyOnDeniedElement)
                    if (mappedTargetId == System.Guid.Empty)
                    {
                        // try creating relationship to existing element
                        mappedTargetId = targetRolePlayer.RolePlayerId;
                    }

                if (mappedTargetId == System.Guid.Empty)
                {
                    // log warning
                    groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergeLinkElementNotCopiedId,
                         ModelValidationViolationType.Error, "Referenced model element was not copied. Relationship: " + linkDomainInfo.Name));
                }
                else
                {
                    ModelElement targetElement = this.Store.ElementDirectory.FindElement(mappedTargetId);
                    if (targetElement == null)
                    {
                        // log error
                        groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergeLinkElementNotFoundId,
                            ModelValidationViolationType.Error, "Referenced model element was not found. Relationship: " + linkDomainInfo.Name));
                    }
                    else
                    {

                        bool bContinue = true;

                        // check cardinalities, so we don't violate them by additing a new relationship
                        if (advancedInfo.SourceRoleMultiplicity == Multiplicity.One || advancedInfo.SourceRoleMultiplicity == Multiplicity.ZeroOne)
                        {
                            if (DomainRoleInfo.GetLinkedElement(this, advancedInfo.SourceRoleId) != null)
                            {
                                // log warning
                                groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergeLinkCreationViolatesMultiplicityId,
                                    ModelValidationViolationType.Error, "Can not create relationship because one already exists. Relationship: " + linkDomainInfo.Name));

                                bContinue = false;
                            }
                        }

                        if (advancedInfo.TargetRoleMultiplicity == Multiplicity.One || advancedInfo.TargetRoleMultiplicity == Multiplicity.ZeroOne)
                        {
                            if (DomainRoleInfo.GetLinkedElement(this, advancedInfo.TargetRoleId) != null)
                            {
                                // log warning
                                groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergeLinkCreationViolatesMultiplicityId,
                                    ModelValidationViolationType.Error, "Can not create relationship because one already exists. Relationship: " + linkDomainInfo.Name));

                                bContinue = false;
                            }
                        }

                        if (bContinue)
                        {
                            // create property assignments
                            PropertyAssignment[] propertyAssignemnts = protoLink.GetPropertyAssignments(this.Store.DefaultPartition,
                                this.GetDomainModelServices().ElementIdProvider.GenerateNewKey());

                            // create role assignments
                            RoleAssignment[] roleAssignments = new RoleAssignment[2];
                            roleAssignments[0] = new RoleAssignment(advancedInfo.SourceRoleId, this);
                            roleAssignments[1] = new RoleAssignment(advancedInfo.TargetRoleId, targetElement);

                            // create new relationship
                            this.Store.ElementFactory.CreateElementLink(linkDomainInfo, propertyAssignemnts, roleAssignments);
                        }
                    }
                }
                #endregion
            }

        }
        /// <summary>
        /// Adds a proto element to the current element.
        /// </summary>
        /// <param name="protoElement">Proto element representation of the element that is to be added.</param>
        /// <param name="groupMerger">
        /// Group merger class used to track id mapping, merge errors/warnings and 
        /// postprocess merging by rebuilding reference relationships.
        /// </param>
        /// <param name="isRoot">Root element?</param>
        public virtual void ModelMerge(ModelProtoElement protoElement, ModelProtoGroupMerger groupMerger, bool isRoot)
        {
            if (!ModelIsPasteAllowed(groupMerger.ProtoGroup.Operation))
            {
                // add warning message
                groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergePasteDisallowedId,
                             ModelValidationViolationType.Warning, "Element couldn't be addded to " + this.DomainElementFullName + " because paste is not allowed."));
                return;
            }

            if (protoElement != null)
            {
                DomainClassInfo elementDomainInfo = this.Partition.DomainDataDirectory.GetDomainClass(protoElement.DomainClassId);
                foreach (DomainRoleInfo info in elementDomainInfo.AllDomainRolesPlayed)
                {
                    if (!info.IsSource)
                        if (info.OppositeDomainRole.RolePlayer.Id == this.GetDomainClassId())
                            if (this.Store.DomainDataAdvDirectory.IsEmbeddingRelationship(info.DomainRelationship.Id) &&
                                !this.Store.DomainDataAdvDirectory.IsAbstractRelationship(info.DomainRelationship.Id))
                            {
                                // create element id
                                Guid newElementId = this.GetDomainModelServices().ElementIdProvider.GenerateNewKey();

                                // create property assignments
                                PropertyAssignment[] propertyAssignemnts = protoElement.GetPropertyAssignments(this.Store.DefaultPartition, newElementId);

                                // create the actual model element
                                DomainModelElement element = this.Store.ElementFactory.CreateElement(elementDomainInfo, propertyAssignemnts) as DomainModelElement;
                                if (element == null)
                                    throw new System.ArgumentNullException("Element is null in ModelMerge: " + elementDomainInfo.Name);

                                if (!element.ModelIsPasteAllowed(groupMerger.ProtoGroup.Operation))
                                {
                                    // add warning message
                                    groupMerger.MergeResult.AddMessage(new ValidationMessage(ModelValidationMessageIds.ModelMergePasteDisallowedId,
                                         ModelValidationViolationType.Warning, "Element couldn't be addded to <#= role.RolePlayer.Name #> because paste is not allowed."));

                                    element.Delete();
                                    return;
                                }

                                // set name
                                if (isRoot && groupMerger.ProtoGroup.Operation != ModelProtoGroupOperation.Move)
                                {
                                    if (element.DomainElementHasName)
                                    {
                                        element.GetDomainModelServices().ElementNameProvider.SetName(element, "Copy of " + element.DomainElementName);
                                    }
                                }

                                // update id mapping
                                groupMerger.SetIdMapping(protoElement.ElementId, newElementId);

                                // add child element
                                if (info.OppositeDomainRole.Multiplicity == Multiplicity.One || info.OppositeDomainRole.Multiplicity == Multiplicity.ZeroOne)
                                {
                                    DomainRoleInfo.SetLinkedElement(this, info.OppositeDomainRole.Id, element);
                                }
                                else
                                {
                                    RoleAssignment[] assignments = new RoleAssignment[2];
                                    assignments[0] = new RoleAssignment(info.OppositeDomainRole.Id, this);
                                    assignments[1] = new RoleAssignment(info.Id, element);


                                    this.Store.ElementFactory.CreateElementLink(info.DomainRelationship, assignments);
                                }

                                // continue with child elements (Embedding Relationship)
                                System.Collections.Generic.List<ModelProtoElement> embeddedProtoElements = groupMerger.GetEmbeddedElements(this.Store.DefaultPartition, protoElement);
                                if (embeddedProtoElements.Count > 0)
                                {
                                    foreach (ModelProtoElement p in embeddedProtoElements)
                                        (element as IModelMergeElements).ModelMerge(p, groupMerger, false);
                                }

                                return;
                            }
                }
            }
        }
Example #34
0
        /// <summary>
        /// Assign existing permission level to group
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="matterCenterContribute">Role to assign a group</param>
        /// <param name="group">RoleAssignment to which permission added</param>
        private static void AssignPermissionLevelToGroup(ClientContext clientContext, RoleDefinition matterCenterContribute, RoleAssignment group)
        {
            clientContext.Load(group.RoleDefinitionBindings, item => item.Include(items => items.Name, items => items.BasePermissions));
            clientContext.ExecuteQuery();

            RoleDefinitionBindingCollection rolesAssignedToGroup = group.RoleDefinitionBindings;
            clientContext.Load(rolesAssignedToGroup, role => role.Include(item => item.Name, item => item.BasePermissions));
            clientContext.ExecuteQuery();
            RoleDefinition roleDefinition = rolesAssignedToGroup.Select(item => item).Where(item => item.Name == matterCenterContribute.Name).FirstOrDefault();
            if (null == roleDefinition)
            {
                group.RoleDefinitionBindings.Add(matterCenterContribute);
                group.Update();
                clientContext.ExecuteQuery();
                ErrorMessage.ShowMessage(string.Format(CultureInfo.InvariantCulture, ConfigurationManager.AppSettings["PermissionAssign"], matterCenterContribute.Name, group.Member.Title), ErrorMessage.MessageType.Notification);
            }
        }
Example #35
0
		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="partition">Partition where new link is to be created.</param>
		/// <param name="roleAssignments">List of relationship role assignments.</param>
		/// <param name="propertyAssignments">List of properties assignments to set on the new link.</param>
		public FactTypeMapsTowardsRole(Partition partition, RoleAssignment[] roleAssignments, PropertyAssignment[] propertyAssignments)
			: base(partition, roleAssignments, propertyAssignments)
		{
		}
Example #36
0
		/// <summary>
		/// Generages the <see cref="ConceptType"/> objects along with any relationships that they have and adds them to the
		/// model.
		/// </summary>
		/// <param name="factTypeMappings">A dictionary of all the final decided FactTypeMapping objects.</param>
		private void GenerateConceptTypes(FactTypeMappingDictionary factTypeMappings)
		{
			ORMModel model = this.ORMModel;
			LinkedElementCollection<ObjectType> modelObjectTypes = model.ObjectTypeCollection;
			AbstractionModel oialModel = this.AbstractionModel;

			// For each object type in the model...
			foreach (ObjectType objectType in modelObjectTypes)
			{
				if (ShouldIgnoreObjectType(objectType))
				{
					continue;
				}
				// If it should have a conctpt type...
				if (ObjectTypeIsConceptType(objectType, factTypeMappings))
				{
					// Create the ConceptType object.
					PropertyAssignment name = new PropertyAssignment(ConceptType.NameDomainPropertyId, objectType.Name);
					ConceptType conceptType = new ConceptType(Store, name);
					ConceptTypeIsForObjectType conceptTypeIsForObjectType = new ConceptTypeIsForObjectType(conceptType, objectType);

					// Add it to the model.
					oialModel.ConceptTypeCollection.Add(conceptType);

					// If this conceptType is for a ValueType...
					if (objectType.IsValueType)
					{
						InformationTypeFormat valueTypeInformationTypeFormat = InformationTypeFormatIsForValueType.GetInformationTypeFormat(objectType);

						RoleAssignment conceptTypeRole = new RoleAssignment(InformationType.ConceptTypeDomainRoleId, conceptType);
						RoleAssignment informationTypeFormat = new RoleAssignment(InformationType.InformationTypeFormatDomainRoleId, valueTypeInformationTypeFormat);
						RoleAssignment[] roleAssignments = { conceptTypeRole, informationTypeFormat };
						PropertyAssignment isMandatory = new PropertyAssignment(InformationType.IsMandatoryDomainPropertyId, true);
						PropertyAssignment informationTypeNameProperty = new PropertyAssignment(InformationType.NameDomainPropertyId, String.Concat(objectType.Name, "Value"));
						PropertyAssignment[] informationTypePropertyAssignments = { isMandatory, informationTypeNameProperty };

						// ConceptType for conceptType gets an InformationType that references InformationTypeFormat for conceptType.
						InformationType informationType = new InformationType(Store, roleAssignments, informationTypePropertyAssignments);

						PropertyAssignment uniquenessNameProperty = new PropertyAssignment(Uniqueness.NameDomainPropertyId, String.Concat(objectType.Name, "Uniqueness"));
						PropertyAssignment isPreferred = new PropertyAssignment(Uniqueness.IsPreferredDomainPropertyId, true);
						PropertyAssignment[] uniquenessPropertyAssignments = { uniquenessNameProperty, isPreferred };

						// Uniqueness constraint
						Uniqueness uniqueness = new Uniqueness(Store, uniquenessPropertyAssignments);
						UniquenessIncludesConceptTypeChild uniquenessIncludesConceptTypeChild = new UniquenessIncludesConceptTypeChild(uniqueness, informationType);

						conceptType.UniquenessCollection.Add(uniqueness);
					}
				}
			}
		}
 /// <summary>
 /// Creates a new instance of the DomainModelLink class.
 /// </summary>
 /// <param name="partition">The Partition instance containing this ElementLink</param>
 /// <param name="roleAssignments">A set of role assignments for roleplayer initialization</param>
 /// <param name="propertyAssignments">A set of attribute assignments for attribute initialization</param>
 protected DomainModelLink(Partition partition, RoleAssignment[] roleAssignments, PropertyAssignment[] propertyAssignments)
     : base(partition, roleAssignments, propertyAssignments)
 {
 }
Example #38
0
 public SPDGClientRoleAssignment(RoleAssignment roleAssignment, SPDGPrincipal member, IEnumerable<SPDGRoleDefinition> roleDefinitionBindings)
     : base(member, roleDefinitionBindings)
 {
     _roleAssignment = roleAssignment;
 }
        /// <summary>
        /// Post process gathered information.
        /// </summary>
        /// <param name="serializationResult">Serialization result.</param>
        /// <param name="store">Store.</param>
        protected virtual void DoPostProcess(Microsoft.VisualStudio.Modeling.SerializationResult serializationResult, Store store)
        {
            foreach (System.Guid domainClassId in this.dictionary.Keys)
            {
                DomainRelationshipInfo relationshipInfo = store.DomainDataDirectory.FindDomainRelationship(domainClassId);
                if (relationshipInfo == null)
                {
                    SerializationUtilities.AddMessage(serializationResult, "", SerializationMessageKind.Warning,
                                "Couldn't find domain relationship data. DomainClassId: " + domainClassId, 0, 0);
                    continue;
                }
                foreach (PostProcessRelationshipData data in this.dictionary[domainClassId])
                {
                    // get source and target elements
                    ModelElement source = store.ElementDirectory.FindElement(data.ModelElementSourceId);
                    ModelElement target = store.ElementDirectory.FindElement(data.ModelElementTargetId);
                    if (target == null)	// target is link ?
                        target = store.ElementDirectory.FindElementLink(data.ModelElementTargetId);

                    if (source == null)
                    {
                        SerializationUtilities.AddMessage(serializationResult, "", SerializationMessageKind.Warning,
                            "Couldn't find the source element of the relationship " + relationshipInfo.Name + ". Id of missing element: " + data.ModelElementSourceId, 0, 0);
                        continue;
                    }
                    if (target == null)
                    {
                        SerializationUtilities.AddMessage(serializationResult, "", SerializationMessageKind.Warning,
                            "Couldn't find the target element of the relationship " + relationshipInfo.Name + ". Id of missing element: " + data.ModelElementTargetId, 0, 0);
                        continue;
                    }

                    if (data.RelationshipId == System.Guid.Empty)
                    {
                        try
                        {
                            // create new relationship
                            RoleAssignment[] roleAssignments = new RoleAssignment[2];
                            roleAssignments[0] = new RoleAssignment(GetSourceDomainRole(relationshipInfo).Id, source);
                            roleAssignments[1] = new RoleAssignment(GetTargetDomainRole(relationshipInfo).Id, target);

                            store.ElementFactory.CreateElementLink(relationshipInfo, roleAssignments);
                        }
                        catch (System.Exception ex)
                        {
                            SerializationUtilities.AddMessage(serializationResult, "", SerializationMessageKind.Warning,
                                "Error while creating new instance of relationship " + relationshipInfo.Name + " between " + source.Id.ToString() + " and " + target.Id.ToString() + ".  Exception: " + ex.Message, 0, 0);
                        }
                    }
                    else
                    {
                        try
                        {
                            // assign role players
                            ElementLink instance = store.ElementDirectory.FindElementLink(data.RelationshipId);
                            if (instance == null)
                                throw new System.ArgumentNullException("Post processing failed because relationship (id=" + data.RelationshipId + ") is not in the store");

                            DomainRoleInfo.SetRolePlayer(instance, GetSourceDomainRole(relationshipInfo).Id, source);
                            DomainRoleInfo.SetRolePlayer(instance, GetTargetDomainRole(relationshipInfo).Id, target);

                            this.trackDictionary.Remove(instance.Id);
                        }
                        catch (System.Exception ex)
                        {
                            SerializationUtilities.AddMessage(serializationResult, "", SerializationMessageKind.Warning,
                                "Error while creating the instance of the relationship " + relationshipInfo.Name + " (id: " + data.RelationshipId + ") between " + source.Id.ToString() + " and " + target.Id.ToString() + ".  Exception: " + ex.Message, 0, 0);
                        }
                    }
                }
            }

            foreach(Guid id in this.trackDictionary)
            {
                ModelElement m = store.ElementDirectory.FindElement(id);
                if( m != null )
                    m.Delete();
            }
        }
Example #40
0
		/// <summary>
		/// Create a new StoreChange structure
		/// </summary>
		/// <param name="e">The <see cref="EventArgs"/> describing the change.</param>
		/// <param name="roleAssignments">The <see cref="RoleAssignment"/> array associated with this change.</param>
		/// <param name="partition">The <see cref="Partition"/> the change occurred in</param>
		private PartitionChange(EventArgs e, RoleAssignment[] roleAssignments, Partition partition)
		{
			myArgs = e;
			myRoleAssignments = (roleAssignments != null && roleAssignments.Length == 2) ? roleAssignments : null;
			myPartition = partition;
		}
        public virtual void AddNewElement(ContextMenuCreationHelper cHelper)
        {
            DomainRoleInfo info = cHelper.RoleInfo;
            using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Create new element"))
            {
                ModelElement modelElement = this.Store.ElementFactory.CreateElement(cHelper.RolePlayerInfo.Id);

                // create and assign name to the element if it has a property marked as "IsElementName"
                if ( (modelElement as IDomainModelOwnable).DomainElementHasName )
                    (modelElement as IDomainModelOwnable).GetDomainModelServices().ElementNameProvider.CreateAndAssignName(this.Element, modelElement);

                RoleAssignment[] roleAssignments = new RoleAssignment[2];
                roleAssignments[0] = new RoleAssignment(info.Id, this.Element);
                roleAssignments[1] = new RoleAssignment(info.OppositeDomainRole.Id, modelElement);

                this.Store.ElementFactory.CreateElementLink(info.DomainRelationship, roleAssignments);

                transaction.Commit();
            }
        }
 public void AddToRoleAssignments(RoleAssignment roleAssignment)
 {
     base.AddObject("RoleAssignments", roleAssignment);
 }
Example #43
0
				public RoleAssignmentDetailBranch(Store store, RoleAssignment assignment)
				{
					myRoleInfo = store.DomainDataDirectory.FindDomainRole(assignment.DomainRoleId);
					myElementId = assignment.RolePlayer.Id;
				}
 public static RoleAssignment CreateRoleAssignment(string userName, string roleName, string sourceAccountName)
 {
     RoleAssignment roleAssignment = new RoleAssignment();
     roleAssignment.UserName = userName;
     roleAssignment.RoleName = roleName;
     roleAssignment.SourceAccountName = sourceAccountName;
     return roleAssignment;
 }
        /// <summary>
        /// Delete element executed.
        /// </summary>
        protected virtual void AddElementCommand_Executed()
        {
            WaitCursor cursor = new WaitCursor();
            try
            {
                // update the default values list first.
                this.UpdateDefaultValuesList();

                using (SelectElementViewModel vm = new SelectElementViewModel(this.ViewModelStore, this.DefaultValues))
                {
                    vm.Title = "Select a role player";

                    if (this.Elements.Count == 1)
                        if (this.Elements[0] is IDomainModelOwnable)
                            vm.Title += " of type " + (this.Elements[0] as IDomainModelOwnable).DomainElementTypeDisplayName;
                        //vm.Title += " of type " + this.ViewModelStore.GetDomainModelServices(this.Elements[0] as ModelElement).ElementTypeProvider.GetTypeDisplayName(
                        //    this.Elements[0] as ModelElement);

                    cursor.Dispose();
                    cursor = null;

                    bool? result = this.GlobalServiceProvider.Resolve<IUIVisualizerService>().ShowDialog("SelectElementPopup", vm);
                    if (result == true && vm.SelectedElement is ModelElement)
                    {
                        try
                        {
                            using (Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add new relationship"))
                            {
                                RoleAssignment[] roleAssignments = new RoleAssignment[2];
                                roleAssignments[0] = new RoleAssignment(this.SourceRoleId, this.Elements[0] as ModelElement);
                                roleAssignments[1] = new RoleAssignment(this.TargetRoleId, vm.SelectedElement as ModelElement);
                                this.Store.ElementFactory.CreateElementLink(this.RelationshipDomainClassId, roleAssignments);

                                transaction.Commit();
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Windows.MessageBox.Show("Error while adding: " + ex.Message);
                        }
                    }
                }
            }
            finally
            {
                if( cursor != null )
                    cursor.Dispose();
            }
            GC.Collect();
        }