Build Query Expressions

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

  • RetrieveByPrincipal
  • RetrieveByOrganization
  • RetrieveBySubContacts



//# Building query expressions
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;

///
/// 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.
///

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