internal void Associate_Disassociate() { //建立等等要關聯用的客戶資料 var account1 = new Account() { Name = "TestAccount" }; var acc1Id = _orgService.Create(account1); var account2 = new Account() { Name = "TestAccount2" }; var acc2Id = _orgService.Create(account2); //建立等等要關聯用的聯絡人資料 var contact1 = new Contact() { FirstName = "Lin", LastName = "Jeremy" }; var contact1Id = _orgService.Create(contact1); //建立客戶主要聯絡人的實體關聯物件 Relationship rel = new Relationship("account_primary_contact"); //把要被設定主要聯絡人的客戶加入到集合中 var accounts = new EntityReferenceCollection(); accounts.Add(new EntityReference(Account.EntityLogicalName, acc1Id)); accounts.Add(new EntityReference(Account.EntityLogicalName, acc2Id)); //從連絡人執行關聯到客戶 _orgService.Associate(Contact.EntityLogicalName, contact1Id, rel, accounts); onLog(string.Format("Associate Product Success")); //從聯絡人解除跟客戶的關聯 _orgService.Disassociate(Contact.EntityLogicalName, contact1Id, rel, accounts); onLog(string.Format("Disassociate Product Success")); //把要設定主要聯絡人的聯絡人加入到集合中 var contacts = new EntityReferenceCollection(); contacts.Add(new EntityReference(Contact.EntityLogicalName, contact1Id)); //從客戶執行關聯到聯絡人 _orgService.Associate(Account.EntityLogicalName, acc1Id, rel, contacts); _orgService.Associate(Account.EntityLogicalName, acc2Id, rel, contacts); onLog(string.Format("Other Way Associate Product Success")); }
/// <summary> /// Associate two or more entity records. /// </summary> /// <param name="entityName">The name of the entity that contains the record.</param> /// <param name="entityId">The id of the record being associated.</param> /// <param name="relationship">The relatiomship to use for association.</param> /// <param name="relatedEntities">The collection of entities to associate the record with.</param> public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { try { using (OrganizationServiceProxy organizationServiceProxy = this.OrganizationServiceProxy) { organizationServiceProxy.Associate(entityName, entityId, relationship, relatedEntities); } } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { throw; } }
public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { ThrowExceptionIfDisposed(); try { _serviceProxy.Associate(entityName, entityId, relationship, relatedEntities); } catch (Exception ex) { Helpers.DTEHelper.WriteExceptionToLog(ex); throw; } }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // For this sample, all required entities are created in the Run() method. // Create/retrieve a user and associate a role. _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(_serviceProxy); // Find the role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); // Associate the user with the role for this sample. if (salesRole != null & amp; & _userId != Guid.Empty) { _serviceProxy.Associate( "systemuser", _userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, salesRole.Id) }); } } }
/// <summary> /// Create and configure the organization service proxy. /// 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. /// Optionally delete any entity records that were created for this sample. /// <para name="organizationFriendlyName">The friendly name of /// the target organization.</para> /// <para name="discoveryServer">The name of the discovery server.</para> /// <param name="promptForDelete">Indicates whether to prompt the user /// to delete the records created in this sample.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); // Assign the queue to a team. _serviceProxy.Associate( Queue.EntityLogicalName, _queueId, new Relationship("queue_team"), new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }); Console.WriteLine("The queue is owned by the team."); DeleteRequiredRecords(promptForDelete); } } // 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 first creates 3 users, a team, 4 leads and a business unit. /// It assigns two users to the team, and gives each user and the team a lead. /// Then it reassigns all the leads from one of the users to another user using /// the ReassignObjectsSystemUserRequest. Next, it reassigns all the leads from /// the team to a user using the ReassignObjectsOwnerRequest. Third, it reassigns /// one user from the root business unit to the created business unit, using the /// SetBusinessSystemUserRequest message. Fourth, it reassigns all users from /// the created business unit to the root business unit and deletes the created /// business unit. Finally, it removes all users from the created team and /// deletes the team. /// </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 { // 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)) // Using the ServiceContext class provides access to the LINQ provider using (_context = new ServiceContext(_serviceProxy)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); Console.WriteLine(); PrintLeads(); var users = from user in _context.SystemUserSet select new { user.FullName, user.Id }; Dictionary <Guid, String> userMapping = new Dictionary <Guid, String>(); foreach (var user in users) { userMapping.Add(user.Id, user.FullName); } #region ReassignObjectsSystemUserRequest // create the request ReassignObjectsSystemUserRequest reassignRequest = new ReassignObjectsSystemUserRequest() { ReassignPrincipal = new EntityReference(SystemUser.EntityLogicalName, _users[1]), UserId = _users[2] }; // execute the request Console.WriteLine(); Console.WriteLine( " Reassigning leads from {0} to {1}", userMapping[_users[2]], userMapping[_users[1]]); _serviceProxy.Execute(reassignRequest); // check results PrintLeads(); #endregion #region ReassignObjectsOwnerRequest // create the request ReassignObjectsOwnerRequest request = new ReassignObjectsOwnerRequest() { FromPrincipal = _team.ToEntityReference(), ToPrincipal = new EntityReference(SystemUser.EntityLogicalName, _users[0]) }; // execute the request Console.WriteLine(); Console.WriteLine( " Reassigning leads from {0} to {1}", _team.Name, userMapping[_users[0]]); _serviceProxy.Execute(request); // check results PrintLeads(); #endregion #region reassign business unit members Console.WriteLine(); Console.WriteLine(" Adding a user to the created business unit"); // track what permissions the user had before reassigning to the new // business unit so that the permissions can be restored when the // user is assigned back to the business unit _originalRolesIds = new List <Guid>(); var roleIds = from user in _context.SystemUserSet join systemuserrole in _context.SystemUserRolesSet on user.SystemUserId equals systemuserrole.SystemUserId join role in _context.RoleSet on systemuserrole.RoleId equals role.RoleId where user.SystemUserId.Value == _users[2] select role.RoleId.Value; foreach (var roleId in roleIds) { _originalRolesIds.Add(roleId); } // add user to the created business unit _serviceProxy.Execute(new SetBusinessSystemUserRequest() { BusinessId = _businessUnit.Id, ReassignPrincipal = new EntityReference( SystemUser.EntityLogicalName, _users[2]), UserId = _users[2] }); #endregion #region delete business unit Console.WriteLine(); Console.WriteLine(" Deleting created business unit"); // remove all users from the business unit, moving them back to the // parent business unit _serviceProxy.Execute(new SetBusinessSystemUserRequest() { BusinessId = _rootBusinessUnit.Id, ReassignPrincipal = new EntityReference( SystemUser.EntityLogicalName, _users[2]), UserId = _users[2] }); // give the user back their original security roles foreach (var roleId in roleIds) { _serviceProxy.Associate( SystemUser.EntityLogicalName, _users[2], new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference( Role.EntityLogicalName, roleId ) } ); } // deactivate business unit before deleting it _serviceProxy.Execute(new SetStateRequest() { EntityMoniker = _businessUnit.ToEntityReference(), // mark the state as inactive (value 1) State = new OptionSetValue(1), Status = new OptionSetValue(-1) }); // delete business unit _serviceProxy.Delete(BusinessUnit.EntityLogicalName, _businessUnit.Id); #endregion #region remove users from team var teamMembers = from team in _context.TeamSet join membership in _context.TeamMembershipSet on team.TeamId equals membership.TeamId where team.TeamId == _team.Id select membership.SystemUserId.Value; _serviceProxy.Execute(new RemoveMembersTeamRequest() { MemberIds = teamMembers.ToArray(), TeamId = _team.Id }); #endregion #region delete team Console.WriteLine(); Console.WriteLine(" Deleting the team"); // Delete the team _serviceProxy.Delete(Team.EntityLogicalName, _team.Id); #endregion DeleteRequiredRecords(promptforDelete); } } // 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> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region create users Console.WriteLine(" Creating users"); var ldapPath = ""; _users = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); _users.Add(SystemUserProvider.RetrieveSystemUser( "dparker", "Darren", "Parker", "Salesperson", _serviceProxy, ref ldapPath)); #endregion #region fetch root business unit // Retrieve the root business unit to use for creating the team for the // sample. var businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = new FilterExpression() }; businessUnitQuery.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null); var businessUnitResult = _serviceProxy.RetrieveMultiple(businessUnitQuery); _rootBusinessUnit = businessUnitResult.Entities[0].ToEntity <BusinessUnit>(); #endregion #region create new business unit Console.WriteLine(" Creating new business unit"); _businessUnit = new BusinessUnit() { Name = "A Sample Business Unit", ParentBusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _businessUnit.Id = _serviceProxy.Create(_businessUnit); #endregion #region create team Console.WriteLine(" Creating a user team"); _team = new Team { AdministratorId = new EntityReference(SystemUser.EntityLogicalName, _users[0]), Name = "Sample team", BusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _team.Id = _serviceProxy.Create(_team); var salespersonRole = (from role in _context.RoleSet where role.Name == "Salesperson" && role.BusinessUnitId.Id == _rootBusinessUnit.Id select role).First(); // assign role to the team _serviceProxy.Associate( Team.EntityLogicalName, _team.Id, new Relationship("teamroles_association"), new EntityReferenceCollection() { salespersonRole.ToEntityReference() } ); // wait for the async job to finish for (int i = 1; i <= 30; i++) { Console.WriteLine(" Checking to see if the async job has finished {0}/30", i); var teamPrivileges = (RetrieveTeamPrivilegesResponse) _serviceProxy.Execute(new RetrieveTeamPrivilegesRequest { TeamId = _team.Id }); if (teamPrivileges.RolePrivileges.Any((rp) => rp.PrivilegeId == new Guid("A8ECAC53-09E8-4A13-B598-8D8C87BC3D33"))) // prvReadLead { break; } System.Threading.Thread.Sleep(1000); } #endregion #region add users to team Console.WriteLine(" Adding users to the team"); AddMembersTeamRequest addMembers = new AddMembersTeamRequest() { TeamId = _team.Id, MemberIds = new Guid[] { _users[0], _users[1] } }; _serviceProxy.Execute(addMembers); #endregion #region create leads Console.WriteLine(" Creating leads"); _leads[0] = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Joe", LastName = "Andreshak", }; _leads[0].Id = _serviceProxy.Create(_leads[0]); _leads[1] = new Lead { CompanyName = "Wingtip Toys", FirstName = "Diogo", LastName = "Andrade" }; _leads[1].Id = _serviceProxy.Create(_leads[1]); _leads[2] = new Lead { CompanyName = "The Phone Company", FirstName = "Ronaldo", LastName = "Smith Jr." }; _leads[2].Id = _serviceProxy.Create(_leads[2]); _leads[3] = new Lead { CompanyName = "Tailspin Toys", FirstName = "Andrew", LastName = "Sullivan", }; _leads[3].Id = _serviceProxy.Create(_leads[3]); #endregion #region assign leads Console.WriteLine(" Assigning leads to users and teams"); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[0]), Target = _leads[0].ToEntityReference() }); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[1]), Target = _leads[1].ToEntityReference() }); _serviceProxy.Execute(new AssignRequest() { Assignee = new EntityReference(SystemUser.EntityLogicalName, _users[2]), Target = _leads[2].ToEntityReference() }); // give the team access to the record so that it can be assigned to it _serviceProxy.Execute(new GrantAccessRequest() { Target = _leads[3].ToEntityReference(), PrincipalAccess = new PrincipalAccess() { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = _team.ToEntityReference() } }); // assign the lead to the team _serviceProxy.Execute(new AssignRequest() { Assignee = _team.ToEntityReference(), Target = _leads[3].ToEntityReference() }); #endregion }
/// <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 first connects to the Organization service. Afterwards, /// creates/retrieves a system user, /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user is prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetAddRoleToUser1> // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Find the role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = {_givenRole} } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity<Role>(); Console.WriteLine("Role {0} is retrieved for the role assignment.", _givenRole); _roleId = salesRole.Id; // Associate the user with the role. if (_roleId != Guid.Empty && _userId != Guid.Empty) { _serviceProxy.Associate( "systemuser", _userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Role is associated with the user."); } } DeleteRequiredRecords(promptforDelete); } //</snippetAddRoleToUser1> } // 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 first connects to the Organization service. Afterwards, /// creates/retrieves a system user, /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user is prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetAddRoleToUser1> // Connect to the Organization service. // The using statement assures that the service proxy is properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Find the role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved for the role assignment.", _givenRole); _roleId = salesRole.Id; // Associate the user with the role. if (_roleId != Guid.Empty && _userId != Guid.Empty) { _serviceProxy.Associate( "systemuser", _userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Role is associated with the user."); } } DeleteRequiredRecords(promptforDelete); } //</snippetAddRoleToUser1> } // 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; } }
public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities) { RunSafe(() => _serviceProxy.Associate(entityName, entityId, relationship, relatedEntities)); }
/// <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 queue entity record and set its property values. // See the Entity Metadata topic in the SDK documentatio to determine // which attributes must be set for each entity. Queue setupQueue = new Queue { Name = "Example Queue", Description = "This is an example queue." }; // Create the queue record. _queueId = _serviceProxy.Create(setupQueue); Console.WriteLine("Created {0}", setupQueue.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)_serviceProxy.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentatio 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 = _serviceProxy.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 documentatio 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 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 = _serviceProxy.Create(setupRole); Console.WriteLine("Created {0}", setupRole.Name); // Create a query expression to find the prvReadQueuePrivilege. QueryExpression queryReadQueuePrivilege = new QueryExpression { EntityName = Privilege.EntityLogicalName, ColumnSet = new ColumnSet("privilegeid", "name"), Criteria = new FilterExpression() }; queryReadQueuePrivilege.Criteria.AddCondition("name", ConditionOperator.Equal, "prvReadQueue"); // Retrieve the prvReadQueue privilege. Privilege readQueuePrivilege = (Privilege)_serviceProxy.RetrieveMultiple( queryReadQueuePrivilege).Entities[0]; Console.WriteLine("Retrieved {0}", readQueuePrivilege.Name); // Add the prvReadQueue privilege to the example role. AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest { RoleId = _roleId, Privileges = new Microsoft.Crm.Sdk.Messages.RolePrivilege[] { // Grant prvReadQueue privilege. new Microsoft.Crm.Sdk.Messages.RolePrivilege { PrivilegeId = readQueuePrivilege.Id } } }; _serviceProxy.Execute(addPrivilegesRequest); Console.WriteLine("Added privilege to role"); // Add the role to the team. _serviceProxy.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); 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)_serviceProxy.Execute( retrieveTeamPrivilegesRequest); foreach (Microsoft.Crm.Sdk.Messages.RolePrivilege rp in retrieveTeamPrivilegesResponse.RolePrivileges) { if (retrieveTeamPrivilegesResponse.RolePrivileges[0].PrivilegeId == readQueuePrivilege.Id) { teamLacksPrivilege = false; break; } else { System.Threading.Thread.CurrentThread.Join(500); } } } return; }
/// <summary> /// This method first creates 3 users, a team, 4 leads and a business unit. /// It assigns two users to the team, and gives each user and the team a lead. /// Then it reassigns all the leads from one of the users to another user using /// the ReassignObjectsSystemUserRequest. Next, it reassigns all the leads from /// the team to a user using the ReassignObjectsOwnerRequest. Third, it reassigns /// one user from the root business unit to the created business unit, using the /// SetBusinessSystemUserRequest message. Fourth, it reassigns all users from /// the created business unit to the root business unit and deletes the created /// business unit. Finally, it removes all users from the created team and /// deletes the team. /// </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 { //<snippetReassignBusinessUnitMembers1> // 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)) // Using the ServiceContext class provides access to the LINQ provider using (_context = new ServiceContext(_serviceProxy)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); Console.WriteLine(); PrintLeads(); var users = from user in _context.SystemUserSet select new { user.FullName, user.Id }; Dictionary<Guid, String> userMapping = new Dictionary<Guid,String>(); foreach (var user in users) userMapping.Add(user.Id, user.FullName); #region ReassignObjectsSystemUserRequest // create the request ReassignObjectsSystemUserRequest reassignRequest = new ReassignObjectsSystemUserRequest() { ReassignPrincipal = new EntityReference(SystemUser.EntityLogicalName, _users[1]), UserId = _users[2] }; // execute the request Console.WriteLine(); Console.WriteLine( " Reassigning leads from {0} to {1}", userMapping[_users[2]], userMapping[_users[1]]); _serviceProxy.Execute(reassignRequest); // check results PrintLeads(); #endregion #region ReassignObjectsOwnerRequest // create the request ReassignObjectsOwnerRequest request = new ReassignObjectsOwnerRequest() { FromPrincipal = _team.ToEntityReference(), ToPrincipal = new EntityReference(SystemUser.EntityLogicalName, _users[0]) }; // execute the request Console.WriteLine(); Console.WriteLine( " Reassigning leads from {0} to {1}", _team.Name, userMapping[_users[0]]); _serviceProxy.Execute(request); // check results PrintLeads(); #endregion #region reassign business unit members Console.WriteLine(); Console.WriteLine(" Adding a user to the created business unit"); // track what permissions the user had before reassigning to the new // business unit so that the permissions can be restored when the // user is assigned back to the business unit _originalRolesIds = new List<Guid>(); var roleIds = from user in _context.SystemUserSet join systemuserrole in _context.SystemUserRolesSet on user.SystemUserId equals systemuserrole.SystemUserId join role in _context.RoleSet on systemuserrole.RoleId equals role.RoleId where user.SystemUserId.Value == _users[2] select role.RoleId.Value; foreach (var roleId in roleIds) _originalRolesIds.Add(roleId); // add user to the created business unit _serviceProxy.Execute(new SetBusinessSystemUserRequest() { BusinessId = _buisnessUnit.Id, ReassignPrincipal = new EntityReference( SystemUser.EntityLogicalName, _users[2]), UserId = _users[2] }); #endregion #region delete business unit Console.WriteLine(); Console.WriteLine(" Deleting created business unit"); // remove all users from the business unit, moving them back to the // parent business unit _serviceProxy.Execute(new SetBusinessSystemUserRequest() { BusinessId = _rootBusinessUnit.Id, ReassignPrincipal = new EntityReference( SystemUser.EntityLogicalName, _users[2]), UserId = _users[2] }); // give the user back their original security roles foreach (var roleId in roleIds) { _serviceProxy.Associate( SystemUser.EntityLogicalName, _users[2], new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference( Role.EntityLogicalName, roleId ) } ); } // deactivate business unit before deleting it _serviceProxy.Execute(new SetStateRequest() { EntityMoniker = _buisnessUnit.ToEntityReference(), // mark the state as inactive (value 1) State = new OptionSetValue(1), Status = new OptionSetValue(-1) }); // delete business unit _serviceProxy.Delete(BusinessUnit.EntityLogicalName, _buisnessUnit.Id); #endregion #region remove users from team var teamMembers = from team in _context.TeamSet join membership in _context.TeamMembershipSet on team.TeamId equals membership.TeamId where team.TeamId == _team.Id select membership.SystemUserId.Value; _serviceProxy.Execute(new RemoveMembersTeamRequest() { MemberIds = teamMembers.ToArray(), TeamId = _team.Id }); #endregion #region delete team Console.WriteLine(); Console.WriteLine(" Deleting the team"); // Delete the team _serviceProxy.Delete(Team.EntityLogicalName, _team.Id); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetReassignBusinessUnitMembers1> } // 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> /// Create and configure the organization service proxy. /// Verify if knowledge management is enabled for the /// Incident entity. /// Create sample records (account and incident). /// Create a knowledge base record. /// Associate the knowledge base record to entity record. /// Dissociate the knowledge base record from entity record. /// Optionally delete/revert any records /// that were created/changed for this sample. /// </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 { // 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(); if (CheckCRMVersion() == true) { // Check if knowledge management is enabled // for the Incident entity. CheckKnowledgeManagementStatus(); // Create required records for the sample. CreateRequiredRecords(); // Create a knowledge base record instance KnowledgeBaseRecord kbRecord = new KnowledgeBaseRecord { // These are sample values. Replace them with // appropriate values as per your integrated // Parature instance. PrivateUrl = "https://www.demo.parature.com/internal", PublicUrl = "https://www.demo.parature.com", Title = "How to track shipping?", UniqueId = "8000/8467/Article/23782" }; _kbRecordId = _serviceProxy.Create(kbRecord); Console.WriteLine("Created knowledge base record with ID: '{0}'.\n", _kbRecordId.ToString()); // Associate the knowledge base record with an incident record // Step 1: Create a collection of knowledge base record that will be // associated to the incident. In this case, we have only a single // knowledge base record to be associated. EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(new EntityReference(KnowledgeBaseRecord.EntityLogicalName, _kbRecordId)); // Step 2: Create an object that defines the relationship between knowledge base record and incident. // Use the many-to-many relationship name (KnowledgeBaseRecord_Incident) between knowledge base // record and incident. Relationship relationship = new Relationship("KnowledgeBaseRecord_Incident"); // Step 3: Associate the knowledge base record with the incident record. _serviceProxy.Associate(Incident.EntityLogicalName, _incidentId, relationship, relatedEntities); // Check to see if the association record is created in the // IncidentKnowledgeBaseRecord intersect entity QueryExpression associationQuery = new QueryExpression { EntityName = IncidentKnowledgeBaseRecord.EntityLogicalName, ColumnSet = new ColumnSet("incidentid", "knowledgebaserecordid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "incidentid", Operator = ConditionOperator.Equal, Values = { _incidentId } }, new ConditionExpression { AttributeName = "knowledgebaserecordid", Operator = ConditionOperator.Equal, Values = { _kbRecordId } } } }, PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; DataCollection <Entity> entityCollection = _serviceProxy.RetrieveMultiple(associationQuery).Entities; if (entityCollection.Count() > 0) { Console.WriteLine("Associated knowledge base record with the incident record."); // Disassociate the records. _serviceProxy.Disassociate(Incident.EntityLogicalName, _incidentId, relationship, relatedEntities); Console.WriteLine("Disasociated knowledge base record from the incident record.\n"); } else { Console.WriteLine("Could not associate knowledge base record with the incident record.\n"); } // Prompt the user to delete the records and attribute created by the sample. DeleteRequiredRecords(promptForDelete); } else { Console.WriteLine("Aborting the sample."); } } } // 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; } }