Sunday, May 27, 2012

How to read Unsecure Configuration

In MS CRM plugin, reading some configration setting/constant is a common requirement . Through Unsecure configuration we can easily achieve this.


Add below configuration xml in unsecure configuration section of appropirate step in plugin registration tool.


<|?xml version="1.0" encoding="utf-8" ?|>
<|Settings>
  <|setting name="ReportExc_ReportExecutionService"|>
    <|value>http://localhost/ReportServer/ReportExecution2005.asmx<|/value>
  <|/setting>
  <|setting name="Unique_Organization">
    <|value>Contoso<|/value>
  <|/setting>
<|/Settings>


Read the configration xml from Plugin
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Xrm.Sdk;
namespace UnsecureConfig
{
    public class PlugInCreate:IPlugin
    {
         private XmlDocument _pluginConfiguration;
         public PlugInCreate(string unsecureConfig, string secureConfig)
         {
             if (string.IsNullOrEmpty(unsecureConfig))
             {
                 throw new InvalidPluginExecutionException("Unsecure configuration missing.");
             }
             _pluginConfiguration = new XmlDocument();
             _pluginConfiguration.LoadXml(unsecureConfig);
         }
         public void Execute(IServiceProvider serviceProvider)
         {
             // Obtain the execution context from the service provider.
             IPluginExecutionContext context =
                 (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext)); 
             // Get a reference to the organization service.
             IOrganizationServiceFactory factory =
                 (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
             IOrganizationService service = factory.CreateOrganizationService(context.UserId); 
             // Get a reference to the tracing service.
             ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
             if (tracingService == null)
                 throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");

             string reportUrl = GetConfigDataString(_pluginConfiguration, "ReportExc_ReportExecutionService");
         }
         public static string GetConfigDataString(XmlDocument doc, string label)
         {
             return GetValueNode(doc, label);
         }
         private static string GetValueNode(XmlDocument doc, string key)
         {
             XmlNode node = doc.SelectSingleNode(String.Format("Settings/setting[@name='{0}']", key));
             if (node != null)
             {
                 return node.SelectSingleNode("value").InnerText;
             }
             return string.Empty;
         }
    }
}

No comments:

Post a Comment