Hello Friends,
Welcome back with another post and a new topic. Today, we are adding Dynamics 365 into our portfolio. We are going to discuss about Plugin in Dynamics 365.
- About Plugin:
- Plugins are used to perform small activities upon an action/event triggered in D365.
- Plugins are nothing but Class Libraries created using Visual Studio. The "dll" thus created is registered in D365 which acts as Plugin.
- It can be Synchronous or Asynchronous.
- Plugins have 2 minutes of timeout restriction. It means, the activity of Plugin must get completed within 2 minutes otherwise it will get terminated due to timeout.
- Plugins supports Impersonation. It means we can run Plugin under other user credentials or with elevated privileges. Impersonation is defined at the time of Plugin registration.
- Plugin Context is an object which stores all the information that is coming from a Form, where an action/event is triggered upon which we have written our Plugin execution. For example, if we are using Plugin upon account creation then the Plugin context will contain all the attributes / fields of Account entity / table.
- Event Execution Pipeline are the various stages where we can execute our Plugin. These are 4 in nature out of which only 3 can be used to register a Plugin. We cannot register Plugin in Core Operation because at this stage the actual operation (CRUD) is getting performed.
- Pre Validation (Rollback Not Supported)
- Pre Operation (Rollback Supported)
- Core Operation (Plugin Cannot Be Registered Here)
- Post Operation (Rollback Supported)
- Tools Required:
- Visual Studio 2015 and above
- NuGet Packages-
- For Namespaces-
- Microsoft.CrmSdk.CoreAssemblies
- For Registration (anyone from below)-
- Xrm.Sdk.PluginRegistration
- Microsoft.CrmSdk.Xrm.Tooling.PluginRegistrationTool
- Test Case:
- User will add a Lead in D365. The moment Lead is added, Plugin will create
- Task
- Email activity
- Plugin Creation:
- Open Visual Studio and choose Class Library. Name the project as "CreatefollowuptaskforLead".
- Click on OK to create the project. It will be having a default class library Class1.cs. Delete this file and add a new class file with the proper naming convention (like CreateTask.cs).
- Convert the class to PUBLIC.
- Now add NuGet Packages. For this right click on project name and select "Manage NuGet Packages..."
- Search for "Microsoft.CrmSdk.CoreAssemblies". Install the appropriate version that supports your Visual Studio and the .Net Framework installed on your system.
- Now search for registration tool. You may search either by name as mentioned above or a generic search "plugin registration tool". Generic search will give you both tools. You may install either of them. I am installing second one "
- Microsoft.CrmSdk.Xrm.Tooling.PluginRegistrationTool".
- Once installed. open the solution physical location folder. For this, you may right click on Solution and choose "Open Folder in File Explorer".
- Go one level up. You will find packages folder. This folder is created by NuGet.
- Open this "packages" folder. Here you will find the Plugin Registration Tool folder. Open it. Then open the "tools" folder.
- Here you will find PluginRegistration.exe. This exe will be used to register the Plugin dll in D365. Double click on it.
- It will start running and a window will appear.
- Click on "+ CREATE NEW CONNECTION"
- Then choose "Online Region". If you know the region, then choose that one otherwise choose "Don't Know".
- Input the Username and Password (your D365 credentials) and click on Login. It will show all the plugins (whether of Microsoft or Others) registered in that region. It will take a couple of minutes to load the data.
- To register our plugin, we need to click on "Register" link.
- So, first we will create our plugin and will register using this tool. You may leave it running or may close it as of now. Let's come back to our Visual Studio.
- Add the namespace "Microsoft.Xrm.Sdk.". It will give us an interface "IPlugin" that we are going to use in this application.
- Inherit the interface "IPlugin". Now, hover the mouse over it. It will show a Bulb icon. Click on this icon. It will give you two options-
- Implement interface
- Implement interface explicitly
- Click on first option "Implement interface". It will implement the Execute method.
- This is the method where we will write our code.
- Before writing our code let us know couple of method which are useful in this process.
- ITracingService-
- It is used for debugging purpose only. During the development process, we can use it and either remove or make it commented before deployment.
- IPluginExecutionContext-
- This holds all the fields of the entity upon which we are going to work and going to register our plugin for the entity. For example, if we are going to register our plugin for "Account" entity, then it will hold all the fields information of "Account" entity.
- This context object contains Input/Output parameters.
- Here, we will check if the InputParameter contains as property named "Target" and if present, then is it of the type "Entity". Entity is nothing but tables in D365.
- If the condition matches, we will fetch the entity from context object and cast it with entity class.
- Next, we will check , if the entity we received from context is of Lead entity (as we are creating this Plugin to perform its activity once a Lead is created). For this, we will check the Logical Name of the entity. If it is "lead" then proceed further else terminate the process.
- If entity is "Lead", then create an object of task entity.
- Set the following properties (field values)-
- Now we will add the reference of the person for whom lead is created to this task object. The ID of reference will be available in the OutputParameters of context object. So, we will check, if the ID property is available in OutputParameters collection. If available, then get the reference object from account entity and assign it to "referenceobjectid" property.
- This regardingobjectid is nothing but a lookup which represents that against which you are going to create an activity.
- Lastly, we will create OrganizationServiceFactory object and using this object we will be creating the task.
- Finally, add the catch part of try block and then else part of IF condition.
- Now, build the solution.
- Next part is to Signing this assembly. For this, just right click on Project in solution explorer window and choose Properties.
- It will open properties window where at the bottom, you will find the Signing option. Click on "Sign the assembly". It will enable the dropdown where you need to select the <New...> option.
- It will open another popup, where give the Key file name (any name you wish to) and uncheck the "Protect my key file with password".
- Click on OK.
- Now Build the solution.
- This completes the coding part.
- Next phase is Plugin Registration.
- Plugin Registration:
- Go to the Plugin registration tool, which we had left in running mode.
- Click on Register >> Register New Assembly.
- It will open a popup.
- The first step is to load the assembly, we had created. Click on Load Assembly button and traverse to the bin >> Debug folder of the solution and select the dll created.
- The moment you load the assembly, it reads the assembly and shows the available classes written in this dll. This is the reason, the class we had created was made as Public, otherwise it would not be able to get read by registration tool.
- Next step is Isolation mode.
- Isolation mode means that the Plugin will run in a restricted environment. What does it mean? It means that we cannot write any such type of logic which is calling any physical folder for fetching any data/information from any server or any other location. Even you cannot call any 3rd party web service from the Plugin.
- That is the reason, in D365 online , every Plugin we are going to register must be registered in Isolation mode. Even the "None" option is by default disabled.
- It means, you will always register your Plugin in Sandbox mode.
- Next step is to choose the storage location of the assembly. Basically, the dll file we had created needs to be stored at some location, from where D365 can call its methods to perform the activity.
- It gives 3 options-
- Database - Assembly will be stored in SQL database of D365.
- Disk - Assembly file will be stored in Installation Directory of D365. This option is normally chosen when we are using D365 on-Prem version. There is a path names "server >> assembly". At this path, the file gets saved.
- GAC - Assembly file will be stored in system GAC (Drive >> Windows >> assembly) folder.
- Among these 3 options, Database has the advantage that if you store your file in Database, then you need not to manually provide the file when moving to QA/Prod environment. It will be automatically moved to other environment when you will be moving your solution. For Disk/GAC, you need to manually transfer the dll.
- Last step (Step 5) is nothing but to show the logs if you had written in your dll.
- Now click on "Register Selected Plugins" button to register the dll.
- It will take couple of minutes to register the Plugin. Once registered, it will start reflecting in Assemblies list.
- We have successfully registered the Plugin. Now we will Register the Step because registering the assembly is not enough, we need to inform the system that at which action/event, it needs to be triggered. For that, click on Plugin class and then click on Register >> Register New Step.
- It will open a popup.
- Here, we need to provide some information-
- Message - The name of action against which this plugin should work. We have designed our plugin to work on lead creation, so we will choose "Create" message. The moment you start typing, it will show the matching message.
- Nest is Primary Entity - The entity against which we need to run our plugin. It is "Lead" here.
- Next is Secondary Entity. It is not required in our case as we have designed our plugin to work on lead creation only. It is required when you need to execute your plugin in a related entity (not the Primary entity).
- Next if Filtering Attributes. It is not required in Create message. It is only required for update message where you need to filter the record. In Update, you need to specify that against which field update, you want to register the plugin. Ideally, Microsoft suggest to run your plugin on specific field update rather than running on all fields updates otherwise for each filed update, your plugin start execution means multiple instances will run for a single update action if you are updating multiple fields at same moment.
- Next 2 are -
- Event Handler - It is by default selected your plugin class for which you had registered the plugin.
- Step Name - It is automatically created a default name. You may change it.
- Next is Run in User's Context. It is equally important. It defines that under which user context (credentials), this plugin will run. We can elevate the Plugin permissions here. It is nothing but Impersonation. We need to carefully choose the person which is having enough Security Matrix (credentials) to perform the activity upon the entity we are using. By default, it is "Calling User". We can leave it as it is.
- Next is Execution Order. By default, it is 1. It plays an important role if you have written multiple plugins for same message and for same entity. Then you need to define the order in which all these needs to be executed. If all are having same order, then basis upon order of installation, the order is set.
- Next is Description. A default description is there, you may write your own as well.
- Next is "Event Pipeline Stage of Execution". This is equally important.
- This is what we were talking above in About section. Choose Post Operation as we want to execute our plugin after creation of lead.
- Next is Execution Mode-
- Asynchronous - Plugin will execute any time without waiting for Core Operation get complete.
- Synchronous - Plugin will execute any time after Core Operation get complete.
- Next is Deployment-
- Server - Plugin will execute only in D365 server
- Offline - Plugin will work for D365 offline also (ex. if you are using D365 in Outlook, then it is an Offline mode, there also, it will work)
- You may choose both as well.
- Now click on Register New Step button at bottom to register the Step.
- This way you can register Plugin and the related Step
- Plugin Update:
- In order to update the Plugin later in future.
- Update the code, build it.
- Run the Plugin Registration tool.
- Select the Plugin and click on Update.
- Rest is same as we did in Registration. Only Register Plugin part need to be repeated.
- Register Step may be repeated if we want to add new step (ex. if we have added new class / message (Update/Delete)).
- Debug Plugin:
- If you wish to debug the Plugin for any error, you need to install the profiler. The same can be installed from Plugin registration tool.
- If profiler is already installed, it will show "Uninstall Profiler" otherwise, "Install Profiler".
- Once installed, click on the step you wish to debug and then click on Start Profiling.
- A popup will appear. Choose "Persist to Entity".
- Click on OK. The moment, profiling started, the Step name gets suffixed by "Profiled" and the Start Profiling button converts to Stop Profiling.
- Now, go to your Dynamics 365 and perform the action for which you had created this Plugin. The moment you perform the activity, your plugin will get executed and the entire activity will be captured by Profiler.
- Now go to your code and click on Debug >> Attach to Process. Here you will find "PluginRegistration.exe" process. choose it and click on Attach.
- Now mark a break point where you want to debug your code.
- Next is go back to Plugin Registration Tool and click on Debug button.
- It will open a popup where it will ask you to choose the profile you want to debug.
- Click on Down arrow button. It will open another popup which will show you the profiles captured. Choose the last created profile.
- You can verify the profile by Type Name / Entity / Message / Created columns. Select the appropriate one and click on Select.
- Then choose the Assembly location. It is the path of your project bin >> Debug >> dll.
- Then choose Plugin and click on Start Execution.
- Make sure the dll would be the same which you have uploaded. If you have made any changes in dll then the Debugger will give you an exception.
- The moment you click on Start Execution, the debugger starts, and it lands up at the breakpoint you had set in code.
- Now, you can debug your code and find the error.
- Once debugging gets complete. Stop the debugging from Visual Studio and Stop Profiling from Plugin Registration Tool (in case if you don't wish to generate more profiles to debug).
- You can generate multiple profiles and can debug later. You only need to remember the profile created date time and other parameters based upon which you would be able to distinguish the profile to debug.
- This way, you can Create / Register / Update / Debug the Plugin.
With this, I am concluding this post.
Happy Coding !!!
Will see you again with some new topics.
Stay Safe !
Stay Healthy !
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.