Pages

Tuesday, 1 May 2012

Create , Assign and Retrieving Field Permission in C# 2011


In this article , I am going to explain how to create Field Security Profile using FieldSecurityProfile Class
and assign profile to team or user using AssociateRequest Class

I next step , I am assigning Role Preveliage to custom entity "new_payment" using AddPrivilegesRoleRequest class and assign
Field permission to specific attribute of "new_payment" entity

In last step , Retrieving user assigned Profile and permission of Security Profile

Namespace need to include

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;



Code to create Field Profile and assign to user or team and retrieving  user all permission

Code to retrieve the security role

    QueryExpression roleQuery = new QueryExpression
    {
        EntityName = Role.EntityLogicalName,
        ColumnSet = new ColumnSet("roleid"),
        Criteria =
        {
            Conditions =
            {
               new ConditionExpression("name", ConditionOperator.Equal,
                 "Marketing Manager")
             }
         }
     };
     Role role = (Role)_serviceProxy.RetrieveMultiple(roleQuery).Entities[0];
     Guid _roleId = role.Id;



Code to retrieve the default business unit

    QueryExpression _bu = new QueryExpression
    {
       EntityName = BusinessUnit.EntityLogicalName,
       ColumnSet = new ColumnSet("businessunitid"),
       Criteria =
       {
            Conditions =
            {
                 new ConditionExpression("parentbusinessunitid", ConditionOperator.Null)
            }
       }
    };
    BusinessUnit _BU = (BusinessUnit)_serviceProxy.RetrieveMultiple(
                    _bu).Entities[0];



Code to create team

    Team _team = new Team
    {
        Name = "ITSoft Management Team",
        BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, _BU.Id)
    };
    Guid _teamId = _serviceProxy.Create(_team);


Code to create Field Security Profile

    FieldSecurityProfile managersProfile = new FieldSecurityProfile();
    managersProfile.Name = "Managers";
    Guid _profileId = _serviceProxy.Create(managersProfile);


Code to Add team to Field Security Profile

    AssociateRequest teamToProfile = new AssociateRequest()
    {
       Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                        _profileId),
       RelatedEntities = new EntityReferenceCollection()
       {
             new EntityReference(Team.EntityLogicalName, _teamId)
       },
       Relationship = new Relationship("teamprofiles_association")
    };
    _serviceProxy.Execute(teamToProfile);




Code to Add team to Field Security Profile

    AssociateRequest teamToProfile = new AssociateRequest()
    {
       Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                        _profileId),
       RelatedEntities = new EntityReferenceCollection()
       {
             new EntityReference(Team.EntityLogicalName, _teamId)
       },
       Relationship = new Relationship("teamprofiles_association")
    };
    _serviceProxy.Execute(teamToProfile);



Code to Add user to Field Security Profile

    AssociateRequest userToProfile = new AssociateRequest()
    {
       Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                        _profileId),
       RelatedEntities = new EntityReferenceCollection()
       {
           new EntityReference(SystemUser.EntityLogicalName, _userId)
       },
       Relationship = new Relationship("systemuserprofiles_association")
    };
    _serviceProxy.Execute(userToProfile);


Add privileges for the Payment entity to the Marketing Role

    RolePrivilege[] privileges = new RolePrivilege[3];
    privileges[0] = new RolePrivilege();
    privileges[0].PrivilegeId = new Guid("{9245fe4a-d402-451c-b9ed-9c1a04247482}");
    privileges[0].Depth = PrivilegeDepth.Global;

    privileges[1] = new RolePrivilege();
    privileges[1].PrivilegeId = new Guid("{3c0d501a-140b-11d1-b40f-00a0c9223196}");
    privileges[1].Depth = PrivilegeDepth.Global;

    privileges[2] = new RolePrivilege();
    privileges[2].PrivilegeId = new Guid("{4747b320-62ce-11cf-a5d6-28db04c10000}");
    privileges[2].Depth = PrivilegeDepth.Global;

    AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest()
    {
        RoleId = _roleId,
        Privileges = privileges,

    };
    AddPrivilegesRoleResponse response =
     (AddPrivilegesRoleResponse)_serviceProxy.Execute(request);



Add Field Security Profile on Attribute

    FieldPermission identityPermission = new FieldPermission()
    {
       AttributeLogicalName = "new_paymentamount",
       EntityName = "new_payment",
       CanRead = new OptionSetValue(FieldPermissionType.Allowed),
       FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId)
    };
    Guid _identityPermissionId = _serviceProxy.Create(identityPermission);



Query to obtain the field security profiles

    // Create list for storing retrieved profiles.
    List<Guid> profileIds = new List<Guid>();

    // Build query to obtain the field security profiles.
    QueryExpression qe = new QueryExpression()
    {
       EntityName = FieldSecurityProfile.EntityLogicalName,
       ColumnSet = new ColumnSet("fieldsecurityprofileid"),
       LinkEntities =
       {
          new LinkEntity
          {
              LinkFromEntityName = FieldSecurityProfile.EntityLogicalName,
              LinkToEntityName = SystemUser.EntityLogicalName,
              LinkCriteria =
              {
                   Conditions =
                   {
                      new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId)
                    }
               }
           }
        }
    };
    RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest()
    {
       Query = qe
    };
    EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute(
                    rmRequest)).EntityCollection;

    // Extract profiles from query result.
    foreach (FieldSecurityProfile profileEnt in bec.Entities)
    {
        profileIds.Add(profileEnt.FieldSecurityProfileId.Value);
    }




Retrieve attribute permissions of a FieldSecurityProfile

    DataCollection<Entity> dc;
    QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName);
    qba.AddAttributeValue("fieldsecurityprofileid", _profileId);
    qba.ColumnSet = new ColumnSet("attributelogicalname");
    dc = _serviceProxy.RetrieveMultiple(qba).Entities;



Complete Code

 using (OrganizationServiceProxy _serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri,
              serverConfig.HomeRealmUri,
              serverConfig.Credentials,
              serverConfig.DeviceCredentials))
  {
     _serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(
     new ProxyTypesBehavior());

     // Get the user from the Helper.
     Guid _userId = new Guid("2eb07ea0-7e70-11d0-a5d6-28db04c10000");


    // Retrieve the security role needed to assign to the user.
    QueryExpression roleQuery = new QueryExpression
    {
        EntityName = Role.EntityLogicalName,
        ColumnSet = new ColumnSet("roleid"),
        Criteria =
        {
            Conditions =
            {
               new ConditionExpression("name", ConditionOperator.Equal,
                 "Marketing Manager")
             }
         }
     };
     Role role = (Role)_serviceProxy.RetrieveMultiple(roleQuery).Entities[0];
     Guid _roleId = role.Id;



    // Retrieve the default business unit needed to create the team.
    QueryExpression _bu = new QueryExpression
    {
       EntityName = BusinessUnit.EntityLogicalName,
       ColumnSet = new ColumnSet("businessunitid"),
       Criteria =
       {
            Conditions =
            {
                 new ConditionExpression("parentbusinessunitid", ConditionOperator.Null)
            }
       }
    };
    BusinessUnit _BU = (BusinessUnit)_serviceProxy.RetrieveMultiple(
                    _bu).Entities[0];


    // Create Team
    Team _team = new Team
    {
        Name = "ITSoft Management Team",
        BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, _BU.Id)
    };
    Guid _teamId = _serviceProxy.Create(_team);



    // Create Field Security Profile.
    FieldSecurityProfile managersProfile = new FieldSecurityProfile();
    managersProfile.Name = "Managers";
    Guid _profileId = _serviceProxy.Create(managersProfile);



    // Add team to profile.
    AssociateRequest teamToProfile = new AssociateRequest()
    {
       Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                        _profileId),
       RelatedEntities = new EntityReferenceCollection()
       {
             new EntityReference(Team.EntityLogicalName, _teamId)
       },
       Relationship = new Relationship("teamprofiles_association")
    };
    _serviceProxy.Execute(teamToProfile);



    // Add user to the profile.
    AssociateRequest userToProfile = new AssociateRequest()
    {
       Target = new EntityReference(FieldSecurityProfile.EntityLogicalName,
                        _profileId),
       RelatedEntities = new EntityReferenceCollection()
       {
           new EntityReference(SystemUser.EntityLogicalName, _userId)
       },
       Relationship = new Relationship("systemuserprofiles_association")
    };
    _serviceProxy.Execute(userToProfile);



    // Add privileges for the Payment entity to the Marketing Role.
    RolePrivilege[] privileges = new RolePrivilege[3];
    privileges[0] = new RolePrivilege();
    privileges[0].PrivilegeId = new Guid("{9245fe4a-d402-451c-b9ed-9c1a04247482}");
    privileges[0].Depth = PrivilegeDepth.Global;

    privileges[1] = new RolePrivilege();
    privileges[1].PrivilegeId = new Guid("{3c0d501a-140b-11d1-b40f-00a0c9223196}");
    privileges[1].Depth = PrivilegeDepth.Global;

    privileges[2] = new RolePrivilege();
    privileges[2].PrivilegeId = new Guid("{4747b320-62ce-11cf-a5d6-28db04c10000}");
    privileges[2].Depth = PrivilegeDepth.Global;

    AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest()
    {
        RoleId = _roleId,
        Privileges = privileges,

    };
    AddPrivilegesRoleResponse response =
     (AddPrivilegesRoleResponse)_serviceProxy.Execute(request);

    //Add Field Security Profile on Attribute
    FieldPermission identityPermission = new FieldPermission()
    {
       AttributeLogicalName = "new_paymentamount",
       EntityName = "new_payment",
       CanRead = new OptionSetValue(FieldPermissionType.Allowed),
       FieldSecurityProfileId = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId)
    };
    Guid _identityPermissionId = _serviceProxy.Create(identityPermission);



    // Create list for storing retrieved profiles.
    List<Guid> profileIds = new List<Guid>();

    // Build query to obtain the field security profiles.
    QueryExpression qe = new QueryExpression()
    {
       EntityName = FieldSecurityProfile.EntityLogicalName,
       ColumnSet = new ColumnSet("fieldsecurityprofileid"),
       LinkEntities =
       {
          new LinkEntity
          {
              LinkFromEntityName = FieldSecurityProfile.EntityLogicalName,
              LinkToEntityName = SystemUser.EntityLogicalName,
              LinkCriteria =
              {
                   Conditions =
                   {
                      new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId)
                    }
               }
           }
        }
    };
    RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest()
    {
       Query = qe
    };
    EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute(
                    rmRequest)).EntityCollection;

    // Extract profiles from query result.
    foreach (FieldSecurityProfile profileEnt in bec.Entities)
    {
        profileIds.Add(profileEnt.FieldSecurityProfileId.Value);
    }




    // Retrieve attribute permissions of a FieldSecurityProfile.
    DataCollection<Entity> dc;
    QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName);
    qba.AddAttributeValue("fieldsecurityprofileid", _profileId);
    qba.ColumnSet = new ColumnSet("attributelogicalname");
    dc = _serviceProxy.RetrieveMultiple(qba).Entities;

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.