One of the guys that work with me came up with a interesting question.
How do I access the Web.config file at design time. After trying hard to
find and answer on google, I finally came up with the right search
criteria. Thanks to the artcile that I found at http://blogs.msdn.com/mszcool/archive/2004/06/30/169793.aspx.
I was able to come up with a way to access the config at design
time. Below is the code snipet of how to achieve
this. One of my concerns is that this wont
work in any designer other than Visual Studio. If not, is there
another way to achieve the same thing so that it can be used from any designer?
///SOURCED FROM http://blogs.msdn.com/mszcool/archive/2004/06/30/169793.aspx
public class TestControlDesigner :
System.Web.UI.Design.ControlDesigner
{
public
override string GetDesignTimeHtml()
{
string html = “found nothing”;
try
{
// Go through the design time environment, look for the
config and read some data
EnvDTE.DTE devenv =
null;
devenv =
(EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject(“VisualStudio.DTE.7.1″);
Array projects =
(System.Array)devenv.ActiveSolutionProjects;
if((projects.Length == 0) || (projects.Length >
1))
{
html =
“Exactly one project must be active”;
}
else
{
// go through the items of the project to find the
configuration
EnvDTE.Project project =
(EnvDTE.Project)(projects.GetValue(0));
foreach(EnvDTE.ProjectItem item in
project.ProjectItems)
{
// if it is the configuration, then open it
up
if(string.Compare(item.Name, “web.config”, true) == 0)
{
System.IO.FileInfo info =
new
System.IO.FileInfo(project.FullName);
html = “<b>Found configuration</b>”;
html += “<br>” + GetConfigSetting(
info.Directory.FullName + “\\” + item.Name);
}
}
}
}
catch(Exception ex)
{
html = “Exception
occured: ” + ex.Message;
}
return html;
}
private
string GetConfigSetting(string fileName)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(fileName);
System.Xml.XmlNode node =
doc.SelectSingleNode(“//appSettings/add[@key='mySetting']“);
if(node == null)
return “<font color=’red’><b>missing
configuration</b></font>”;
else
return string.Format(“<font
color=’blue’><b>setting value: {0}</b></font>”,
node.Attributes["value"].Value);
}
}

1 comment
Comments feed for this article
August 5, 2008 at 3:15 am
martyn harris
Hi,
Just thought I’d post besause this article is top result in google despite it being very out of date.
There is now a much more elegant way to access the web.config at design time.
Please see the following code.
IWebApplication webApp = (IWebApplication)Site.GetService(typeof(IWebApplication));
System.Configuration.Configuration config = webApp.OpenWebConfiguration(true);
string mySettingValue = config.AppSettings.Settings["mySetting"];