Thursday, September 15, 2016

How to create a custom Lookup control to be used in web resource in Microsoft Dynamic CRM (MS CRM)?



Requirement 

I was working for one report requirement, which require to filter out records based on Account (Customer).

Let’s assume, if we want to list all opportunities based on account selected.

The first question comes to my mind was, can I use look up control of dynamic CRM as a control directly in my custom report (web-resource) ?

The answer is ‘Yes’, with a little bit of scripting and CSS, we can create our own look up control and invoke Dynamic CRM Look Up Dialog box.

Guidelines to write good JavaScript code in Microsoft Dynamic CRM

https://vjcity.blogspot.com/2019/08/guidelines-to-write-good-javascript.html


Outcome as in images below












Solution with step by step approach

1)      We need to make reference to JQuery and ClientGlobalContext.js.aspx files in our solution.

<script type="text/javascript" src="ClientGlobalContext.js.aspx"></script>
<script src="https://test.crm4.dynamics.com//WebResources/vj_jquery.min"></script> 

2)      The JavaScript method which are used to invoke lookup dialog box of dynamic CRM.

function OpenLookup(objecttypecode)
{
   var serverurl = "https://test.crm4.dynamics.com";
   var DialogOptions = new Xrm.DialogOptions();
   DialogOptions.width = 800;
   DialogOptions.height = 600;

   var url = serverurl + "/_controls/lookup/lookupsingle.aspx?class=null&objecttypes=" + objecttypecode + "&browse=0&ShowNewButton=0&ShowPropButton=1&DefaultType=0";

   Xrm.Internal.openDialog(url, DialogOptions, null, null, CallbackFunction);
}

function CallbackFunction(event)
{
   var name = event.items[0].name;
   var id = event.items[0].id;
   $('#txt_lookup_name')[0].value = name;
   $('#txt_lookup_id')[0].value = id;
}

Objecttypecode parameter of method OpenLookup, represent internal value for an entity. 

For an example.
Entity
Object Type Code
account
1
contact
2
opportunity
3

You can further refer to various entity type and its internal object type code here


3)      A small bit of CSS for making it look like CRM Look Up control.

    <style>
        .enjoy-css {
            display: block;
            float: left;
            padding:2px 5px;
            border: 1px solid #b7b7b7;
            font: normal 12px/normal segoe ui;
        }
        .lookupImg {
            display: block;
            float: left;
            padding-top:2px;
            border: 1px solid #b7b7b7;
        }
        .lookupAlignment {
            text-align:left;
            vertical-align:middle;
        }
        span {
            font: normal 16px/normal segoe ui;
        }
        td {
            font: normal 14px/normal segoe ui; width:200px;
        }
    </style>

4)      HTML Code for rendering control and invoking JavaScript methods.

OpenLookup – method is highlighted in below code and ‘1’ is passed to open lookup control for account entity.

<body>
    <br />
    <span>
        Custom Lookup Control by - Vipin Jaiswal ( <u>vipinjaiswal12@gmail.com</u> )
    </span>

    <br /><br /><br /><br />
    <table>
        <tr>
            <td>Account </td>
            <td class="lookupAlignment">
                <input type="text" id="txt_lookup_name" class="enjoy-css" />
                <img id="img_lookup_search" src="https://test.crm4.dynamics.com//WebResources/vj_search_normal.gif"
                    onclick="OpenLookup('1')"
                    class="lookupImg" />

            </td>
        </tr>
        <tr>
            <td>Selected Account Guid
            </td>
            <td>
                <input type="text" id="txt_lookup_id" class="enjoy-css" />
            </td> 
        </tr> 
    </table>
    <br />   
</body>



5)      An Image which represent search Icon





Here I am updating this article further, just to inform that we would be getting all values of the Selected view from CRM Dialog box.


We can get other values of the view as well from the dialog box.
In above article, we JavaScript method – function CallbackFunction(event)
In the parameter event, we are getting all the values of selected view.

I put a debugger to check, values.




And here are the values in the JSon format. 

[{"name":"name","value":"XX"},
{"name":"telephone1","value":"+917974058950"},
{"name":"address1_city","value":"Bhopal"},
{"name":"primarycontactid","value":"Test Contact"},{"name":"accountprimarycontactidcontactcontactid.emailaddress1","value":"vipinjaiswal12@gmail.com"},
{"name":"processid","value":""},
{"name":"processts","value":""}]

I hope you find this article interesting.

Thanks.

vipinjaiswal12@gmail.com

Friday, September 9, 2016

Could not load file or assembly 'Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies



Exception Messages

File Load Exceptions: "Could not load file or assembly 'Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.
(Exception from HRESULT: 0x80131040)":"Microsoft.Xrm.Sdk, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"


How and When Problem Occurs

It so happen that I referred latest version of Microsoft Dynamic CRM Dll ('Microsoft.Xrm.Sdk) in my project. The version for this DLL is 8.0.0.0.

I forgot to update other Microsoft Dynamic CRM Dll’s (Microsoft.Crm.Sdk.Proxy) in the same project. The version for this DLL is 6.0.0.0.

These DLL’s are dependent on each other and cannot refer to other version of DLL’s at the same time in same project. So there was a mismatch of the version and that’s why CRM platform given File Load Exceptions.


Solution :

When connecting to MS CRM 2016, we need to refer MS CRM 2016 SDK DLL’s with all same version to avoid File Load Exception.

You can download MS CRM 2016 SDK latest DLL from here.

Microsoft.Xrm.Sdk                          version – 8.0.0.0
Microsoft.Crm.Sdk.Proxy                version – 8.0.0.0



Thursday, September 8, 2016

Metadata contains a reference that cannot be resolved: MS CRM (Microsoft Dynamic CRM)

Exception Messages

Metadata contains a reference that cannot be resolved: 'https://************.*******/XRMServices/2011/Organization.svc?wsdl'.

Inner Exception Messages

The remote server returned an error: (407) Proxy Authentication Required.

How and When Problem Occurs

This is generic WCF Service issue, usually occur when a custom application is unable to resolve service references.

The above error is very generic and it could be due to multiple reason, therefore it is advisable to look more into Inner exception details or detail exception data.

Here, we are going to discuss special case about “The remote server returned an error: (407) Proxy Authentication Required.” And this resulted in unable to resolve service reference.

Note : When you are connected on LAN or working in your organization, there may be a possibility  that an organization has set default proxy to avoid access to such services.

Solution :

Try turning off the proxy and check if your application or custom code is able to resolve metadata reference.

If “Yes”, then definitely it’s a proxy issue, and we can edit the config file to provide required authentication.

Add the below tag to avoid proxy issue.               

  <system.net>
    <defaultProxy useDefaultCredentials="true"></defaultProxy>
  </system.net>


Thanks.

Let me know if this does not resolve issue.


Thursday, August 18, 2016

How to find email template being used in workflows in Microsoft Dynamic CRM

In Microsoft Dynamic CRM, we use workflow to automate business processes.
We often use Send Email as a step in workflow to send out any notification or communication.

We have two option here to Send an Email.
1)   Create Email Message
This option creates an email template specific to workflow and no other workflow in a CRM system can use this.

2)   Use Template
Here we use existing template to send our communication.

When we go for second option that is “Use Template”, then how do we know if this email template is being used by any other workflow in the system ?

Now what if someone edit this template, it would then be reflected in all existing workflows using this template.


How to identify the template that is being used in the workflow so I know which one to edit.

Solution in brief

There is no direct and out of the box way to find all references of email template being used in any of the workflow in Microsoft Dynamic CRM.

However, there are indirect ways to find out all references of an email template.
A)     Using SQL Statements
B)     Using MS CRM API and building custom application.

A)   Solution in Details – Using SQL Statement

Here is a SQL Query statement which can be run under MS CRM database to get the name of workflow using given Email template.

  Select ActiveWorkflowIdName,PrimaryEntity,*
  from Workflow 
  Where WorkflowId in (  
        Select ObjectId
        From DependencyNode
        Where DependencyNodeId In (
               SELECT DependentComponentNodeId
               FROM [DependencyBase]
               Where RequiredComponentNodeId In (    
                  SELECT DependencyNodeId
                  FROM DependencyNode  
                  Where ObjectId = '00000000-000000000-0000-000000000000')))

Note : In Order to use this query we need to replace '00000000-000000000-0000-000000000000' with actual email template Guid.


Now how to find the email template Guid ?
Here are  the steps to find Guid for a given email Template.

Step 1) Go to Setting -> Template -> Email Templates.

 

Step 2) Open you email template as in below image and copy the complete url as highlighted in image

 

Step 3) If Url is not displayed, then open template in another browser window using short cut key Ctrl + N.

Step 4) Consider below url is following example.

https://kalunge.crm4.dynamics.com/tools/emailtemplateeditor/emailtemplateeditor.aspx?id=%7b62E5E1EE-9F60-E611-80E4-5065F38B3531%7d

Within %7b ---  and %7d is url template unique guid for internal CRM reference.

You need this guid to replace with above guid as in SQL Query.


B) Solution in Details – Using MS CRM Web API Calls

The SQL solution is a quick one, but it has got its limitations
1)    Its suits only a developer who understand technical aspects.
2)    It can only work in MS CRM (On-Premise) and ADFS.
3)    MS CRM Online does not support SQL Statements.

There is a class in MS CRM which find out dependent component of a given object.
In our scenario, template is being an object and workflows are dependent components.

The name of the class is : RetrieveDependentComponentsRequest Class

You can refer this MSDN article for further reference.


We can built a custom application using such classes and MS CRM SDK and make it available directly for business user to check email template references.

Happy Learning J


Saturday, August 6, 2016

A binary operator with incompatible types was detected. Found operand types 'Edm.DateTimeOffset' and 'Edm.String' for operator kind 'GreaterThanOrEqual'


Exception Details

Type1 A binary operator with incompatible types was detected. Found operand types 'Edm.DateTimeOffset' and 'Edm.String' for operator kind 'GreaterThanOrEqual'

Type2 Operator 'ge' incompatible with operand types 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' and 'System.String' at position 10.


Usually the error comes when there is a syntax error in the query we designed and dealing with date time filters in Microsoft Dynamic CRM .

Now how to use Date Filter in Web API or O Data Query in Microsoft Dynamic CRM ?

Let’s consider a case where we want to query all sales order with booked date in year 2015.

SQL select query for this would be

Select *
from SalesOrder
Where new_BookedDate >= '2015-01=01' And new_BookedDate <= '2015-12-31'


Equivalent Fetch Xml would be


    <fetch mapping="logical" version="1.0">
      <entity name="SalesOrder">
        <all-attributes />
        <filter>
          <condition attribute="new_BookedDate" operator="ge" value="2015-01=01" />
          <condition attribute="new_BookedDate" operator="le" value="2015-12-31" />
        </filter>
      </entity>
    </fetch>
     

OData Syntax for Query would be

// Getting Server Context
var serverUrl = Xrm.Page.context.getClientUrl();

// Defining the OData complete Url
serverUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/" ;

// Name of the entity
serverUrl = serverUrl + "SalesOrderSet?";  

// Filter Criteria with Date
serverUrl = serverUrl + "$filter=new_BookedDate ge datetime'2015-01-01' and new_BookedDate 



Web API Syntax for Query would be

// Getting Server Context
var serverUrl = Xrm.Page.context.getClientUrl();

serverUrl = serverUrl + "/api/data/v8.1/" ; // Defining the OData complete Url
serverUrl = serverUrl + "salesorders?";    // Name of the entity

// Filter Criteria with Date
serverUrl = serverUrl + "$filter=new_BookedDate ge 2015-01-01 and new_BookedDate le 2015-12-31"; 


I hope the information is useful !!!

Crm Exception: Message: 'Entity' metadata entity doesn't contain metadata attribute with Name


Crm Exception: Message: 'Entity' metadata entity doesn't contain metadata attribute with Name = 'isslaenabled'., ErrorCode: -2147217149

The specified field does not exist in Microsoft Dynamics CRM

Exception Details


MSCRM Error Report:
--------------------------------------------------------------------------------------------------------
Error: 'Entity' metadata entity doesn't contain metadata attribute with Name = 'isslaenabled'.
Error Number: 0x80041103
Error Message: 'Entity' metadata entity doesn't contain metadata attribute with Name = 'isslaenabled'.
Error Details: 'Entity' metadata entity doesn't contain metadata attribute with Name = 'isslaenabled'.
Source File: Not available
Line Number: Not available
Request URL:
Stack Trace Info: [CrmException: 'Entity' metadata entity doesn't contain metadata attribute with Name = 'isslaenabled'.]
   at Microsoft.Crm.Application.Platform.ServiceCommands.PlatformCommand.XrmExecuteInternal()
   at Microsoft.Crm.Application.Platform.ServiceCommands.ImportSolutionCommand.Execute()
   at Microsoft.Crm.Application.Platform.DataSource.ImportSolution(Byte[] customizationFile, Boolean overwriteUnmanagedCustomizations, Boolean publishWorkflows, Guid importJobId, Boolean convertToManaged, Boolean skipProductUpdateDependencies, Boolean holdingSolution, IOrganizationContext context)
   at Microsoft.Crm.Web.Tools.Solution.SolutionImportProcessPage.ImportSolution()

   at Microsoft.Crm.Web.Tools.Solution.SolutionImportProcessPage.ProcessRequestData()

Exception Detailed Trace 
--------------------------------------------------------------------------------------------------------
Web Service Plug-in failed in SdkMessageProcessingStepId: {1B830950-E106-4EE1-B3FD-D348CB65DC8D}; EntityName: none; Stage: 30; MessageName: ImportSolution; AssemblyName: Microsoft.Crm.Extensibility.InternalOperationPlugin, Microsoft.Crm.ObjectModel, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35; ClassName: Microsoft.Crm.Extensibility.InternalOperationPlugin; Exception: Unhandled Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Web.Services.Protocols.LogicalMethodInfo.Invoke(Object target, Object[] values)
   at Microsoft.Crm.Extensibility.InternalOperationPlugin.Execute(IServiceProvider serviceProvider)
   at Microsoft.Crm.Extensibility.V5PluginProxyStep.ExecuteInternal(PipelineExecutionContext context)
   at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
Inner Exception: Microsoft.Crm.Metadata.MetadataAttributeMetadataNotFoundException: 'Entity' metadata entity doesn't contain metadata attribute with Name = 'isslaenabled'.
   at Microsoft.Crm.Tools.ImportExportPublish.ImportXml.RunImport(String[] ImportEntities)
   at Microsoft.Crm.Tools.ImportExportPublish.ImportXml.RunImport()
   at Microsoft.Crm.WebServices.ImportXmlService.ImportSolutionSkipCapable(Boolean overwriteUnmanagedCustomizations, Boolean publishWorkflows, Byte[] customizationFile, Guid importJobId, Boolean convertToManaged, Boolean skipProductUpdateDependencies, Boolean holdingSolution, ExecutionContext context)


Cause of an Exception

1) This error gets generated usually when doing import of a solution.
2) When you are trying to create any field in Microsoft Dynamic CRM.

Resolution

Solution being exported should match the version where it is being imported of a CRM instance

1) Check your solution version, if it is
     - Version 8.0  (denote MS CRM 2016)

      OR

     - Version 8.1  (denote MS CRM 2016 with Service Pack 1)

2)  Check your destination CRM instance version where you are trying to import your                  solution to.



3) Try to match your solution version with CRM instance version.

Once you apply a Service Pack 1 to Microsoft Dynamic CRM, don't forget to update an organization from Deployment Manager

1) Open deployment manager.
2) Select your organization.
3) Right click an organization and select update.

That's it, import of a solution should be working then.