Adding client side business logic to CRM forms using Silverlight managed code

I have recently been prototyping some concept applications for Windows Live using managed code in Silverlight V1.1 Alpha and thought it would be cool, if Dynamics CRM developers could take advantage and write their client side logic in, lets say, C# rather than JavaScript. Currently, you can use CRM form events (Onload/OnSave/OnChange) to add JavaScript code to the forms. Some of the reasons why someone would do that is to create richer and more interactive user experience, implement form verification/validation or mash up data from multiple sources, without spending the cost of making a round trip to the server.

I am excited about Silverlight V1.1 and the ability to write client side code in C#, so I spent a few hours to build a simple example that shows how to extend Dynamics CRM forms business logic using Silverlight V1.1 Alpha managed code. Here is why I think anybody should care about this sample compared to what is already enabled:

  1. Developer experience: I personally have more fun writing in strongly typed and rich languages like C# than JavaScript.
  2. Performance: Silverlight runs compiled C# code on the client. JavaScript is an interpreted language and hence generally slower in performance.
  3. Protecting your investment: There are limited ways to protect JavaScript code since the code is viewable by the client, on the other hand, the prospects of protecting Silverlight managed assemblies is much higher (Obfuscation, MSLP, etc).

Note that all these reasons only makes sense if you are convinced that your code should run on the client and don’t want to pay the cost for making a round trip to the server for processing every function.

On to the sample…..the sample implements a very simple logic just to help better understand the architecture: if the value of a field is changed, based on some logic, set the value of another field.

Requirements

  1. Install Visual Studio 2008 RTM (install the trial verion for free).  
  2. Install Microsoft Silverlight 1.1 Tools Alpha for Visual Studio 2008 RTM. This tool enables you to create, view and compile Silverlight 1.1 projects in Visual Studio.
  3. Install Microsoft Silverlight 1.1 Alpha September Refresh Runtime on all the clients that you want to run the managed assembly on. Note that Silverlight will automatically install this on the first use so no deployment is really needed. But to get your development environment quickly setup, I suggest that you install the runtime on your dev/test machine.
  4. Access to a server that runs Microsoft Dynamics CRM 3.0 or 4.0 (I have tested it with CRM V4.0 RC0)

Get started

1) Build your Silverlight Assembly: First lets build a Silverlight managed assembly to be called by CRM forms.  Open VS and create a new Silverlight V1.1 project (or use the one that I have already created in the attachement). VS creates some default files.  Rename the files to make your project look like below image (ignore the OnChange.js file for now).

Update the HTML page of the project, CRMSilverlight.html, to look like this. It is pretty standard, all I did was to rename some of the files. This HTML page is the one that is hosting the Silverlight control and will be exposed through an IFrame on CRM form(see below).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<!-- saved from url=(0014)about:internet -->
<head>
<title>Microsofft CRM Silverlight IFrame</title>
<script type="text/javascript" src="Silverlight.js"></script>
<script type="text/javascript" src="CRMSilverlight.html.js"></script>
<style type="text/css">
.silverlightHost { width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="SilverlightControlHost" class="silverlightHost" >
<script type="text/javascript">
createSilverlight();
</script>
</body>
</html>  

Add a new C# managed method to Page.xaml.cs by creating calculateRating method. This is a simple method that will be called from CRM form. This is where all the fun begins, you can write all of your client side code in C#, beautiful! The method takes an int from CRM form and returns a string reflecting how good the credit score is, simple. The Scriptable tags simply means that the class and the method are accessible from JavaScript.

namespace CRMSilverlight    
{
   [Scriptable]   
   public partial class Page : Canvas    
   {        
      //This method is Scriptable which means it can be called from HTML DOM        
      //Put all of your complex logic in this method.  You can write all of your logic in C#        
      //This methods takes a credit score integer and returnes a string rating       
      [Scriptable]        
      public string calculateRating (int creditScore)       
     {
         string creditRating;
         if (creditScore <= 500)               
             creditRating = "Bad";
         else if (creditScore >500 && creditScore <=700)
            creditRating = "Good";
         else
         creditRating = "Excellent";
         return creditRating;
     }
    
     //When the page is loaded, a new object called basic is registered        
     //This object is used to access methods and properties of this class        
     //from HTML DOM
     public void FromCRMForm(object o, EventArgs e)        
     {
         // Required to initialize variables
         InitializeComponent();
        // This class will be referenced in JavaScript using keyword "basic"             
         WebApplication.Current.RegisterScriptableObject("basic", this);       
     }
}

That is it! compile your project.  It should compile with no errors and create two files in the ClientBin folder of your VS project: CRMSilverlight.dll and CRMSilverlight.pdb. You are now ready to copy the project files onto the CRM server.

2) Publish the Silverlight managed assembly on CRM server

Now you need to put the project files on IIS so they can be accessed by CRM forms.  Go to the server where CRM server is installed. Open IIS manager and create a new folder, SLCRM, in CRM web application root.  Copy the files that are shown below from the VS project into this folder, including the ClientBin folder and its content (it includes the Silverlight managed assembly, CRMSilverlight.dll and its pdb, CRMSilverlight.pdb). Make sure that all the files, including the dll, can be opened from your browser (i.e. IIS correctly serves all the files).

3) Add an IFrame and two custom fields to CRM Form

Choose a CRM form to host the Silverlight control.  I used the Account form and added an IFrame to the bottom of the Administration tab.  Note that this IFrame is only there to host the Silverlight control on the page so you can make it as small and unnoticeable as possible.  Set the URL of the IFrame to the URL of the CRMSilverlight.html file that you published on the server in step 2. 

Now add two attributes to the Account Business Entity: Silver_CreditScore (number) and Silver_CreditRating (string).  The attributes will then show on CRM Form designer as fields.  Add these fields to the Account form, Administration section.  All standard CRM customization stuff.

4) Hook up CRM form events to call the Silverlight managed assembly

In CRM form designer, add the following JavaScript code to the OnChange event for Silver_CreditScore field that you earlier added to Account form.  Whenever this field is changed, this event is fired.  

//This is how to access the Silverlight control on the IFrame page
//IFRAME_HiddenSL is the ID of the IFrame added earlier
var control = window.frames['IFRAME_HiddenSL'].document.getElementById('SilverlightControl');
var score = crmForm.all.silver_creditscore.DataValue;
//This is how to access the calculateRating method in the Silverlight managed assembly
var rating = control.Content.basic.calculateRating(parseInt(score));
crmForm.all.silver_creditrating.DataValue = rating;

I also included this script in the VS project that is attached (in OnChange.Js file).

That is it folks.  Now save and publish the Account form using CRM customization tools.  Open an account form, this will load the Iframe that has the Silverlight Control on it.  Set a value in Credit Score field, this will fire the OnChange event.  The OnChange event will then reach into the Silverlight Control in the IFrame and call the C# calculateRating method by passing the value of the Credit Score field.  The rating gets calculated in managed assembly that is running in the browser and return the result to the CRM form.  The last line of the OnChange script sets the value returned from Silverlight managed assembly to the Credit Rating field.  Sweet...

The VS project for this sample is here:

CRMSilverlight.zip (131.88 kb)

Currently rated 4.6 by 9 people

  • Currently 4.555555/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5