private void SetUpPermissions() { if (GetExistingUser() == null) { var roleId = GetRoleId(); var privileges = GetPrivilegeRecords(); var addPrivilegesRoleRequest = new AddPrivilegesRoleRequest { RoleId = roleId, Privileges = ( from p in privileges select new RolePrivilege(RequiredPrivileges[(string)p.Value["name"]], (Guid)p.Value["privilegeid"], BusinessUnitId.Value) ).ToArray() }; CrmSvc.ExecuteCrmOrganizationRequest(addPrivilegesRoleRequest); var user = CreateProposalManagerUser(); PackageLog.Log("User created..."); PackageLog.Log(user.ToString()); CrmSvc.Associate( "systemuser", user, new Relationship("systemuserroles_association"), new EntityReferenceCollection { new EntityReference("role", roleId) }); } }
private void ModifyRolePrivileges(Guid idRole , IEnumerable <RolePrivilege> privilegesAdd , IEnumerable <RolePrivilege> privilegesRemove ) { if (privilegesAdd != null && privilegesAdd.Any()) { AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = idRole, Privileges = privilegesAdd.ToArray(), }; _service.Execute(request); } if (privilegesRemove != null && privilegesRemove.Any()) { foreach (var priv in privilegesRemove) { RemovePrivilegeRoleRequest request = new RemovePrivilegeRoleRequest() { RoleId = idRole, PrivilegeId = priv.PrivilegeId }; _service.Execute(request); } } }
public static void CreateRolePrivilegesInBulk(IOrganizationService svc, Guid roleid, List <RolePrivilege> rolePrivileges) { AddPrivilegesRoleRequest addPrivs = new AddPrivilegesRoleRequest(); addPrivs.Privileges = rolePrivileges.ToArray(); addPrivs.RoleId = roleid; svc.Execute(addPrivs); }
/// <summary> /// Add privileges to the current role. /// </summary> /// <param name="Service">Organization Service</param> /// <param name="Privileges">Privileges to add to the current role.</param> public void AddPrivileges(IOrganizationService Service, List <RolePrivilege> Privileges) { AddPrivilegesRoleRequest Request = new AddPrivilegesRoleRequest() { RoleId = this.Id, Privileges = Privileges.ToArray() }; Service.Execute(Request); }
public static void CreateRolePrivileges(IOrganizationService svc, Guid roleid, Guid privilegeid, int privilegeDepthMask) { var rolePrivilege = new RolePrivilege(privilegeDepthMask, privilegeid); RolePrivilege[] rolePrivileges = { rolePrivilege }; AddPrivilegesRoleRequest addPrivs = new AddPrivilegesRoleRequest(); addPrivs.Privileges = rolePrivileges; addPrivs.RoleId = roleid; svc.Execute(addPrivs); }
/// <summary> /// Add a existing <c>Privilege</c> to a <c>Role</c>. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addprivilegesrolerequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="roleId"></param> /// <param name="privilege"></param> /// <returns><see cref="AddPrivilegesRoleResponse"/></returns> public AddPrivilegesRoleResponse AddPrivilege(Guid roleId, RolePrivilege privilege) { ExceptionThrow.IfGuidEmpty(roleId, "roleId"); ExceptionThrow.IfNull(privilege, "privilege"); AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = roleId, Privileges = new RolePrivilege[] { privilege } }; return((AddPrivilegesRoleResponse)this.OrganizationService.Execute(request)); }
/// <summary> /// Add set of <c>Privilege</c> to a <c>Role</c>. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addprivilegesrolerequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="roleId"></param> /// <param name="privilegeList"></param> /// <returns> /// <see cref="AddPrivilegesRoleResponse"/> /// </returns> public AddPrivilegesRoleResponse AddPrivilege(Guid roleId, List <RolePrivilege> privilegeList) { ExceptionThrow.IfGuidEmpty(roleId, "roleId"); ExceptionThrow.IfNullOrEmpty(privilegeList, "privilegeList"); AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = roleId, Privileges = privilegeList.ToArray() }; return((AddPrivilegesRoleResponse)this.OrganizationService.Execute(request)); }
private void UpdateSecurityRoleEntityPermission(IOrganizationService client, string entitySchemaName, string securityRoleName, string privilege, PrivilegeDepth?privilegeDepth, EntityReference rootBusinessUnit, TracingHelper t) { if (privilegeDepth == null) { return; } var entityPrivilegeName = $"prv{privilege}{entitySchemaName}"; var role = GetExistingSecurityRoleQuery(securityRoleName, rootBusinessUnit) .RetrieveSingleRecord(client); var retrievePrivilegesByName = new QueryExpression("privilege") { ColumnSet = new ColumnSet(true), Criteria = new FilterExpression { Conditions = { new ConditionExpression("name", ConditionOperator.Equal, $"{entityPrivilegeName}") } } }; var privilegeId = retrievePrivilegesByName.RetrieveSingleRecord(client); if (privilegeId == null) { t.Warning($"Privilege with name {entityPrivilegeName} cannot be found. " + $"{entityPrivilegeName} for role {securityRoleName} has been skipped"); return; } var addedPrivilege = new AddPrivilegesRoleRequest() { RoleId = role.Id, Privileges = new[] { new RolePrivilege() { PrivilegeId = privilegeId.Id, Depth = privilegeDepth.Value } } }; client.Execute(addedPrivilege); t.Debug($"{securityRoleName} role updated with permissions for entity {entityPrivilegeName}: {privilegeDepth.Value}"); }
/// <summary> /// Add a privilege to the current role. /// </summary> /// <param name="Service">Organization Service</param> /// <param name="EntityLogicalName">Entity Logical Name</param> /// <param name="Type">Privilege Type</param> /// <param name="Depth">Privilege Level</param> public void AddPrivilege(IOrganizationService Service, string EntityLogicalName, PrivilegeType Type, PrivilegeDepth Depth) { RetrieveEntityRequest RERequest = new RetrieveEntityRequest() { LogicalName = base.LogicalName, EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Privileges }; RetrieveEntityResponse REResponse = Service.Execute(RERequest) as RetrieveEntityResponse; SecurityPrivilegeMetadata Privilege = (from Priv in REResponse.EntityMetadata.Privileges where Priv.PrivilegeType == Type select Priv).FirstOrDefault(); if (Privilege != null) { AddPrivilegesRoleRequest Request = new AddPrivilegesRoleRequest() { RoleId = this.Id, Privileges = new RolePrivilege[] { new RolePrivilege { BusinessUnitId = this.GetAttributeValue <Guid>("businessunitid"), PrivilegeId = Privilege.PrivilegeId, Depth = Depth } } }; Service.Execute(Request); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// authorization profile is created, and associated to a team. Then an entity /// is created and permissions for the entity are assigned to the profile. These /// permissions are then retrieved. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetRetrieveSecuredFieldsForAUser1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; _serviceProxy.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; _serviceProxy.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)_serviceProxy.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List <Guid> profileIds = new List <Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection <Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = _serviceProxy.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveSecuredFieldsForAUser1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a queue record. /// Create a team record. /// Create a role and add queue privileges. /// Assign role to team. /// </summary> public void CreateRequiredRecords() { var QueueViewType = new { Public = 0, Private = 1 }; // Create a queue instance and set its property values. Queue newQueue = new Queue { Name = "Example Queue", Description = "This is an example queue.", QueueViewType = new OptionSetValue(QueueViewType.Private) }; // Create a new queue and store its returned GUID in a variable for later use. _queueId = _serviceProxy.Create(newQueue); Console.WriteLine("Created {0}", newQueue.Name); // Retrieve the default business unit for the creation of the team and role. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "parentbusinessunitid", Operator = ConditionOperator.Null } } } }; BusinessUnit defaultBusinessUnit = (BusinessUnit)_serviceProxy.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Create a new example team. Team setupTeam = new Team { Name = "Example Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.BusinessUnitId.Value) }; _teamId = _serviceProxy.Create(setupTeam); Console.WriteLine("Created {0}", setupTeam.Name); // Create a new example role. Role setupRole = new Role { Name = "Example Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.BusinessUnitId.Value) }; _roleId = _serviceProxy.Create(setupRole); Console.WriteLine("Created {0}", setupRole.Name); // Retrieve the prvReadQueue and prvAppendToQueue privileges. QueryExpression queryQueuePrivileges = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.In, Values = { "prvReadQueue", "prvAppendToQueue" } } } } }; DataCollection <Entity> retrievedQueuePrivileges = _serviceProxy.RetrieveMultiple(queryQueuePrivileges).Entities; Console.WriteLine("Retrieved prvReadQueue and prvAppendToQueue privileges."); // Define a list to hold the RolePrivileges we'll need to add List <RolePrivilege> rolePrivileges = new List <RolePrivilege>(); foreach (Privilege privilege in retrievedQueuePrivileges) { RolePrivilege rolePrivilege = new RolePrivilege( (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value); rolePrivileges.Add(rolePrivilege); } // Add the prvReadQueue and prvAppendToQueue privileges to the example role. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = rolePrivileges.ToArray() }; _serviceProxy.Execute(addPrivilegesRequest); Console.WriteLine("Retrieved privileges are added to {0}.", setupRole.Name); // Add the example role to the example team. _serviceProxy.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); // It takes some time for the privileges to propogate to the team. // Verify this is complete before continuing. bool teamLacksPrivilege = true; while (teamLacksPrivilege) { RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = new RetrieveTeamPrivilegesRequest { TeamId = _teamId }; RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse = (RetrieveTeamPrivilegesResponse)_serviceProxy.Execute( retrieveTeamPrivilegesRequest); if (retrieveTeamPrivilegesResponse.RolePrivileges.Any( rp => rp.PrivilegeId == rolePrivileges[0].PrivilegeId) && retrieveTeamPrivilegesResponse.RolePrivileges.Any( rp => rp.PrivilegeId == rolePrivileges[1].PrivilegeId)) { teamLacksPrivilege = false; } else { Thread.Sleep(1000); } } Console.WriteLine("{0} has been added to {1}", setupRole.Name, setupTeam.Name); return; }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates the email activity. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // Retrieve the default business unit needed to create the team and role. var query = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; var defaultBusinessUnit = service.RetrieveMultiple(query) .Entities.Cast <BusinessUnit>().FirstOrDefault(); // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentation // to determine which attributes must be set for each entity. var setupTeam = new Team { Name = "An Example Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a team record. _teamId = service.Create(setupTeam); Console.WriteLine("Created team '{0}'", setupTeam.Name); // Instantiate a role entity record and set its property values. // See the Entity Metadata topic in the SDK documentation // to determine which attributes must be set for each entity. var setupRole = new Role { Name = _roleName, BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create the role record. _roleId = service.Create(setupRole); Console.WriteLine("Created role '{0}'", setupRole.Name); // Define an array listing the privileges that we want to add to the role String[] privilegesToAdd = new string[] { "prvReadContact", "prvCreateContact", "prvReadAccount", "prvCreateAccount" }; // Query for the privileges we want to add to the role var queryPrivileges = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression() }; queryPrivileges.Criteria.AddCondition("name", ConditionOperator.In, privilegesToAdd); DataCollection <Entity> returnedPrivileges = service.RetrieveMultiple( queryPrivileges).Entities; Console.WriteLine("Retrieved privileges to add to role"); // Define a list to hold the RolePrivileges we'll need to add List <RolePrivilege> rolePrivileges = new List <RolePrivilege>(); foreach (Privilege privilege in returnedPrivileges) { var rolePrivilege = new RolePrivilege( (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value); rolePrivileges.Add(rolePrivilege); } // Add the retrieved privileges to the example role. var addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = rolePrivileges.ToArray() }; service.Execute(addPrivilegesRequest); Console.WriteLine("Added privileges to role"); }
/// <summary> /// Create or update security roles /// </summary> /// <param name="manifest"></param> /// <param name="client"></param> /// <param name="t"></param> /// <param name="publisherPrefix"></param> public void CreateSecurityRoles(ConfigurationManifest manifest, IOrganizationService client, TracingHelper t, string publisherPrefix) { if (manifest.SecurityRoles == null) { t.Debug($"No security roles in manifest to be processed"); } else { var rootBusinessUnit = XrmClient.GetRootBusinessUnit(client); foreach (var securityRole in manifest.SecurityRoles) { var existingRole = GetExistingSecurityRoleQuery(securityRole.Name, rootBusinessUnit) .RetrieveSingleRecord(client); var role = new Role() { Name = securityRole.Name, BusinessUnitId = rootBusinessUnit }.CreateOrUpdate(client, GetExistingSecurityRoleQuery(securityRole.Name, rootBusinessUnit)); SolutionWrapper.AddSolutionComponent(client, manifest.SolutionName, role.Id, ComponentType.Role); if (securityRole.Privileges == null) { continue; } foreach (var rolePrivilege in securityRole.Privileges) { var retrievePrivilegesByName = new QueryExpression("privilege") { ColumnSet = new ColumnSet(true), Criteria = new FilterExpression { Conditions = { new ConditionExpression("name", ConditionOperator.Equal, rolePrivilege) } } }; var privilegeId = retrievePrivilegesByName.RetrieveSingleRecord(client); if (privilegeId == null) { t.Warning($"Privilege with name {rolePrivilege} cannot be found. " + $"{rolePrivilege} for role {securityRole.Name} has been skipped"); continue; } var addedPrivilege = new AddPrivilegesRoleRequest() { RoleId = role.Id, Privileges = new [] { new RolePrivilege() { PrivilegeId = privilegeId.Id, Depth = PrivilegeDepth.Global } } }; client.Execute(addedPrivilege); } } } }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a queue record. /// Create a team record. /// Create a role and add queue privileges. /// Assign role to team. /// </summary> public void CreateRequiredRecords() { var QueueViewType = new { Public = 0, Private = 1 }; // Create a queue instance and set its property values. Queue newQueue = new Queue { Name = "Example Queue", Description = "This is an example queue.", QueueViewType = new OptionSetValue(QueueViewType.Private) }; // Create a new queue and store its returned GUID in a variable for later use. _queueId = _serviceProxy.Create(newQueue); Console.WriteLine("Created {0}", newQueue.Name); // Retrieve the default business unit for the creation of the team and role. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "parentbusinessunitid", Operator = ConditionOperator.Null } } } }; BusinessUnit defaultBusinessUnit = (BusinessUnit)_serviceProxy.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Create a new example team. Team setupTeam = new Team { Name = "Example Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.BusinessUnitId.Value) }; _teamId = _serviceProxy.Create(setupTeam); Console.WriteLine("Created {0}", setupTeam.Name); // Create a new example role. Role setupRole = new Role { Name = "Example Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.BusinessUnitId.Value) }; _roleId = _serviceProxy.Create(setupRole); Console.WriteLine("Created {0}", setupRole.Name); // Retrieve the prvReadQueue and prvAppendToQueue privileges. QueryExpression queryQueuePrivileges = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.In, Values = { "prvReadQueue", "prvAppendToQueue" } } } } }; DataCollection<Entity> retrievedQueuePrivileges = _serviceProxy.RetrieveMultiple(queryQueuePrivileges).Entities; Console.WriteLine("Retrieved prvReadQueue and prvAppendToQueue privileges."); // Define a list to hold the RolePrivileges we'll need to add List<RolePrivilege> rolePrivileges = new List<RolePrivilege>(); foreach (Privilege privilege in retrievedQueuePrivileges) { RolePrivilege rolePrivilege = new RolePrivilege( (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value); rolePrivileges.Add(rolePrivilege); } // Add the prvReadQueue and prvAppendToQueue privileges to the example role. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = rolePrivileges.ToArray() }; _serviceProxy.Execute(addPrivilegesRequest); Console.WriteLine("Retrieved privileges are added to {0}.", setupRole.Name); // Add the example role to the example team. _serviceProxy.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); // It takes some time for the privileges to propogate to the team. // Verify this is complete before continuing. bool teamLacksPrivilege = true; while (teamLacksPrivilege) { RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = new RetrieveTeamPrivilegesRequest { TeamId = _teamId }; RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse = (RetrieveTeamPrivilegesResponse)_serviceProxy.Execute( retrieveTeamPrivilegesRequest); if (retrieveTeamPrivilegesResponse.RolePrivileges.Any( rp => rp.PrivilegeId == rolePrivileges[0].PrivilegeId) && retrieveTeamPrivilegesResponse.RolePrivileges.Any( rp => rp.PrivilegeId == rolePrivileges[1].PrivilegeId)) { teamLacksPrivilege = false; } else { Thread.Sleep(1000); } } Console.WriteLine("{0} has been added to {1}", setupRole.Name, setupTeam.Name); return; }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a team, an account and a role. /// Add read account privileges to the role. /// Assign the role to the team so that they can read the account. /// Assign the account to the team. /// </summary> public void CreateRequiredRecords() { // Instantiate an account entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Account setupAccount = new Account { Name = "Example Account" }; // Create the account record. _accountId = _service.Create(setupAccount); Console.WriteLine("Created {0}", setupAccount.Name); // Retrieve the default business unit needed to create the team and role. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid" ), Criteria = new FilterExpression() }; queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); BusinessUnit defaultBusinessUnit = (BusinessUnit)_service.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Team setupTeam = new Team { Name = "Example Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a team record. _teamId = _service.Create(setupTeam); Console.WriteLine("Created {0}", setupTeam.Name); // Instantiate a role entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Role setupRole = new Role { Name = "Example Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a role record. Typically you would use an existing role that has the // the correct privileges. For this sample we need to be sure the role has // at least the privilege to read account records. _roleId = _service.Create(setupRole); Console.WriteLine("Created {0}", setupRole.Name); // Create a query expression to find the prvReadAccountPrivilege. QueryExpression queryReadAccountPrivilege = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression() }; queryReadAccountPrivilege.Criteria.AddCondition("name", ConditionOperator.Equal, "prvReadAccount"); // Retrieve the prvReadAccount privilege. Entity readAccountPrivilege = _service.RetrieveMultiple( queryReadAccountPrivilege)[0]; Console.WriteLine("Retrieved {0}", readAccountPrivilege.Attributes["name"]); //<snippetAssignRecordToTeam2> // Add the prvReadAccount privilege to the example roles to assure the // team can read accounts. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = new[] { // Grant prvReadAccount privilege. new RolePrivilege { PrivilegeId = readAccountPrivilege.Id } } }; _service.Execute(addPrivilegesRequest); //</snippetAssignRecordToTeam2> Console.WriteLine("Added privilege to role"); // Add the role to the team. _service.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Assigned team to role"); //<snippetAssignRecordToTeam3> // It takes some time for the privileges to propagate to the team. Delay the // application until the privilege has been assigned. bool teamLacksPrivilege = true; while (teamLacksPrivilege) { RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = new RetrieveTeamPrivilegesRequest { TeamId = _teamId }; RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse = (RetrieveTeamPrivilegesResponse)_service.Execute( retrieveTeamPrivilegesRequest); foreach (RolePrivilege rp in retrieveTeamPrivilegesResponse.RolePrivileges) { if (rp.PrivilegeId == readAccountPrivilege.Id) { teamLacksPrivilege = false; break; } else { System.Threading.Thread.CurrentThread.Join(500); } } } //</snippetAssignRecordToTeam3> return; }
[STAThread] // Added to support UX static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { #region Sample Code //////////////////////////////////////// #region Set up SetUpSample(service); #endregion Set up #region Demonstrate // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = service.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; service.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; service.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_message", DisplayName = new Label("Message", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Message", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; service.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)service.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)service.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_picture", DisplayName = new Label("Picture", 1033), SchemaName = "New_Picture", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)service.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = service.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List <Guid> profileIds = new List <Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)service.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection <Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = service.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); #region Clean up CleanUpSample(service); #endregion Clean up } #endregion Demonstrate #endregion Sample Code else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Microsoft Dataverse"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// authorization profile is created, and associated to a team. Then an entity /// is created and permissions for the entity are assigned to the profile. These /// permissions are then retrieved. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetRetrieveSecuredFieldsForAUser1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; _serviceProxy.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; _serviceProxy.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)_serviceProxy.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List<Guid> profileIds = new List<Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection<Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = _serviceProxy.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveSecuredFieldsForAUser1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a team, an account and a role. /// Add read account privileges to the role. /// Assign the role to the team so that they can read the account. /// Assign the account to the team. /// </summary> public void CreateRequiredRecords() { // Instantiate an account entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Account setupAccount = new Account { Name = "Example Account" }; // Create the account record. _accountId = _service.Create(setupAccount); Console.WriteLine("Created {0}", setupAccount.Name); // Retrieve the default business unit needed to create the team and role. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); BusinessUnit defaultBusinessUnit = (BusinessUnit)_service.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Team setupTeam = new Team { Name = "Example Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a team record. _teamId = _service.Create(setupTeam); Console.WriteLine("Created {0}", setupTeam.Name); // Instantiate a role entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Role setupRole = new Role { Name = "Example Role", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a role record. Typically you would use an existing role that has the // the correct privileges. For this sample we need to be sure the role has // at least the privilege to read account records. _roleId = _service.Create(setupRole); Console.WriteLine("Created {0}", setupRole.Name); // Create a query expression to find the prvReadAccountPrivilege. QueryExpression queryReadAccountPrivilege = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression() }; queryReadAccountPrivilege.Criteria.AddCondition("name", ConditionOperator.Equal, "prvReadAccount"); // Retrieve the prvReadAccount privilege. Entity readAccountPrivilege = _service.RetrieveMultiple( queryReadAccountPrivilege)[0]; Console.WriteLine("Retrieved {0}", readAccountPrivilege.Attributes["name"]); //<snippetAssignRecordToTeam2> // Add the prvReadAccount privilege to the example roles to assure the // team can read accounts. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = new[] { // Grant prvReadAccount privilege. new RolePrivilege { PrivilegeId = readAccountPrivilege.Id } } }; _service.Execute(addPrivilegesRequest); //</snippetAssignRecordToTeam2> Console.WriteLine("Added privilege to role"); // Add the role to the team. _service.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Assigned team to role"); //<snippetAssignRecordToTeam3> // It takes some time for the privileges to propagate to the team. Delay the // application until the privilege has been assigned. bool teamLacksPrivilege = true; while (teamLacksPrivilege) { RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = new RetrieveTeamPrivilegesRequest { TeamId = _teamId }; RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse = (RetrieveTeamPrivilegesResponse)_service.Execute( retrieveTeamPrivilegesRequest); foreach (RolePrivilege rp in retrieveTeamPrivilegesResponse.RolePrivileges) { if (rp.PrivilegeId == readAccountPrivilege.Id) { teamLacksPrivilege = false; break; } else { System.Threading.Thread.CurrentThread.Join(500); } } } //</snippetAssignRecordToTeam3> return; }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a team, a queue and a role. /// Add read queue privileges to the role. /// Assign the role to the team so that they can read the queue. /// Assign the queue to the team. /// </summary> public void CreateRequiredRecords() { // Instantiate a dynamic entity and set its property values. // See the Entity Metadata topic in the SDK documentatio to determine // which attributes must be set for each entity. Entity setupQueue = new Entity("queue"); setupQueue["name"] = "Example Queue"; setupQueue["description"] = "This is an example queue."; // Create the queue record. _queueId = _service.Create(setupQueue); Console.WriteLine("Created {0}", setupQueue["name"]); // Retrieve the default business unit needed to create the team and role. QueryExpression queryDefaultBusinessUnit = new QueryExpression("businessunit"); queryDefaultBusinessUnit.ColumnSet = new ColumnSet("businessunitid"); queryDefaultBusinessUnit.Criteria = new FilterExpression(); queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); Entity defaultBusinessUnit = _service.RetrieveMultiple(queryDefaultBusinessUnit).Entities[0]; // Instantiate a dynamic entity and set its property values. // See the Entity Metadata topic in the SDK documentatio to determine // which attributes must be set for each entity. Entity setupTeam = new Entity("team"); setupTeam["name"] = "Example Team"; setupTeam["businessunitid"] = new EntityReference("businessunit", defaultBusinessUnit.Id); // Create a team record. _teamId = _service.Create(setupTeam); Console.WriteLine("Created {0}", setupTeam["name"]); // Instantiate a dynamic entity and set its property values. // See the Entity Metadata topic in the SDK documentatio to determine // which attributes must be set for each entity. Entity setupRole = new Entity("role"); setupRole["name"] = "Example Role"; setupRole["businessunitid"] = new EntityReference("businessunit", defaultBusinessUnit.Id); // Create a role record. Typically you would use an exisitng role that has the // the correct privileges. For this sample we need to be sure the role has // at least the privilege to read queue records. _roleId = _service.Create(setupRole); Console.WriteLine("Created {0}", setupRole["name"]); // Create a query expression to find the prvReadQueue Privilege and prvReadMailbox Privilege. QueryExpression queryReadQueuePrivilege = new QueryExpression { EntityName = "privilege", ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression() }; queryReadQueuePrivilege.Criteria.AddCondition("name", ConditionOperator.In, "prvReadQueue", "prvReadMailbox"); // Retrieve the prvReadQueue privilege and prvReadMailbox Privilege. DataCollection <Entity> readQueuePrivilege = _serviceProxy.RetrieveMultiple(queryReadQueuePrivilege).Entities; Console.WriteLine("Retrieved {0}", readQueuePrivilege.Count); // Define a list to hold the RolePrivileges we'll need to add List <RolePrivilege> rolePrivileges = new List <RolePrivilege>(); foreach (Privilege privilege in readQueuePrivilege) { RolePrivilege rolePrivilege = new RolePrivilege( (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value); rolePrivileges.Add(rolePrivilege); } // Add the prvReadQueue and prvReadMailbox privilege to the example role. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = rolePrivileges.ToArray() }; _service.Execute(addPrivilegesRequest); Console.WriteLine("Added privilege to role"); // Add the role to the team. AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(Team.EntityLogicalName, _teamId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }, Relationship = new Relationship("teamroles_association") }; _service.Execute(associate); Console.WriteLine("Assigned team to role"); // It takes some time for the privileges to propogate to the team. Delay the // application until the privilege has been assigned. bool teamLacksPrivilege = true; while (teamLacksPrivilege) { RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = new RetrieveTeamPrivilegesRequest { TeamId = _teamId }; RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse = (RetrieveTeamPrivilegesResponse)_service.Execute(retrieveTeamPrivilegesRequest); foreach (Microsoft.Crm.Sdk.Messages.RolePrivilege rp in retrieveTeamPrivilegesResponse.RolePrivileges) { if (retrieveTeamPrivilegesResponse.RolePrivileges[0].PrivilegeId == readQueuePrivilege[0].Id && retrieveTeamPrivilegesResponse.RolePrivileges[1].PrivilegeId == readQueuePrivilege[1].Id) { teamLacksPrivilege = false; break; } else { System.Threading.Thread.CurrentThread.Join(500); } } } return; }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates a team and a role. /// </summary> public void CreateRequiredRecords() { // Retrieve the default business unit needed to create the team and role. QueryExpression query = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = _service.RetrieveMultiple(query) .Entities.Cast<BusinessUnit>().FirstOrDefault(); // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentation // to determine which attributes must be set for each entity. Team setupTeam = new Team { Name = "An Example Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create a team record. _teamId = _service.Create(setupTeam); Console.WriteLine("Created team '{0}'", setupTeam.Name); // Instantiate a role entity record and set its property values. // See the Entity Metadata topic in the SDK documentation // to determine which attributes must be set for each entity. Role setupRole = new Role { Name = _roleName, BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; // Create the role record. _roleId = _service.Create(setupRole); Console.WriteLine("Created role '{0}'", setupRole.Name); // Define an array listing the privileges that we want to add to the role String[] privilegesToAdd = new string[] { "prvReadContact", "prvCreateContact", "prvReadAccount", "prvCreateAccount" }; // Query for the privileges we want to add to the role QueryExpression queryPrivileges = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression() }; queryPrivileges.Criteria.AddCondition("name", ConditionOperator.In, privilegesToAdd); DataCollection<Entity> returnedPrivileges = _service.RetrieveMultiple( queryPrivileges).Entities; Console.WriteLine("Retrieved privileges to add to role"); // Define a list to hold the RolePrivileges we'll need to add List<RolePrivilege> rolePrivileges = new List<RolePrivilege>(); foreach (Privilege privilege in returnedPrivileges) { RolePrivilege rolePrivilege = new RolePrivilege( (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value); rolePrivileges.Add(rolePrivilege); } // Add the retrieved privileges to the example role. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = rolePrivileges.ToArray() }; _service.Execute(addPrivilegesRequest); Console.WriteLine("Added privileges to role"); }