This documentation is archived and is not being maintained.

Build Query Expressions

Forefront
banner art

[Applies to: Microsoft Dynamics CRM 4.0]

Find the latest SDK documentation: CRM 2015 SDK

This sample shows how to write code to perform the function of the following APIs that are deprecated.

  • RetrieveByPrincipal
  • RetrieveByOrganization
  • RetrieveBySubContacts

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\Query\HowToRetrieveMultiple.cs
Server\HowTo\VB\Query\HowToRetrieveMultiple.vb

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

Example

[C#]
using System;
using System.Web.Services.Protocols;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
    // Using following Microsoft Dynamics CRM namespace(s) in the sample.
    using CrmSdk;

   /// <summary>
   /// This Sample shows how to perform retrieveby methods that have been deprecated using RetrieveMultiple
   ///  -use RetrieveMultiple to carry out a RetrieveByPrincipal command
   ///  -use RetrieveMultiple to carry out a RetrieveByOrganization command
   ///  -use RetrieveMultiple to carry out a RetrieveBySubContacts command.
   /// </summary>
   public class HowToRetrieveMultiple
   {
        static void Main(string[] args)
        {
            try
            {
                // TODO: Change the server URL and Organization to match your 
                //  CRM Server and CRM Organization
                HowToRetrieveMultiple.Run("http://localhost:5555", "CRM_Organization");
                Console.WriteLine("RetrieveByPrincipal, RetrieveByOrganization" +
                "and RetrieveBySubContacts messages retrieved successfully.");
            }
            catch (SoapException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Detail.InnerText);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    SoapException se = ex.InnerException as SoapException;
                    if (se != null)
                        Console.WriteLine(se.Detail.InnerText);
                }
            }
            finally
            {
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
      
      public static bool Run(string crmServerUrl, string orgName)
      {
            // Set up the CRM Service.
            CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
            // Cache credentials so each request does not have to be re-authenticated.
            service.PreAuthenticate = true;

         #region Setup Data Required for this Sample
         
            bool success = false;
            
            // Get user information.
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

            // Get the organizationId.
            TargetRetrieveBusinessUnit targetGetBusinessUnit = new TargetRetrieveBusinessUnit();
            targetGetBusinessUnit.EntityId = user.BusinessUnitId;

            RetrieveRequest getBusinessUnit = new RetrieveRequest();
            getBusinessUnit.Target = targetGetBusinessUnit;
            // Be aware that using AllColumns may adversely affect
            // performance and cause unwanted cascading in subsequent 
            // updates. A best practice is to retrieve the least amount of 
            // data required.
            getBusinessUnit.ColumnSet = new AllColumns();

            RetrieveResponse businessUnitResponse = (RetrieveResponse)service.Execute(getBusinessUnit);
            Lookup org = ((businessunit)businessUnitResponse.BusinessEntity).organizationid;

            Guid organizationId = org.Value;

            // Create a sample account.
            account accountCreate = new account();
            accountCreate.name = "Fourth Coffee";

            TargetCreateAccount targetCreate = new TargetCreateAccount();
            targetCreate.Account = accountCreate;

            CreateRequest create = new CreateRequest();
            create.Target = targetCreate;

            CreateResponse created = (CreateResponse)service.Execute(create);

            Guid accountId = created.id;

            //Create contact
            contact contactCreate = new contact();
            contactCreate.firstname = "Oliveira";
            contactCreate.lastname = "Leonardo";
            //Set the account created above to be the parent account for the contact
            Customer parentCustomer = new Customer();
            parentCustomer.type = "account";
            parentCustomer.Value = accountId;
            contactCreate.parentcustomerid = parentCustomer;

            TargetCreateContact targetCreateContact = new TargetCreateContact();
            targetCreateContact.Contact = contactCreate;

            CreateRequest createContactRequest = new CreateRequest();
            createContactRequest.Target = targetCreateContact;

            CreateResponse createdContact = (CreateResponse)service.Execute(createContactRequest);

            #endregion
 
         #region RetrieveByPrincipal
         // The following code example demonstrates how to use RetrieveMultiple 
            // to carry out a RetrieveByPrincipal.

         // Sets the principalId to be the principal.
            //SDK: Guid principalId = new Guid("2aa418c2-82ff-dd11-95c2-00155da4c706"); 
            Guid principalId = user.UserId;
      
         // Create a column set holding the names of the columns to be retrieved.
         ColumnSet colsPrincipal = new ColumnSet();

         // Set the properties of the column set.
         colsPrincipal.Attributes = new string [] {"name", "accountid"};

         // Create a ConditionExpression.
         ConditionExpression conditionPrincipal = new ConditionExpression();

         // Set the ConditionExpressions properties so that the condition is true when the 
         // ownerid of the account equals the principalId.
         conditionPrincipal.AttributeName = "ownerid";
         conditionPrincipal.Operator = ConditionOperator.Equal;
         conditionPrincipal.Values = new object [1];
            conditionPrincipal.Values[0] = principalId;

         // Create the FilterExpression.
         FilterExpression filterPrincipal = new FilterExpression();

         // Set the properties of the FilterExpression.
         filterPrincipal.FilterOperator = LogicalOperator.And;
         filterPrincipal.Conditions = new ConditionExpression[] {conditionPrincipal};

         // Create the QueryExpression.
         QueryExpression queryPrincipal = new QueryExpression();

         // Set the properties of the QueryExpression.
         queryPrincipal.EntityName = EntityName.account.ToString();
         queryPrincipal.ColumnSet = colsPrincipal;
         queryPrincipal.Criteria = filterPrincipal;

         // Create the request object.
         RetrieveMultipleRequest retrievePrincipal = new RetrieveMultipleRequest();

         // Set the properties of the request object.
         retrievePrincipal.Query = queryPrincipal;
      
         // Execute the request.
         RetrieveMultipleResponse principalResponse = 
                (RetrieveMultipleResponse) service.Execute(retrievePrincipal);
         #endregion

         #region RetrieveByOrganization
         // The following code example demonstrates how to use RetrieveMultiple 
            // to carry out a RetrieveByOrganization.

         // Create a column set that holds the names of the columns to be retrieved.
         ColumnSet colsOrganization = new ColumnSet();
         colsOrganization.Attributes = new string [] {"fullname", "systemuserid"};

         // Create a ConditionExpression.
         ConditionExpression conditionUsersInOrganization = new ConditionExpression();

         // Set the ConditionExpressions properties so that the condition is true when
         // the organizationid of the user is equal to the organizationId.
         conditionUsersInOrganization.AttributeName = "organizationid";
         conditionUsersInOrganization.Operator = ConditionOperator.Equal;
         conditionUsersInOrganization.Values = new object [1];
            // SDK: conditionUsersInOrganization.Values[0] = new Guid("435547a3-10e4-dd11-acef-00155da4c70}");
         conditionUsersInOrganization.Values[0] = organizationId;

         // Create the FilterExpression.
         FilterExpression filterUsersInOrganization = new FilterExpression();

         // Set the properties of the FilterExpression.
         filterUsersInOrganization.FilterOperator = LogicalOperator.And;
         filterUsersInOrganization.Conditions = new ConditionExpression[] {conditionUsersInOrganization};

         // Create the QueryExpression.
         QueryExpression queryUsersInOrganization = new QueryExpression();
         
         // Set the properties of the QueryExpression.
         queryUsersInOrganization.EntityName = EntityName.systemuser.ToString();
         queryUsersInOrganization.ColumnSet = colsOrganization;
         queryUsersInOrganization.Criteria = filterUsersInOrganization;

         // Create the request object.
         RetrieveMultipleRequest retrieveUsersInOrganization = new RetrieveMultipleRequest();

         // Set the properties of the request object.
         retrieveUsersInOrganization.Query = queryUsersInOrganization;
      
         // Execute the request.
         RetrieveMultipleResponse retrievedUsers = 
                (RetrieveMultipleResponse) service.Execute(retrieveUsersInOrganization);
         #endregion

         #region RetrieveBySubContacts
         // The following code example demonstrates how to use RetrieveMultiple 
            // to carry out a RetrieveBySubContacts command.

            // Create a column set that holds the names of the columns to be retrieved.
         ColumnSet colsContact = new ColumnSet();
         colsContact.Attributes = new string [] {"fullname", "contactid"};

         // Create the ConditionExpression.
         ConditionExpression conditionContact = new ConditionExpression();
         
         // Set the ConditionExpressions Properties so that the condition is true when
         // the accountid or the contact is equal to accountId.
         conditionContact.AttributeName = "accountid";
         conditionContact.Operator = ConditionOperator.Equal;
            // SDK: conditionContact.Values = new string [] {"f0df7fbf-b51f-de11-892f-00155da4c706"};
         conditionContact.Values = new string [] {accountId.ToString()};

         // Create the FilterExpression.
         FilterExpression filterContact = new FilterExpression();

         // Set the properties of the FilterExpression.
         filterContact.FilterOperator = LogicalOperator.And;
         filterContact.Conditions = new ConditionExpression[] {conditionContact};

         // Create the QueryExpression.
         QueryExpression queryContact = new QueryExpression();

         // Set the properties of the QueryExpression.
         queryContact.EntityName = EntityName.contact.ToString();
         queryContact.ColumnSet = colsContact;
         queryContact.Criteria = filterContact;
      
         // Retrieve the contacts.
         BusinessEntityCollection contacts = service.RetrieveMultiple(queryContact);
         #endregion

         #region check success

         if ((principalResponse.BusinessEntityCollection.EntityName.ToLower().Equals("account")) &&
            (retrievedUsers.BusinessEntityCollection.EntityName.ToLower().Equals("systemuser")) &&
            (contacts.EntityName.ToLower().Equals("contact")))
         {
            success = true;
         }
         #endregion

            #region Remove Data Required for this Sample

            service.Delete(EntityName.contact.ToString(), createdContact.id);
            service.Delete(EntityName.account.ToString(), accountId);

            #endregion


         return success;
      }
   }
}
[Visual Basic .NET]
Imports System
Imports System.Web.Services.Protocols
Imports Microsoft.Crm.Sdk.Utility

Imports CrmSdk
Namespace Microsoft.Crm.Sdk.HowTo
    ' Using following Microsoft Dynamics CRM namespace(s) in the sample.

    ''' <summary>
    ''' This Sample shows how to perform retrieveby methods that have been deprecated using RetrieveMultiple
    '''  -use RetrieveMultiple to carry out a RetrieveByPrincipal command
    '''  -use RetrieveMultiple to carry out a RetrieveByOrganization command
    '''  -use RetrieveMultiple to carry out a RetrieveBySubContacts command.
    ''' </summary>
    Public Class HowToRetrieveMultiple
        Shared Sub Main(ByVal args() As String)
            Try
                ' TODO: Change the server URL and Organization to match your 
                '  CRM Server and CRM Organization
                HowToRetrieveMultiple.Run("http://localhost:5555", "CRM_Organization")
                Console.WriteLine("RetrieveByPrincipal, RetrieveByOrganization" & _
                        "and RetrieveBySubContacts messages retrieved successfully.")
            Catch ex As SoapException
                Console.WriteLine("The application terminated with an error.")
                Console.WriteLine(ex.Message)
                Console.WriteLine(ex.Detail.InnerText)
            Catch ex As System.Exception
                Console.WriteLine("The application terminated with an error.")
                Console.WriteLine(ex.Message)

                ' Display the details of the inner exception.
                If ex.InnerException IsNot Nothing Then
                    Console.WriteLine(ex.InnerException.Message)

                    Dim se As SoapException = TryCast(ex.InnerException, SoapException)
                    If se IsNot Nothing Then
                        Console.WriteLine(se.Detail.InnerText)
                    End If
                End If
            Finally
                Console.WriteLine("Press <Enter> to exit.")
                Console.ReadLine()
            End Try
        End Sub

        Public Shared Function Run(ByVal crmServerUrl As String, ByVal orgName As String) As Boolean
            ' Set up the CRM Service.
            Dim service As CrmService = CrmServiceUtility.GetCrmService(crmServerUrl, orgName)
            ' Cache credentials so each request does not have to be re-authenticated.
            service.PreAuthenticate = True

            '         #Region "Setup Data Required for this Sample"

            Dim success As Boolean = False

            ' Get user information.
            Dim userRequest As New WhoAmIRequest()
            Dim user As WhoAmIResponse = CType(service.Execute(userRequest), WhoAmIResponse)

            ' Get the organizationId.
            Dim targetGetBusinessUnit As New TargetRetrieveBusinessUnit()
            targetGetBusinessUnit.EntityId = user.BusinessUnitId

            Dim getBusinessUnit As New RetrieveRequest()
            getBusinessUnit.Target = targetGetBusinessUnit
            ' Be aware that using AllColumns may adversely affect 
            ' performance and cause unwanted cascading in subsequent 
            ' updates.  A best practice is to retrieve the least amount of 
            ' data required.
            getBusinessUnit.ColumnSet = New AllColumns()

            Dim businessUnitResponse As RetrieveResponse = CType(service.Execute(getBusinessUnit), RetrieveResponse)
            Dim org As Lookup = (CType(businessUnitResponse.BusinessEntity, businessunit)).organizationid

            Dim organizationId As Guid = org.Value

            ' Create a sample account.
            Dim accountCreate As New account()
            accountCreate.name = "Fourth Coffee"

            Dim targetCreate As New TargetCreateAccount()
            targetCreate.Account = accountCreate

            Dim create As New CreateRequest()
            create.Target = targetCreate

            Dim created As CreateResponse = CType(service.Execute(create), CreateResponse)

            Dim accountId As Guid = created.id

            'Create contact
            Dim contactCreate As New contact()
            contactCreate.firstname = "Oliveira"
            contactCreate.lastname = "Leonardo"
            'Set the account created above to be the parent account for the contact
            Dim parentCustomer As New Customer()
            parentCustomer.type = "account"
            parentCustomer.Value = accountId
            contactCreate.parentcustomerid = parentCustomer

            Dim targetCreateContact As New TargetCreateContact()
            targetCreateContact.Contact = contactCreate

            Dim createContactRequest As New CreateRequest()
            createContactRequest.Target = targetCreateContact

            Dim createdContact As CreateResponse = CType(service.Execute(createContactRequest), CreateResponse)

            '         #End Region

            '         #Region "RetrieveByPrincipal"
            ' The following code example demonstrates how to use RetrieveMultiple 
            ' to carry out a RetrieveByPrincipal.

            ' Sets the principalId to be the principal.
            'SDK: Guid principalId = new Guid("2aa418c2-82ff-dd11-95c2-00155da4c706"); 
            Dim principalId As Guid = user.UserId

            ' Create a column set holding the names of the columns to be retrieved.
            Dim colsPrincipal As New ColumnSet()

            ' Set the properties of the column set.
            colsPrincipal.Attributes = New String() {"name", "accountid"}

            ' Create a ConditionExpression.
            Dim conditionPrincipal As New ConditionExpression()

            ' Set the ConditionExpressions properties so that the condition is true when the 
            ' ownerid of the account equals the principalId.
            conditionPrincipal.AttributeName = "ownerid"
            conditionPrincipal.Operator = ConditionOperator.Equal
            conditionPrincipal.Values = New Object(0) {}
            conditionPrincipal.Values(0) = principalId

            ' Create the FilterExpression.
            Dim filterPrincipal As New FilterExpression()

            ' Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = LogicalOperator.And
            filterPrincipal.Conditions = New ConditionExpression() {conditionPrincipal}

            ' Create the QueryExpression.
            Dim queryPrincipal As New QueryExpression()

            ' Set the properties of the QueryExpression.
            queryPrincipal.EntityName = EntityName.account.ToString()
            queryPrincipal.ColumnSet = colsPrincipal
            queryPrincipal.Criteria = filterPrincipal

            ' Create the request object.
            Dim retrievePrincipal As New RetrieveMultipleRequest()

            ' Set the properties of the request object.
            retrievePrincipal.Query = queryPrincipal

            ' Execute the request.
            Dim principalResponse As RetrieveMultipleResponse = _
            CType(service.Execute(retrievePrincipal), RetrieveMultipleResponse)
            '         #End Region

            '         #Region "RetrieveByOrganization"
            ' The following code example demonstrates how to use RetrieveMultiple 
            ' to carry out a RetrieveByOrganization.

            ' Create a column set that holds the names of the columns to be retrieved.
            Dim colsOrganization As New ColumnSet()
            colsOrganization.Attributes = New String() {"fullname", "systemuserid"}

            ' Create a ConditionExpression.
            Dim conditionUsersInOrganization As New ConditionExpression()

            ' Set the ConditionExpressions properties so that the condition is true when
            ' the organizationid of the user is equal to the organizationId.
            conditionUsersInOrganization.AttributeName = "organizationid"
            conditionUsersInOrganization.Operator = ConditionOperator.Equal
            conditionUsersInOrganization.Values = New Object(0) {}
            ' SDK: conditionUsersInOrganization.Values[0] = new Guid("435547a3-10e4-dd11-acef-00155da4c70}");
            conditionUsersInOrganization.Values(0) = organizationId

            ' Create the FilterExpression.
            Dim filterUsersInOrganization As New FilterExpression()

            ' Set the properties of the FilterExpression.
            filterUsersInOrganization.FilterOperator = LogicalOperator.And
            filterUsersInOrganization.Conditions = New ConditionExpression() {conditionUsersInOrganization}

            ' Create the QueryExpression.
            Dim queryUsersInOrganization As New QueryExpression()

            ' Set the properties of the QueryExpression.
            queryUsersInOrganization.EntityName = EntityName.systemuser.ToString()
            queryUsersInOrganization.ColumnSet = colsOrganization
            queryUsersInOrganization.Criteria = filterUsersInOrganization

            ' Create the request object.
            Dim retrieveUsersInOrganization As New RetrieveMultipleRequest()

            ' Set the properties of the request object.
            retrieveUsersInOrganization.Query = queryUsersInOrganization

            ' Execute the request.
            Dim retrievedUsers As RetrieveMultipleResponse = _
            CType(service.Execute(retrieveUsersInOrganization), RetrieveMultipleResponse)
            '         #End Region

            '         #Region "RetrieveBySubContacts"
            ' The following code example demonstrates how to use RetrieveMultiple 
            ' to carry out a RetrieveBySubContacts command.

            ' Create a column set that holds the names of the columns to be retrieved.
            Dim colsContact As New ColumnSet()
            colsContact.Attributes = New String() {"fullname", "contactid"}

            ' Create the ConditionExpression.
            Dim conditionContact As New ConditionExpression()

            ' Set the ConditionExpressions Properties so that the condition is true when
            ' the accountid or the contact is equal to accountId.
            conditionContact.AttributeName = "accountid"
            conditionContact.Operator = ConditionOperator.Equal
            ' SDK: conditionContact.Values = new string [] {"f0df7fbf-b51f-de11-892f-00155da4c706"};
            conditionContact.Values = New String() {accountId.ToString()}

            ' Create the FilterExpression.
            Dim filterContact As New FilterExpression()

            ' Set the properties of the FilterExpression.
            filterContact.FilterOperator = LogicalOperator.And
            filterContact.Conditions = New ConditionExpression() {conditionContact}

            ' Create the QueryExpression.
            Dim queryContact As New QueryExpression()

            ' Set the properties of the QueryExpression.
            queryContact.EntityName = EntityName.contact.ToString()
            queryContact.ColumnSet = colsContact
            queryContact.Criteria = filterContact

            ' Retrieve the contacts.
            Dim contacts As BusinessEntityCollection = service.RetrieveMultiple(queryContact)
            '         #End Region

            '         #Region "check success"

            If (principalResponse.BusinessEntityCollection.EntityName.ToLower().Equals("account")) _
            AndAlso (retrievedUsers.BusinessEntityCollection.EntityName.ToLower().Equals("systemuser")) _
            AndAlso (contacts.EntityName.ToLower().Equals("contact")) Then
                success = True
            End If
            '         #End Region

            '         #Region "Remove Data Required for this Sample"

            service.Delete(EntityName.contact.ToString(), createdContact.id)
            service.Delete(EntityName.account.ToString(), accountId)

            '         #End Region


            Return success
        End Function
    End Class
End Namespace

See Also

Reference


© 2010 Microsoft Corporation. All rights reserved.


Show: