November 12, 2008

How to access the IIS Metabase programmatically, IIS metabase

The IIS Metabase is XML representation of the IIS instance, it's actually an XML file stored in IIS. It can be access using apps like MetaEdit or programmatically using the Active Directory through a class System.DirectoryServices.DirectoryEntry.

using System.Collections.Generic;
using System.Text;

using System;
using System.Data;
using System.Configuration;


using System.DirectoryServices;
using System.Web.Configuration;

namespace IISMetabase
{
class IISMetabase
{
private string _machineName = "localhost";
private System.Collections.IDictionary _applications;//collection of websites
private Configuration _config;

public IISMetabase()
{
_applications = new System.Collections.Hashtable();
}

public System.Collections.IDictionary GetApplications()
{
DirectoryEntry webentry = new DirectoryEntry();
String path = "IIS://" + _machineName + "/W3SVC/1/ROOT";


webentry.Path = path;
Boolean exists = false;
try
{
exists = DirectoryEntry.Exists(path);
}
catch (System.Runtime.InteropServices.COMException e)
{
String error = e.Message;
Console.WriteLine(error + "\n");
}

if (exists)
{
DirectoryEntries webSiteChildren = webentry.Children;


foreach (DirectoryEntry website in webSiteChildren)
{
String scn = website.SchemaClassName;
String se = website.SchemaEntry.ToString();

if (website.Properties.Contains("KeyType"))
{
String webName = website.Name;

try
{
Object keyTypeValue = website.InvokeGet("KeyType");
String keyTypeValueStr = keyTypeValue.ToString();
if (!keyTypeValueStr.Equals(""))
{
try
{
_config = WebConfigurationManager.OpenWebConfiguration("/" + webName);

_applications.Add(webName, _config);
}
catch (ConfigurationErrorsException err)
{
String error = err.Message;
Console.WriteLine(error + "\n");
}
}
}
catch (Exception err)
{
Console.WriteLine(err.Message + "\n");
continue;
}
}
}

}
else
{
String err = "The Directory " + webentry.Path + "does not exist\n";
Console.WriteLine(err + "\n");
}

return _applications;
}

}
}

No comments: