Reading .NET Configuration files

"exePath must be specified when not running inside a stand alone exe."

Ever seen this exception before? I sure didn't....before yesterday, that is, when my custom wrapper over .NET's System.Configuration.Configuration class decided to go down in flames once used in a IIS hosted WCF service.

Why I'm relying on a custom wrapper is an entirely different story but seeing how many people are having problems dealing with the .NET's default Configuration object, I might just release it in the open if anyone needs it. Let me know.....

After a quick check I figured out that there's actually nothing wrong with my web.config file - it was my wrapper that didn't properly read the configuration file because.....Microsoft managed to introduce (patch??? bolt on???) one brand new way of figuring out on what plannet your config file is located. As if two was not enough.......

Welcome to VirtualPathExtension, the newest addition to the already schizoid family of Mr. OpenExeConfiguration, Mrs. OpenWebConfiguration and their lil' son HttpContext. There's little information out there about it but a couple of links were of great help:
WCF equivalent to MapPath? and Wenlong Dong's great post about reading configuration data from hosted WCF services.

public Configuration GetDefaultConfig()
{
Configuration cfg;

System.Web.HttpContext ctx = System.Web.HttpContext.Current;

//WCF services hosted in IIS...
VirtualPathExtension p = null;
try
{
p = OperationContext.Current.Host.Extensions.Find<VirtualPathExtension>();
}
catch (Exception ex)
{
}

if (ctx != null)
{
cfg = WebConfigurationManager.OpenWebConfiguration(ctx.Request.ApplicationPath);
}
else if (p != null)
{
cfg = WebConfigurationManager.OpenWebConfiguration(p.VirtualPath);
}
else
{
cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
return cfg;
}

If you don't like the try/catch part, check for null!=OperationContext.Current to see if you're in a hosted environment.

PS: relative paths stored in config & IIS hosted environments don't mix well. You can use HostingEnvironment.MapPath for that but more on this later.

Comments

Popular Posts