Saturday, January 29, 2022

Dynamics 365: Plugin

 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.

  1. About Plugin:
    1. Plugins are used to perform small activities upon an action/event triggered in D365.
    2. Plugins are nothing but Class Libraries created using Visual Studio. The "dll" thus created is registered in D365 which acts as Plugin.
    3. It can be Synchronous or Asynchronous.
    4. 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.
    5. 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.
    6. 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.
    7. 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.
      1. Pre Validation (Rollback Not Supported)
      2. Pre Operation (Rollback Supported)
      3. Core Operation (Plugin Cannot Be Registered Here)
      4. Post Operation (Rollback Supported)
  2. Tools Required:
    1. Visual Studio 2015 and above
    2. NuGet Packages-
      1. For Namespaces-
        1. Microsoft.CrmSdk.CoreAssemblies
      2. For Registration (anyone from below)-
        1. Xrm.Sdk.PluginRegistration
        2. Microsoft.CrmSdk.Xrm.Tooling.PluginRegistrationTool
  3. Test Case:
    1. User will add a Lead in D365. The moment Lead is added, Plugin will create 
      1. Task
      2. Email activity
  4. Plugin Creation:
    1. Open Visual Studio and choose Class Library. Name the project as "CreatefollowuptaskforLead".
    2. 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).
    3. Convert the class to PUBLIC.
    4. Now add NuGet Packages. For this right click on project name and select "Manage NuGet Packages..."
    5. Search for "Microsoft.CrmSdk.CoreAssemblies". Install the appropriate version that supports your Visual Studio and the .Net Framework installed on your system.
    6. 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 "
    7. Microsoft.CrmSdk.Xrm.Tooling.PluginRegistrationTool".
    8. Once installed. open the solution physical location folder. For this, you may right click on Solution and choose "Open Folder in File Explorer".
    9. Go one level up. You will find packages folder. This folder is created by NuGet.
    10. Open this "packages" folder. Here you will find the Plugin Registration Tool folder. Open it. Then open the "tools" folder.
    11. Here you will find PluginRegistration.exe. This exe will be used to register the Plugin dll in D365. Double click on it.
    12. It will start running and a window will appear.
    13. Click on "+ CREATE NEW CONNECTION"
    14. Then choose "Online Region". If you know the region, then choose that one otherwise choose "Don't Know".
    15. 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.
    16. To register our plugin, we need to click on "Register" link.
    17. 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.
    18. Add the namespace "Microsoft.Xrm.Sdk.". It will give us an interface "IPlugin" that we are going to use in this application.
    19. 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-
      1. Implement interface
      2. Implement interface explicitly
    20. Click on first option "Implement interface". It will implement the Execute method.

    21. This is the method where we will write our code.
    22. Before writing our code let us know couple of method which are useful in this process.
      1. ITracingService-
        1. It is used for debugging purpose only. During the development process, we can use it and either remove or make it commented before deployment.
      2. IPluginExecutionContext-
        1. 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. 
        2. This context object contains Input/Output parameters. 
      3. 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.
      4. If the condition matches, we will fetch the entity from context object and cast it with entity class.
      5. 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.
      6. If  entity is "Lead", then create an object of task entity.
      7. Set the following properties (field values)-
        1. subject
        2. description
        3. scheduledstart
        4. scheduledend
        5. category
      8. 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.
      9. This regardingobjectid is nothing but a lookup which represents that against which you are going to create an activity.
      10. Lastly, we will create OrganizationServiceFactory object and using this object we will be creating the task.
      11. Finally, add the catch part of try block and then else part of IF condition.
      12. Now, build the solution.
      13. Next part is to Signing this assembly. For this, just right click on Project in solution explorer window and choose Properties.
      14. 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.
      15. 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".
      16. Click on OK.
      17. Now Build the solution.
      18. This completes the coding part.
      19. Next phase is Plugin Registration.
  5. Plugin Registration:
    1. Go to the Plugin registration tool, which we had left in running mode.
    2. Click on Register >> Register New Assembly.
    3. It will open a popup.
    4. 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.
    5. 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.
    6. Next step is Isolation mode.
    7. 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.
    8. 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.
    9. It means, you will always register your Plugin in Sandbox mode.
    10. 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.
    11. It gives 3 options-
      1. Database - Assembly will be stored in SQL database of D365.
      2. 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.
      3. GAC - Assembly file will be stored in system GAC (Drive >> Windows >> assembly) folder.
    12. 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.
    13. Last step (Step 5) is nothing but to show the logs if you had written in your dll.
    14. Now click on "Register Selected Plugins" button to register the dll.
    15. It will take couple of minutes to register the Plugin. Once registered, it will start reflecting in Assemblies list.
    16. 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.
    17. It will open a popup.
    18. Here, we need to provide some information-
      1. 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.
        1.  
    19. Nest is Primary Entity - The entity against which we need to run our plugin. It is "Lead" here.

    20. 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).
    21. 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.

    22. Next 2 are - 
      1. Event Handler - It is by default selected your plugin class for which you had registered the plugin.
      2. Step Name - It is automatically created a default name. You may change it.
    23. 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.
    24. 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. 
    25. Next is Description. A default description is there, you may write your own as well.
    26. Next is "Event Pipeline Stage of Execution". This is equally important.

    27. This is what we were talking above in About section. Choose Post Operation as we want to execute our plugin after creation of lead.
    28. Next is Execution Mode-
      1. Asynchronous - Plugin will execute any time without waiting for Core Operation get complete.
      2. Synchronous - Plugin will execute any time after Core Operation get complete.
    29. Next is Deployment-
      1. Server - Plugin will execute only in D365 server
      2. 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)
    30. You may choose both as well.
    31. Now click on Register New Step button at bottom to register the Step.
    32. This way you can register Plugin and the related Step
  6. Plugin Update:
    1. In order to update the Plugin later in future.
    2. Update the code, build it.
    3. Run the Plugin Registration tool.
    4. Select the Plugin and click on Update.
    5. Rest is same as we did in Registration. Only Register Plugin part need to be repeated.
    6. Register Step may be repeated if we want to add new step (ex. if we have added new class / message (Update/Delete)).
  7. Debug Plugin:
    1. 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.
    2. If profiler is already installed, it will show "Uninstall Profiler" otherwise, "Install Profiler".
    3. Once installed, click on the step you wish to debug and then click on Start Profiling.
    4. A popup will appear. Choose "Persist to Entity".
    5. Click on OK. The moment, profiling started, the Step name gets suffixed by "Profiled" and the Start Profiling button converts to Stop Profiling.
    6. 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.
    7. 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.
    8. Now mark a break point where you want to debug your code.
    9. Next is go back to Plugin Registration Tool and click on Debug button.
    10. It will open a popup where it will ask you to choose the profile you want to debug.
    11. Click on Down arrow button. It will open another popup which will show you the profiles captured. Choose the last created profile.
    12. You can verify the profile by Type Name / Entity / Message / Created columns. Select the appropriate one and click on Select. 
    13. Then choose the Assembly location. It is the path of your project bin >> Debug >> dll.
    14. Then choose Plugin and click on Start Execution.
    15. 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.
    16. The moment you click on Start Execution, the debugger starts, and it lands up at the breakpoint you had set in code.
    17. Now, you can debug your code and find the error.
    18. 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).
    19. 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.
  8. 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.