Overview: In Dynamics CRM, when we create a plugin, we sometimes need to pass data to that plugin, instead of writing this data inside the plugin code. We can pass it using Secure and Unsecure configurations.
Advantge
Security - Protect sensitive information like API Key.
Flexibility -Easily change configuration values without modifying the Plugin code.
Reusability - Use the same plugin in different environments with different configuration values.
Sample Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Newtonsoft.Json;
namespace SendCustomerData
{
public class SendCustomerDataUnSecureAndSecureConfig : IPlugin
{
private readonly string _unsecureString;
private readonly string _secureString;
public SendCustomerDataUnSecureAndSecureConfig(string unsecureString, string secureString)
{
_unsecureString = unsecureString;
_secureString = secureString;
}
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory =
(IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
tracingService.Trace("Unsecure Config: {0}", _unsecureString);
tracingService.Trace("Secure Config: {0}", _secureString);
IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
//Ensure that the plugin is trigger on Create Mesage .
if (context.MessageName != "Create" || context.PrimaryEntityName.ToLower() != "contact")
{
return;
}
//Get the contact details from the input parameters
Entity contact = (Entity)context.InputParameters["Target"];
string firstName = contact.Contains("firstname") ? contact["firstname"].ToString() : string.Empty;
string lastName = contact.Contains("lastname") ? contact["lastname"].ToString() : string.Empty;
string email = contact.Contains("emailaddress1") ? contact["emailaddress1"].ToString() : string.Empty;
//Prepare the customer data to be sent
var customerdata = new
{
FirstName = firstName,
LastName = lastName,
Email = email
};
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(customerdata);
tracingService.Trace("Customer Data JSON: {0}", jsonData);
try
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_unsecureString);
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {_secureString}");
client.DefaultRequestHeaders.Add("Accept", "application/json");
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("addCustomInfo", content).Result;
if (response.IsSuccessStatusCode)
{
tracingService.Trace("Customer data sent successfully.");
}
else
{
tracingService.Trace("Failed to send customer data. Status Code: {0}, Reason: {1}",
response.StatusCode, response.ReasonPhrase);
}
}
}
catch (Exception ex)
{
tracingService.Trace("An error occurred while sending customer data.");
throw new InvalidPluginExecutionException("An error occurred in SendCustomerDataUnSecureAndSecureConfig plugin.", ex);
}
}
}
}