ApplicationPool creation in Metabase with Csharp

In our project we create IIS application pools from code. For this we connect to the metabase with DirectoryEntry. This is COM and the exceptions are ridiculous somewhat cryptic.

Below is code to create an Application Pool. The comments describe the HRESULT of the exception that is most likely to occur on that line of code.

var nameOfAppPool = "MyNewAppPool";
var schemaClassName = "IisApplicationPool";
var newAppPool = default(DirectoryEntry);
var applicationPools = new DirectoryEntry(
    "IIS://localhost/W3SVC/AppPools");
try
{
    // 0x80070005 > no administrative rights
    newAppPool = applicationPools.Children.Find(
        nameOfAppPool, schemaClassName);
}
catch (System.IO.DirectoryNotFoundException)
{
    // 0x8000500F > SchemaClassName is wrong, 
    //              no administrative rights
    newAppPool = applicationPools.Children.Add(
        nameOfAppPool, schemaClassName);
}

// 0x8000500C > unknown propertyvalue
// 0x80070585 > unknown index (= unknown propertyvalue)
newAppPool.Properties["ManagedRuntimeVersion"][0] = "v4.0";
// 1=Classic, 0=Integrated
newAppPool.Properties["ManagedPipelineMode"][0] = "0"; 
newAppPool.CommitChanges();

To use this code in newer versions of IIS check the IIS6 Management Compatibility in the Windows Features.

References

Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.