Customising the Activity Views (and other such views) via Plugins

RetrieveMultiplePluginfeatureThe Requirement

I had a requirement to display a list of activities, both open and closed on the dashboard. Simple enough I hear you say. Well, it was until I needed to include a few more fields to make the user experience better. I wanted to categorise the activities, so as well as showing the type of activity (email,phone,letter,task), I wanted to give them a short description that would make a lengthy list of activities easily readable.

The Idea

Upon looking at the activities, such as email and phone call, I noticed they had a system default field called category, of which it was a single line of text. As it was present on all of the activities, I thought I would just use it. After much time spent updating my workflows to populate these category fields with the appropriate tags, I was ready to update the view.

The Problem

Bugger, it was then that I realised that the category field was unique to each activity, and not stored on the activity pointer (the entity that you would normally use to list all types of activities in one view). The activity pointer had the subject and description fields that are shared across other activities (plus a few more), but not the category field. And to top it off, the activity pointer entity is not customisable. So, at that point I started to think about using workflows or JavaScript to just simply prepend the tags I wanted to use to the beginning of the subject line, but it soon became apparent that it was not going to be suitable as there would be too much involved with making sure manual updates to activities didn’t spoil my tagging.

I began the “google”.

The Solution

Eventually, I happened upon a possible solution using plugins. Initially I was thinking of using a create or update plugin to change the subject field. Got too confusing, but, there was light at the end of the tunnel. I began experimenting with a plugin for the RetrieveMultiple command. This is what provides data for views within Dynamics, and even the activity pointer entity can have a RetrieveMultiple plugin to intercept the data it is about to send back to the web browser allowing you to tinker with the data returned.

To begin with, using the CRM Developer Toolkit for Visual Studio 2012, I browsed to the Activity Entity in the CRM Explorer window, right clicked and selected Create Plugin. Below are the selections I made to set up the plugin.

RetrieveMultiplePlugin

After that, I just added the code (at the bottom of this post) to intercept the returned EntityCollection’s subject field, and alter it in such a way so that it has the activities category and direction fields within.

The below line gets the EntityCollection that is about to be returned to the clients Grid View from the plugins OutputParameters collection.

EntityCollection entityCollection = (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"];

I then loop through every entity, find the category from the appropriate activity entity (the activitypointer id is the same id that is stored within the email entity for example), and then modify the activitypointer’s subject attribute to include the category.

It really is that simple.

Interesting, this could be used in all kind of situations where you need to alter the displayed views (perhaps hiding fields based on security roles, or encrypting/decrypting passwords for viewing etc). One of the key uses though may be to retrieve data from other entities to include in a view that may not be possible by just using fetchxml.

Below is the Execute code to include in the plugin to achieve what I have described.

 protected void ExecutePostActivityRetrieveMultiple(LocalPluginContext localContext)
        {
            if (localContext == null)
            {
                throw new ArgumentNullException("localContext");
            }
            if (localContext.PluginExecutionContext.OutputParameters.Contains("BusinessEntityCollection"))
            {
                EntityCollection entityCollection = 
                    (EntityCollection)localContext.PluginExecutionContext.OutputParameters["BusinessEntityCollection"];
                if (true)       // This could be some form of user role check
                {
                    if (entityCollection.Entities.Count > 0)
                    {
                        Entity ActivityEntity = null;
                        foreach (Entity entity in entityCollection.Entities)
                        {
                            if (entity.Contains("activitytypecode"))
                            {
                                string type = entity.Attributes["activitytypecode"].ToString();
                                if (type != "")
                                {
                                    // These Activities have a direction field to indicate outgoing or incoming
                                    if (type == "email" || type == "letter" || type == "phonecall") 
                                        
                                        ActivityEntity = localContext.OrganizationService.Retrieve(
                                            type, entity.Id, new ColumnSet("category", "directioncode"));
                                    else
                                        ActivityEntity = localContext.OrganizationService.Retrieve(
                                            type, entity.Id, new ColumnSet("category"));
                                    if (ActivityEntity.Attributes.Contains("category"))
                                    {
                                        if (ActivityEntity.Attributes.Contains("directioncode"))
                                        {
                                            entity.Attributes["subject"] = 
                                                ActivityEntity.Attributes["category"].ToString().PadRight(30) + " - " +
                                                ((bool)ActivityEntity.Attributes["directioncode"] ? "Outgoing" : "Incoming")
                                                + " - " + entity.Attributes["subject"];
                                        }
                                        else
                                        {
                                            entity.Attributes["subject"] = 
                                                ActivityEntity.Attributes["category"].ToString().PadRight(30) + " - " + 
                                                entity.Attributes["subject"];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

LinqPad for testing plugin development and workflow activities

We all know that developing and debugging plugins with Microsoft Dynamics CRM 2011 (and 2013) can be troublesome.  Having to code blind and expecting it to work when you deploy it to your server to test it.

I have recently started using LinqPad to develop my plugin and workflow code, testing to make sure the logic works, before copying the code into Visual Studio and deploying.

LinqPad is a very handy tool that reminds me of days before where you could just write code straight into an editor, and run it, not having to create projects, and building and debugging.

Its fully extendable, and once you have it set up, makes writing straight forward C# code and Linq queries very easy.  There are a couple of ways to use it depending on if you prefer early or late bound approaches to manipulating and retrieving your Dynamics Entities.

First things first though, download and install it from the LinqPad website.

LinkPad

Install it on your machine, and run it.

There are two ways of using it, late bind and early bind.  I prefer Late bind (where you reference your entities in a generic fashion) but early bind (where you can reference your entities and attributes by name) has its uses.  For plugin development, late bind is bar far the easiest to get started with as you dont have to generate class files for your Dynamics deployment, and your assemblies are much smaller.

To set up early bind, you simply add the Dynamics URL as a data connection within LinqPad, and your ready to go.  To use late bind, you have to write some C# code to enable a connection to your Dynamics Server (but don’t worry, I am going to provide you with some sample code).

Adding a connection for Early Bind

To add a connection so that you can reference your entities via name, simply click on the Add Connection link at the top left to bring up the “Choose Data Context” window.

LinqPad2

Choose WCF Data Services 5.5 (Odata 3) and on the next screen, enter the following URI :

LinqPad3


You can leave the username and password section blank if your logged in with Active Directory, ad you can also select either XML or JSON. When you hit OK, the data connection will now appear and you can expand it out to show all of your entities, and their attributes.

LinqPad4

You can now begin writing code as long as the code window has the connection set to use the connection you have just created.

Adding a connection using custom code

In my opinion, the best way to use LinqPad is to write your own connection. If you are a registered user of LinqPad, you can use NuGet to download all of the CRM assemblies ready to roll, but I am going to go through the steps required in case you are just using the free version.

The first thing you need to do is to select the My Extensions document in the bottom left window. This is where you can write some code that will allow you to connect to Microsoft Dynamics.  I have enclosed a sample below which you should just be able to copy and paste into the window once you have set up the environment.

First things first, in the My Extensions window, hit the F4 key to bring up the windows properties. In this window, this is where you need to add all of the MSCRM SDK DLL’s you will be requiring, such as

LinqPad5

Simply browse to the files (assuming you have already download the SDK) and add them in to your extensions window. You then also need to set up your namespaces so that you can access them.

Microsoft.Xrm.Client
Microsoft.Xrm.Sdk
Microsoft.Xrm.Sdk.Client
Microsoft.Xrm.Sdk.Deployment.Proxy
System.Collections.Specialized

Now for the code that you will use to connect to Dynamics. Simply Paste the following :

void Main()
{
	// Write code to test your extensions here. Press F5 to compile and run.
}

/// My Extensions is a class to allow a connection to MS Dynamics 2011	
public static class MyExtensions
{
	// Stores a number of specific connection strings
	public static  NameValueCollection ServerConnections = new NameValueCollection();
	// Populates the connection strings
	public static void PopulateConnectionStrings()
		{
			ServerConnections.Add("HALL2013","url=http://crm2013/HALL2013/XRMServices/2011/Organization.svc;");
			ServerConnections.Add("HALL2011","url=http://crm2011/HALL2011/XRMServices/2011/Organization.svc;");
		}
	// GetOrgContext - return a connection 
	public static OrganizationServiceContext GetOrgContext(string connectionString)
		{
			PopulateConnectionStrings();
			CrmConnection connection = CrmConnection.Parse(ServerConnections[connectionString]);
		
			var result = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(
				connection.ServiceUri,
				connection.HomeRealmUri,
				connection.ClientCredentials,
				connection.DeviceCredentials);
		
			result.EnableProxyTypes();
			Microsoft.Xrm.Sdk.Client.OrganizationServiceContext orgcontext = new OrganizationServiceContext(result);
			return orgcontext;
		}
	// GetOrgService - return a connection
	public static IOrganizationService GetOrgService(string connectionString)
		{
			PopulateConnectionStrings();
			CrmConnection connection = CrmConnection.Parse(ServerConnections[connectionString]);
			
			var result = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(
			connection.ServiceUri,
			connection.HomeRealmUri,
			connection.ClientCredentials,
			connection.DeviceCredentials);
			
			result.EnableProxyTypes();
			return result;
		}
}

Hit the green play button, and in theory, it should build and compile.

I have coded this so that you can add extra connection strings in case you have multiple environments. You can then simply instantiate a connection by using :

var conn = MyExtensions.GetOrgContext("HALL2011");

Writing Code

Now, to begin, create a new query by clicking on the plus sign at the top of the main text window. A query will be set up and it should be ready to go with all of the assemblies and namespaces you set up within your extension.  Make sure you have C# Statements selected, and type in the following as a simple test to make sure everything is working :

var conn = MyExtensions.GetOrgContext("HALL2011");

var response = (WhoAmIResponse)conn.Execute(new WhoAmIRequest());

response.Dump();

Should give you the following

LinqPad1Res1

The results, by default are rendered as XML, but you can click the grid button just along from the run button to display the data as a grid. You will notice the line response.Dump().  LinqPad extends everything with this command, and will output it within the results pane.  You can use this to output variables and objects so you can see what it looks like.

LinqPad1Res2

And your set. You can now right code, linq queries etc and run them straight away.  If you change the Language selector to C# Program, you can even create functions and test them just as you would in Visual Studio.  This allows you to test all of your plugin and workflow activities logic within LinqPad before putting the code into your CRM server. You can easily add other reference assemblies and namespaces to your queries as you see fit.

Another example (using an email template and then finding the attachments)

InstantiateTemplateRequest instTemplateReq = new InstantiateTemplateRequest

{

TemplateId = new Guid("CE6E9346-8FFB-E311-8997-005056A507B0"),

ObjectId = new Guid("995623E6-58F8-E311-8997-005056A507B0"),

ObjectType = "incident"

};

InstantiateTemplateResponse instTemplateResp = (InstantiateTemplateResponse)conn.Execute(instTemplateReq);


Guid id = new Guid("CE6E9346-8FFB-E311-8997-005056A507B0");

var files = from f in conn.CreateQuery("activitymimeattachment")

where (Guid)f["objectid"] == id &&

(string)f["objecttypecode"] == "template"

selectnew {f};

files.Dump();

Debugging within Visual Studio

And it gets better, why not just use LinqPad to set up some test data, and then call your plugin code directly and debug within Visual Studio.

In LinkPad, within your query window, hit the F4 key and add your plugin assembly and its namespace to your query properties.

In LinqPad, you can set up any variables your plugin code may need. As an example, I have started to place my plugin logic within a separate static class with various methods that take parameters.  This way, the plugin can deal with the input and output parameters, but I then have separate code blocks that do the processing.  In LinqPad, you can then simply call this logic with the appropriate parameters.

If you then use the command

Debugger.Launch();

It will kick off Visual Studio’s debugger and you can step through your plugin code. Simples.

Updating Plugins and Workflow Activities

When updating plugins or workflow activities, if you are adding input / output parameters, or changing the name or display, sometimes after updating, the changes do not take effect within the Dynamics Workflow editor.

Instead of having to stop and start services, did you know that the update can be triggered by changing the assembly version information before you update.

In Visual Studio, just edit the properties of your Workflow Project as outlined in the screenshots, increment the assembly version, and rebuild and deploy.  The change in version will be enough for Dynamics to refresh its cache for using the activity in the workflow designer.

assemblyinfo1assemblyinfo2