Home | Contact Us

Powered by Blogger

Sunday, October 29, 2006

Programmatically read the isv.config.xml file

I recently had a need to read settings from the isv.config.xml file at runtime and spent more time than I should have trying to find an elegant way to do this.  In the end I took a rather simple approach, but it has proven quite effective.

The first requirement I had was to utilize the same physical configuration file Microsoft CRM uses, to ensure synchronicity.  To do this I was able to query the physical path to the CRM web site from the system registry and (assuming) the location of the isv.config.xml file is constant we get this:

string fileName = Registry.GetValue(RegistryHive.LocalMachine,
@"SOFTWARE\Microsoft\MSCRM", "WebSitePath").ToString() +
"\\_resources\\isv.config.xml";

Next, I wanted to cache the file so it would only need to be reread when the contents had changed.  For this, I used the built-in ASP.NET cache object:

HttpContext.Current.Cache.Add("isv.config.xml", result,
new CacheDependency(fileName), Cache.NoAbsoluteExpiration,
Cache.NoSlidingExpiration, CacheItemPriority.Default,
null);

Now all was left was to read the file from the cache and parse the XML:

public static XmlDocument Document
{
get
{
// First, look in the web cache
XmlDocument result = (XmlDocument)
HttpContext.Current.Cache["isv.config.xml"];

if (result == null)
{
// Load the XML configuration
string fileName = <see code above> ;

// Import the values
result = new XmlDocument();
result.Load(fileName);

// Cache the result
HttpContext.Current.Cache.Add( <see code above> );
}

return result;
}
}

The rest is straight XML:

public static XmlNode Configuration
{
get
{
XmlDocument parent = IsvConfig.Document;

return (parent == null) ? null :
parent.SelectSingleNode("/configuration");
}
}
public static XmlNode Entities
{
get
{
XmlNode parent = IsvConfig.Configuration;

return (parent == null) ? null :
parent.SelectSingleNode("Entities");
}
}
public static XmlNode GetEntity(string entityName)
{
XmlNode parent = IsvConfig.Entities;

return (parent == null) ? null :
parent.SelectSingleNode("Entity[@name='" +
entityName + "']");
}

The rest is up to you... :-)


Copyright © 2007 AdvantageWorks Software Group, LLC. All rights reserved.