Saturday, 13 June 2015

Analyze plug-in performance in Dynamics CRM 2015 On-Prem/Online



The Plug-in Profiler is a tool that profiles the execution of plug-ins and custom workflow activities for an enhanced debugging experience in Microsoft Visual Studio. This tool, which can be run from the Command Prompt window or from within the Plug-in Registration tool, makes developing custom code against Microsoft Dynamics CRM 2015 and Microsoft Dynamics CRM Online 2015 Update quicker and easier. In addition, users can profile the execution of failing code and send the results to the developer of the code or independent software vendor (ISV) for analysis. The developer can replay the plug-in or custom workflow activity execution and debug the code remotely even when disconnected from the Microsoft Dynamics CRM server.
The tool can be used in either the debug or replay mode. Each of these modes is described in the following sections.

 

Debug a plug-in using the plug-in profiler

1.       Run the Plug-in Registration tool. You can find the tool’s executable file in the Tools\PluginRegistration folder of the SDK. Download the Microsoft Dynamics CRM SDK package.
2.       Click or tap CREATE NEW CONNECTION to connect to a Microsoft Dynamics CRM server and organization. For more information on connecting to a server and organization, refer to the SDK topic: Walkthrough: Register a plug-in using the plug-in registration tool.
3.       Register a plug-in and step on the Microsoft Dynamics CRM server. Keep a copy of the debug compiled plug-in assembly on the computer where you are running the tool.
4.       In the toolbar for the target organization, select Install Profiler. You will now see a Plug-in Profiler node in the list.
5.       Select a plug-in step and click Start Profiling in the toolbar to begin profiling. You can choose how the profiler executes in the displayed Profiler Settings dialog.
6.       Perform the operation in Microsoft Dynamics CRM that causes the plug-in to run. For example, if the step is configured for an update to an account, then update an account.
7.       If you have selected the Exception option in the Profiler Settings dialog, after the plug-in throws an exception and the Business Process Error dialog is displayed, clickDownload Log File and save this file. Alternately, if the plug-in does not throw an exception, click Stop Profiling.
8.       In the Plug-in Registration tool, click Debug.
9.       In the Debug an Existing Plug-in dialog box, provide the requested information in the Setup tab. Enter the location of the previously saved log file in the Profile field. Enter or choose the location of the plug-in assembly and the class name of the plug-in that was executed.
10.    Launch Microsoft Visual Studio and attach the debugger to the PluginRegistration.exe process.
11.    Set a breakpoint in the plug-in code.
12.    Click Start Execution in the Debug an Existing Plug-in dialog box.
13.    After a slight delay, the plug-in will execute using the same execution context that was passed to it by the Microsoft Dynamics CRM server and the debugger will stop execution on the breakpoint that you previously set.
14.    Continue debugging the plug-in as you would normally do. Any traces that the plug-in outputs are shown in the Debug an Existing Plug-in dialog box.
At this point you can alter the plug-in code, build it, re-attach the debugger to the PluginRegistration.exe process, and click Start Execution to continue with your debugging session. While performing these operations, you do not need to close the Debug an Existing Plug-in form.
You do not need to re-deploy the plug-in to the Microsoft Dynamics CRM server until after you have fixed the code problem. This debugging scenario works even if you have an optimized version of the plug-in on the server and a debug version of the plug-in on the computer where you are debugging.

Replay plug-in execution

Replaying plug-in execution does not require a connection to a Microsoft Dynamics CRM server and organization. The advantage of this method is that you can obtain the plug-in execution profile from a customer and debug the plug-in remotely. A restriction of the replay feature is that you cannot change the sequence of calls your plug-in code makes in the debugger while you are debugging.
The replay feature provides the plug-in with a snapshot of the call data and event execution context from the Microsoft Dynamics CRM server. You are getting the same events, GUIDs, and so on from calls to the Organization service but no data is being modified on the server as you debug the plug-in. During the debugging procedure in the previous section, the plug-in actually connects to the server and makes calls in real time.

Replay plug-in execution

1.       Launch Microsoft Visual Studio and attach the debugger to the PluginRegistration.exe process.
2.       Click REPLAY PLUG-IN EXECUTION.
3.       Enter the log and plug-in assembly locations in the dialog box.
4.       Click Start Execution.
5.       Debug the plug-in as you would normally.

Run the plug-in profiler standalone

The profiler can be executed from a Command Prompt window independent of the Plug-in Registration tool. This is useful to obtain the plug-in profile log from a customer's Microsoft Dynamics CRM server to debug a failed plug-in. A developer can then use that log to replay the plug-in's execution in the Plug-in Registration tool and debug the plug-in usingMicrosoft Visual Studio.

Run the plug-in profiler from a command prompt

1.       Open a Command Prompt window and set the working directory to the Tools\PluginRegistration folder in the SDK download.
2.       Type the command: PluginProfiler.Debugger.exe /?.
3.       Review the supported parameter list and re-run the PluginProfiler.Debugger.exe program with the appropriate parameters.


Dynamics CRM and ILMerge: The Easy Way to Merge DLLs for Plugins


 Being able to use external DLLs in Dynamics CRM plugins is challenging but doable. Most people who have been doing development on the Dynamics CRM platform for any period of time know that it is not enough to simply reference the DLLs in Visual Studio – you must somehow make them available to run on the server – this can range from mildly annoying to impossible (if you using CRM Online.)
You can read the Dynamics CRM Blog article by Michael Scott for more details, but here is the jist (the same rules apply to 2013/2015):
You may have noticed that Microsoft Dynamics CRM 2011 (and CRM 4 before it) does not really have support for referencing custom assemblies from a plug-in assembly. You are limited to .NET Framework assemblies and the public Microsoft Dynamics CRM 2011 Software Development Kit (SDK)assemblies. In Microsoft Visual Studio, your references will look something like this:
If you wanted to reference an assembly that you had written, your options were pretty limited:
§  Register the assembly on disk with any referenced assemblies in the same directory.
§  Register the referenced assembly in the GAC
§  Include the relevant source code in the plug-in assembly
With the introduction of Solutions in Microsoft Dynamics CRM 2011, the first two options are not very manageable (as they require special setup on multiple servers during the installation of the solution”>PICTURE REMOVED]
If you wanted to reference an assembly that you had written, your options were pretty limited:
§  Register the assembly on disk with any referenced assemblies in the same directory.
§  Register the referenced assembly in the GAC
§  Include the relevant source code in the plug-in assembly
With the introduction of Solutions in Microsoft Dynamics CRM 2011, the first two options are not very manageable
. In addition, those options don’t work in Microsoft Dynamics CRM Online, since assemblies must be registered in the database in CRM Online. If you include source code, as the last option suggests, then all of the benefits of a referenced assembly are lost, without gaining any real benefits.
In the same article it is recommended to use ILMerge. ILMerge is a tool from Microsoft Research that can combine multiple DLLs into a single DLL – eliminating the problem (in the case of Dynamics CRM) of having multiple DLL files.
The article goes on to describe the basics of using ILMerge to create a single plugin DLL. While I have done this on many projects over the year it has always been more complicated to initially setup and maintain than I would prefer. It can also be challenging to teach new developers – many of whom are still getting comfortable with Dynamics CRM development.
I recently decided to do some research and figure out a simple and well defined set of step-by-step instructions to use ILMerge in development. In the next several steps I will describe the exact process I now use, which doesn’t involve any editing of MSBUILD files, creation of PowerShell or BAT scripts, etc. It only requires the use of Nuget and the Visual Studio GUI.
1.       Start by creating a new Blank Solution in Visual Studio (Other Project Types -> Video Studio Solutions.) Name it as you wish, I used ThinkCrmBlog.PluginDllMerge.

2.       Now that you have a new solution add a couple of class libraries. I’ve named mine ThinkCrmBlog.CrmHelper (this is inline with my best practice of having a standalone DLL of helper classes that can be used for CRM development but are not specific to any particular CRM org and can be used in plugins, workflows, and client side code) and ThinkCrmBlog.DemoPlugin (which will hold my IPlugin class.
3.       So now your solution should look like this picture (assuming you deleted the Class1.cs files.)
4.       We’ll add the Dynamics CRM libraries using NuGet.
5.       Search for Microsoft.CrmSdk.CoreAssemblies and install.
6.       You want to install to both projects.
7.       Using NuGet greatly simplifies some tasks by including required dependencies. In this case it is Microsoft.IdentifyModel. Although technically not required to compile a plugin DLL if you were to use the core assemblies in a client side app it is necessary and can be something of pain when you do not realize you need it until runtime.
8.       You can tell that everything has succeeded by the green check.
9.       So now it is time to get ILMerge installed. Luckily for the modern developer we have NuGet to make this super simple. We don’t want just ILMerge, we want a tool that automates the ILMerge process into the build process. Do a search for MSBuild.ILMerge.Task and click install.
10.    We only want to install to the project that will need to have DLLs merged, so uncheck the box next to ThinkCrmBlog.CrmHelper. Now, if you had more projects creating plugin DLLs that referenced ThinkCrmBlog.CrmHelper you would want to check the box for each of those projects.
11.    The ILMerge application itself is available as a NuGet package and is a dependency, so it will be installed.
12.    Again, the green check is your confirmation of success.
13.    Now we need to add a reference to ThinkCrmBlog.CrmHelper from ThinkCrmBlog.DemoPlugin.
14.    Just check the box.
15.    Now we have to do a property update on the CRM SDK DLL files so they don’t get merged into our final DLL. The ILMerge build task we installed will merge all the DLLs in the \bin directory. To avoid merge the CRM SDK DLLs and Microsoft.IdentityModel.DLL into our plugin DLL we need to tell Visual Studio to not copy them on build. Select the three files and set the property “Copy Local” to false.
16.    One last, but critical step, be sure to sign both of the projects. Dynamics CRM requires that DLLs be signed and therefore any DLLs we include must be signed.
17.    The solution should look similar to this picture.
18.    For the source code, which I’ve placed online on GitHub @ https://github.com/nicknow/ThinkCrmBlog.PluginDllMerge, I created a very basic plugin will create an instance of a class in CrmHelper and call a method before throwing an exception to allow the user to via the trace log. This was done just for demonstration – it serves no real-world purpose. Afte writing the code I did a Clean Solution and a Rebuild Solution.
19.    In the output directory you’ll see only the final DLL – the merged DLL(s) have been deleted. If you open the DLL in a decompiler, such as dotPeek, you’ll see that the DLL contains both the ThinkCrmBlog.DemoPlugin and ThinkCrmBlog.CrmHelper namespaces.
20.    Install the DLL using the Plugin Registration Tool (or any other preferred tool.) You’ll see that it is a Sandbox deployment – so it will work with CRM Online.

Remember, just because you can merge DLLs doesn’t mean you don’t have any limitations. Code running in Sandbox must still adhere to the rules – no SQL calls, disk access, reflection, etc. Also, be careful that you aren’t merging so much that your plugin DLL becomes bloated causing issues with deployment or (possibly) a negative performance hit.


Saturday, 6 June 2015

Create real-time workflows in CRM 2015 Online and On Premises

Similar to asynchronous workflows, real-time workflows can be used to model and automate real world business processes. They can optionally require user input, can start automatically based on specified event conditions, or can be started manually by a user. Real-time workflows are for business users, for example business analysts, to implement similar functionality to synchronous plug-ins without requiring .NET Framework programming experience. You can create asynchronous or real-time workflows in the Microsoft Dynamics CRM web application or in code.
WorkFlow Stages:
1. If the workflow is to be triggered by the creation of a record, the workflow will only be apply post event, i.e. after record is created
2. When there is a change in the record status, owner or a designated field value changes, the workflow can be set to either post or pre-event, i.e. make it will make a validatation before data is changed
3. When record is deleted, the real time workflow will only apply on pre event, i.e. before record is deleted
Real Time Workflows are beneficial in a situations where data validation is required to preserve data integrity by reverting back the operation if a particular condition isn’t validated, or if calculation fails due to any technical or constructive issue.

Some key points about a real-time workflow include the following items:

  • Defined by using a Workflow entity record, similar to an asynchronous workflow.
  • Executes in a stage of the event execution pipeline, similar to synchronous plug-ins. The real-time workflow can execute before (pre-operation), after (post-operation), or during the core operation. A real-time workflow that is executed during the core operation is the implementation of a custom action. Real-time workflows can be ranked within a stage just like you can do with plug-ins. More information: Pipeline Stages
  • Whether configured to run on-demand or in response to an event, a real-time workflow runs immediately rather than being queued to run at a later time.
  • Can run in the security context of the logged on user or owner of the workflow. However, workflows set to run on-demand always run under the security context of the logged on user. 
  • Can’t contain any delay or wait activities.
  • Only logs errors, and only when logging is enabled.
  • Executes in the current transaction. All activities in the workflow and any child workflows, except asynchronous workflows, are part of a single transaction. Asynchronous child workflows are queued and execute in a separate transaction.
  • Can be converted to asynchronous workflow and back to real-time.

Create and edit business rules Dynamics CRM 2015

Why business rules?
Business rules provide an easy declarative way to consistently evaluate the business logic on both client and server, without the need to write code. The client-side logic evaluation is more immediate because it is performed when you open and update the record form, while the server-side provides consistent logic evaluation on the server.
  • The business rule is executed only on the client, if the rule’s scope is set at a form level (all forms or a specific form). The rules are executed when a record form is loaded and updated.
  • The business rule is executed both on the server and client, if the rule’s scope is set at an entity level. The rules on the server-side are executed when a record is created or saved.
What can business rules do?
Business rules allow for a subset of the capabilities provided by form scripts. You can define conditions and apply the following actions:
  • Set field values
  • Clear field values
  • Set field requirement levels
  • Show or hide fields
  • Enable or disable fields
  • Validate data and show error messages
Business rules can be set to apply to all Main or Quick Create entity forms or specific Main forms that you choose. You can also set the rule to apply to an entity.

You can transport business rules from one organization to another by including them in a solution and you can install solutions that contain business rules.


Among the slew of improvements in the Dynamics CRM 2015 Update is a refresh to Business Rules which fixes this these restrictions and adds wider functions.
This includes:

• Support for enriched business logic including if / else
• Combining expressions using and / or conditional rules
• Using Rules to set default field values
• Synchronous server side Business Rule logic execution
• Visual editing

Set the scope
In the top right of the form, use the Scope field to set the scope for the rule.

Scope
Where it runs run
Entity
All forms and server
All forms
All forms
Specific form
Just that form
You cannot select multiple specific forms. If you choose All Forms, the rule will be applied to all the Main forms and the Quick Create form, as long as the form includes all the fields referenced by the rule. If you create a new business rule by using the form editor, the default scope is just that form.

Server side business rules and support for IF-Else and AND/OR logic
Previously, you had an ability to evaluate the business rules on an individual client. To evaluate the business rule logic on the server and apply it to all clients, you had to provide the plug-ins, which are expensive to develop and maintain. Setting the scope of the business rule at an entity level, gives you an ability to evaluate the business rule once on the server and apply it to all clients without writing code. You can move the logic for commonly used scenarios out of plug-ins into the entity-level business rules. In addition, we provided the support for default values in a business rule. For instance, if Contoso only does business in the United States, a simple business rule can be implemented that on creation of an incoming lead, the country/region is automatically set to U.S.A.

Business rules are intended to address common actions. Compared to what a developer can do by using form scripts, business rules have limitations. However, business rules are not intended to replace form scripts.
Here are a few limitations to using business rules:
  • Business rules run only when the form loads and when field values change. They do not run when a record is saved, unless the scope for the rule is set at an entity level.
  • Business rules work only with fields. If you need to interact with other visible elements, such as tabs and sections, within the form you need use form scripts.
  • When you set a field value by using a business rule, any OnChange event handlers for that field will not run. This is to reduce the potential for a circular reference, which could lead to an infinite loop.
  • If a business rule references a field that is not present on a form, the rule will simply not run. There will be no error message.
  • Whole Number fields that use the formats for TimeZone, Duration, or Language will not appear in the rule editor for the conditions or actions, so they cannot be used with business rules.
  • For Microsoft Dynamics CRM for tablets, the definition of the business rules are downloaded and cached when CRM for tablets opens. Changes made to business rules are not applied until CRM for tablets is closed and re-opened.
  • When you set the value of a lookup field, the text of the primary field value that is set in the form will always match the text that is visible in the rule definition. If the text representing the primary field value of the record you are setting in the lookup changes, the value set by your rule will continue to use the text portion of the primary field value defined by the rule. To fix this, update the rule definition to use the current primary name field value.



    It is useful to understand that the value set for a lookup has three parts:
    • Name: The text of the primary field value you see in the form.
    • Id: The unique identifier for the record. This is the data that is saved. This is not visible in the form.
    • LogicalName: The name of the entity, such as contactaccount, or opportunity.
The rule will set all three parts of this value. The Id value for a specific record never changes, but the Name value might change.

For example, if you define a rule to set a lookup to a contact that has the Full Name of ‘Old Name’, this text is the Name you will see in the lookup when it is set by your business rule even if someone later changes the Full Name of the contact to ‘New Name’. The lookup Id value will be correctly set to the expected record, but the Name(which is not saved) will reflect the rule definition value rather than the current Full Name value of the record it references.