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);

  }

}

Advertisements