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.

InnerException:

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.

 

 

Advertisements

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.

 

SELECT DISTINCT
                      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]

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 {
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read()) {
string json = Buildjson(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString());
HttpPost(json);
}
reader.Close();
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
}

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+

Firefox

ff                       

 

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.

 

 

 

 

 
 
 
 
 
 
 

CRM CSS Look and Feel, Now With jQuery Support

jQuery ThemeRoller

I’m currently creating a framework for using jQuery and jqGrid with Microsoft Dynamics CRM. I will be posting the final concept and making it public soon.  One piece that may be helpful to some even if they don’t utilize the framework is a jQuery UI Dynamics CRM theme which I have added to my CRM Look and Feel Kit.  Both can be downloaded here.

How to Programmatically Create a Microsoft Word Document from Dynamics CRM

Recently I had a need to create a Microsoft Word document and dynamically populate it from data in CRM.  Microsoft Word can be invoked from JavaScript using the ActiveXObject .  This first example shows a very basic application of the concept.  Create a blank document , add a report title then add some body  text.  In my application I call the JavaScript from a toolbar button added with the ISV.config file.  For more information on adding buttons that call javaScript see Calling JavaScript from Microsoft CRM  Toolbar Buttons

// Start a new instance of Microsoft Word

var MsWord = new ActiveXObject(“Word.Application”);

// Create a new document

MsWord.Documents.Add();

//Carriage Return

MsWord.Selection.TypeParagraph();

//Report Name

MsWord.Selection.TypeText(crmForm.all.new_name.value);

//Carriage Return
MsWord.Selection.TypeParagraph();
//Carriage Return
MsWord.Selection.TypeParagraph();

//Memo field from CRM containing paragraphs of text

MsWord.Selection.TypeText(crmForm.all.new_body.value);

//Show Microsoft Word

MsWord.Visible = true;

 

To create a new document using a Microsoft Word Template do this:

msWord.Documents.Add(“http://myserver:5555/documentTemplate.dotx”);

To add text to a specific Microsoft Word form field first create a Word template and add a field to it using the developer toolbar then use this code:
msWord.ActiveDocument.FormFields(“Text1”).Result = crmForm.all.new_name.value;

Obviously you can take this much further, in my application I use a AJAX call to a web service to get related CRM records.  I also lock all the fields so their content can’t be modified by the user.  What the user can do is add content to the document which may include HTML content.  The need to generate a report but then add custom content was the genesis for this feature.

Here’s a article about creating fields in Microsoft Word.  Click Here

Microsoft CRM 4.0 Look and Feel Kit

I notice confusion out there about CSS styles to achieve a native CRM look and feel, for reasons I’m not sure of many folks can’t find the CSS template provided in the CRM SDK which can be downloaded here. Additionally the CSS template that is included by Microsoft doesn’t have much in it, for example there aren’t any CSS styles for grids.

For those of you new to CRM what were really discussing here is iFrames embedded in to your CRM entity form page so the need to match up to CRM to present seamless integration and a clean user interface is important.

I’m going to post the CSS template and images I use in my projects and as I add more styles to it I will update it from time to time.

Click here to download the CRM Look and Feel Kit

Monitoring your Microsoft Dynamics CRM Infrastructure with System Center Operations Manager 2007

Introduction

For any organisation, Systems Availability is crucial to the business and business continuity. Because of the nature and complexity of a CRM Architecture, it is vital to understand the current state of its various components and computers. The entire CRM Architecture can be centrally managed and monitored using System Center Operations Manager 2007 (SCOM), a Dynamic Systems Initiative from Microsoft to help support and be more effective and efficient, thereby saving time and money. The use of SCOM takes guess work out of the support equation, by identifying the root cause of an issue and providing the appropriate solution. As a predictive product it also provides alerts on unforeseen potential problems, enabling proactive support. In this document we discuss the use of SCOM to manage and monitor the CRM architecture comprising of Windows 2003 server, Microsoft SQL Server 2005 or 2008, Microsoft Exchange Server 2003 or 2007, Microsoft Internet Information Server IIS 6 and 7, BizTalk Server 2006, Microsoft Dynamics CRM 4.0, Windows XP, 2000, Vista, Microsoft Office 2007 and custom .Net applications

 SCOM alerts are based on real world problems and solutions developed by domain experts and Windows error reporting is linked to latest resolution knowledge. For illustration purposes the diagram below shows the Asynchronous Service Architecture, a small part of the CRM 4.0 Architecture. The Asynchronous architecture is monitored in the SCOM deployment for CRM 4.0.

  

 SCOM Solution for a Dynamics CRM 4.0 Architecture

Microsoft Dynamics CRM 4.0 architecture can be complex, depending on deployment. To ensure that all the CRM 4.0 components are functioning properly requires a robust support infrastructure. Microsoft System Center Operations Manager is a software solution that meets the need for end-to-end service monitoring in the enterprise. Deploying SCOM is key to effective support for any organisation that values its technology investment, and takes systems availability and uptime seriously.

SCOM components

Operational Database consists of operational data and configuration data for a management group. A Root Management Server is used for configuration management. Management Agents discover, collect, analyse and manage servers’ and clients’ alerts so as to resolve issues and can also wake failed systems. A Reporting Server provides reports for the management group and is displayed in the SCOM console.

Agentless Exception Monitoring extends monitoring to operating systems and applications. It configures error-reporting clients to redirect their reports to the management server providing information on failure and available solutions. An Audit Collector, found on the management server, provides information on security of managed computers from audit enabled agents. In DMZ configurations, a Gateway Server can be used for agents beyond a firewall or found in Non Trusted Domains.

Deploying SCOM

To setup SCOM OpmMgr and RMS databases, SCOM is deployed on a MS SQL Server where the Action, SDK and Service Accounts are specified. A webconsole is deployed specifying the SQL instance, the database name and SQL Listening port, plus provide relevant accounts. With installation complete, an Administrator has to logon to the SCOM server to complete the setup by configuring Discovery and select the managed objects in addition to configuring computers and devices to manage, and importing management packs[1].

Operations Manager 2007 Reporting is setup by installing the data reporting data warehouse and reporting server for reports and dashboards. It is recommended to install the Data Warehouse and Reporting Server on separate servers. A SQL Server Instance is used for the Audit Collection Service and Audit Collection Database setup and enablement.

SCOM Monitoring

A SCOM Monitor looks at different application aspects, known as Object Types, consisting of system devices or services with one of three operational states: healthy, warning or failure. A Distributed Application Designer is built on Service Oriented Monitoring and is easy to configure using a graphic designer. It can also be used to monitor ports and IP addresses of given systems. It also handles Line of Business Applications.

Roles have to be created to manage the SCOM system. Roles are integrated with Active Directory and they can manage tasks authorised for specified roles.

Notifications can be delivered individually via Email, Pager, Instant Messaging, Session Initiation Protocol, Short Message Service support (SMS) and SMTP via the Notification Device Wizard.

SCOM can be integrated with AD for Security Discovery and Agent Management enabling agent deployment and configuration automatically. The SCOM Discovery Wizard feature uses LDAP identify devices in the Directory to manage agents automatically. The MOMADAdmin tool is used to integrate with AD by creating an admin access point with the ability to specify exclusions through the ADSI Edit[2] tool.

To setup Agentless Exception Monitoring, requires configuring the Customer Experience Improvement Program (CEIP) and Error alert routing, transmission settings (through HTTP/S or with SSL with authentication preferences) and Error Crash Behaviour. These alerts can be forwarded to Microsoft and Microsoft will provide available information to solve the issue or in crash cases Microsoft will investigate the issue further.

SCOM Management Features

Through the monitoring space, administrators are able to see in Real-Time the state of systems and or services. Through the health explorer administrators can see the events that are not healthy and can then take corrective action to fix the problem using diagnostics and recovery features found in the management packs. Administrators can work with reports, creating reports for customers etc. and report on planned and unplanned operations and much more. Reports can also be specific, providing information on specific issues.

SCOM 2007 has an excellent and customisable knowledgebase known as Company Knowledge. This knowledgebase is an invaluable resource that provides information on root causes of issues and how they can be resolved. The Company Knowledge is editable, allowing for the addition of company related issues and how they have been resolved.  

 

Company Knowledge is used to capture the steps required to resolve an alert in an OpsMgr installation.  When paired with the Product knowledge (which provides application developers knowledge on the causes and suggested resolution steps for an alert), the two help any operator with the best steps they can take to resolve an alert. Product Knowledge is embedded in a rule or monitor.

 

The power of SCOM lies in the End-to-End visibility of the health and performance of the CRM architecture. This powerful feature empowers support staff to have a complete view of their supported environment, with access to easily accessed information on how to resolve issues affecting their CRM environment in case of an IT issue. They are empowered to take proactive action regarding issues before users can start calling or before systems actually fail, ensuring short Mean Time To Identify (MTTI) and Mean Time to Repair (MTR).

Figure 2 SCOM monitoring in a CRM Architecture

Organisations that have successfully deployed System Center Operations Manager 2007 testify to the ability to provide efficient support and avoiding time wasting extensive manual investigations that can give support a bad name.  Many have deployed SCOM and integrated it with their Helpdesk systems. This integration facilitates the automatic generation of tickets or calls, leading to a significant reduction in waste of support staff effort used to manually create, update and manage tickets or support Calls.

A Microsoft Dynamics CRM (Customer Relationship Management) 4.0 system is built on a three tier Enterprise Architecture consisting of; Client, Application and Data.  SCOM is able to monitor the health and performance of these systems and their applications, easily providing service level monitoring that allows the support team to meet their operational level agreements. Because CRM can be web-enabled, SCOM has the capability to monitor several URLs at any one time and provide real-time data on connectivity status.

Note

SCOM has the capability to monitor non Microsoft technology through Operations Manager Connector Framework. It does this through the bi-directional synchronised partner connector solutions that connects to the third party management packs.

Microsoft Dynamics CRM 4.0 Management Pack

At the time of writing, there is no SCOM Management Pack for Microsoft Dynamics CRM 4.0. However, Microsoft Dynamics CRM 4.0 can be managed using SCOM, by converting the MOM 2005 Management Pack for CRM[3]. This particular management pack monitors the CRM Architecture including:

  1. CRM Asynchronous Processing services.
  2. World Wide Web Publishing
  3. Microsoft Dynamics CRM Deletion Service
  4. Microsoft Dynamics CRM databases

 

Deploying SCOM 2007 provides support staff with an easy-to-use monitoring environment to monitor corporate servers, applications, and clients. This coverage gives staff a full view of the organisation’s systems, something that allows support staff to provide pro-active solutions to issues before they happen, enabling them to proactively maintain and reduce resolution times for any issues that may affect overall availability and performance of the CRM system.

 Microsofts SCOM site can be found here

Attaching Javascript code to a CRM Toolbar Button

Attaching Javascript code to a tool bar button can be very ugly.  Generally the code needs to be included within the CRM, ISV Config  XML file.  It’s pretty easy to add a button via the ISV Config.  Click Here for more information on adding custom buttons to a Microsoft Dynamics CRM Entity form, toolbar.

The red highlighted Javascript tag below shows you where you would typically place your JavaScript or JavaScript function call but this isn’t the best place for the JavaScript.  I have seen huge JavaScript routines embedded in to the tag whci makes debugging and readability a painful exercise.  Even if you call a JavaScript function and leave the tag nice and cleas as shown here that Javascript function has to be maintained outside of the CRM Model.

<Entities>
        <Entity name=”new_customentity”>
          <ToolBar ValidForCreate=”0″ ValidForUpdate=”1″>
            <ToolBarSpacer></ToolBarSpacer>
            <Button Icon=”/_imgs/ico_18_debug.gif” JavaScript=”
DuplicateRecord (10016);”>
              <Titles>
                <Title LCID=”1033″ Text=”Duplicate Record” />
              </Titles>
              <ToolTips>
                <ToolTip LCID=”1033″ Text=”Copies a record based on this open record.” />
              </ToolTips>
            </Button>
            <ToolBarSpacer />
          </ToolBar>
        </Entity>
      </Entities>
 

The solution is pretty simple.

If we change the structure of our JavaScript function a bit we can simply place it in a Entity’s form OnLoad Event.  The key syntax is simply  MyFunction = function() .

Here is a working example of a function I wrote which calls a web service to copy the  current open record and create a new one based on it,

The CRM Form OnLoad Event JavaScript

DuplicateRecord = function() {

    try {
        var oXmlHTTP = new ActiveXObject(“Msxml2.XMLHTTP”);
       oXmlHTTP.Open(“POST”, “/somepath/ DuplicateRecord Service.asmx/ DuplicateRecord?mso-spacerun: yes”>      + crmForm.ObjectId, false);
        oXmlHTTP.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”)
        oXmlHTTP.Send(‘jobId=’ + crmForm.ObjectId);
        var newId = oXmlHTTP.responseXML.selectSingleNode(“string”).text;
   }
    catch (e) {
        debugger;
        return null;
    }
}

 

The ISV Config  XML Tag

<Button Icon=”” Url=”” PassParams=”1″ WinParams=”” WinMode=”0″ JavaScript=” DuplicateRecord ();”>
              <Titles>
                <Title LCID=”1033″ Text=” Duplicate This Record ” />
              </Titles>
              <ToolTips>
                <ToolTip LCID=”1033″ Text=”Copy Record” />
              </ToolTips>
            </Button>
 

Conclusion

I like this approach because now all our JavaScript is still maintained within the CRM Entity’s and for a number of good reasons that’s where a Microsoft Dynamics CRM  application should store the JavaScript.  Because its with the entity it will get exported with your model and other customizations.