Building SQL Query using Query Expression programmatically

Today we will see how to query the data in ms crm similar to a SQL Query using Query Expression.

// Build the following SQL query using QueryExpression:
// SQL Query:
//		SELECT contact.fullname, contact.address1_telephone1
//		FROM contact
//			LEFT OUTER JOIN account
//				ON contact.parentcustomerid = account.accountid
//				AND
//				account.name = 'Litware, Inc.'
//		WHERE (contact.address1_stateorprovince = 'WA'
//		AND
//			contact.address1_city in ('Redmond', 'Bellevue', 'Kirkland', 'Seattle')
//		AND 
//			contact.address1_telephone1 like '(206)%'
//			OR
//			contact.address1_telephone1 like '(425)%'
//		AND
//			DATEDIFF(DAY, contact.createdon, GETDATE()) > 0
//		AND
//			DATEDIFF(DAY, contact.createdon, GETDATE()) < 30
//		AND
//			contact.emailaddress1 Not NULL
//			   )


Similar Query using QueryExpression:
QueryExpression query = new QueryExpression()
{
    Distinct = false,
    EntityName = Contact.EntityLogicalName,
    ColumnSet = new ColumnSet("fullname", "address1_telephone1"),
    LinkEntities = 
    {
        new LinkEntity 
        {
            JoinOperator = JoinOperator.LeftOuter,
            LinkFromAttributeName = "parentcustomerid",
            LinkFromEntityName = Contact.EntityLogicalName,
            LinkToAttributeName = "accountid",
            LinkToEntityName = Account.EntityLogicalName,
            LinkCriteria = 
            {
                Conditions = 
                {
                    new ConditionExpression("name", ConditionOperator.Equal, "Litware, Inc.")
                }
            }
        }
    },
    Criteria =
    {
        Filters = 
        {
            new FilterExpression
            {
                FilterOperator = LogicalOperator.And,
                Conditions = 
                {
                    new ConditionExpression("address1_stateorprovince", ConditionOperator.Equal, "WA"),
                    new ConditionExpression("address1_city", ConditionOperator.In, new String[] {"Redmond", "Bellevue" , "Kirkland", "Seattle"}),
                    new ConditionExpression("createdon", ConditionOperator.LastXDays, 30),
                    new ConditionExpression("emailaddress1", ConditionOperator.NotNull)
                },
            },
            new FilterExpression
            {
                FilterOperator = LogicalOperator.Or,
                Conditions =
                {
                    new ConditionExpression("address1_telephone1", ConditionOperator.Like, "(206)%"),
                    new ConditionExpression("address1_telephone1", ConditionOperator.Like, "(425)%")
                }
            }
        }
    }
};

DataCollection<Entity> entityCollection = _service.RetrieveMultiple(query).Entities;

// Display the results.
Console.WriteLine("List all contacts matching specified parameters");
Console.WriteLine("===============================================");
foreach (Contact contact in entityCollection)
{
    Console.WriteLine("Contact ID: {0}", contact.Id);
    Console.WriteLine("Contact Name: {0}", contact.FullName);
    Console.WriteLine("Contact Phone: {0}", contact.Address1_Telephone1);
}
Console.WriteLine("<End of Listing>");
Console.WriteLine();
Cheers,
PMDY

Using Pre & Post Entity images in MS CRM

Options we have to access fields that are not included in the context.

  1. Obtain a reference to Organisation Service within your plugin, and then use a Retrieve request to return the fields you need from the plugin. As the context will always contain the GUID for the record that has changed, this is generally the most common way you will see this done.
  2. Utilise either a Pre or Post Entity Image of the record, which contains the attributes that you need to access.

Previously we would be using the First option for any kind of operations.Recently though, I have been evaluating Entity Images more and more, and have begun to actively use them as part of my plugins. Entity Images are, essentially, snapshots of the CRM record that are stored on the platform either before the database operation has completed or straight after – you can decide which one you want to use, depending on what your plugin is doing. They are configured as part of deploying your plugin to your target CRM instance, and the steps involved are actually quite simple – I think it’s generally the case that they are not well-understood or utilised by developers who are learning about CRM for the first time.

So why should you go to the extra effort to use them within your plugins?

As alluded to above, using Pre Entity Images means you can get a snapshot of your CRM data before the data was changed. This may prove to be particularly invaluable in cases where you need to perform a before/after comparison on a particular field, and then execute a specific action either way. The only non-entity image way of doing this within CRM would be via hidden field that stores the current value of your field in question, which is referenced and updated once your business logic has completed. A slightly inelegant solution, and one that is questionable, given that we can utilise Entity Images instead. Having ready access to the attributes which may not necessarily be exposed to the plugin when it is executed is particularly invaluable, given that this avoids a scenario where you would have to go down option 1). Disadvantages of this approach is the potential for unnecessary delays in your plugin completing and problems with your CRM instance as a whole, if your CRM’s web services are already accessed to breaking point.

In these cases, we go with plugin images. That’s all for today.. would be sharing code related stuff about using plugin images in my next blog post..

Cheers,

PMDY