Tuesday, March 16, 2010

Some functions in c # to manage IIS

I leave here some useful features to manage IIS using c #.

public static class IISController
{
static string user = System.Configuration.ConfigurationSettings.AppSettings["user"];
static string pass = System.Configuration.ConfigurationSettings.AppSettings["pass"];
static string puerto = System.Configuration.ConfigurationSettings.AppSettings["puerto"];

#region CreateSite

public static bool CreateSite(string metabasePath,
string siteName,
string physicalPath,
string ipAddress,
string hostHeader,
string dotNetVersion)
{

try
{
return CreateSite(metabasePath,
siteName,
physicalPath,
ipAddress,
hostHeader,
dotNetVersion,
null,
null);
}
catch { throw; }
}
#endregion

#region CreateSite
public static bool CreateSite(string metabasePath,
string siteName,
string physicalPath,
string ipAddress,
string hostHeader,
string dotNetVersion,
string windowsUserName,
string windowsUserPassword)
{
int siteID = -1;
object[] hosts = new object[1];
string appPoolID = "";
string newMetaBasePath = "";

try
{

//hostHeader = hostHeader.Replace("www.", "");

hosts[0] = ipAddress + ":"+puerto+":" + hostHeader;
//hosts[1] = ipAddress + ":80:" + "www." + hostHeader;

siteID = GetNextAvailableSiteID(metabasePath);

appPoolID = CreateAppPool(metabasePath + "/AppPools", "GcarsAppPool-"+puerto);

CreateIISSite(metabasePath, siteID.ToString(), siteName, physicalPath, appPoolID, hosts);

newMetaBasePath = metabasePath + "/" + siteID.ToString() + "/Root";

if ((windowsUserName != null) && (windowsUserPassword != null))
{
if ((windowsUserName.Trim().Length > 0) && (windowsUserPassword.Trim().Length > 0))
{
SetSingleProperty(newMetaBasePath, "AnonymousUserName", windowsUserName.Trim());
SetSingleProperty(newMetaBasePath, "AnonymousUserPass", windowsUserPassword.Trim());
SetSingleProperty(newMetaBasePath, "AnonymousPasswordSync", true);
}
}

RegisterASPNETApplicationVersion("W3SVC/" + siteID + "/Root", dotNetVersion);

return true;
}
catch { throw; }
}
#endregion

#region Create IIS Site
private static void CreateIISSite(string metabasePath,
string siteID,
string siteName,
string physicalPath,
string appPoolID,
object hosts)
{
// metabasePath is of the form "IIS:///"
// for example "IIS://localhost/W3SVC"
// siteID is of the form "", for example "555"
// siteName is of the form "", for example, "My New Site"
// physicalPath is of the form ":\", for example, "C:\Inetpub\Wwwroot"

try
{
DirectoryEntry service = new DirectoryEntry(metabasePath);
string className = service.SchemaClassName.ToString();

if (!className.EndsWith("Service")) { return; }

DirectoryEntries sites = service.Children;
DirectoryEntry newSite = sites.Add(siteID, (className.Replace("Service", "Server")));
newSite.Properties["ServerComment"][0] = siteName;
newSite.Properties["ServerBindings"].Value = hosts;
newSite.Invoke("Put", "ServerAutoStart", 1);
newSite.Invoke("Put", "ServerSize", 1);
newSite.CommitChanges();

DirectoryEntry siteVDir;
siteVDir = newSite.Children.Add("Root", "IIsWebVirtualDir");
siteVDir.Properties["Path"][0] = physicalPath;
siteVDir.Properties["EnableDefaultDoc"][0] = true;
siteVDir.Properties["DefaultDoc"].Value = "alogin.aspx";
siteVDir.Properties["AppIsolated"][0] = 2;
siteVDir.Properties["AccessRead"][0] = true;
siteVDir.Properties["AccessWrite"][0] = false;
siteVDir.Properties["AccessScript"][0] = true;
siteVDir.Properties["AccessFlags"].Value = 513;
siteVDir.Properties["AppRoot"][0] = @"/LM/W3SVC/" + siteID.ToString() + "/Root";
siteVDir.Properties["AppPoolId"].Value = appPoolID;
siteVDir.Properties["AuthNTLM"][0] = true;
siteVDir.Properties["AuthAnonymous"][0] = true;
siteVDir.CommitChanges();

}
catch { throw; }
}
#endregion

#region Register ASPNET Application Version
private static void RegisterASPNETApplicationVersion(string applicationMetaPath,
string dotNetVersion)
{
string aspnet = "";

try
{

dotNetVersion = dotNetVersion.Replace("v", "");

aspnet = string.Format(@"{0}\Microsoft.NET\Framework\v{1}\aspnet_regiis.exe",
Environment.GetEnvironmentVariable("windir"),
dotNetVersion);

ProcessStartInfo startInfo = new ProcessStartInfo(aspnet);

startInfo.Arguments = string.Format("-sn \"{0}\"", applicationMetaPath);
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;

Process process = new Process();
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
process.Dispose();

}
catch { throw; }

}
#endregion

#region Create Virtual Directory with metabasePath Att

public static bool CreateVirtualDirectoryMBPath(string metabasePath,
string virtualDirectoryName,
string physicalPath)
{
// metabasePath is of the form "IIS://///Root[/]"
// for example "IIS://localhost/W3SVC/1/Root"
// vDirName is of the form "", for example, "MyNewVDir"
// physicalPath is of the form ":\", for example, "C:\Inetpub\Wwwroot"


try
{
DirectoryEntry site = new DirectoryEntry(metabasePath);
string className = site.SchemaClassName.ToString();

if ((className.EndsWith("Server")) || (className.EndsWith("VirtualDir")))
{
DirectoryEntries vdirs = site.Children;
DirectoryEntry newVDir = vdirs.Add(virtualDirectoryName,
(className.Replace("Service", "VirtualDir")));
newVDir.Properties["Path"][0] = physicalPath;
newVDir.Properties["AccessScript"][0] = true;
// These properties are necessary for an application to be created.
newVDir.Properties["AppFriendlyName"][0] = virtualDirectoryName;
newVDir.Properties["AppIsolated"][0] = "1";
newVDir.Properties["AppRoot"][0] = "/LM" +
metabasePath.Substring(metabasePath.IndexOf("/", ("IIS://".Length)));

newVDir.CommitChanges();

return true;
}

return false;

}
catch { throw; }
}
#endregion

#region Assigns AppPool to Virtual Directory
///
/// Assigns AppPool to Virtual Directory
///

///
///
public static bool AssignVDirToAppPool(string metabasePath, string appPoolName)
{
// metabasePath is of the form "IIS:///W3SVC//Root[/]"
// for example "IIS://localhost/W3SVC/1/Root/MyVDir"
// appPoolName is of the form "", for example, "MyAppPool"
//Console.WriteLine("\nAssigning application {0} to the application pool named {1}:", metabasePath, appPoolName);

DirectoryEntry vDir = new DirectoryEntry(metabasePath);
string className = vDir.SchemaClassName.ToString();
try
{
if (className.EndsWith("VirtualDir"))
{
object[] param = { 0, appPoolName, true };
vDir.Invoke("AppCreate3", param);
vDir.Properties["AppIsolated"][0] = "2";
vDir = null;
return true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
return false;

//}
//else
//throw new Exception(" Failed in AssignVDirToAppPool; only virtual directories can be assigned to application pools");
}
#endregion

#region Configurar Documents a DirectorioVirtual

public static void AddDocumentsToDirV(string IISPath)
{
string metabasePath = String.Format(IISPath, 1);
//Change one way
using (DirectoryEntry de = new DirectoryEntry(metabasePath))
{
de.Properties["DefaultDoc"].Value = "alogin.aspx";
de.CommitChanges();
}

}

#endregion

#region Create Virtual Directory with WebSite Att

/*
* Usage : CreateVirtualDirectory("localhost","MyWebApplication");
*
*/

public static bool CreateVirtualDirectoryWS(string sWebSite, string sAppName, string sPath)
{
System.DirectoryServices.DirectoryEntry iISSchema =
new System.DirectoryServices.DirectoryEntry("IIS://" + sWebSite + "/Schema/AppIsolated");
bool bCanCreate = !(iISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN");
iISSchema.Dispose();

if (bCanCreate)
{
bool bPathCreated = false;
try
{
System.DirectoryServices.DirectoryEntry iISAdmin =
new System.DirectoryServices.DirectoryEntry("IIS://" + sWebSite + "/W3SVC/1/Root");

//make sure folder exists
if (!System.IO.Directory.Exists(sPath))
{
System.IO.Directory.CreateDirectory(sPath);
bPathCreated = true;
}

//If the virtual directory already exists then delete it
foreach (System.DirectoryServices.DirectoryEntry vd in iISAdmin.Children)
{
if (vd.Name == sAppName)
{
//iISAdmin.Invoke("Delete", new string(){vd.SchemaClassName,AppName};);
iISAdmin.Invoke("Delete", new string[] { vd.SchemaClassName, sAppName });
iISAdmin.CommitChanges();
break;
}
}

//Create and setup new virtual directory
System.DirectoryServices.DirectoryEntry vdir = iISAdmin.Children.Add(sAppName, "IIsWebVirtualDir");

vdir.Properties["Path"][0] = sPath;
vdir.Properties["AppFriendlyName"][0] = sAppName;
vdir.Properties["EnableDirBrowsing"][0] = false;
vdir.Properties["AccessRead"][0] = true;
vdir.Properties["AccessExecute"][0] = true;
vdir.Properties["AccessWrite"][0] = false;
vdir.Properties["AccessScript"][0] = true;
vdir.Properties["AuthNTLM"][0] = true;
vdir.Properties["EnableDefaultDoc"][0] = true;
vdir.Properties["DefaultDoc"][0] = "default.htm,default.aspx,default.asp";
vdir.Properties["AspEnableParentPaths"][0] = true;
vdir.CommitChanges();

//'the following are acceptable params
//'INPROC = 0
//'OUTPROC = 1
//'POOLED = 2
vdir.Invoke("AppCreate", 1);

return true;
}
catch (Exception ex)
{
if (bPathCreated)
{
System.IO.Directory.Delete(sPath);
throw ex;
}
}
}
return false;
}

#endregion

#region Delete Virtual Directory

/*
* Usage : DeleteVirtualDirectory("localhost","MyWebApplication");
*
*/

public static bool DeleteVirtualDirectory(string sWebSite, string sAppName)
{
System.DirectoryServices.DirectoryEntry iISSchema =
new System.DirectoryServices.DirectoryEntry("IIS://" + sWebSite + "/Schema/AppIsolated");
bool bCanCreate = !(iISSchema.Properties["Syntax"].Value.ToString().ToUpper() == "BOOLEAN");
iISSchema.Dispose();

if (bCanCreate)
{
try
{
System.DirectoryServices.DirectoryEntry iISAdmin =
new System.DirectoryServices.DirectoryEntry("IIS://" + sWebSite + "/W3SVC/1/Root");

string sWebPath = iISAdmin.Properties["Path"].Value.ToString();

//If the virtual directory already exists then delete it
foreach (System.DirectoryServices.DirectoryEntry vd in iISAdmin.Children)
{
if (vd.Name == sAppName)
{
sWebPath += "\"" + vd.Name;

//if(((System.DirectoryServices.PropertyCollection)((vd.Properties))).valueTable.Count > 0 )
//Original = IIsWebDirectory
//Custom = IIsWebVirtualDir
if (vd.Properties["KeyType"].Value.ToString().Trim() == "IIsWebVirtualDir")
sWebPath = vd.Properties["Path"].Value.ToString();

//iISAdmin.Invoke("Delete", new string(){vd.SchemaClassName,AppName};);
iISAdmin.Invoke("Delete", new string[] { vd.SchemaClassName, sAppName });
System.IO.Directory.Delete(sWebPath);
iISAdmin.CommitChanges();
return true;
}
}
}
catch (Exception ex)
{
return false;
}
}
return false;
}

#endregion

#region Create App Pool
public static string CreateAppPool(string metabasePath, string appPoolName)
{

try
{
if (!metabasePath.EndsWith("/W3SVC/AppPools"))
{
throw new Exception("metaBasePath " + metabasePath
+ " is invalid. It must end with W3SVC/AppPools");
}

DirectoryEntry newPool;
DirectoryEntry appPools = new DirectoryEntry(metabasePath);

foreach (DirectoryEntry entry in appPools.Children)
{

if (entry.Name.ToLower() == appPoolName.ToLower())
{
return entry.Name;
}

}

newPool = appPools.Children.Add(appPoolName, "IIsApplicationPool");

newPool.CommitChanges();

newPool = new DirectoryEntry(metabasePath + "/" + appPoolName);

newPool.Properties["PeriodicRestartMemory"].Value = "0";
newPool.Properties["PeriodicRestartPrivateMemory"].Value = "0";
if (user.Length<=1) { newPool.Properties["AppPoolIdentityType"].Value = "0"; } else { newPool.Properties["AppPoolIdentityType"].Value = "3"; newPool.Properties["WAMUserName"].Value = user; newPool.Properties["WAMUserPass"].Value = pass; } newPool.CommitChanges(); return appPoolName; } catch { throw; } } #endregion #region Set Single Property
public static bool SetSingleProperty(string metabasePath,
string propertyName,
object newValue)
{
// metabasePath is of the form "IIS:///"
// for example "IIS://localhost/W3SVC/1"
// propertyName is of the form "", for example "ServerBindings"
// value is of the form "", for example, ":80:"


try
{
DirectoryEntry path = new DirectoryEntry(metabasePath);


path.Properties[propertyName][0] = newValue;
path.CommitChanges();
return true;

}
catch { throw; }
}
#endregion

#region Get Next Available Site ID
public static int GetNextAvailableSiteID(string metabasePath)
{
int siteID = 101;

try
{
DirectoryEntry root = new DirectoryEntry(metabasePath);


foreach (DirectoryEntry e in root.Children)
{
if (e.SchemaClassName == "IIsWebServer")
{
int ID = Convert.ToInt32(e.Name);

if (ID >= siteID)
{
siteID = ID + 1;
}
}
}
}
catch { throw; }
return siteID;
}
#endregion

}

2 comments: