Posts Tagged ‘queryexpression’

Reading LinkEntity attributes using Query Expression in CRM 2011

October 25, 2012 4 comments

Assume you have to retrieve

  • All the “Contact” records with fields  “Full Name, Address1_City”
  • Along with ‘Account Number’ field of ‘Account’ whom the contacts are associated with.

Relationship between Contact & Account

In CRM, there is out of the box 1:N relationship between Account & Contact.

  • Contact has ‘ParentCustomerId’ field as foreignkey of ‘Account’ entity
  • ‘Account’ entity’s primary field is ‘AccountId’

Preparing Query Expression

  • To get the ‘Contact’ attributes along with LinkEntity (i.e.,Account) attributes (i.e., Account Number),  we will write a Query Expression with (Entity as ‘Contact’ and LinkEntity as ‘Account’)
  • To read LinkEntity attribute’s we have to read the attribute along with ‘EntityAlias’ of LinkEntity (i.e., EntityAlias.AttributeName)

Below is the query expression 

 var query = new QueryExpression(“contact”);

var columnNames = new[] { “fullname”,”address1_city” };

query.ColumnSet = new ColumnSet(columnNames);

// ‘Account’ as LinkEntity

var colsAccount = new[] { “accountnumber” };

LinkEntity linkEntityAccount = new LinkEntity() {

LinkFromEntityName = “contact”,

LinkFromAttributeName = “parentcustomerid”,

LinkToEntityName = “account”,

LinkToAttributeName = “accountid”,

JoinOperator = JoinOperator.Inner,

Columns = new ColumnSet(colsAccount),

EntityAlias = “aliasAccount



// Execute Query using RetrieveMultiple

EntityCollection contacts = this.service.RetrieveMultiple(query);

if (contacts != null) {

foreach (var targetEntity in contacts.Entities) {

// Read “Account Number” along with Alias

var accountNumber = getAttributeValue(targetEntity, “aliasAccount.accountnumber“);

var contactFullname = getAttributeValue(targetEntity, “fullname”);



/// <summary>

/// Generic function to get value from attribute

/// </summary>

private string getAttributeValue(Entity targetEntity, string attributeName) {

if (string.IsNullOrEmpty(attributeName)) {

return string.Empty;


if (targetEntity[attributeName] is AliasedValue) {

return (targetEntity[attributeName] as AliasedValue).Value.ToString();


else {

return targetEntity[attributeName].ToString();



return string.Empty;




Setting default view using Plug-in’s in CRM 2011

January 17, 2012 7 comments


We often get the requirement to set a default view based on some criteria (Ex – Could be based on logged in user role, etc…). We can achieve this using a Plug-in.

Little insight :-

  • When you click on an entity (i.e., ‘Contacts’ in my sample) in CRM application, In the background a “RetreieveMultiple” method call  happens on “savedquery” entity.

'Contacts' link

  • “savedquery” is a system entity in CRM which stores the meta data of all the views in the system

Plug-in Logic :-

  • We register a Plug-in for the RetreieveMultiple message on the savedquery entity to be executed in the post stage
  • From “Outputparameters” fetch the “BusinessEntityCollection” (i.e., Views of particular entity)
  • Loop through the views and set “isdefault” property to “true” for the desired view

–          Below is the sample code

public void Execute(IServiceProvider serviceProvider)


this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

var service = serviceFactory.CreateOrganizationService(this.context.UserId);

if (this.context.InputParameters.Contains(“Query”) && this.context.InputParameters[“Query”] is QueryExpression && this.context.Stage == 40){

var qe = (QueryExpression)this.context.InputParameters[“Query”];

if (qe.Criteria != null) {

var condition = (ConditionExpression)qe.Criteria.Conditions[1];

// “Type code” of entity you want default views ( Object type code of ‘contact’ is 2)

//  Refer Useful article on how to get “Object Type Code”

if (condition.Values[0].Equals(2)) {

// Name of the view you want to set as Default

string ourDefaultView = “My custom view – Contacts”;

if (!string.IsNullOrEmpty(ourDefaultView)){

var collection = (EntityCollection)this.context.OutputParameters[“BusinessEntityCollection”];

collection = ChangeViewCollection(ourDefaultView, collection);

this.context.OutputParameters[“BusinessEntityCollection”] = collection;




/// <summary>

/// Setting IsDefault property of views

/// </summary>

private EntityCollection ChangeViewCollection(string ourDefaultViewName, EntityCollection records){

foreach (Entity record in records.Entities){

string viewName = (string)record[“name”];

if (viewName.Equals(ourDefaultViewName)){

record[“isdefault”] = new bool();

record[“isdefault”] = true;


else {

record[“isdefault”] = new bool();

record[“isdefault”] = false;



return records;


Plug-in Registration Steps :-

Message Name – RetrieveMultiple

Entity – SavedQuery

Stage – post

  • Register the assembly & Refresh the CRM application

@@ 🙂 Here goes my 50th article. Thanks for all your visits and valuable comments 🙂 @@