Accessing custom properties at runtime through managed modules (part 1)
Following on my last post in developing my module for app-building week, I want to talk about how I wrote the code for my managed module (C# code). So far, I have custom configuration schema that could be accessed through various built-in tools and I know that I can access custom configuration through managed code, but I needed to find some samples.
So I searched iis.net for some articles, tools and forum posts about this problem.
I found this article first:
http://www.iis.net/articles/view.aspx/IIS7/Extending-IIS7/Extending-IIS7-Configuration/Extending-IIS7-Schema-and-Accessing-the-custom-sec?Page=2
This example isn’t so detailed for a c# newbie like myself and I needed an example to access collections.
I found an example of code accessing collections here: http://forums.iis.net/t/1026445.aspx
And another one here:
With these examples, I was able to write a little console application that would read and write my configuration. A good start.
Here is my code:
using System;
using Microsoft.Web.Administration;
namespace PonyConsole
{
class Program
{
static void Main(string[] args)
{
// Initialize the server manager used to administer the sections
ServerManager serverManager = new ServerManager();
// Get the applicationHost.config file
Configuration config = serverManager.GetApplicationHostConfiguration();
// Get the custom configuration section from that file
ConfigurationSection section = config.GetSection("ENC-Pony");
// Output the default value of the booleanProperty
Console.WriteLine(section.GetAttributeValue("CanIHaveAPonyPlease"));
// Set the new value of the booleanProperty
section.SetAttributeValue("CanIHaveAPonyPlease", true);
// add an item to the collection
ConfigurationElementCollection collection = section.GetCollection("ponies");
ConfigurationElement newElement = collection.CreateElement();
newElement.SetAttributeValue("PonyLocation", "HttpLink");
newElement.SetAttributeValue("value", "c:\\pic");
collection.Add(newElement);
// Update the config file with the changes that you have made
serverManager.CommitChanges();
Console.WriteLine("Finished writing ... ");
// Output the default value of the booleanProperty
Console.WriteLine(section.GetAttributeValue("CanIHaveAPonyPlease"));
Console.WriteLine("YesResponse is: " + section.GetAttributeValue("YesResponse"));
Console.WriteLine("NoResponse is: " + section.GetAttributeValue("NoResponse"));
foreach (ConfigurationElement element in section.GetCollection("ponies"))
{
Console.WriteLine(element.GetAttribute("PonyLocation").Value);
Console.WriteLine(element.GetAttribute("value").Value);
}
}
}
}
At this point I had successfully written code using our new managed interface to read and write to my custom configuration properties. Very exciting ... next post is how do I make this work in the context of an IIS pipeline module.