Welcome to ExtremeCRM…

Microsoft CRM  Logo

ExtremeCRM provides coding examples, insights, concepts and options for developing customizations for Microsoft Dynamics CRM 2011.  The primary contributor, Brenden Smith is a Microsoft MCP and Microsoft CRM 2011 Architect with deep experience with both federal agencies in the Washing D.C. area and large private sector clients


Microsoft Dynamics CRM 2013 setup with SQL Server 2014 High Availability

When Dynamics CRM is setup with SQL Server 2013 High Availability a Listener is required to be used in the connection string.  However when doing a Organization import from for example your Test server CRM will not allow you use a Listener if you attempt to use a Listener Dynamics CRM with throw the following error.


System.Net.Sockets.SocketException (0x80004005): No such host is known

at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)

at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)

at Microsoft.Crm.Setup.Server.Utility.ManagedNetworkUtility.IsHostNameLocal(String hostName)

at Microsoft.Crm.Setup.Server.Utility.ManagedNetworkUtility.AreHostNamesSynonymous(String host1, String host2)

at Microsoft.Crm.Tools.Admin.GrantSrsAccessToConfigDBAction.GrantSrsServiceAccessToLocalConfigDB(Uri reportingUrl)

at Microsoft.Crm.Setup.Shared.CrmAction.ExecuteAction(CrmAction action, IDictionary parameters, Boolean undo)

Because Microsoft does not provide a way within its UI to update the connection string back to the physical server name the only option seems to be to manually update the Organization table in the MSCRM_Config database directly, which of course is unsupported by Microsoft.  This has been confirmed by Microsoft Support.


Below is the official response from Microsoft CRM Support

Thank you for your time over the case today.

As discussed earlier, I can confirm that the issue with importing organization is reproducible, in an environment where CRM is configured with SQL 2012 Always On. To fix this issue, we have to update the Connection String in MSCRM registry hive as well as the Organization table in the MSCRM_Config DB, to change the DataSource Name from Lister to the Primary Replica. Once these changes are done the Organization import works just fine and then they go back and revert the changes.

Following changes are done:

  • Change the Data Source from the SQL Server instance name to the availability group listener name.

The complete connection string should appear similar to the following example, where MSCRMAG is the availability group listener name for the availability group that includes the Microsoft Dynamics CRM configuration database:

Data Source MSCRMAG;Initial Catalog= MSCRM_CONFIG;Integrated Security=SSPI

  • Update query for MSCRM_Config DB

Update Organization

set ConnectionString = ‘Provider=SQLOLEDB;Data Source=AG_Listener_Name,Port_Number;Initial Catalog=OrganizationName_MSCRM;Integrated Security=SSPI;multisubnetfailover=true’ where DatabaseName = ‘OrganizationName_MSCRM’

I have discussed this with our senior resources at Microsoft, and we can confirm that this is a workaround for now and the same is supported. The deployment will continue to stay supported until and unless there are no other changes made to the database, then the ones mentioned above.



Custom Dynamics CRM 2011 ToolTips

Dynamics CRM 2011 does not support custom tooltips or any other built-in method for delivering helpful information to the user when filling out a form. The code snippet below will popup a tooltip and display a custom tooltip on as many of the CRM form fields as you like. Just attach this code to you CRM form onload event.

function OnLoad() {
CreateToolTip("img_equipmentneeded", "Provide a brief history of why the services or equipment are needed.");

var Tooltip = null;

function CreateToolTip(controlId, toolTip) {
var control = document.getElementById(controlId);

control.ToolTip = toolTip;

control.attachEvent("onmouseover", ShowToolTip);

control.attachEvent("onfocus", ShowToolTip);

control.attachEvent("onmouseout", HideToolTip);

function ShowToolTip() {
var control = event.srcElement;

Tooltip = window.createPopup();

var ToolTipHTML = "<DIV style='width:100%;height:100%;border:1px solid gray;background-color: #d8e8ff;filter: progid: DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr=#ffffff,EndColorStr=#cecfde);padding-left:2px;font:12px tahoma'>" + control.ToolTip + "</DIV>";

Tooltip.document.body.innerHTML = ToolTipHTML;

var Width = control.offsetWidth;

var Height = 30;

var Position = GetControlPostion(control);

var Left = Position.X + 1;

var Top = Position.Y + 1;

Tooltip.show(Left, Top, Width, Height, null);

function GetControlPostion(control) {
var Position = new Object();

var controlHeight = control.offsetHeight;

var iY = 0, iX = 0;

while (control != null) {
iY += control.offsetTop;

iX += control.offsetLeft;

control = control.offsetParent;

Position.X = iX + screenLeft;

Position.Y = iY + screenTop + controlHeight;

return Position;

function HideToolTip() {
if (Tooltip)




Executing a Dynamics CRM WorkFlow from a Plugin

As part of a StateFlow engine I writing for a Microsoft Dynamics CRM 2011 project I needed to be able to run a series of custom workflow activities.  I needed the workflow activities to be driven off a configuration entity that would hold rules like, how often to run, what status reason to set a matching record to and so on.  One part that was a bit less than obvious was how to get the GUID for the workflow I wanted to execute in a search by “workflow name”.  I’m sure there are several ways to do this but I was surprised when I found you could query it just like any other entity.  Just be sure that you add a condition of “type”, ConditionOperator.Equal, 1 otherwise CRM will grab the unpublished version of the workflow and throw a error “workflow must be in published state”.

Code Snippets

The following is a code sample that calls two methods: GetProcessId and ExecuteWorkFlow before we can do so we need to get the ID of the workflow which is stored in the PrimaryEntityId attribute of the workflow context.

// Create the context

IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();

_primaryEntity = context.PrimaryEntityId;

Guid processId = new Guid(GetProcessId(service, “workflow”, “name”, “StateFlow”).Id.ToString());

ExecuteWorkFlow(service, processId, _primaryEntity);

private void ExecuteWorkFlow(IOrganizationService service, Guid workFlowId, Guid entityId)




// Create an ExecuteWorkflow request.

ExecuteWorkflowRequest request = new ExecuteWorkflowRequest()


WorkflowId = workFlowId,

EntityId = entityId


// Execute the workflow.

ExecuteWorkflowResponse response =



catch (Exception ex)


throw new InvalidPluginExecutionException();





private Entity GetProcessId(IOrganizationService service, string EntityLogicalName, string SearchFieldName, object SearchValue)

//Internal method used to search for entity records


EntityLogicalName = EntityLogicalName.ToLower();

SearchFieldName = SearchFieldName.ToLower();

QueryExpression query = new QueryExpression(EntityLogicalName);

query.ColumnSet = new ColumnSet(true);

query.Criteria.AddCondition(new ConditionExpression(SearchFieldName, ConditionOperator.Equal, SearchValue));

query.Criteria.AddCondition(new ConditionExpression(“type”, ConditionOperator.Equal, 1));



EntityCollection response = service.RetrieveMultiple(query);

if (response != null && response.Entities.Count > 0)

return response.Entities[0];

else { return null; }


catch (Exception ex)


//Do error hadling

throw ex;



Dynamics CRM 2011 Security Roles Best Practices

Security roles in Microsoft Dynamics CRM 2011 are deceptively simple in CRM.  Just click a few bubbles and you good.  Truth is they can become very difficult to manage if not setup and maintained properly.  Here are some best practices to keep in mind.

  • Never use the Out-Of-Box Security roles, rather always clone them.
  • Business Units are data security related and not a business hierarchy.
  • Security Roles are roles not job titles.
  • Limit sharing to a minimum. If you must share, share to teams.
  • Do not let anyone function as system administrator or system customizer roles. IT and Admins should log in with special accounts to make changes. Example CRM Admin account (Which would have System Administrative access)
  • Keep the number of security roles as minimal as is practical.
  • Use meaningful roll names.


The SQL below will give you a listing of each entity and role interaction and setting.


                      FilteredRole.name, EntityView.PhysicalName AS [Entity Name],
                      CASE Privilege.AccessRight WHEN 1 THEN 'READ' WHEN 2 THEN 'WRITE' WHEN 4 THEN 'APPEND' WHEN 16 THEN 'APPENDTO' WHEN 32 THEN 'CREATE' WHEN 65536
                       THEN 'DELETE' WHEN 262144 THEN 'SHARE' WHEN 524288 THEN 'ASSIGN' END AS [Access Level],
                      CASE PrivilegeDepthMask WHEN 1 THEN 'User' WHEN 2 THEN 'Business Unit' WHEN 4 THEN 'Parent: Child Business Unit' WHEN 8 THEN 'Organisation' END AS [Security Level]
FROM         RolePrivileges INNER JOIN
                      FilteredRole ON RolePrivileges.RoleId = FilteredRole.roleid INNER JOIN
                      PrivilegeObjectTypeCodes ON RolePrivileges.PrivilegeId = PrivilegeObjectTypeCodes.PrivilegeId INNER JOIN
                      Privilege ON RolePrivileges.PrivilegeId = Privilege.PrivilegeId INNER JOIN
                      EntityView ON EntityView.ObjectTypeCode = PrivilegeObjectTypeCodes.ObjectTypeCode
WHERE     (FilteredRole.roletemplateid IS NULL)
ORDER BY FilteredRole.name, [Entity Name]

How to get Microsoft CRM 2011 field attributes

How to get CRM field attributes

Say you need to know what all the Required Fields are or list of other field attributes like MaxLength or MinValue, for a set of entities in Microsoft Dynamics CRM 2011, you could open each entity one at a time and then open each field attribute to determine its requirement level but if you have a large solution that process is time consuming and tedious.

A quick simple solution is to query the MetadataSchema.Attribute and the MetadataSchema.Entity found  in the Microsoft Dynamics CRM 2011 Organization database.  Using the SQL I have provided below you can get a listing of just about anything you might want to know about your solutions entity attributes and field attributes.


SELECT MetadataSchema.Attribute.Name,   MetadataSchema.Attribute.AttributeRequiredLevelId,   MetadataSchema.Attribute.PhysicalName, MetadataSchema.Attribute.Length,

MetadataSchema.Attribute.MaxLength,   MetadataSchema.Attribute.DefaultValue,   MetadataSchema.Attribute.VisibleToPlatform,   MetadataSchema.Attribute.IsPKAttribute,

MetadataSchema.Attribute.PrecisionValue,   MetadataSchema.Attribute.MinValue, MetadataSchema.Attribute.MaxValue,   MetadataSchema.Attribute.AttributeId,

MetadataSchema.Entity.Name,   MetadataSchema.Entity.OriginalLocalizedName

FROM    MetadataSchema.Entity INNER JOIN

MetadataSchema.Attribute ON   MetadataSchema.Entity.EntityId = MetadataSchema.Attribute.EntityId



Dynamic JSON Converter and CRM 2011

The Dynamics CRM 2011 REST API is a powerful integration option for XRM developers.  In a past post I attempted to demonstrate a simplified example of a console app grabbing some SQL data from a non-CRM source and posting that data to CRM using the REST API.  Retrieving data back from CRM is just as straightforward but since it returns as JSON you need a strategy to handle that. I wanted to find a way I could deserialize JSON on the fly dynamically, below are my results.  I have greatly parsed down the example, hopefully making it easier for readers to comprehend my approach but at the end of this post I will include the full DynamicJsonConverter class for your use.

The JavaScriptSerializer class is used internally by the Dynamics CRM 2011 asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.

To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method which is where our DynamicJsonConverter class comes in.

Step 1) First we get some data from a XRM proxy service based on the concepts found here Dynamics CRM 2011 REST API

publicdynamic GetListofEntities(string entityName, string entityField)



   XRMServiceClient xrm = newXRMServiceClient();

          string json = xrm.GetAllEntititiesSpecifyFields(entityName, entityField);




Step 2)

We declare a JavaScriptSerializer dynamic object and register our custom converter.

          var serializer = newJavaScriptSerializer();



          dynamic data = serializer.Deserialize(json, typeof(object));


          return data.Items;





The sample code above would then be implemented by code similar to below.  In this example (Step 3 below) we are just passing in a email address of a contact and getting back the corresponding contact entity record from CRM.  Next we can store our contact in local variables or as a class which I also show below.

Notice here that using these methods we are able to use dot notation to access entity attributes (entityRecord.telephone1).  That’s pretty cool considering our GetListofEntities method above has no concept of a contact or any of the specific attributes, it only knows how to fetch JSON based data and convert it. Even the keyword Items is dynamic and resolved only at runtime.

Step 3)

foreach (var entityRecord in GetListofEntities(“contact”, “emailaddress1”))


first = newContact() { FirstName = entityRecord.firstname };

last = newContact() { LastName = entityRecord.lastname };

phone = newContact() { Phone = entityRecord.telephone1 };




publicclassContact : IEntity


publicstring FirstName { get; set; }

publicstring LastName { get; set; }

publicstring Phone { get; set; }




Here’s the JSONConverter class in sound working order.  However the example code above is not necessarily Intended for direct use.

using System;

using System.Collections;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Dynamic;

using System.Linq;

using System.Text;

using System.Web.Helpers;

using System.Web.Script.Serialization;

namespace JSONConverter




        publicclassDynamicJsonConverter : JavaScriptConverter


            publicoverrideobject Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)


                if (dictionary == null)



                return type == typeof(object) ? newDynamicJsonObject(dictionary) : null;



            publicoverrideIDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)





            publicoverrideIEnumerable<Type> SupportedTypes


                get { returnnewReadOnlyCollection<Type>(newList<Type>(new[] { typeof(object) })); }



            privatesealedclassDynamicJsonObject : DynamicObject


                privatereadonlyIDictionary<string, object> _dictionary;


                public DynamicJsonObject(IDictionary<string, object> dictionary)


                    if (dictionary == null)


                    _dictionary = dictionary;



                publicoverridestring ToString()


                    var sb = newStringBuilder(“{“);


                    return sb.ToString();



                privatevoid ToString(StringBuilder sb)


                    var firstInDictionary = true;

                    foreach (var pair in _dictionary)


                        if (!firstInDictionary)


                        firstInDictionary = false;

                        var value = pair.Value;

                        var name = pair.Key;

                        if (value isstring)


                            sb.AppendFormat(“{0}:\”{1}\””, name, value);


                        elseif (value isIDictionary<string, object>)


                            newDynamicJsonObject((IDictionary<string, object>)value).ToString(sb);


                        elseif (value isArrayList)


                            sb.Append(name + “:[“);

                            var firstInArray = true;

                            foreach (var arrayValue in (ArrayList)value)


                                if (!firstInArray)


                                firstInArray = false;

                                if (arrayValue isIDictionary<string, object>)

                                    newDynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);

                                elseif (arrayValue isstring)

                                    sb.AppendFormat(“\”{0}\””, arrayValue);


                                    sb.AppendFormat(“{0}”, arrayValue);






                            sb.AppendFormat(“{0}:{1}”, name, value);






                publicoverridebool TryGetMember(GetMemberBinder binder, outobject result)


                    if (!_dictionary.TryGetValue(binder.Name, out result))


                        // return null to avoid exception.  caller can check for null this way…

                        result = null;




                    var dictionary = result asIDictionary<string, object>;

                    if (dictionary != null)


                        result = newDynamicJsonObject(dictionary);




                    var arrayList = result asArrayList;

                    if (arrayList != null && arrayList.Count > 0)


                        if (arrayList[0] isIDictionary<string, object>)

                            result = newList<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => newDynamicJsonObject(x)));


                            result = newList<object>(arrayList.Cast<object>());















Dynamics CRM 2011 REST API

Dynamics CRM 2011 offers a multitude of integration options. There are number of additional items exposed to enable delivery of more dynamic integrated soluions. CRM 2011 supports both Early and Late-bound interfaces allowing access to business data in CRM 2011. Additonally, Microsoft has introduced REST endpoint as an alternative to SOAP-based Web Services that allows executing requests using a service that is based on URI. This new interface allows developing client applications using ASP.NET AJAX or Microsoft Silverlight as well as other technologies such as Drupal, PHP, Ruby on Rails,etc. In this post, we will highlight some tips that should give you a good starting point to work from.

Sample Project

Challenge: To explore this let’s use a fictional company we will call Northwind Real Estate. Northwind would like to capture leads and applications on their public website and feed them in to their new Dynamics CRM 2011 back-office system. Northwind has had an ASP.NET website for years and it runs on the .NET 3.x Framework. Unfortunately the CRM 2011 SDK requires .NET 4.0 so we can’t use traditional CRM SDK methods to integrate Northwind’s public facing website with CRM.

Solution: Utilizing CRM 2011 REST API, Northwind can continue to operate their Web site in the .NET 3.x Framework and yet consume CRM REST interface to interact with their new CRM 2011 back-office system. Bottemline, we should be able to achieve the following steps:

  1. Get some data that should be sent to CRM 2011
  2. Format the data in to JavaScript Object Notation (JSON)
  3. Pass it to a method which will make the REST call

GetData is just a simple SQL DataReader method example that grabs some columns from our database and passes the results to second method that formats the results to JSON format.

static void GetData() {
string connectionString = GetConnectionString();
string queryString =
"SELECT FirstName, LastName, Email, PrimaryPhone FROM Leads;";
using (SqlConnection connection = new SqlConnection(connectionString)) {
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try {
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string json = Buildjson(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString());
catch (Exception ex) {

Next create some simple JSON Objects

A JSON object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

static private string Buildjson(string firstName, string lastName, string email, string phone) {
  string json = "{\'new_firstname\':\'" + firstName + "\'";
  json += ",\'new_lastname\':\'" + lastName + "\'";
  json += ",\'new_email\':\'" + email + "\'";
  json += ",\'new_phone\':\'" + phone + "\'";
  json += "}";
  return json;

Now we are ready to look at the code that executes the REST call

The HttpWebRequest object in .NET allows us to POST to the CRM 2011 REST API (we could use cURL for a similar PHP function), it’s important to choose a content type of “application/json” and a method of POST as some of the other REST methods don’t seem to be fully supported.

static string HttpPost( string json) {
   //The service call will require a URL, active CRM account name, password and domain
   string domain = ConfigurationManager.AppSettings["domain"];
   string url = ConfigurationManager.AppSettings["restEndPoint"] + endpoint.ToString();
   string user = ConfigurationManager.AppSettings["crmUser"];
   string pwd = ConfigurationManager.AppSettings["crmPWD"];
     // HttpWebRequest exposes common HTTP header values sent to the Internet resource //as properties, set by methods, or set by the system;
   HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
   req.Method = "POST";
      // Set the content type of the data being posted.
   req.ContentType = "application/json";
   // Set credentials to use for this request.
   req.Credentials = new NetworkCredential(user, pwd, domain);
     // Encode the parameters as form data:
   byte[] formData = UTF8Encoding.UTF8.GetBytes(json);
   req.ContentLength = formData.Length;
   // Send the request:
   using (Stream post = req.GetRequestStream()) {
   // Write out the response just for testing and debugging
     post.Write(formData, 0, formData.Length);
   // Pick up the response:
   string result = null;
   using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse) {
     StreamReader reader = new StreamReader(resp.GetResponseStream());
     result = reader.ReadToEnd();
   return result;

Dynamics CRM 2011 Rollup 12 Cross-Browser Support

Dynamics CRM 2011 Rollup 12 offers cross-browser support.  Microsoft claims a wide range of support which is shown in the table below.  My own findings were not as successful.  While Firefox seems to run Dynamics CRM 2011 very smoothly Google Chrome seems to have trouble, parts of some basic forms don’t display at all.  I was able to successfully load Dynamics CRM 2011 pages on a Mozilla browser running on my Samsung S3 which was pretty cool.  Even if the Chrome has issues this still seems to be a major step forward for Dynamics CRM 2011.


OS Internet Explorer Firefox Chrome Safari
Windows 8 IE 10 (Desktop mode) 16+ 21+ Not Supported
Windows 7/Vista IE 8/9 16+ 21+ Not Supported
Windows XP IE 7/8 16+ 21+ Not Supported
Mac OS-x 10.7 (Lion) Not Supported Not Supported Not Supported 6+
Mac OS-x 10.8 (Mountain Lion) Not Supported Not Supported Not Supported 6+




CRM 4.0 Master Schema Management and Customization Change Control

 Recently I found a CRM 4.0 Schema comparison tool that I find makes life much easier when I’m playing the role of Schema Master.  Managing schema changes is in my opinion a arduous and very manual process.  It is  not advisable to use TFS for schema file comparisons and definitely not for merging, this is because TFS does line by line comparison not XML tag comparisons.  The Customization Comparison Utility lets you compare the customization files between two Microsoft Dynamics CRM systems and the Configuration Data Utility lets you transfer custom configuration data from one Microsoft Dynamics CRM system to another.   You can download the solution file here

The process I recommend for the proper management and change control practices   essential for the ongoing life cycle of a Microsoft CRM Dynamics Organization Database Schema.  The diagram below represents the three typical scenarios that the Schema Master may encounter on a frequent basis.  The three scenarios are Jr. Developer or Third Party Developer interactions, Senior Developer Interactions and Multi-Developer Entity Edits.  Using the Customization Comparison Utility along with this process will ensure the integrity of your CRM schema and save you from a lot of pain.


Master Schema Scenarios

Scenario 1

Under scenario 1 a junior developer or a third-party or outside vendor may need to promote changes to the CRM Master Schema.  In this circumstance the Schema Master would likely be responsible for heavy validation of the schema changes.

1.       The schema items impacted are exported from the developers environment .

2.       The schema items impacted are documented in a standard SharePoint change-log.

3.       The schema export file is checked in to the weekly schema build folder.

4.       The Schema Master reviews the change-log and the may make manual or automated adjustments to the Master Schema.

Scenario 2

Under scenario 2 a senior developer may need to promote changes to the CRM Master Schema in this circumstance would likely be responsible for validation of the schema changes.

1.       The schema items impacted are exported from the developers environment .

2.       The schema items impacted are documented in a standard SharePoint change-log.

3.       The schema export file is checked in to the weekly schema build folder.

4.       The Schema Master reviews the  change-log and the may make manual or automated adjustments to the Master Schema.

Scenario 3

Under scenario 3 multiple developers may need to promote changes to the CRM Master Schema impacting the same entity.  In this circumstance the developers would likely be responsible for creating and validating a single schema export file.

1.       The schema items impacted are exported from the developers environment .

2.       The schema items impacted are documented in a standard SharePoint change-log.

3.       The schema export file is checked in to the weekly schema build folder.

4.       The Schema Master notifies the developers of potential conflicts or collisions.

5.       The developers create a single schema export file and check it in to TFS.

6.       The Schema Master reviews the change-log and the may make manual or automated adjustments to the Master Schema.

The TFS Role

TFS is used as a repository for the incremental schema edits that are proposed as candidates to the Schema-Master.  It’s critical that developers only submit specific entity schema segments rather than the full CRM schema, this is because TFS analyzes code line by line rather than in the XML  tag format the CRM schema model uses.  Also because the environment that the CRM schema is exported from can alter the format and order of the XML.  For these reasons it will be incumbent upon the Schema-Master to understand where the schema segments are coming from and to identify the risks associated with the submitting party.

The SharePoint Role

A standard SharePoint form should be used to capture the schema changes being submitted by each developer.  The SharePoint form should capture at minimum:


o    ID Number

o    Entity, Workflow or Role Name

o    Attribute

o    Deployment Comments

o    Impact Analysis Comments

The ID Number shoul


d always be references within the TFS check-in comments   and included in the release and deploy notes sent to the Deployment team for each build.






HTML Editor for Microsoft Dynamics CRM 4.0

Until Microsoft Dynamics 5.0 to comes out the only way to get a HTML or Rich Text editor capability in Microsoft Dynamics CRM 4.0 is to roll your own or use a third party application.  I have had tremendous success using the TinyMCE  editor.  click here to download The editor has a plethora of features available including everything from spell check to word count and is available in a number of  build format and examples including;   jQuery, JavaScript, PHP, .Net and JSP.  I prefer to use the jQuery build for my Microsoft Dynamics CRM 4.0 implementations.

Below I have included a code sample you can use in your custom iFrame.  Accessing the raw HTML source during the CRM onSave event was a little bit tricky, here’s the code for that.


You can either make a call to the CRM SDK and save this value to the database or use javascript and simply copy to a hidden  nText  field located  directly on the form next to the iFrame.  All we have to do is save and load the raw HTML and the HTML editor does the rest.

I use a FetchXML function to load the raw HTML…


The GetContacts function simply uses FetchXML to retrieve the value of a nText attribute I have added to the Contacts entity.

Here’s a page that instantiates a HTML editor in a iFrame for use in Microsoft Dynamics CRM 4.0.

<title>Full featured Microsoft Dynamics CRM 4.0 tinyMCE example using jQuery plugin by ExtremeCRM.net</title>

<!-- Load jQuery -->
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
 google.load("jquery", "1");

<!-- Load TinyMCE -->
<script type="text/javascript" src="../jscripts/tiny_mce/jquery.tinymce.js"></script>
<script type="text/javascript">
 $().ready(function() {
 // Location of TinyMCE script
 script_url : '../jscripts/tiny_mce/tiny_mce.js',

 // General options
 theme : "advanced",
 plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

 // Theme options
 theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
 theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
 theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
 theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
 theme_advanced_toolbar_location : "top",
 theme_advanced_toolbar_align : "left",
 theme_advanced_statusbar_location : "bottom",
 theme_advanced_resizing : true,

 // Example content CSS (should be your site CSS)
 content_css : "css/content.css",

 // Drop lists for link/image/media/template dialogs
 template_external_list_url : "lists/template_list.js",
 external_link_list_url : "lists/link_list.js",
 external_image_list_url : "lists/image_list.js",
 media_external_list_url : "lists/media_list.js",

 // Replace values for the template plugin
 template_replace_values : {
 username : "Some User",
 staffid : "991234"


 //Here we load the input textbox named elm1.  This input text box will be overloaded by the tinyMCE editor at runtime.
 //See the GetContacts function below.

<!-- /TinyMCE -->


 <form id="form1" runat="server">
 <h3>Full featured example using jQuery plugin</h3>

 This example shows how TinyMCE can be used from Microsoft Dynamics CRM 4.0  using jQuery. The jQuery plugin will also attach it's self to various jQuery methods to make it more easy to get/set editor contents etc.

 <!-- Gets replaced with TinyMCE, remember HTML in a textarea should be encoded -->
 <textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 80%">
 This is some example text that you can edit inside the &lt;strong&gt;TinyMCE editor&lt;/strong&gt;.
 ExtremeCRM provides developers coding examples, insights, concepts and options for developing customizations for Microsoft CRM 4.0.  The primary contributor, Brenden Smith is a Microsoft MCP and Microsoft CRM 4.0 Lead developer for a federal agency in Washing D.C.  If you would like to be a contributor for extremeCRM.net

 <!-- Some integration calls -->
 <a href="javascript:;" onmousedown="$('#elm1').tinymce().show();">[Show]</a>
 <a href="javascript:;" onmousedown="$('#elm1').tinymce().hide();">[Hide]</a>
 <a href="javascript:;" onmousedown="$('#elm1').tinymce().execCommand('Bold');">[Bold]</a>
 <a href="javascript:;" onmousedown="alert($('#elm1').html());">[Get contents]</a>
 <a href="javascript:;" onmousedown="alert($('#elm1').tinymce().selection.getContent());">[Get selected HTML]</a>
 <a href="javascript:;" onmousedown="alert($('#elm1').tinymce().selection.getContent({format : 'text'}));">[Get selected text]</a>
 <a href="javascript:;" onmousedown="alert($('#elm1').tinymce().selection.getNode().nodeName);">[Get selected element]</a>
 <a href="javascript:;" onmousedown="$('#elm1').tinymce().execCommand('mceInsertContent',false,'<b>Hello world!!</b>');">[Insert HTML]</a>
 <a href="javascript:;" onmousedown="$('#elm1').tinymce().execCommand('mceReplaceContent',false,'<b>{$selection}</b>');">[Replace selection]</a>

 <br />
 <input type="submit" name="save" value="Submit" />
 <input type="reset" name="reset" value="Reset" />
<script type="text/javascript">
if (document.location.protocol == 'file:') {
 alert("The examples might not work properly on the local file system due to security settings in your browser. Please use a real webserver.");