/// <summary>
        /// Demonstrates parallelized execution of multiple team privilege requests using generic method
        /// </summary>
        /// <param name="teamIds">The list of teams who's privileges that should be retrieved</param>
        /// <returns>The list of team privileges</returns>
        public IDictionary <Guid, RetrieveTeamPrivilegesResponse> ParallelGenericExecuteRequests(Guid[] teamIds)
        {
            IDictionary <Guid, RetrieveTeamPrivilegesResponse> responses = null;
            var requests = new Dictionary <string, RetrieveTeamPrivilegesRequest>();

            Array.ForEach(teamIds, id =>
            {
                var request = new RetrieveTeamPrivilegesRequest()
                {
                    TeamId = id
                };

                requests.Add(id.ToString(), request);
            });

            try
            {
                responses = this.Manager.ParallelProxy.Execute <RetrieveTeamPrivilegesRequest, RetrieveTeamPrivilegesResponse>(requests)
                            .ToDictionary(r => Guid.Parse(r.Key), r => r.Value);

                foreach (var response in responses)
                {
                    Console.WriteLine("Retrieves {0} privileges for team with id={1}",
                                      response.Value.RolePrivileges.Length,
                                      response.Key);
                }
            }
            catch (AggregateException ae)
            {
                // Handle exceptions
            }

            return(responses);
        }
Beispiel #2
0
        /// <summary>
        /// Retrieve the <c>privileges</c> for a team.
        /// </summary>
        /// <param name="id"><c>Team</c> Id</param>
        /// <returns>
        /// <see cref="RetrieveTeamPrivilegesResponse"/>.
        /// You can get <c>Privilege</c> list with <see cref="RetrieveTeamPrivilegesResponse.RolePrivileges"/> property.
        /// </returns>
        public RetrieveTeamPrivilegesResponse GetPrivileges(Guid id)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");

            RetrieveTeamPrivilegesRequest request = new RetrieveTeamPrivilegesRequest()
            {
                TeamId = id
            };

            return((RetrieveTeamPrivilegesResponse)this.OrganizationService.Execute(request));
        }
        private IEnumerable <RolePrivilege> GetTeamPrivileges(Guid idTeam)
        {
            var request = new RetrieveTeamPrivilegesRequest()
            {
                TeamId = idTeam,
            };

            var response = (RetrieveTeamPrivilegesResponse)_service.Execute(request);

            return(response.RolePrivileges);
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a team, a queue and a role.
        /// Add read queue privileges to the role.
        /// Assign the role to the team so that they can read the queue.
        /// Assign the queue to the team.
        /// </summary>
        public void CreateRequiredRecords()
        {
            // Instantiate a dynamic entity and set its property values.
            // See the Entity Metadata topic in the SDK documentatio to determine
            // which attributes must be set for each entity.
            Entity setupQueue = new Entity("queue");

            setupQueue["name"]        = "Example Queue";
            setupQueue["description"] = "This is an example queue.";

            // Create the queue record.
            _queueId = _service.Create(setupQueue);
            Console.WriteLine("Created {0}", setupQueue["name"]);

            // Retrieve the default business unit needed to create the team and role.
            QueryExpression queryDefaultBusinessUnit = new QueryExpression("businessunit");

            queryDefaultBusinessUnit.ColumnSet = new ColumnSet("businessunitid");
            queryDefaultBusinessUnit.Criteria  = new FilterExpression();
            queryDefaultBusinessUnit.Criteria.AddCondition("parentbusinessunitid", ConditionOperator.Null);

            Entity defaultBusinessUnit = _service.RetrieveMultiple(queryDefaultBusinessUnit).Entities[0];

            // Instantiate a dynamic entity and set its property values.
            // See the Entity Metadata topic in the SDK documentatio to determine
            // which attributes must be set for each entity.
            Entity setupTeam = new Entity("team");

            setupTeam["name"]           = "Example Team";
            setupTeam["businessunitid"] = new EntityReference("businessunit",
                                                              defaultBusinessUnit.Id);

            // Create a team record.
            _teamId = _service.Create(setupTeam);
            Console.WriteLine("Created {0}", setupTeam["name"]);

            // Instantiate a dynamic entity and set its property values.
            // See the Entity Metadata topic in the SDK documentatio to determine
            // which attributes must be set for each entity.
            Entity setupRole = new Entity("role");

            setupRole["name"]           = "Example Role";
            setupRole["businessunitid"] = new EntityReference("businessunit",
                                                              defaultBusinessUnit.Id);

            // Create a role record. Typically you would use an exisitng role that has the
            // the correct privileges. For this sample we need to be sure the role has
            // at least the privilege to read queue records.
            _roleId = _service.Create(setupRole);
            Console.WriteLine("Created {0}", setupRole["name"]);

            // Create a query expression to find the prvReadQueue Privilege and prvReadMailbox Privilege.
            QueryExpression queryReadQueuePrivilege = new QueryExpression
            {
                EntityName = "privilege",
                ColumnSet  = new ColumnSet("privilegeid", "name"),
                Criteria   = new FilterExpression()
            };

            queryReadQueuePrivilege.Criteria.AddCondition("name", ConditionOperator.In, "prvReadQueue", "prvReadMailbox");

            // Retrieve the prvReadQueue privilege and prvReadMailbox Privilege.
            DataCollection <Entity> readQueuePrivilege = _serviceProxy.RetrieveMultiple(queryReadQueuePrivilege).Entities;

            Console.WriteLine("Retrieved {0}", readQueuePrivilege.Count);

            // Define a list to hold the RolePrivileges we'll need to add
            List <RolePrivilege> rolePrivileges = new List <RolePrivilege>();

            foreach (Privilege privilege in readQueuePrivilege)
            {
                RolePrivilege rolePrivilege = new RolePrivilege(
                    (int)PrivilegeDepth.Local, privilege.PrivilegeId.Value);
                rolePrivileges.Add(rolePrivilege);
            }

            // Add the prvReadQueue and prvReadMailbox privilege to the example role.
            AddPrivilegesRoleRequest addPrivilegesRequest = new AddPrivilegesRoleRequest
            {
                RoleId     = _roleId,
                Privileges = rolePrivileges.ToArray()
            };

            _service.Execute(addPrivilegesRequest);
            Console.WriteLine("Added privilege to role");

            // Add the role to the team.
            AssociateRequest associate = new AssociateRequest()
            {
                Target          = new EntityReference(Team.EntityLogicalName, _teamId),
                RelatedEntities = new EntityReferenceCollection()
                {
                    new EntityReference(Role.EntityLogicalName, _roleId)
                },
                Relationship = new Relationship("teamroles_association")
            };

            _service.Execute(associate);

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

            // It takes some time for the privileges to propogate to the team. Delay the
            // application until the privilege has been assigned.
            bool teamLacksPrivilege = true;

            while (teamLacksPrivilege)
            {
                RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = new RetrieveTeamPrivilegesRequest
                {
                    TeamId = _teamId
                };

                RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse =
                    (RetrieveTeamPrivilegesResponse)_service.Execute(retrieveTeamPrivilegesRequest);

                foreach (Microsoft.Crm.Sdk.Messages.RolePrivilege rp in retrieveTeamPrivilegesResponse.RolePrivileges)
                {
                    if (retrieveTeamPrivilegesResponse.RolePrivileges[0].PrivilegeId == readQueuePrivilege[0].Id && retrieveTeamPrivilegesResponse.RolePrivileges[1].PrivilegeId == readQueuePrivilege[1].Id)
                    {
                        teamLacksPrivilege = false;
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.CurrentThread.Join(500);
                    }
                }
            }

            return;
        }
        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.");
        }
Beispiel #6
0
        /// <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;
        }
Beispiel #7
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 void CreateRequiredRecords()
        {
            // Instantiate an account entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine
            // which attributes must be set for each entity.
            Account setupAccount = new Account
            {
                Name = "Example Account"
            };

            // Create the account record.
            _accountId = _service.Create(setupAccount);
            Console.WriteLine("Created {0}", setupAccount.Name);

            // Retrieve the default business unit needed to create the team and role.
            QueryExpression queryDefaultBusinessUnit = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet  = new ColumnSet("businessunitid"),
                Criteria   = new FilterExpression()
            };

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

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

            // Instantiate a team entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine
            // which attributes must be set for each entity.
            Team setupTeam = new Team
            {
                Name           = "Example Team",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName,
                                                     defaultBusinessUnit.Id)
            };

            // Create a team record.
            _teamId = _service.Create(setupTeam);
            Console.WriteLine("Created {0}", setupTeam.Name);

            // Instantiate a role entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine
            // which attributes must be set for each entity.
            Role setupRole = new Role
            {
                Name           = "Example Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName,
                                                     defaultBusinessUnit.Id)
            };

            // Create a role record. Typically you would use an existing role that has the
            // the correct privileges. For this sample we need to be sure the role has
            // at least the privilege to read account records.
            _roleId = _service.Create(setupRole);
            Console.WriteLine("Created {0}", setupRole.Name);

            // Create a query expression to find the prvReadAccountPrivilege.
            QueryExpression queryReadAccountPrivilege = new QueryExpression
            {
                EntityName = Privilege.EntityLogicalName,
                ColumnSet  = new ColumnSet("privilegeid", "name"),
                Criteria   = new FilterExpression()
            };

            queryReadAccountPrivilege.Criteria.AddCondition("name",
                                                            ConditionOperator.Equal, "prvReadAccount");

            // Retrieve the prvReadAccount privilege.
            Entity readAccountPrivilege = _service.RetrieveMultiple(
                queryReadAccountPrivilege)[0];

            Console.WriteLine("Retrieved {0}", readAccountPrivilege.Attributes["name"]);

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

            _service.Execute(addPrivilegesRequest);
            //</snippetAssignRecordToTeam2>

            Console.WriteLine("Added privilege to role");

            // Add the role to the team.
            _service.Associate(
                Team.EntityLogicalName,
                _teamId,
                new Relationship("teamroles_association"),
                new EntityReferenceCollection()
            {
                new EntityReference(Role.EntityLogicalName, _roleId)
            });

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

            //<snippetAssignRecordToTeam3>
            // It takes some time for the privileges to propagate to the team. Delay the
            // application until the privilege has been assigned.
            bool teamLacksPrivilege = true;

            while (teamLacksPrivilege)
            {
                RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest =
                    new RetrieveTeamPrivilegesRequest
                {
                    TeamId = _teamId
                };

                RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse =
                    (RetrieveTeamPrivilegesResponse)_service.Execute(
                        retrieveTeamPrivilegesRequest);

                foreach (RolePrivilege rp in
                         retrieveTeamPrivilegesResponse.RolePrivileges)
                {
                    if (rp.PrivilegeId == readAccountPrivilege.Id)
                    {
                        teamLacksPrivilege = false;
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.CurrentThread.Join(500);
                    }
                }
            }
            //</snippetAssignRecordToTeam3>

            return;
        }
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create a 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;
        }
Beispiel #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 void CreateRequiredRecords()
        {
            // Instantiate an account entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine 
            // which attributes must be set for each entity.
            Account setupAccount = new Account
            {
                Name = "Example Account"
            };

            // Create the account record.
            _accountId = _service.Create(setupAccount);
            Console.WriteLine("Created {0}", setupAccount.Name);

            // Retrieve the default business unit needed to create the team and role.
            QueryExpression queryDefaultBusinessUnit = new QueryExpression
            {
                EntityName = BusinessUnit.EntityLogicalName,
                ColumnSet = new ColumnSet("businessunitid" ),
                Criteria = new FilterExpression()
            };

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

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

            // Instantiate a team entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine 
            // which attributes must be set for each entity.
            Team setupTeam = new Team
            {
                Name = "Example Team",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName,
                    defaultBusinessUnit.Id)
            };

            // Create a team record.
            _teamId = _service.Create(setupTeam);
            Console.WriteLine("Created {0}", setupTeam.Name);

            // Instantiate a role entity record and set its property values.
            // See the Entity Metadata topic in the SDK documentation to determine 
            // which attributes must be set for each entity.
            Role setupRole = new Role
            {
                Name = "Example Role",
                BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName,
                    defaultBusinessUnit.Id)
            };

            // Create a role record. Typically you would use an existing role that has the
            // the correct privileges. For this sample we need to be sure the role has
            // at least the privilege to read account records.
            _roleId = _service.Create(setupRole);
            Console.WriteLine("Created {0}", setupRole.Name);

            // Create a query expression to find the prvReadAccountPrivilege.
            QueryExpression queryReadAccountPrivilege = new QueryExpression
            {
                EntityName = Privilege.EntityLogicalName,
                ColumnSet = new ColumnSet("privilegeid", "name"),
                Criteria = new FilterExpression()
            };
            queryReadAccountPrivilege.Criteria.AddCondition("name", 
                ConditionOperator.Equal, "prvReadAccount");

            // Retrieve the prvReadAccount privilege.
            Entity readAccountPrivilege = _service.RetrieveMultiple(
                queryReadAccountPrivilege)[0];
            Console.WriteLine("Retrieved {0}", readAccountPrivilege.Attributes["name"]);

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

            Console.WriteLine("Added privilege to role");

            // Add the role to the team.
            _service.Associate(
                       Team.EntityLogicalName,
                       _teamId,
                       new Relationship("teamroles_association"),
                       new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) });

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

            //<snippetAssignRecordToTeam3>
            // It takes some time for the privileges to propagate to the team. Delay the
            // application until the privilege has been assigned.
            bool teamLacksPrivilege = true;
            while (teamLacksPrivilege)
            {
                RetrieveTeamPrivilegesRequest retrieveTeamPrivilegesRequest = 
                    new RetrieveTeamPrivilegesRequest
                {
                    TeamId = _teamId
                };

                RetrieveTeamPrivilegesResponse retrieveTeamPrivilegesResponse =
                    (RetrieveTeamPrivilegesResponse)_service.Execute(
                    retrieveTeamPrivilegesRequest);

                foreach (RolePrivilege rp in 
                    retrieveTeamPrivilegesResponse.RolePrivileges)
                {
                    if (rp.PrivilegeId == readAccountPrivilege.Id)
                    {
                        teamLacksPrivilege = false;
                        break;
                    }
                    else
                    {
                        System.Threading.Thread.CurrentThread.Join(500);
                    }
                }
            }
            //</snippetAssignRecordToTeam3>

            return;
        }