public void BusinessUnitChange() { using (var context = new Xrm(orgAdminUIService)) { var rootBu = context.BusinessUnitSet.FirstOrDefault(); var anotherBusinessUnit = new BusinessUnit(); anotherBusinessUnit["name"] = "Business unit name"; anotherBusinessUnit.Id = orgAdminUIService.Create(anotherBusinessUnit); var user = crm.CreateUser(orgAdminUIService, anotherBusinessUnit.ToEntityReference(), SecurityRoles.SystemAdministrator) as SystemUser; // Create and check account user/bu var acc = new Account(); acc.Id = orgAdminUIService.Create(acc); acc = orgAdminUIService.Retrieve <Account>(acc.Id); Assert.Equal(acc.OwnerId.Id, crm.AdminUser.Id); // Update and check new account user/bu var upd = new Account(acc.Id) { OwnerId = user.ToEntityReference() }; orgAdminUIService.Update(upd); acc = orgAdminUIService.Retrieve <Account>(acc.Id); Assert.Equal(acc.OwnerId.Id, user.Id); Assert.Equal(acc.OwningBusinessUnit.Id, user.BusinessUnitId.Id); } }
public void TestRelatedNullWorkflow() { using (var context = new Xrm(orgAdminUIService)) { crm.AddWorkflow(Path.Combine("../../..", "Metadata", "Workflows", "RelatedWorkflow.xml")); var businessunit = new BusinessUnit(); businessunit["name"] = "business unit name 1"; businessunit.Id = orgAdminUIService.Create(businessunit); var user = crm.CreateUser(orgAdminUIService, new SystemUser() { LastName = null, BusinessUnitId = businessunit.ToEntityReference() }, SecurityRoles.SystemAdministrator) as SystemUser; var service = crm.CreateOrganizationService(user.Id); var con = new Contact() { LastName = "SomeLastname" }; con.Id = service.Create(con); var acc = new Account { Name = "Related", PrimaryContactId = con.ToEntityReference() }; acc.Id = service.Create(acc); var retrieved = orgAdminUIService.Retrieve(Account.EntityLogicalName, acc.Id, new ColumnSet(true)) as Account; Assert.Equal(user.LastName + " - " + con.LastName + " ", retrieved.Name); } }
public void TestCreateSecurity() { using (var context = new Xrm(orgAdminUIService)) { var orgUser = new SystemUser(); orgUser.Id = orgAdminUIService.Create(orgUser); var businessunit = new BusinessUnit(); businessunit.Id = orgAdminUIService.Create(businessunit); var user = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.Scheduler); var service = crm.CreateOrganizationService(user.Id); try { service.Create(new Lead()); Assert.Fail(); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(FaultException)); } service.Create(new Contact()); try { var otherAccount = new Contact(); otherAccount.OwnerId = orgUser.ToEntityReference(); service.Create(otherAccount); Assert.Fail(); } catch (Exception e) { Assert.IsInstanceOfType(e, typeof(FaultException)); } } }
public void TestParentChangeCascading() { using (var context = new Xrm(orgAdminUIService)) { var businessunit = new BusinessUnit(); businessunit.Id = orgAdminUIService.Create(businessunit); var parentUser = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.Scheduler); var service = crm.CreateOrganizationService(parentUser.Id); var bus = new dg_bus(); bus.Id = service.Create(bus); var parentChild = new dg_child(); parentChild.dg_parentBusId = bus.ToEntityReference(); parentChild.Id = service.Create(parentChild); var otherChild = new dg_child(); otherChild.Id = orgAdminUIService.Create(otherChild); FaultException faultException = null; try { service.Retrieve(otherChild.LogicalName, otherChild.Id, new ColumnSet(true)); Assert.Fail(); } catch (FaultException e) { faultException = e; } otherChild.dg_parentBusId = bus.ToEntityReference(); orgAdminUIService.Update(otherChild); service.Retrieve(otherChild.LogicalName, otherChild.Id, new ColumnSet(true)); } }
public void TestAddMembers() { var bu1 = new BusinessUnit() { Name = "bu1", ParentBusinessUnitId = crm.RootBusinessUnit }; bu1.Id = orgAdminService.Create(bu1); var bu2 = new BusinessUnit() { Name = "bu2", ParentBusinessUnitId = crm.RootBusinessUnit }; bu2.Id = orgAdminService.Create(bu2); var user1 = crm.CreateUser(orgAdminService, bu1.ToEntityReference(), SecurityRoles.SystemCustomizer); var user2 = crm.CreateUser(orgAdminService, bu2.ToEntityReference(), SecurityRoles.SystemCustomizer); var team = crm.CreateTeam(orgAdminService, crm.RootBusinessUnit, SecurityRoles.SystemCustomizer); crm.AddUsersToTeam(team.ToEntityReference(), user1.ToEntityReference(), user2.ToEntityReference()); using (var context = new Xrm(orgAdminUIService)) { var fetchedTeam = context.TeamMembershipSet.Where(x => x.TeamId == team.Id).ToList(); Assert.AreEqual(2, fetchedTeam.Count); var user1Member = fetchedTeam.FirstOrDefault(x => x.SystemUserId == user1.Id); Assert.IsNotNull(user1Member); var user2Member = fetchedTeam.FirstOrDefault(x => x.SystemUserId == user2.Id); Assert.IsNotNull(user2Member); } }
public void When_querying_the_same_entity_records_with_joins_no_collection_modified_exception_is_thrown() { var fakedContext = new XrmFakedContext { }; var service = fakedContext.GetFakedOrganizationService(); var entityAccount = new Account { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!", LogicalName = "account" }; var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference() }; var entityBusinessUnit = new BusinessUnit { Name = "TestBU", BusinessUnitId = Guid.NewGuid() }; var initiatingUser = new SystemUser { Id = Guid.NewGuid(), FirstName = "TestUser", DomainName = "TestDomain", BusinessUnitId = entityBusinessUnit.ToEntityReference() }; fakedContext.Initialize(new List <Entity>() { entityBusinessUnit, entityAccount, entityContact, initiatingUser }); var fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='systemuser'> <attribute name='fullname' /> <attribute name='systemuserid' /> <attribute name='businessunitid' /> <filter type='and'> <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='#userId#' /> </filter> <link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='bu' intersect='true' > <attribute name='name' /> </link-entity> </entity> </fetch> "; var UserRequest = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.Replace("#userId#", initiatingUser.Id.ToString())) }; var response = ((RetrieveMultipleResponse)service.Execute(UserRequest)); var entities = response.EntityCollection.Entities; Assert.True(entities.Count == 1); Assert.True(entities[0].Attributes.ContainsKey("bu.name")); Assert.IsType <AliasedValue>(entities[0]["bu.name"]); Assert.Equal("TestBU", (entities[0]["bu.name"] as AliasedValue).Value.ToString()); }
public void When_There_Are_Multiple_LinkedEntities_The_Output_EntityAlias_Should_All_Be_Suffixed_With_1() { var context = new XrmFakedContext(); var service = context.GetOrganizationService(); var entities = new List <Entity>(); var user1 = new SystemUser { Id = Guid.NewGuid(), ["fullname"] = "User1" }; entities.Add(user1); var businessUnit = new BusinessUnit { Id = Guid.NewGuid(), Name = "BusinessUnit1" }; entities.Add(businessUnit); var user2 = new SystemUser { Id = Guid.NewGuid(), BusinessUnitId = businessUnit.ToEntityReference(), ["fullname"] = "User2", ["modifiedby"] = user1.ToEntityReference() }; entities.Add(user2); context.Initialize(entities); var query = new QueryExpression(SystemUser.EntityLogicalName) { LinkEntities = { new LinkEntity(SystemUser.EntityLogicalName, SystemUser.EntityLogicalName, "modifiedby", "systemuserid", JoinOperator.Inner) { Columns = new ColumnSet("fullname"), }, new LinkEntity(SystemUser.EntityLogicalName, BusinessUnit.EntityLogicalName, "businessunitid", "businessunitid", JoinOperator.Inner) { Columns = new ColumnSet("name"), } } }; var result = service.RetrieveMultiple(query); var resultingEntity = result.Entities[0]; Assert.Equal(2, resultingEntity.Attributes.Count); Assert.Equal("User1", ((AliasedValue)resultingEntity["systemuser1.fullname"]).Value); Assert.Equal("BusinessUnit1", ((AliasedValue)resultingEntity["businessunit1.name"]).Value); }
public void AddMembersToBusinessUnit() { var team = RetrieveBusinessUnitDefaultTeamAndCheckAttributes(_businessUnit1); crm.CreateUser(orgAdminService, _businessUnit1.ToEntityReference(), SecurityRoles.SystemCustomizer); using (var context = new Xrm(orgAdminService)) { var fetchedTeam = context.TeamMembershipSet.Where(x => x.TeamId == team.Id).ToList(); Assert.AreEqual(1, fetchedTeam.Count); } }
public void TestSharingAccess() { using (var context = new Xrm(orgAdminUIService)) { var businessunit = new BusinessUnit(); businessunit["name"] = "business unit name"; businessunit.Id = orgAdminUIService.Create(businessunit); var otherUser = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles._000TestingRole); var sharingUser = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator); var otherService = crm.CreateOrganizationService(otherUser.Id); var sharingService = crm.CreateOrganizationService(sharingUser.Id); var contact = new Contact(); contact.Id = sharingService.Create(contact); try { otherService.Retrieve(Contact.EntityLogicalName, contact.Id, new ColumnSet(true)); throw new XunitException(); } catch (Exception e) { Assert.IsType <FaultException>(e); } var req = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess() { AccessMask = AccessRights.ReadAccess, Principal = otherUser.ToEntityReference() }, Target = contact.ToEntityReference() }; sharingService.Execute(req); otherService.Retrieve(Contact.EntityLogicalName, contact.Id, new ColumnSet(true)); } }
public void WhoAmIRequestForOtherUser() { var bu = new BusinessUnit { Name = "child bu", ParentBusinessUnitId = crm.RootBusinessUnit }; bu.Id = orgAdminUIService.Create(bu); var user = crm.CreateUser(orgAdminService, new SystemUser { BusinessUnitId = bu.ToEntityReference() }, SecurityRoles.SalesManager) as SystemUser; var service = crm.CreateOrganizationService(user.Id); var whoAmI = (WhoAmIResponse)service.Execute(new WhoAmIRequest()); Assert.AreEqual(whoAmI.UserId, user.Id); Assert.AreEqual(whoAmI.BusinessUnitId, bu.Id); }
public void TestOwningBusinessUnitValidNameWorkflow() { using (var context = new Xrm(orgAdminUIService)) { crm.AddWorkflow(Path.Combine("../..", "Metadata", "Workflows", "OwningBUWorkflow.xml")); var businessunit = new BusinessUnit(); businessunit.Name = "delegatelab4"; businessunit.Id = orgAdminUIService.Create(businessunit); var user = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator) as SystemUser; var service = crm.CreateOrganizationService(user.Id); var acc = new Account(); acc.Name = "Some name"; acc.Id = service.Create(acc); var retrieved = orgAdminUIService.Retrieve(Account.EntityLogicalName, acc.Id, new ColumnSet(true)) as Account; Assert.AreEqual("SetOwningBU", retrieved.Name); } }
public void TestSendMailWorkflow() { using (var context = new Xrm(orgAdminUIService)) { crm.AddWorkflow(Path.Combine("../../..", "Metadata", "Workflows", "SendMailWorkflow.xml")); var businessunit = new BusinessUnit { Name = "delegatelab4" }; businessunit.Id = orgAdminUIService.Create(businessunit); crm.CreateUser(orgAdminService, new SystemUser() { Id = new Guid("9732d6d5-8e46-44e1-b408-32d3801c5724"), FirstName = "Kaspar", LastName = "Bøgh Christensen", BusinessUnitId = crm.RootBusinessUnit }, SecurityRoles.SystemAdministrator); var user = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator) as SystemUser; var service = crm.CreateOrganizationService(user.Id); var acc = new Account { Name = "Some name" }; acc.Id = service.Create(acc); var retrieved = orgAdminUIService.Retrieve(Account.EntityLogicalName, acc.Id, new ColumnSet(true)) as Account; var email = orgAdminService.RetrieveMultiple(new QueryExpression { EntityName = Email.EntityLogicalName, ColumnSet = new ColumnSet(true) }).Entities.FirstOrDefault() as Email; Assert.IsNotNull(email); Assert.AreEqual("<span><span>Some kind of email</span></span>", email.Description); Assert.AreEqual("Something", email.Subject); Assert.AreEqual(retrieved.ToEntityReference(), email.RegardingObjectId); } }
public void TestCreateSecurity() { using (var context = new Xrm(orgAdminUIService)) { var orgUser = new SystemUser(); orgUser.Id = orgAdminUIService.Create(orgUser); var businessunit = new BusinessUnit(); businessunit["name"] = "business unit name 1"; businessunit.Id = orgAdminUIService.Create(businessunit); var scheduler = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.Scheduler); var schedulerService = crm.CreateOrganizationService(scheduler.Id); try { schedulerService.Create(new Lead()); throw new XunitException(); } catch (Exception e) { Assert.IsType <FaultException>(e); } schedulerService.Create(new Contact()); try { var contact = new Contact { OwnerId = orgUser.ToEntityReference() }; schedulerService.Create(contact); throw new XunitException(); } catch (Exception e) { Assert.IsType <FaultException>(e); } } }
public void TestMyConditionWorkflow() { using (var context = new Xrm(orgAdminUIService)) { crm.AddWorkflow(Path.Combine("../..", "Metadata", "OtherWorkflows", "MyConditionWorkflow.xml")); var businessunit = new BusinessUnit(); businessunit.Name = "deledevelopmentasd"; businessunit.Id = orgAdminUIService.Create(businessunit); var user = crm.CreateUser(orgAdminUIService, businessunit.ToEntityReference(), SecurityRoles.SystemAdministrator) as SystemUser; var service = crm.CreateOrganizationService(user.Id); var acc = new Account(); acc.Name = "Some name"; acc.Revenue = 3000; acc.DoNotFax = true; acc.DoNotBulkPostalMail = false; acc.Id = service.Create(acc); var retrieved = orgAdminUIService.Retrieve(Account.EntityLogicalName, acc.Id, new ColumnSet(true)) as Account; Assert.AreEqual("MyCondition", retrieved.Name); } }
public void MoveMemberFromBUOneToBUTwo() { var retrievedUser = orgAdminService.Retrieve("systemuser", _user2.Id, new ColumnSet("businessunitid")); retrievedUser.Attributes["businessunitid"] = _businessUnit4.ToEntityReference(); // retrievedUser.Attributes["name"] = "Just changed the name ;)"; orgAdminService.Update(retrievedUser); var team3 = RetrieveBusinessUnitDefaultTeamAndCheckAttributes(_businessUnit3); var team4 = RetrieveBusinessUnitDefaultTeamAndCheckAttributes(_businessUnit4); using (var context = new Xrm(orgAdminService)) { var fetchedTeam = context.TeamMembershipSet.Where(x => x.TeamId == team3.Id).ToList(); Assert.AreEqual(0, fetchedTeam.Count); } using (var context = new Xrm(orgAdminService)) { var fetchedTeam = context.TeamMembershipSet.Where(x => x.TeamId == team4.Id).ToList(); Assert.AreEqual(1, fetchedTeam.Count); } }
public void TestQueryOnLinkedRoleTemplate() { // All MS Dynamics CRM instances share the same System Admin role GUID. // Hence, we can hardode it as this will not represent a security issue Guid adminId = new Guid("627090FF-40A3-4053-8790-584EDC5BE201"); var businessunit = new BusinessUnit(); businessunit["name"] = "business unit name 1"; businessunit.Id = orgAdminUIService.Create(businessunit); var user = new SystemUser(); user["businessunitid"] = businessunit.ToEntityReference(); var adminuser = crm.CreateUser(orgAdminService, user, SecurityRoles.SystemAdministrator); var q = new QueryExpression("role"); q.Criteria.AddCondition("roletemplateid", ConditionOperator.Equal, adminId); var link = q.AddLink("systemuserroles", "roleid", "roleid"); link.LinkCriteria.AddCondition("systemuserid", ConditionOperator.Equal, adminuser.Id); Assert.True(orgAdminService.RetrieveMultiple(q).Entities.Count > 0); }
/// <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 }
public TestTeams(XrmMockupFixture fixture) : base(fixture) { EntityReference businessUnitId = crm.RootBusinessUnit; businessUnit1 = new BusinessUnit { ParentBusinessUnitId = businessUnitId, Name = "Business Unit 1" }; businessUnit1.Id = orgAdminService.Create(businessUnit1); businessUnit2 = new BusinessUnit { ParentBusinessUnitId = businessUnitId, Name = "Business Unit 2" }; businessUnit2.Id = orgAdminService.Create(businessUnit2); team1 = new Team { Name = "Team 1", BusinessUnitId = businessUnit1.ToEntityReference() }; #if !(XRM_MOCKUP_2011) team1.TeamType = Team_TeamType.Owner; #endif team1 = crm.CreateTeam(orgAdminService, team1, SecurityRoles.SystemCustomizer).ToEntity <Team>(); team2 = new Team { Name = "Team 2", BusinessUnitId = businessUnit1.ToEntityReference() }; #if !(XRM_MOCKUP_2011) team2.TeamType = Team_TeamType.Owner; #endif team2 = crm.CreateTeam(orgAdminService, team2, SecurityRoles.SystemCustomizer).ToEntity <Team>(); team3 = new Team { Name = "Team 3", BusinessUnitId = businessUnit1.ToEntityReference() }; #if !(XRM_MOCKUP_2011) team3.TeamType = Team_TeamType.Owner; #endif team3 = crm.CreateTeam(orgAdminService, team3, SecurityRoles.SystemAdministrator).ToEntity <Team>(); team4 = new Team { Name = "Team 4", BusinessUnitId = businessUnit1.ToEntityReference() }; #if !(XRM_MOCKUP_2011) team4.TeamType = Team_TeamType.Owner; #endif team4 = crm.CreateTeam(orgAdminService, team4, SecurityRoles.SystemAdministrator).ToEntity <Team>(); // SystemCustomizer - read account - user level, write account - user level user11 = crm.CreateUser(orgAdminService, businessUnit1.ToEntityReference(), SecurityRoles.SystemCustomizer) as SystemUser; user12 = crm.CreateUser(orgAdminService, businessUnit1.ToEntityReference(), SecurityRoles.SystemCustomizer) as SystemUser; user21 = crm.CreateUser(orgAdminService, businessUnit2.ToEntityReference(), SecurityRoles.SystemCustomizer) as SystemUser; user22 = crm.CreateUser(orgAdminService, businessUnit2.ToEntityReference(), SecurityRoles.SystemCustomizer) as SystemUser; parent1 = new EntityReference(Account.EntityLogicalName, orgAdminService.Create(new Account { Name = "Parent 1" })); parent2 = new EntityReference(Account.EntityLogicalName, orgAdminService.Create(new Account { Name = "Parent 2" })); account11 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 1.1", ParentAccountId = parent1, OwnerId = user11.ToEntityReference() })); account12 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 1.2", ParentAccountId = parent1, OwnerId = user12.ToEntityReference() })); account21 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 2.1", ParentAccountId = parent2, OwnerId = user21.ToEntityReference() })); account22 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 2.2", ParentAccountId = parent2, OwnerId = user22.ToEntityReference() })); account1 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 1", ParentAccountId = parent1, OwnerId = team1.ToEntityReference() })); account2 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 2", ParentAccountId = parent2, OwnerId = team2.ToEntityReference() })); account3 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 3", ParentAccountId = parent1, OwnerId = team2.ToEntityReference() })); account4 = new EntityReference(Account.EntityLogicalName, orgGodService.Create(new Account { Name = "Child 4", ParentAccountId = parent2, OwnerId = team3.ToEntityReference() })); }
/// <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"); _buisnessUnit = new BusinessUnit() { Name = "A Sample Business Unit", ParentBusinessUnitId = _rootBusinessUnit.ToEntityReference() }; _buisnessUnit.Id = _serviceProxy.Create(_buisnessUnit); #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 }
public void When_querying_the_same_entity_records_with_joins_no_collection_modified_exception_is_thrown() { var fakedContext = new XrmFakedContext { }; var service = fakedContext.GetFakedOrganizationService(); var entityAccount = new Account { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!", LogicalName = "account" }; var entityContact = new Contact { Id = Guid.NewGuid(), ParentCustomerId = entityAccount.ToEntityReference() }; var entityBusinessUnit = new BusinessUnit { Name = "TestBU", BusinessUnitId = Guid.NewGuid() }; var initiatingUser = new SystemUser { Id = Guid.NewGuid(), FirstName = "TestUser", DomainName = "TestDomain", BusinessUnitId = entityBusinessUnit.ToEntityReference() }; fakedContext.Initialize(new List<Entity>() { entityBusinessUnit,entityAccount,entityContact,initiatingUser }); var fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='systemuser'> <attribute name='fullname' /> <attribute name='systemuserid' /> <attribute name='businessunitid' /> <filter type='and'> <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='#userId#' /> </filter> <link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='bu' intersect='true' > <attribute name='name' /> </link-entity> </entity> </fetch> "; var UserRequest = new RetrieveMultipleRequest { Query = new FetchExpression(fetchXml.Replace("#userId#", initiatingUser.Id.ToString())) }; var response = ((RetrieveMultipleResponse)service.Execute(UserRequest)); var entities = response.EntityCollection.Entities; Assert.True(entities.Count == 1); Assert.True(entities[0].Attributes.ContainsKey("bu.name")); Assert.IsType<AliasedValue>(entities[0]["bu.name"]); Assert.Equal("TestBU", (entities[0]["bu.name"] as AliasedValue).Value.ToString()); }