top of page
Writer's pictureDrew Clark

How to create a Microsoft Dynamics Plugin to search for Commodity Pricing

Updated: Apr 28, 2023

Microsoft Dynamics Commodity Plugin

  • Open Microsoft Visual Studio and create a new project. Choose "Class Library" as the project type and give it a name.

  • In the project, right-click on the "References" folder and select "Add Reference". In the "Reference Manager" window, choose "Microsoft.Xrm.Sdk" and "Microsoft.Crm.Sdk.Proxy" under "Assemblies" and click "OK". These assemblies are necessary for interacting with Microsoft Dynamics.

  • Add a new class to the project and give it a meaningful name, such as "CommodityPricePlugin". This class will contain the code for the plugin.

  • At the top of the class file, add the necessary using statements:

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

These using statements allow you to use the necessary classes and interfaces for interacting with Microsoft Dynamics and calling the Alpha Vantage API.


  • Implement the "IPlugin" interface by adding the following code to the class

public class CommodityPricePlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider){
        // TODO: Add plugin code here
    }
}

This code defines the plugin and the Execute method that will be called when the plugin is triggered.

  • Within the Execute method, retrieve the execution context and organization service:

IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

These lines of code retrieve the necessary services and context objects for interacting with Microsoft Dynamics.


  • Get the name of the commodity to retrieve the price for. This can be done by retrieving the target entity from the execution context:

Entity target = (Entity)context.InputParameters["Target"];
string commodityName = target.GetAttributeValue<string>("name");

This code retrieves the name of the commodity that triggered the plugin from the "Target" input parameter.


  • Use an API to retrieve the commodity price. In this example, we'll use the Alpha Vantage API, which provides real-time and historical stock prices. You'll need to sign up for an API key to use the service. Here's an example of how to call the API and retrieve the price for a specific commodity:

string apiKey = "YOUR_API_KEY";
string apiUrl = $"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={commodityName}&apikey={apiKey}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CommodityPriceResponse));
CommodityPriceResponse commodityPrice = (CommodityPriceResponse)serializer.ReadObject(stream);
decimal price = commodityPrice.Price;

This code creates a request to the Alpha Vantage API using the commodity name and your API key. It then deserializes the JSON response using a DataContractJsonSerializer and retrieves the price from the response.


  • Finally, update the commodity entity with the retrieved price:

Entity updatedCommodity = new Entity("commodity");
updatedCommodity.Id = target.Id;
updatedCommodity["price"] = new Money(price);
service.Update(updatedCommodity);
  • Build the project to generate the plugin assembly.

  • Register the plugin in Microsoft Dynamics by navigating to Settings > Customizations > Customize the System > Components > Plug-in Assemblies. Click "New" to add a new assembly, and upload the generated plugin assembly.

Register the plugin step by navigating to Settings > Customizations > Customize the System > Components > Plug-in Steps. Click "New" to add a new step, and specify the following settings:

  • Message: Update

  • Primary Entity: Commodity

  • Event Pipeline Stage of Execution: Post-Operation

  • Deployment: Server

  • Execute: Asynchronous

  • Step Name: Retrieve Commodity Price

  • Plugin: CommodityPricePlugin

Here is the full code sample

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.Net;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace CommodityPricePlugin
{
    public class CommodityPricePlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            // Retrieve the execution context and organization service
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // Get the name of the commodity to retrieve the price for
            Entity target = (Entity)context.InputParameters["Target"];
            string commodityName = target.GetAttributeValue<string>("name");

            // Call the Alpha Vantage API to retrieve the commodity price
            string apiKey = "YOUR_API_KEY";
            string apiUrl = $"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={commodityName}&apikey={apiKey}";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CommodityPriceResponse));
            CommodityPriceResponse commodityPrice = (CommodityPriceResponse)serializer.ReadObject(stream);
            decimal price = commodityPrice.Price;

            // Update the commodity entity with the retrieved price
            Entity updatedCommodity = new Entity("commodity");
            updatedCommodity.Id = target.Id;
            updatedCommodity["price"] = new Money(price);
            service.Update(updatedCommodity);
        }
    }

    // Data contract for deserializing the Alpha Vantage API response
    [DataContract]
    public class CommodityPriceResponse
    {
        [DataMember(Name = "Global Quote")]
        public CommodityQuote Quote { get; set; }

        public decimal Price
        {
            get { return decimal.Parse(Quote.Price, System.Globalization.NumberStyles.Float); }
        }
    }

    [DataContract]
    public class CommodityQuote
    {
        [DataMember(Name = "05. price")]
        public string Price { get; set; }
    }
}

Note that you'll need to replace "YOUR_API_KEY" with your actual Alpha Vantage API key for this code to work. Also, make sure to include the necessary using statements at the top of your class file.




Comments


bottom of page