コード例 #1
0
        private void AddSecurityRoleToUser(Entity user, Guid roleId)
        {
            var roleReference = new EntityReference("role", roleId);
            var roleRefs      = new EntityReferenceCollection(new List <EntityReference>()
            {
                roleReference
            });

            _client.Associate(
                "systemuser",
                user.Id,
                new Relationship("systemuserroles_association"),
                roleRefs);
        }
コード例 #2
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            // Create/retrieve a user and associate a role.

            _userId = SystemUserProvider.RetrieveAUserWithoutAnyRoleAssigned(service);
            // Find the role.
            var 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 = service.RetrieveMultiple(query);

            if (roles.Entities.Count > 0)
            {
                Role salesRole = service.RetrieveMultiple(query).Entities[0].ToEntity <Role>();

                // Associate the user with the role for this sample.
                if (salesRole != null && _userId != Guid.Empty)
                {
                    service.Associate(
                        "systemuser",
                        _userId,
                        new Relationship("systemuserroles_association"),
                        new EntityReferenceCollection()
                    {
                        new EntityReference(Role.EntityLogicalName, salesRole.Id)
                    });
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            Contact contact1 = new Contact
            {
                FirstName                = "Colin",
                LastName                 = "Wilcox",
                Address1_City            = "Redmond",
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98052",
                Anniversary              = new DateTime(2010, 3, 5),
                CreditLimit              = new Money(300),
                Description              = "Alpine Ski House",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(1),
                NumberOfChildren         = 1,
                Address1_Latitude        = 47.6741667,
                Address1_Longitude       = -122.1202778,
                CreditOnHold             = false
            };

            _contactId1 = service.Create(contact1);

            Console.Write("Created a sample contact 1: {0}, ", contact1.FirstName + " " + contact1.LastName);

            Contact contact2 = new Contact
            {
                FirstName                = "Brian",
                LastName                 = "Smith",
                Address1_City            = "Bellevue",
                FamilyStatusCode         = new OptionSetValue(3),
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98008",
                Anniversary              = new DateTime(2010, 4, 5),
                CreditLimit              = new Money(30000),
                Description              = "Coho Winery",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(2),
                NumberOfChildren         = 2,
                Address1_Latitude        = 47.6105556,
                Address1_Longitude       = -122.1994444,
                CreditOnHold             = false
            };

            _contactId2 = service.Create(contact2);

            Console.Write("Created a sample contact 2: {0}, ", contact2.FirstName + " " + contact2.LastName);

            Contact contact3 = new Contact
            {
                FirstName                = "Darren",
                LastName                 = "Parker",
                Address1_City            = "Kirkland",
                FamilyStatusCode         = new OptionSetValue(3),
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98033",
                Anniversary              = new DateTime(2010, 10, 5),
                CreditLimit              = new Money(10000),
                Description              = "Coho Winery",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(2),
                NumberOfChildren         = 2,
                Address1_Latitude        = 47.6105556,
                Address1_Longitude       = -122.1994444,
                CreditOnHold             = false
            };

            _contactId3 = service.Create(contact3);

            Console.Write("Created a sample contact 3: {0}, ", contact3.FirstName + " " + contact3.LastName);

            Contact contact4 = new Contact
            {
                FirstName                = "Ben",
                LastName                 = "Smith",
                Address1_City            = "Kirkland",
                FamilyStatusCode         = new OptionSetValue(3),
                Address1_StateOrProvince = "WA",
                Address1_PostalCode      = "98033",
                Anniversary              = new DateTime(2010, 7, 5),
                CreditLimit              = new Money(12000),
                Description              = "Coho Winery",
                StatusCode               = new OptionSetValue(1),
                AccountRoleCode          = new OptionSetValue(2),
                NumberOfChildren         = 2,
                Address1_Latitude        = 47.6105556,
                Address1_Longitude       = -122.1994444,
                CreditOnHold             = true
            };

            _contactId4 = service.Create(contact4);

            Console.Write("Created a sample contact 4: {0}, ", contact4.FirstName + " " + contact4.LastName);

            Incident incident1 = new Incident
            {
                Title          = "Test Case 1",
                PriorityCode   = new OptionSetValue(1),      // 1 = High
                CaseOriginCode = new OptionSetValue(1),      // 1 = Phone
                CaseTypeCode   = new OptionSetValue(2),      // 2 = Problem
                Description    = "Description for Test Case 1.",
                FollowupBy     = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                CustomerId     = new EntityReference(Contact.EntityLogicalName, _contactId2)
            };

            _incidentId1 = service.Create(incident1);

            Console.Write("Created a sample incident 1: {0}, ", incident1.Title);

            Relationship relationship1 = new Relationship("incident_customer_contacts");
            EntityReferenceCollection relatedEntities1 = new EntityReferenceCollection();

            relatedEntities1.Add(new EntityReference(Contact.EntityLogicalName, _contactId1));
            service.Associate(Incident.EntityLogicalName, _incidentId1, relationship1, relatedEntities1);

            Console.Write("Added relationship between incident 1 and contact 1, ");


            Account account1 = new Account
            {
                Name          = "Coho Winery",
                Address1_Name = "Coho Vineyard & Winery",
                Address1_City = "Redmond"
            };

            _accountId1 = service.Create(account1);

            Console.Write("Created a sample account 1: {0}, ", account1.Name);

            Incident incident2 = new Incident
            {
                Title          = "Test Case 2",
                PriorityCode   = new OptionSetValue(1),      // 1 = High
                CaseOriginCode = new OptionSetValue(1),      // 1 = Phone
                CaseTypeCode   = new OptionSetValue(2),      // 2 = Problem
                Description    = "Description for Sample Case 2.",
                FollowupBy     = DateTime.Now.AddHours(3.0), // follow-up in 3 hours
                CustomerId     = new EntityReference(Contact.EntityLogicalName, _contactId1)
            };

            _incidentId2 = service.Create(incident2);

            Console.Write("Created a sample incident 2: {0}, ", incident2.Title);

            Relationship relationship2 = new Relationship("incident_customer_accounts");
            EntityReferenceCollection relatedEntities2 = new EntityReferenceCollection();

            relatedEntities2.Add(new EntityReference(Account.EntityLogicalName, _accountId1));
            service.Associate(Incident.EntityLogicalName, _incidentId2, relationship2, relatedEntities2);

            Console.Write("Added relationship between incident 2 and account 1, ");

            Lead lead = new Lead()
            {
                FirstName = "Diogo",
                LastName  = "Andrade"
            };

            _leadId = service.Create(lead);
            Console.Write("Created a sample Lead: {0} ", lead.FirstName + " " + lead.LastName);

            Account account2 = new Account
            {
                Name              = "Contoso Ltd",
                ParentAccountId   = new EntityReference(Account.EntityLogicalName, _accountId1),
                Address1_Name     = "Contoso Pharmaceuticals",
                Address1_City     = "Redmond",
                OriginatingLeadId = new EntityReference(Lead.EntityLogicalName, _leadId)
            };

            _accountId2 = service.Create(account2);

            Console.Write("Created a sample account 2: {0}, ", account2.Name);

            Relationship relationship3 = new Relationship("account_primary_contact");
            EntityReferenceCollection relatedEntities3 = new EntityReferenceCollection();

            relatedEntities3.Add(new EntityReference(Account.EntityLogicalName, _accountId2));
            service.Associate(Contact.EntityLogicalName, _contactId2, relationship3, relatedEntities3);

            Console.WriteLine("Added relationship between account 2 and contact 2.");

            Console.WriteLine("Required records have been created.");
        }
コード例 #4
0
        [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

                    // Retrieve a role from CRM.
                    var query = new QueryExpression
                    {
                        EntityName = Role.EntityLogicalName,
                        ColumnSet  = new ColumnSet("roleid"),
                        Criteria   = new FilterExpression
                        {
                            Conditions =
                            {
                                // You would replace the condition below with an actual role
                                // name, or skip this query if you had a role id.
                                new ConditionExpression
                                {
                                    AttributeName = "name",
                                    Operator      = ConditionOperator.Equal,
                                    Values        = { _roleName }
                                }
                            }
                        }
                    };

                    var role = service.RetrieveMultiple(query).Entities.
                               Cast <Role>().First();


                    // 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 role to team");
                    //</snippetAssignSecurityRoleToTeam1>

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    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);
            }
        }
コード例 #5
0
        public static void AssignAccessTeam()
        {
            Entity entTeam = new Entity("team");

            entTeam.Attributes["name"] = "test unit";
            entTeam["businessunitid"]  = new EntityReference("businessunit", new Guid("7DFC241C-06DA-E911-AA24-000D3A3ABDB6"));
            Guid teamId = svc.Create(entTeam);


            Console.WriteLine("Created {0}", entTeam.Attributes["name"]);

            // Add the role to the team.
            svc.Associate(
                "team",
                teamId,
                new Relationship("teamroles_association"),
                new EntityReferenceCollection()
            {
                new EntityReference("role", new Guid("81FC241C-06DA-E911-AA24-000D3A3ABDB6"))
            });

            Console.WriteLine("Assigned team to role");

            // 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)svc.Execute(
                        retrieveTeamPrivilegesRequest);

                foreach (RolePrivilege rp in
                         retrieveTeamPrivilegesResponse.RolePrivileges)
                {
                    if (rp.PrivilegeId == new Guid("81FC241C-06DA-E911-AA24-000D3A3ABDB6"))
                    {
                        teamLacksPrivilege = false;
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.CurrentThread.Join(500);
                    }
                }
            }

            AssignRequest assignRequest = new AssignRequest()
            {
                Assignee = new EntityReference("team", teamId),
                Target   = new EntityReference("madmv_ma_application", new Guid("6d52f446-38ec-e911-a812-000d3a3349d4")) // app 1469
            };



            svc.Execute(assignRequest);

            Console.WriteLine("The account is owned by the team.");
        }
コード例 #6
0
 public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     _service.Associate(entityName, entityId, relationship, relatedEntities);
 }
コード例 #7
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);

                    #region Demonstrate
                    // Associate the accounts to the contact record.

                    // Create a collection of the entities that will be
                    // associated to the contact.
                    var relatedEntities = new EntityReferenceCollection();
                    relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account1Id));
                    relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account2Id));
                    relatedEntities.Add(new EntityReference(Account.EntityLogicalName, _account3Id));

                    // Create an object that defines the relationship between the contact and account.
                    var relationship = new Relationship("account_primary_contact");


                    //Associate the contact with the 3 accounts.
                    service.Associate(Contact.EntityLogicalName, _contactId, relationship,
                                      relatedEntities);

                    Console.WriteLine("The entities have been associated.");

                    //Disassociate the records.
                    service.Disassociate(Contact.EntityLogicalName, _contactId, relationship,
                                         relatedEntities);

                    Console.WriteLine("The entities have been disassociated.");
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                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();
            }
        }
コード例 #8
0
        [STAThread] // Required to support the interactive login experience
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    // Create any entity records that the demonstration code requires
                    SetUpSample(service);
                    #region Demonstrate

                    // 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 = service.RetrieveMultiple(query);
                    if (roles.Entities.Count > 0)
                    {
                        Role salesRole = service.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)
                        {
                            service.Associate(
                                "systemuser",
                                _userId,
                                new Relationship("systemuserroles_association"),
                                new EntityReferenceCollection()
                            {
                                new EntityReference(Role.EntityLogicalName, _roleId)
                            });

                            Console.WriteLine("Role is associated with the user.");
                        }
                    }
                    #endregion Demonstrate

                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service";
                    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();
            }
        }
コード例 #9
0
        /// <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 static void CreateRequiredRecords(CrmServiceClient service)
        {
            // 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.
            var queryDefaultBusinessUnit = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   = new FilterExpression()
            };

            queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid",
                                                           ConditionOperator.Null);

            var 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.
            var 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.
            var 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.
            var 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"]);

            // Add the prvReadAccount privilege to the example roles to assure the
            // team can read accounts.
            var addPrivilegesRequest = new AddPrivilegesRoleRequest
            {
                RoleId     = _roleId,
                Privileges = new[]
                {
                    // Grant prvReadAccount privilege.
                    new RolePrivilege
                    {
                        PrivilegeId = readAccountPrivilege.Id
                    }
                }
            };

            service.Execute(addPrivilegesRequest);

            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");

            // 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)
            {
                var retrieveTeamPrivilegesRequest =
                    new RetrieveTeamPrivilegesRequest
                {
                    TeamId = _teamId
                };

                var 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);
                    }
                }
            }

            return;
        }
 public void Associate(string entityName, Guid entityId, Relationship relationship, EntityReferenceCollection relatedEntities)
 {
     Retry(() => { CrmServiceClient.Associate(entityName, entityId, relationship, relatedEntities); return(true); });
 }
コード例 #11
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Creates the email activity.
        /// </summary>
        public static void CreateRequiredRecords(CrmServiceClient service)
        {
            var QueueViewType = new
            {
                Public  = 0,
                Private = 1
            };

            // Create a queue instance and set its property values.
            var 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 = service.Create(newQueue);
            Console.WriteLine("Created {0}", newQueue.Name);

            // Retrieve the default business unit for the creation of the team and role.
            var queryDefaultBusinessUnit = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   = new FilterExpression
                {
                    Conditions =
                    {
                        new ConditionExpression
                        {
                            AttributeName = "parentbusinessunitid",
                            Operator      = ConditionOperator.Null
                        }
                    }
                }
            };

            var defaultBusinessUnit = (BusinessUnit)service.RetrieveMultiple(
                queryDefaultBusinessUnit).Entities[0];

            // Create a new example team.
            var setupTeam = new Team
            {
                Name           = "Example Team",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.BusinessUnitId.Value)
            };

            _teamId = service.Create(setupTeam);
            Console.WriteLine("Created {0}", setupTeam.Name);

            // Create a new example role.
            var setupRole = new Role
            {
                Name           = "Example Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.BusinessUnitId.Value)
            };

            _roleId = service.Create(setupRole);
            Console.WriteLine("Created {0}", setupRole.Name);

            // Retrieve the prvReadQueue and prvAppendToQueue privileges.
            var 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 =
                service.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.
            var addPrivilegesRequest = new AddPrivilegesRoleRequest
            {
                RoleId     = _roleId,
                Privileges = rolePrivileges.ToArray()
            };

            service.Execute(addPrivilegesRequest);
            Console.WriteLine("Retrieved privileges are added to {0}.", setupRole.Name);


            // Add the example role to the example team.
            service.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)service.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;
        }