Tuesday, October 14, 2014

How to debug a sandbox plugin in CRM 2013 online

How to debug a sandbox plugin in CRM 2013 online

Preface

Debugging a sandboxed plugin in CRM 2013 online may sound a little obscure at first but don't you deny that it would be really life saver. Maybe you've given up the idea and instead decided to do something that I call poor man's debugging - throwing InvalidPluginExecutionExceptions everywhere and hoping to find a solution? I admit, I used to do that a lot too but this is just wrong. Throwing exceptions is not a solution for debugging, it is solution for handling exceptions and should stay that way.

In this blog post I'm teaching you, step by step, how you can debug a plugin in CRM and save a huge amount of time and effort in the future.

First we go through what you'll need. You probably own all necessary components already since you are a CRM programmer.

Then I explain an example scenario that I'm using while going through this debuggin process.

You may now close all other tabs in your browser. This blog post contains all you need in order to debug a plugin in CRM Online.

What you need

  1. Plugin to debug
  2. CRM 2013 online (although this might work for on-premises as well)
  3. CRM 2013 SDK
  4. Visual Studio (I'm using Visual Studio 2012)

Scenario

Let's pretend we are developing a plugin that has to generate an email address for a contact. Email address is generated by using contact's full name and by adding a fixed "@exampledomain.com" to the end. 

We've created a plugin that'll be fired always when a contact is created or updated (running a plugin on every update is not preferred in this case but just play along). 

Both steps are registered on pre-operation stage of execution.

Below is my plugin code. Note that I've divided some of the common plugin logic to its own class (Plugin.cs) which we are inheriting in our actual plugin. 


So what happens there is we take target entity's full name property and add "@exampledomain.com" to it. Then we assign that new email string to entity's emailaddress1 property. Since this is a pre-operation plugin we don't have to call update.

This plugin works well on create because full name is business required field. But for some reason on update this is not working... Well we all know the reason already, but let's pretend we don't.

It's debugging time!

Debug a plugin

Step 1
Open your plugin registration tool. It is located in SDK\Tools\PluginRegistration folder.


Step 2
While plugin registration opened you want to install something called a profiler. All you need to do is to press "Install Profiler" and wait for a moment. 



When the profiler is installed (when you see "Profiler Installed Succesfully") press Ok. 

Note: This (profiler) creates a new managed solution to CRM. As I was writing this tutorial something weird happened (CRM happened) and my plugin registration tool lost a connection to CRM. I wasn't able to connect CRM for a little moment so I went and deleted that managed solution from CRM manually. I don't know if it was only coincidence or if it actually helped but everything worked normally after that. So that's something to keep in mind for sure!

Step 3
Choose a plugin and a plugin step you want to debug.

As described in the scenario our plugin is crashing on update event. So we want to debug our plugin on update step / event. 

Highlight a correct step and press "Start Profiling"



Step 4
Set up profiler settings. You may want to leave them as they are. Press OK when ready.



Step 5
Once you've started the profiler you have to raise an event that will fire the plugin. In our case that means we have to update an existing contact.

I'm updating Fernando Alonso's job title to 1st driver which will raise an update event but will also crash our plugin (well, you know why don't you). When that happens a profiler gives us a log file that we have to download and store locally for further use.

Download the log file and then close business process error popup by pressing ok.



Step 6
Go back to your plugin registration tool and press debug.



Step 7
Replay Plug-in Execution popup opens on the screen. There are three fields that has to be filled.

1. To "Profile" field search the log file you just downloaded in step 5.
2. Assembly Location: To this field you need to search for your plugin's DLL file. When you are building your projects in Visual Studio it creates a debug folder under a bin directory. Use the DLL file from the debug folder.
3. Select the right plugin

Do not press Start Execution yet



Step 8
Open Visual Studio and your plugin solution / project if not already opened.

Add break points to your code. 

So from now on it works as normal debugging. I add one break point to beginning of the plugin.



Step 9
Attach Visual Studio to PluginRegistration process.

When Visual Studio and your plugin solution / project is opened go to Debug -> Attach to process.



Step 10
Select PlugingRegistration.exe from the list. If you have more than one opened at the same time make sure to select a right one. Then press attach. Your Visual Studio will go to a debug mode.

Step 11
This is the moment we've been waiting for. Go back to plugin registration tool and press "Start Execution".



Step 12
Now you can actually debug your code, step by step!



Step 13
Enjoy! When you're done stop profiling and remove profiler. I'm sure you'll find out how, just do the steps in reverse order :)

Final step
Find the problem and fix it.

For those who wonder the problem was that target entity didn't carry full name property because it was not changed and thus not passed for the execution context. That's why we got "The given key was not present in the dictionary"


Final words

Thank you for reading. Hopefully I was able to clear things out. This may seem little overkill but trust me on this, it'll save you a lot of time on a long run.

Please do not pay too much attention to code in this post. I wanted to keep it simple as possible. Don't do what I do, do what I say :)

Monday, August 18, 2014

How to edit Microsoft Dynamics CRM 2013 command bar / ribbon by using Visual Studio 2012 and schemas

How to edit Microsoft Dynamics CRM 2013 command bar / ribbon by using Visual Studio 2012 and schemas

NOTE: Applies also to Microsoft Dynamics CRM 2011 and probably to other versions of Visual Studio as well

NOTE: In CRM 2011 what used to be called Ribbon is now basically called Command Bar in CRM 2013 even though it's not basically the same thing. Ribbons are available in CRM 2013 as well (Outlook client for example).

Preface

Usually I would recommend editing MS CRM 2013 / 2011 ribbon / command bar by using 3rd party tools such as Visual Ribbon Editor or Ribbon Workbench.

Sometimes though, it is desired, that editing is made by hand. You'll face these situations more likely when you don't have an access to install 3rd party softwares or you just wanna be hardcore... or any other reason.

I would divide editing (manual editing) process into five steps
  1. Create a solution that contains concerned entity and then export the solution.
  2. Unzip solution
  3. Edit customizations.xml
  4. Zip files back to one package
  5. Import .zip file back to CRM
While steps 1, 2, 4 and 5 are pretty simple and self explatonary step 3 can be done many different ways.

You could just open Notepad++ and start editing and hope that everything is in place when you import your solution back. Or you could open Visual Studio, attach schemas from the SDK and make your life much easier.

You will need

Step 1. Create a solution and export it

The first step is to create a solution that contains entity / entities whose ribbon(s) you want to edit. You could just export the default solution but for the sake of the peace of mind I recommend you to create a new solution that contains only entities you really want to edit. Otherwise your customization.xml will be really big and hard to read (even with modern editors such as Visual Studio). In this example I'm editing account's command bar.



Step 2. Unzip solution

Unzip the solution to any folder you wish. You'll end up with at least these three files



Step 3. Edit customizations.xml

Now this is the part actual work happens. First I want you to open customizations.xml with your Visual Studio.

Then you should open File Properties window. You can open it from View -> Properties Window or by pressing F4.

After that open Schemas window by pressing the button with three dots in it (see picture below).



Now select the following schema files (.xsd files) from the CRM 2013 SDK (SDKFolder\Schemas) by pressing Add... button



Then click OK. Now you may wonder how this will help you. When you attach these schema files to your xml file it tells to Visual Studio automatically check your xml file against schema files. So it's real time validation.

But even better advantage (imo) is that you'll get Intellisense. So no longer you need to constantly go and see what properties are available and for what node. Visual Studio will tell you.

Take this as an example. I want to add new button to account's form. I know that I need to add custom action node under custom actions but I'm not quite sure how to continue from there. I could go to MSDN and find out, or I could save time and let Visual Studio tell me.




So as you can see I wrote only "<" and Visual Studio told me that under CustomerAction node there should be CommandUIDefinition. If I just add CommandUIDefinition and leave it like that Visual Studio can tell me that it is incomplete and that I still need to add something before it matches the schemas.



So it goes without saying that this is really neat feature and it can save you alot of time. The good rule of thumb is that when your xml passes validation it should be okey for importing. But do not take that for granted either.

Step 4. Zip files back to one package.

Again, this should be piece of cake. Just make sure that your folder structure is same than when you unzipped exported solution. Some packaging softwares tend to add one extra root folder if you're not carefull.

Step 5. Import solution (.zip file) back to CRM

Import your solution back to CRM and enjoy your customizations.

More reading

For more reading this is good place to start http://msdn.microsoft.com/en-us/library/gg309639.aspx

Wednesday, August 13, 2014

How to use Regex with GCC 4.8.2

How to use Regex with GCC 4.8.2

My setup:

Operation system: Ubuntu 14.04
Compiler: GCC 4.8.2
IDE: Eclipse 3.8.1

Problem:

I've included regex (#include <regex>) to my header file but my IDE keeps complaining that type of 'something' could not be resolved. I've tried using namespaces such as std:: and std::tr1, like people from google has adviced, with no success.

Solution:

Solution is as simple as the problem itself. If you take a look at usr/include/c++/4.8 you'll notice the regex file in root folder is kind of a stub. However there's another regex file in /tr1 folder.

The trick is, that instead of writing #include <regex>, you should write #include <tr1/regex>

After that you're able to use regex through std::tr1:: namespace.

For exmaple like this: std::tr1::smatch

Hope that helps!

Saturday, October 12, 2013

Edit command bar / ribbon in Microsoft Dynamics CRM 2013

As Microsoft Dynamics CRM 2013 came out the ribbon was excluded with couple exceptions. Instead of ribbon we now have something that's called "command bar", well, because it is a command bar. However, you could think it as a "ribbon in disguise" because all modifications are still to be done through RibbonDiffXml. You can modify your RibbonDiffXml by hand or you can make your life much easier and use Ribbon Workbench software / solution. It will allow you to modify both your command bar and the ribbon. Some few entities / forms in Crm 2013 still use ribbons. Outlook client use ribbons in a certain depth as well so it's definitely something to keep in mind. I also recommend to take a look at the CRM 2013 SDK as it can help you to understand this whole concept.

Example

In this example I'm adding a simple button to my custom entity's command bar

RibbonDiffXml:


And here is what it looks like. Notice my custom webresource icon. You can find tons of icons in CRM SDK.




And this is how Ribbon Workbench looks like. I definitely recommend using it but of course it's always good to know what happens under the hood!



Resources:

Thursday, October 10, 2013

Business rules in Microsoft Dynamics CRM 2013

Business rules in Microsoft Dynamics CRM 2013


Microsoft Dynamics CRM 2013 has been released a little time ago with a lot of new features and changes.

Business rules are one of the new features in CRM 2013. Business rules are relatively easy, well, business rules, that you can create through the user interface. Let's say you want to show or hide a certain field depending on another field's value. That would have take some javascript coding with CRM 2011 but with CRM 2013 you can actually achieve this by using only UI. So no programming needed, which is of course always welcome - especially for programmers.

So what can you do with business rules? Below lies a short list of different possibilities

  • Show error message
  • Set field value
  • Set business required
  • Set visibility
  • Lock or unlock field
So very basic but indeed very helpful stuff. Let's take a look at how to actually implement a business rule.

Show or hide a field using business rules

Example:

I have created an xRM system which I use to keep track of my sport activities. I have created a custom entity type named "Sport activity". In the sport activity form I have a drop down list of different sport activity types (including running, cycling, badminton, football). I also have a "Distance" field in the form (hidden by default) and I want to show it only when I've selected a certain sport activity type (such as running or cycling).

So what I need to do is to create a new business rule that'll set distance field visible when the sport activity type equals running or cycling. I can start this by opening a form designer and double clicking the sport activity type -field. There I see Business Rules tab with the "New" button. Refer the picture below.


Click "New" and fill the form. My business rule looks like this



Notice the Scope option on a top right hand side corner. It means that this business rule applies for Information form by default. You can change the value to be "All forms" for example or if you've created a custom form you can set it as a scope.

When you're ready simply Activate your business rule and you're on the go.

Note that you have to create another business rule to hide the distance field in relevant cases. Otherwise it would never go away after the first time it is set visible.


Monday, October 7, 2013

How to display a loading gif until a javascript function has been completed

The day may come when you come across the situation where you have so heavy javascript function that it actually takes some time to finish. While the code is running it freezes the UI which is not very user friendly but what can we do? Well, I'd say we have three options.

  1. The first thing I'd do is to check the logic of the code. If something is slow (speaking of javascript) there's probably better way to do it. But in some cases that's not an option. You may have actually written pretty decent code or you just don't have enough time to fix the whole past two years of someone's poor coding. Then I'd move to option two.
  2. Option two is Web Workers.

    "A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background." 

    Sounds ideal. And it is. But remember that Web Workers are not supported by IE 8 or other slightly older browser that are still in heavy use. So what do we do now?
  3. My third option would be to add a loading gif / loading text to the screen so that a user at least can tell there's something happening even if he's not be able to use the page while the script is running. And this is the topic of this post. 

How to show loading gif on the screen until the function has completed

So I created very simplified solution for this not-a-real-world example. See my solution in action. My code is below. I tried to comment the code so that you could have a sense what's happening there. But in a nutshell what I did.

A recursive function that waits one millisecond every time it's been called. You could think this as a home-made FOR-loop since we're keeping track of the quantity of function calls. Anyways, you could have this without a counter so that It would run till the end of the world. It would not freeze the browser because the timeout.



I hope this will help you in a way or another.

Wednesday, September 4, 2013

How to copy an entity using C# plugin and early bound classes

Hello,

In this post I'm going to explain you how to copy an entity by using plugin written in C#. I'm also demonstrating you the power of CrmSvcUtil which "generates early-bound .NET Framework classes that represent the entity data model used by Microsoft Dynamics CRM" for your Visual Studio project. I'm not going through how to use CrmSvcUtil. If you need help getting started with it please refer Create Early Bound Entity Classes with the Code Generation Tool (CrmSvcUtil.exe).

As an example I'm going to use Contact entity. I'm going to attach my plugin in Delete event / message so that when ever the user deletes the contact my plugin will run and copy that contact.

Some prerequisites are

  • You have Visual Studio and know how to create a solution and a project.
  • You have plugin registration tool and know how to register a plugin
  • You have CrmSvcUtil and know how to generate classes and import them as part of your Visual Studio project.
  • You have Microsoft Dynamics CRM SDK (which actually includes plugin registration tool and CrmSvcUtil)
So let's get started. I'm writing this post as I'm doing this task so you may want to do some things in different order maybe.

Step 1

Create a new solution (or use existing one) and add new project into it. There are some assemblies you have to add.
  • Microsoft.Xrm.Sdk (this can be found inside the SDK)
  • Microsoft.Xrm.Sdk.Client
  • System.ServiceModel
  • System.Runtime.Serialization

Step 2

Generate classes by running CrmSvcUtil.exe from console. You may want to check all available attributes from the link I provided in a beginning. As a reference this is how my command looks like

C:\Program Files (x86)\Microsoft Dynamics CRM 2011 SDK\bin>CrmSvcUtil.exe /url:https://antaumus601.crm4.dynamics.com/XRMServices/2011/Organization.svc /out:EarlyBoundClasses.cs /username:"myUsername" /password:"myPassword" /namespace:AntaumusCRMSolution

When the .cs file is ready add it to your Visual Studio project.

Step 3

Write the core plugin components (implement IPlugin interface etc.). If you need help with writing plugin please refer Plug-in Development for Microsoft Dynamics CRM

Step 4

Now let's write the actual logic.Very important part when using early bound types is OrganizationServiceContext class. Please refer Use the Organization Service Context Class. In this case it will help us to add our new contact easily to CRM but it has a lot of good benefits (for example LINQ providing).

"To instantiate the context class, you must pass the class constructor an object that implements the IOrganizationService interface."

Fortunately we can create IOrganizationService indirectly from IServiceProvider that is passed for Execute method by writing following lines

IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(executionContext.UserId);
OrganizationServiceContext orgServiceContext = new OrganizationServiceContext(service);  

So in shortly what happens here is we take IOrganizationServiceFactory from service provider and then use the factory for creating a service. If you want to know more about factories this might be good place to start: Exploring the Factory Design Pattern

Now when everything is settled you can create new entities like this

Contact newContact = new Contact();

And access its properties like this

newContact.FirstName

You can add entity / entities for set OrganizationServiceContext is tracking by using AddObject method. When running SaveChanges() function all changes are  performed for entities that are in the set.

Very simple. I'm not going to explain my whole code here but instead I'll paste it to the end so you can take a look at it by yourself. To keep it very simple I did not copy whole contact in my code, only first name and last name. The approach I'm using in this example may not be the best. If I should really copy the whole contact (and related entities) I might think about using LINQ for sure.

Step 5

Register your plugin in a way you want. I registered it in Post-operation Delete message synchronously and created Pre Entity image. You may have to sign you Visual Studio project first.



















Final result