共用方式為


Sample: Retrieve field sharing records

 

Applies To: Dynamics CRM 2013

This sample code is for Microsoft Dynamics CRM 2013 and Microsoft Dynamics CRM Online. Download the Microsoft Dynamics CRM SDK package. It can be found in the following location in the download package:

SampleCode\CS\FieldSecurity\RetrieveUserSharedAttributePermissions.cs

SampleCode\VB\FieldSecurity\RetrieveUserSharedAttributePermissions.vb

Requirements

For more information about the requirements for running the sample code provided in this SDK, see Use the sample and helper code.

Example

This sample shows how to retrieve the PrincipalObjectAttributeAccess (field sharing) records for an entity.


// Connect to the Organization service. 
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
{
    // This statement is required to enable early bound type support.
    _serviceProxy.EnableProxyTypes();

    CreateRequiredRecords();


    #region Check if this user has prvReadPOAA
    // Get the GUID of the current user.
    WhoAmIRequest whoAmI = new WhoAmIRequest();
    Guid userLoggedId = 
        ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId;
    Console.WriteLine("User logged: " + userLoggedId);

    // Check if this user has prvReadPOAA.
    RetrieveUserPrivilegesRequest userPrivilegesRequest = 
        new RetrieveUserPrivilegesRequest();
    userPrivilegesRequest.UserId = userLoggedId;
    RetrieveUserPrivilegesResponse userPrivilegesResponse =
        (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest);

    // Fixed the GUID for prvReadPOAA.
    Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}");

    if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA)))
    {
        Console.WriteLine("This user DOES have prvReadPOAA");
    }
    else
    {
        Console.WriteLine("This user DOESN'T have prvReadPOAA");
    }
    Console.WriteLine();
    #endregion Check if this user has prvReadPOAA
    #region Create an account record

    // Create an account record
    Account accountRecord = new Account();
    accountRecord.Name = "Ane";
    accountRecord["secret_phone"] = "123456";
    _accountRecordId = _serviceProxy.Create(accountRecord);
    Console.WriteLine("Account record created.");

    #endregion Create an account record

    #region Create POAA entity for field #1

    // Create POAA entity for field #1
    PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess
    {
        AttributeId = _secretHomeId,
        ObjectId = new EntityReference
            (Account.EntityLogicalName, _accountRecordId),
        PrincipalId = new EntityReference
            (SystemUser.EntityLogicalName, userLoggedId),
        ReadAccess = true,
        UpdateAccess = true
    };

    _serviceProxy.Create(poaa);
    Console.WriteLine("POAA record for custom field Secret_Home created.");

    #endregion Create POAA entity for field #1

    #region Create POAA entity for field #2

    // Create POAA entity for field #2
    poaa = new PrincipalObjectAttributeAccess
    {
        AttributeId = _secretPhoneId,
        ObjectId = new EntityReference
            (Account.EntityLogicalName, _accountRecordId), 
        PrincipalId = new EntityReference
            (SystemUser.EntityLogicalName, userLoggedId),
        ReadAccess = true,
        UpdateAccess = true
    };

    _serviceProxy.Create(poaa);
    Console.WriteLine("POAA record for custom field Secret_Phone created.");

    #endregion Create POAA entity for field #2

    #region Retrieve User Shared Attribute Permissions
    // Create the query for retrieve User Shared Attribute permissions.
    QueryExpression queryPOAA =
        new QueryExpression("principalobjectattributeaccess");
    queryPOAA.ColumnSet = new ColumnSet
        (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" });
    queryPOAA.Criteria.FilterOperator = LogicalOperator.And;
    queryPOAA.Criteria.Conditions.Add
        (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId));
    queryPOAA.Criteria.Conditions.Add
        (new ConditionExpression("principalid", ConditionOperator.EqualUserId));

    Console.WriteLine();
    Console.WriteLine("POAA for user: " + userLoggedId.ToString());
    Console.WriteLine();

    try
    {
        // Execute the query.
        EntityCollection responsePOAA = _serviceProxy.RetrieveMultiple(queryPOAA);

        foreach (var entity in responsePOAA.Entities)
        {
            Console.WriteLine("  principalid: " + ((EntityReference)entity["principalid"]).Id);
            Console.WriteLine("  attributeid: " + entity["attributeid"].ToString());
            Console.WriteLine("  readaccess: " + entity["readaccess"].ToString());
            Console.WriteLine("  updateaccess: " + entity["updateaccess"].ToString());
            Console.WriteLine();
        }
    }
    catch (Exception exc)
    {
        Console.WriteLine("Error: " + exc.Message);
    }

    #endregion Retrieve User Shared Attribute Permissions

    DeleteRequiredRecords(promptforDelete);

}

' Connect to the Organization service. 
' The using statement assures that the service proxy will be properly disposed.
_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)
Using _serviceProxy
    ' This statement is required to enable early-bound type support.
    _serviceProxy.EnableProxyTypes()

    CreateRequiredRecords()

    '                   #Region "Check if this user has prvReadPOAA"
    ' Get the GUID of the current user.
    Dim whoAmI As New WhoAmIRequest()
    Dim userLoggedId As Guid = (CType(_serviceProxy.Execute(whoAmI), 
                                WhoAmIResponse)).UserId
    Console.WriteLine("User logged: " & userLoggedId.ToString())

    ' Check if this user has prvReadPOAA.
    Dim userPrivilegesRequest As New RetrieveUserPrivilegesRequest()
    userPrivilegesRequest.UserId = userLoggedId
    Dim userPrivilegesResponse As RetrieveUserPrivilegesResponse =
        CType(_serviceProxy.Execute(userPrivilegesRequest), RetrieveUserPrivilegesResponse)

    ' Fixed the GUID for prvReadPOAA.
    Dim prvReadPOAA As New Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}")

    If userPrivilegesResponse.RolePrivileges.Any(Function(r) r.PrivilegeId.Equals(prvReadPOAA)) Then
        Console.WriteLine("This user DOES have prvReadPOAA")
    Else
        Console.WriteLine("This user DOESN'T have prvReadPOAA")
    End If
    Console.WriteLine()
    '                   #End Region ' Check if this user has prvReadPOAA

    '                   #Region "Create an account record"

    ' Create an account record.
    Dim accountRecord As New Account()
    accountRecord.Name = "Ane"
    accountRecord("secret_phone") = "123456"
    _accountRecordId = _serviceProxy.Create(accountRecord)
    Console.WriteLine("Account record created.")

    '                   #End Region ' Create an account record

    '                   #Region "Create POAA entity for field #1"

    ' Create the POAA entity for field #1.
    Dim poaa As PrincipalObjectAttributeAccess =
        New PrincipalObjectAttributeAccess With
        {
            .AttributeId = _secretHomeId,
            .ObjectId = New EntityReference(Account.EntityLogicalName, _accountRecordId),
            .PrincipalId = New EntityReference(SystemUser.EntityLogicalName, userLoggedId),
            .ReadAccess = True,
            .UpdateAccess = True
        }

    _serviceProxy.Create(poaa)
    Console.WriteLine("POAA record for custom field Secret_Home created.")

    '                   #End Region ' Create POAA entity for field #1

    '                   #Region "Create POAA entity for field #2"

    ' Create the POAA entity for field #2.
    poaa = New PrincipalObjectAttributeAccess With
           {
               .AttributeId = _secretPhoneId,
               .ObjectId = New EntityReference(Account.EntityLogicalName, _accountRecordId),
               .PrincipalId = New EntityReference(SystemUser.EntityLogicalName, userLoggedId),
               .ReadAccess = True,
               .UpdateAccess = True
           }

    _serviceProxy.Create(poaa)
    Console.WriteLine("POAA record for custom field Secret_Phone created.")

    '                   #End Region ' Create POAA entity for field #2

    '                   #Region "Retrieve User Shared Attribute Permissions"
    ' Create the query for retrieve User Shared Attribute permissions.
    Dim queryPOAA As New QueryExpression("principalobjectattributeaccess")
    queryPOAA.ColumnSet = New ColumnSet(New String() {"attributeid", "readaccess",
                                                      "updateaccess", "principalid"})
    queryPOAA.Criteria.FilterOperator = LogicalOperator.And
    queryPOAA.Criteria.Conditions.Add(New ConditionExpression("objectid",
                                                              ConditionOperator.Equal,
                                                              _accountRecordId))
    queryPOAA.Criteria.Conditions.Add(New ConditionExpression("principalid",
                                                              ConditionOperator.EqualUserId))

    Console.WriteLine()
    Console.WriteLine("POAA for user: " & userLoggedId.ToString())
    Console.WriteLine()

    Try
        ' Execute the query.
        Dim responsePOAA As EntityCollection = _serviceProxy.RetrieveMultiple(queryPOAA)

        For Each entity In responsePOAA.Entities
            Console.WriteLine("  principalid: " & _
                              (CType(entity("principalid"), EntityReference)).Id.ToString())
            Console.WriteLine("  attributeid: " & _
                              entity("attributeid").ToString())
            Console.WriteLine("  readaccess: " & entity("readaccess").ToString())
            Console.WriteLine("  updateaccess: " & entity("updateaccess").ToString())
            Console.WriteLine()
        Next entity
    Catch exc As Exception
        Console.WriteLine("Error: " & exc.Message)
    End Try

    '                   #End Region ' Retrieve User Shared Attribute Permissions

    DeleteRequiredRecords(promptforDelete)

End Using

See Also

IOrganizationService
How field security can be used to control access to field values in Microsoft Dynamics CRM 2013
Field security entities