Sunday, September 06, 2009

Overriding Records per page count for Microsoft Dynamics CRM 4.0

I've decided to use idea and code from one of my previous posts.

Idea:
1. Add field to user entity which will contain count of records to show.
2. Replace system-defined count of records with value from 1 trough catching and handling Execute message.


Field:





Code of the plugin:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using System.Xml;
using Microsoft.Crm.SdkTypeProxy;
using Microsoft.Crm.Sdk.Query;

namespace RecordPerPage
{
public class RecordCounterExtender : IPlugin
{
#region IPlugin Members

public void Execute(IPluginExecutionContext context)
{
if (context.MessageName == "Execute" && context.InputParameters.Contains("FetchXml"))
{
//I create a crmservice instance
ICrmService crmservice = context.CreateCrmService(true);

//I form a query to retrieve field with count of records
TargetRetrieveDynamic target = new TargetRetrieveDynamic();
target.EntityId = context.UserId;
target.EntityName = EntityName.systemuser.ToString();

RetrieveRequest request = new RetrieveRequest();
request.ColumnSet = new ColumnSet(new string[] { "new_recordscount" });
request.Target = target;
request.ReturnDynamicEntities = true;

//I retrieve field
DynamicEntity currentuser = (DynamicEntity)((RetrieveResponse)crmservice.Execute(request)).BusinessEntity;

//If the field is empty it would not be in response
//and this must be handled
if (currentuser.Properties.Contains("new_recordscount"))
{
//I create document to manipulate request query
XmlDocument indoc = new XmlDocument();
indoc.LoadXml((string)context.InputParameters["FetchXml"]);

//There can not be such attribute
//and this must be handled
if (indoc.DocumentElement.Attributes["count"] != null)
{
//I replace standard value with field from user form
indoc.DocumentElement.Attributes["count"].Value = ((CrmNumber)currentuser["new_recordscount"]).Value.ToString();
//and return modified request to the context
context.InputParameters["FetchXml"] = indoc.OuterXml;
}
}
}
}

#endregion
}
}


Step registration:



Demonstration:






And source code and customization: