Wednesday, July 15, 2015

Restrict customer lookup to select a specific entity records in CRM 2013/2015

A few years ago, I wrote a blog addCustomFilter method for lookup control in CRM2013. Some of the readers asked if “addCustomFilter” can be used to restrict/default the customer lookup to a specific entity. The answer to the question is that you can restrict the customer lookup to return the results for a specific entity, but you can’t default it to the contact entity.
Here is an example on how to restrict the customer lookup on the case entity to display contact records. I am using the same code that I have used in my original blog with a few changes.


 function addEventHandler() {  
   // add the event handler for PreSearch Event  
 function addFilter() {  
   //create a filter xml  
    var filter ="<filter type='and'>" +  
            "<condition attribute='accountid' operator='null'/>" +  
     //apply the filter  

In the above code, I am using the filter where accountid is null and applying it to the account entity. The account record will always have an accountid, therefore no account records will be returned.


The following screen shot displays the customer lookup returning only contact records.

If the user clicks on the “Look Up More Records”, CRM will display the following screen.

The customer lookup does not return any account records as shown in the screen shot above.
The user can change the “Look for” entity to contact and choose the contact record.


Wednesday, June 10, 2015

Branding in CRM2015 SP1

How many times do customers ask to add branding to their dynamics CRM solution? The answer is that they have been asking for this from the good old CRM 1.2 days. At last it is here in CRM2015 SP1. It still does not provide full fledged branding functionality, but is a good start.
To add branding to your CRM solution, follow the following steps:
  1. Go to Setting>>customization>> as shown in the following screen shot

  2. Click on “Themes”. The system will display “CRM Default Theme” in the grid. As the name suggests, it is the default theme for the CRM.

  3. Open the “CRM Default Theme” and click the Clone button on the command bar. The system will clone the default theme.
  4. Make the changes to the theme and click save. There are a few options available in the theme. I have made 3-4 changes to my theme for this blog.

  5. Click on “Preview” button to preview the changes.
  6. If you are happy with the changes, click “Publish Theme” to push the changes to all the users.

CRM Screen shot of with default theme


CRM Screen shot of with my theme



  1. Themes are not solution aware. To deploy the theme to other environments, use export to excel functionality and import it in the target environment.
  2. A new field named color is added to the entity customization screen. This color is used to represent the entities in the navigation bar as shown below.



You will not be able to change the color of the entity forms, they are still white as I write this blog.

Best Practices

Check the following link for the best practices and color contrasts.

CTI integration between CRM USD and Microsoft Lync - Part 2

This is the second part of the blog CTI integration between CRM USD and Microsoft Lync - Part 1. The last blog covered how to receive the CTI event in USD. In this blog we will use the telephone number provided by the CTI system to pop up a customer record in USD.  To achieve this we have to create a windows navigation rule record.

Creating a Window Navigation Rule

  1. Logon to CRM.
  2. Navigate to Settings>>Window Navigation Rules
  3. Click “New” and fill in the following fields

    Field Name Value
    Name LyncIntegration Route
    Order 1
    Hosted Control LyncCTIManager
    Direction Both

  4. Save the record.
  5. Click + in the CTI search section of the form, as shown below, to create a new CTI Search record.

  6. Fill the form with the following values as shown below.

    Field Name Value
    Name LyncIntegration ContactSearch
    Order 1
    FetchXML <fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
      <entity name="contact">
        <attribute name="fullname" />
        <attribute name="parentcustomerid" />
        <attribute name="telephone1" />
        <attribute name="emailaddress1" />
        <attribute name="contactid" />
        <order attribute="fullname" descending="false" />
        <filter type="and">
          <condition attribute="telephone1" operator="eq" value="[[cti.telephone1]]" />

    To create the fetchxml use the advance find functionality in CRM and then download the xml. The highlighted part in the xml [[cti.telephone1]] represents the parameter passed as a query string by the LyncConnector middleware application

  7. Save the record and return back to windows navigation rule.
Based on the result of the CTI Search, we can configure the behaviour of the windows navigation rule.

Single Match (Single contact is found)

  1. Under Single Match, in the Decision field, select Create Session, Load Match then Do Action.
  2. Under Single Match, in the Action field, click the search icon to select a value, and then click New.

  3. It will open up a new “Action Call” record. Fill this form with the following values:

    Field Name Value
    Name LyncIntegration Open Contact
    Hosted Control CRM Global Manager
    Action Open CRM Page
    Data Id=[[$Context.Id]]

  4. Save the "Action Call” record and return back to the windows navigation rule record.
  5. Under the Result area, fill the Destination, Target Tab and Show Tab field as shown in the screen shot below.

  6. Save the window navigation rule record.

No Matches (No contact is found)

  1. Under No Matches, in the Decision field, select Do Action.
  2. Under No Matches, in the Action field, click the search icon to select a value, and then click New.

  3. It will open up a new “Action Call” record. Fill this form with the following values:

    Field Name Value
    Name Search Contact Action Call
    Hosted Control Search
    Action Find
    Data contact

  4. Save the "Action Call” record and return back to the windows navigation rule record. This action will open a USD search screen with the contact tab selected.
  5. Save the windows navigation rule.

Multiple Matches

I did not find a way to display multiple results. I will try to come up with a custom hosted control in the future. If anyone has any idea please let me know.

Testing the Integration

  1. Logon to USD.
  2. Ring the Lync number.
  3. If everything is working properly and system has found the matching contact, the system will then display the contact record and it will start a session as shown in the screen shot below

  4. If no contact is found with the matching number USD will display the search screen with the contact tab selected as shown in the screen shot below. There is an issue with this solution; USD does not set the focus on the “Search” tab.


Where to From Here

This is the simplest example of the integration. The middleware built in this blog is just posting the URL on a generic listener port. It can be modified to send Lync chat and contact information.
Going forward, middleware can be used to retrieve the interaction history from Lync and create CRM records as required.
Some people suggested to process the call in the LyncConnector, pass the customer id to USD, and create the session.  I am just exploring USD and would rather create my custom search control in USD.
Please keep the suggestions coming.

Sunday, May 10, 2015

CTI integration between CRM USD and Microsoft Lync - Part 1

Last year, Microsoft released USD (Unified Service Desk) for CRM 2013. USD is a framework to build contact centre applications to provides a unified view of customer data stored in CRM and other applications.
It provides the adapters and modules to manipulate CRM UI elements, agent scripting, configuration toolbars and a CTI adapter.  For more information on USD please check
For this tutorial, we are only interested in CTI adapters. The following 2 types of adapters can be used to integrate USD with CTI systems.
  • Generic listener adapter:
    USD provides this adapter out of the box. This adapter listens for HTTP request on a port 5000 ( http://localhost:5000/). On receiving a request, the generic listener adapter extracts a query string from the URL and uses the query string as parameters to raise a CTI screen pop up in USD.

  • Custom CTI adapter:
    User Interface Integration(UII) CTI framework provides the component to build custom CTI adapters. The customer adapter can provide a lot of functionality to manage calls and agent state. Here is the link on how to build a custom CTI adapter for USD.

  • We will be using the generic listener adapter to achieve USD and Lync integration.


    1. Access to CRM2013 (I m using a on premise CRM)
    2. Lync client installed on the development machine 
    3. Microsoft Lync  2013 SDK installed on the development machine (Download)
    4. USD (Unified Service Desk) installed on the development machine
      The following article lists the step by step instructions to install USD.  The USD installation involves:
      • Installing USD client (UnifiedServiceDesk.msi)
      • Deploying USD Solution using Package Deployer (CRM2013-USD-PackageDeployer.exe) For this tutorial, deploy “CRM 2013 SP1” solution

    Process Flow Diagram

    1. Customer makes a phone call
    2. Phone call pop up appears in the Lync Client
    3. A custom middleware application receives the conversation event and posts a HTTP request on “http://localhost:5000” with customer phone number.
    4. USD generic listener pickup the event, extract the query parameter and use these parameters to pop contact record

    Configuring the generic listener adapter in CRM

    Make sure that all the prerequisite steps have been completed
    1. Logon to CRM  and navigate to “Settings>>Hosted Controls”
    2. Click “New” enter the fields as shown in the screen shot below

      USD component, Display Group,Assembly URL and Assembly Type are the important fields and should contain the exactly same values.
      Assembly URL : Microsoft.Crm.UnifiedServiceDesk.GenericListener
      Assembly Type: Microsoft.Crm.UnifiedServiceDesk.GenericListener.DesktopManager
    3. Save the record.

    Creating a Lync Connector (Middleware application)

    A Lync connector application will capture the conversation event of the Lync client when a phone call is made or received.  This application is a client side application.
    I am creating the Lync connector as a WPF application.  I don’t need a user interface for the connector for this blog but may use it add more functionality to it in future.
    1. Create a new WPF application project and name it “LyncConnector”.

    2. Add “Microsoft.Lync.Model.dll” as reference to the project. The file will be available in the following location.
      \Microsoft Lync\SDK\Assemblies\Desktop

    3. The following code is going in the “MainWindow.xaml.cs file.
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows;
      using System.Windows.Controls;
      using System.Windows.Data;
      using System.Windows.Documents;
      using System.Windows.Input;
      using System.Windows.Media;
      using System.Windows.Media.Imaging;
      using System.Windows.Navigation;
      using System.Windows.Shapes;
      using Microsoft.Lync.Model;
      using Microsoft.Lync.Model.Conversation;
      using System.Net;
      using System.Text.RegularExpressions;
      using System.Collections.Specialized;
      namespace LyncConnector
          /// <summary>
          /// Interaction logic for MainWindow.xaml
          /// </summary>
          public partial class MainWindow : Window
              private LyncClient _lyncClient;
              public MainWindow()
                  //Get the link client- Make sure Lync client is running
                  _lyncClient = LyncClient.GetClient();
                  // Invoke the conversation event when the conversation starts in Lync Client
                  _lyncClient.ConversationManager.ConversationAdded +=
                      new EventHandler<Microsoft.Lync.Model.Conversation.ConversationManagerEventArgs>(
              void OnConversationAdded(object sender, Microsoft.Lync.Model.ConversationConversationManagerEventArgs e)
                  // Get the properties for this conversation.
                  IDictionary<ConversationProperty, object> properties = e.Conversation.Properties;
                  // Get the Contact object for the person initiating the conversation.
                  Contact inviterContact = properties[ConversationProperty.Inviter] as Contact;
                  // Get the URI of the inviter.
                  string inviterUri = inviterContact.Uri;
                  // Try to match a phone number in the URI.
                  Regex phoneRegex = new Regex(@"\+(\d+)");
                  Match phoneMatch = phoneRegex.Match(inviterUri);
                  string callerId = string.Empty;
                  if (phoneMatch.Success)
                      // Load the data only if the caller is from a PSTN number.
                      callerId = phoneMatch.ToString();
              private void LoadDataForCaller(string callerId)
                  string UsdLocalAddress = "http://localhost:5000";
                  using (var wb = new WebClient())
                      var data = new NameValueCollection();
                      // By default generic listener pass the follwing 3 parameters to USD/
                      //You can use them to post some data. If you don't use them then generic listener will still post the empty values for these parameters. 
                      data["ani"] = Ani;
                      data["dnis"] = Dnis;
                      data["type"] = CallType;
                      data["telephone1"] = callerId;
                          if (Uri.IsWellFormedUriString(UsdLocalAddress, UriKind.RelativeOrAbsolute))
                              wb.UploadValues(new Uri(UsdLocalAddress), "POST", data);
                      catch (SystemException ex)
                          //System.Windows.MessageBox.Show(ex.Message, "Failed to send call event");

    4. Compile  and Run the code

    Test the integration

    1. Make sure Lync client is running
    2. Make sure Lync Connector application is running.
    3. Logon to USD and click on the setting >>Debug


    4. Delete all the entries in the “Action Calls” tab by clicking the delete button as shown in the screen shot below.


    5. Make a phone call or ask someone to ring you on Lync. If everything is working properly,  a new event will appear in Action Calls tab as shown in the screen shot.


    So here you go, we have successfully passed the caller's phone number to USD.
    That is it for today. In the next tutorial we will use this phone number to pop up the contact record.

    Tuesday, March 31, 2015

    How to create a message in a Scribe Insight queue using C#

    If you are familiar with Scribe Insight then you would know that “queue” based integration is the preferred integration method. The reason for that is performance. Multiple message processors can be allocated to process the queues. For more information please read this blog on the “Message Processor”.

    Scribe Adapters can create the queue message automatically, but, what if we need to create the queue message from the portal or a custom program? This blog will show you how to create a MSMQ message using C#.

    The code below will create a message with the label "PortalCustomer" and put it in the ScribeIn queue.

    using System;
    using System.Messaging;
    namespace MSMQ
        class Program
            static void Main(string[] args)
                Console.WriteLine("Initiating MSMQ object");
               // queue address
                string queueAddress = @"FormatName:Direct=OS:machinename\private$\scribein";
                Console.WriteLine("Queue Path: {0}", queueAddress);
                //Create an instance of MSMQ Manager
                MSMQManager msmq = new MSMQManager(queueAddress);
                Console.WriteLine("Message sent successfully");
        // Class that initiate the message queue and send the message
        class MSMQManager
            private string queueAddress;
            public MSMQManager(string queueAddress)
                this.queueAddress = queueAddress;
            //Creating and sending the message
            public void SendMessageToQueue()
                MessageQueue msMq = new MessageQueue(queueAddress);
                   //create an instance of customer class
                    Customer req = new Customer()
                    Console.WriteLine("Creating customer request: {0}", req.ToString());
                    //create the message
                    Message m = new Message()
                        Body = req,
                        Label = "PortalCustomer",
                        Recoverable = true,
                    Console.WriteLine("Initialising message: {0}", m.Label);
                catch (MessageQueueException e)
                catch (Exception e)
                    Console.Write("Error Message: {0}. Trace: {1}", e.Message, e.StackTrace);
    Here is the code for the customer class.

    using System;
    namespace MSMQ
        public class Customer
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DateTime ReceivedDate { get; set; }
            public override string ToString()
                return string.Format("Link: {0} - Response: {1} - ReceivedDate: {2}", FirstName, LastName , ReceivedDate.ToString());

    Run the code and look in the ScribeIn queue or in the Dead Message queue (if you don’t have any integration using label “PortalCustomer”).


    Make sure that MSMQ are installed on the machine where the code is hosted, and can communicate  with Scribe server on port 1801.

    Thursday, February 5, 2015

    Microsoft CRM publisher stuck on “Initializing” in Scribe Insight

    If you are trying to create a CRM publisher in Scribe Insight and it is stuck on “Initializing” as shown in the screen shot below:
    It means that there is something wrong.


    If you check in the event viewer, you may find the following error:
    An unexpected error occurred.
    Microsoft Dynamics CRM Publisher
    Error setting publisher settings: System.Messaging.MessageQueueException (0x80004005): Invalid queue path name.
       at System.Messaging.MessageQueue.ResolveFormatNameFromQueuePath(String queuePath, Boolean throwException)
       at System.Messaging.MessageQueue.Exists(String path)
       at Scribe.AdapterBase.Publisher.QueueService.InitPublisherQueues(String pubInQueueName, String pubSucceededQueueName, String pubFailedQueueName)
       at Scribe.AdapterBase.Publisher.ScribePubWorkerBase.InitPublisherQueues()
       at Scribe.AdapterBase.Publisher.ScribePubWorkerBase.setSettings(String settingsXML, String entitiesXML, Object lastRunTime, Object lastRunTimeUTC)
    The error suggests that there is problem with the path of the queue


    Compare the queue names in the CRM publisher and message queues in component services as shown in the following screen shots.
    image image
    If the queue names are different then we have to update the queue names in the internal database.
    Note: I don’t know if this is a supported solution.
    1. Backup your ScribeInternal database.
    2. Look into the scribe.bridges table and find the bridgeid of your CRM publisher. All the publisher settings including the queues are stored in the settings column.
    3. Now update the settings column with the proper queue paths.
    Note: Settings column stores the data as XML. Please be careful when updating the column.

    Wednesday, January 28, 2015

    'Security Negotiation Exception' during plug-in execution in CRM2013

    A few months ago, we experienced an issue during a plugin execution in the dev. environment. We were using Scribe Insight for integration. We were using the “Microsoft Dynamics CRM publisher” for scribe that registered a plugin on the contact entity. Everything was working perfectly until we received the following error:

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The following error has occurred in the Scribe Change History plug-in: System.ServiceModel.Security.SecurityNegotiationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #0CCC3255  


    During troubleshooting we found the following entry in the event viewer of the backend server. 

    The Kerberos client received a KRB_AP_ERR_MODIFIED error from the server serviceaccountname. The target name used was HTTP/CRMFrontEndServer. This indicates that the target server failed to decrypt the ticket provided by the client. This can occur when the target server principal name (SPN) is registered on an account other than the account the target service is using. Ensure that the target SPN is only registered on the account used by the server. This error can also happen if the target service account password is different than what is configured on the Kerberos Key Distribution Center for that target service. Ensure that the service on the server and the KDC are both configured to use the same password. If the server name is not fully qualified, and the target domain (DomainName) is different from the client domain (DomainName), check if there are identically named server accounts in these two domains, or use the fully-qualified name to identify the server 

    The “EventSourceName” was Kerberos.

    Looking at the error we hypothesised that there was an SPN issue for the CRMFrontEndServer server.

    You can receive this error for any plugin published in the sandbox. It will only happen if the sandbox service is not installed on the same server as CRM web site and kerberos authentication is enabled for the website.


    We used the following account to list all the SPNs registered for the serviceaccountname.
    setspn –l domain\serviceaccountname

    The command displays only the SPN registered on the HTTP/  (Fully Qualified domain name of the CRM front end server).

    We added a new SPN on the servername using the following command setspn –a http/CRMFrontEndServer domain\serviceaccountname That was it. We restarted the sandbox service and the error was gone.

    For more information on SPNs and their configuration you can check out this KB article from Microsoft.