Sunday, August 20, 2023

Plugin Development: Create and Register Plugin - Dynamics 365 CE - Part 1

Title: Plugin Development: Create and Register Plugin - Dynamics 365 CE - Part 1

  

Dynamics 365 Customer Engagement (CE) is a dynamic powerhouse that empowers businesses to optimize processes and enhance customer interactions. One of the most powerful tools within the Dynamics 365 toolkit is plugins. In this blog, we'll demonstrate the creation of Dynamics 365 CE plugins. 

  


What are Dynamics 365 CE Plugins? 

Plugins are custom code snippets that allow you to inject your logic into the core operations of Dynamics 365 CE. These robust pieces of code spring into action when specific events occur within the system, enabling you to customize, extend, or automate various processes. 

  


Why Use Plugins?  

 

Automation: Plugins enable you to automate complex business processes that aren't achievable through out-of-the-box functionalities. Let’s just take a simple Example: On Create of Account, create a new Task record automatically for the account.  

 

Seamless Integration: Plugins offer a way to integrate Dynamics 365 CE with external systems and services, allowing you to harness the full power of your ecosystem. 

  


Creating Your First Plugin 


Step 1: Prepare Your Environment 

Ensure you have Visual Studio 2017 and above and the .NET Framework 4.62 and above installed. These tools provide the foundation for plugin development. I used Visual Studio 2022 and .NET 4.6.2.  


  

Step 2: Create a New Plugin Project 

Open Visual Studio > New Project > Visual C# > Class Library > create a new Class Library (.NET Framework) project. 

Click Next 

  

 

On the Next screen, give the Project Name, select Location where you want to save the solution and .Net Framework. 4.6.2 (if you don’t see the .NET4.6.2 version in the dropdown, install it from Visual Studio installer) 


Click Create. 

 


A Solution created with a Project Name provided and empty class 

 

 

In the Solution Explorer, right-click the project and select Manage NuGet Packages… from the context menu. 

 

 

Select Browse and search for Microsoft.CrmSdk.CoreAssemblies and install the latest version. 

 

 

Click OK 

 

 

Click I Accept – License acceptance  

 

 

Once Installation is finished, you can see Output window for progress, it's just taken a moment to complete.  

Now Solution Explorer, expand the Reference and see required assemblies are added.


Microsoft.Xrm.Sdk.dll and Microsoft.Crm.Sdk.Proxy.dll assembly used to write plug-in.

 

 

 

Let’s give a proper name to Class, In Solution Explorer, right-click the Class1.cs file and choose Rename in the context menu. 

 

 

Rename the Class1.cs file to PostAccountCreate.cs. 

Now add the following using statement in the class. 

 
using System.ServiceModel; 

using Microsoft.Xrm.Sdk; 

 
Implement IPlugin interface, if you just type: IPlugin after the class name, Visual Studio will suggest implementing Execute method.   

 

 

 

Implement interface: on the line of class there will be a small icon, click to expand it.  

 


Execute method added; plug code execution start from here.  

 

 


Step 3: Implement Your Logic 

In your plugin project, define the logic that should execute upon a specific event. This might involve data manipulation, calculations, or even external API calls. 

Now, let's add some code: replace the Execute Method with the following code of lines.  

 


Let’s learn little about the Interfaces and purposes of use in code.  

  • IServiceProvider: Defines a mechanism for retrieving a service object; Method: GetServiceType(Type) 
  • IPluginExecutionContext: Context contains contextual information passed to plug-in at run-time 
  • OrganizationServiceFactory: Help for creating IOrganizationService instance 
  • IOrganizationService: Provides access to the metadata and data of the organization. 

  • TracingService: Tracing service to log/trace run time trace information/ messages for plugin 

 

Now add the following code to create a Task record automatically using Plugin code.  

 

 


Complete Code

 

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Text; 

using System.Threading.Tasks; 

 
 

using System.ServiceModel; 

using Microsoft.Xrm.Sdk; 

 
 

namespace MyFirstDemoPlugin 

{ 

    public class PostAccountCreate : IPlugin 

    { 

        public void Execute(IServiceProvider serviceProvider) 

        { 

            // Obtain the execution context from the service provider.   

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 

 
 

            // Obtain the tracing service 

            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService)); 

 
 

            // Obtain the Organization Service factory service from the service provider 

            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); 

             

            // Use the factory to generate the Organization Service. 

            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); 

 
 

            try 

            { 

                //to do code goes here 

                //Tracing some log 

                tracingService.Trace("PostAccountCreate Started"); 

                 

                //check plugin cotext contains the Target Property - Target Property holds the metadata information passed to plugin 

                if (context.InputParameters["Target"] != null && context.InputParameters["Target"] is Entity) 

                { 

                    Entity entity = (Entity)context.InputParameters["Target"]; 

 
 

                    //get current record GUID; this we will use to set Task activity regarding object 

                    Guid accountId = entity.Id;  

 
 

                    //create Task record 

                    Entity taskObj = new Entity("task"); 

                    taskObj.Attributes.Add("subject", "This Task created from Plugin"); 

                    taskObj.Attributes.Add("description", "A sample Task created from Plugin code automatically"); 

                    taskObj.Attributes.Add("regardingobjectid", new EntityReference("account", accountId)); 

                    service.Create(taskObj); 

 
 

                    tracingService.Trace("PostAccountCreate Finished"); 

                } 

            } 

            catch (Exception ex) 

            { 

                tracingService.Trace(ex.ToString()); 

            } 

        } 

    } 

} 

 
 

 

Step 4:  Sign the Plugin 

In Solution Explorer, right click the Plugin project and in the context, menu select Properties. 

 


In the project properties, select the Signing tab and select the Sign the assembly checkbox. 


 

In the Choose a strong name key file: dropdown, select <New…>. 

 


Enter the Key file name and uncheck the protect my key file with password. 


Click OK 

 

 

The Strong Name Key file is added to the solution.  

 



Now, save all the changes and Build the Solution, right click on Project Name and click Build/ Rebuild. The output window will show the status of build succeeded. 




 


Part 2 -



Kindly follow the following link for part 2 to register the plugin..  


Plugin Development: Create and Register Plugin - Dynamics 365 CE - Part 2


 

Best Practices for Plugin Development 


1. Modular Coding: Divide your logic into reusable modules for maintainability. 

2. Error Handling: Implement robust error handling to ensure smooth operation. 

3. Avoid Infinite Loops: Carefully design your plugin to avoid triggering an infinite loop of events. 

4. Logging: Utilize logging mechanisms to track plugin execution and troubleshoot issues. 

5. Testing: Test your plugin in a sandbox environment before deploying it to production. 

  

 

*Conclusion 

Dynamics 365 CE plugins open the door to endless possibilities for customization, automation, and integration. By mastering the art of creating plugins, you're equipped to unleash the full potential of Dynamics 365 CE and tailor it precisely to your organization's needs.  

 


Stay tuned for more in-depth explorations into the Dynamics 365 CE Platform and Plugin Development. 

#Dynamics365 #Development #Plugin #PowerApps #PowerPlatform 

 



Next Steps: Learn more about other powerful features of Plugin! 

  

 
 

No comments:

Post a Comment