Add users to the IIS_WPG group using C#.Net

The following function adds a user to the IIS_WPG group using the ntrights.exe utility by Microsoft. Note that in order for this function to work you have to have the ntrights utility downloaded. To download it check Microsoft’s wensite:

http://www.microsoft.com/downloads/details.aspx?FamilyID=9D467A69-57FF-4AE7-96EE-B18C4790CFFD&displaylang=en

public static void AddUserToWPG(string currentFolderPath, string user)
{
  try
  {
    Process process = new Process();
    //run the script
    process.StartInfo.FileName = System.Environment.SystemDirectory + @"\net.exe";
    process.StartInfo.Arguments = string.Format(" localgroup \"{0}\" {1} /add",     wpgGroup, user);
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.UseShellExecute = true;
    process.Start();
    process.WaitForExit();

    process.StartInfo.FileName = Path.Combine(currentFolderPath, "ntrights.exe");
    process.StartInfo.Arguments = string.Format(" +r \"seTcbPrivilege\" -u \"{0}\"",     user);
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.UseShellExecute = true;
    process.Start();
    process.WaitForExit();
  }
  catch
  {
     throw new Exception("your message");

  }

}

Advertisements

Change the ASP.Net version of a website on IIS6 using C#.Net

Sometimes, while creating a website pragmatically, you wish to change the ASP.Net version the site is using. The following function change the ASP.Net version a website is using to ASP.Net 2.0

public static void UpdateASPNetVersion(string siteidentifier, string virtualDirectoryName)
{
   //get virtual directory and site name for m context parameters
   string targetSite = "W3SVC/" + siteidentifier + "/ROOT";
   string targetVDir = virtualDirectoryName;
   Process process = new Process();
   //run the script
   process.StartInfo.FileName =         Path.GetDirectoryName(System.Environment.SystemDirectory) + @"\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe";
   process.StartInfo.Arguments = string.Format(" -s {0}/{1}", targetSite, targetVDir);
   process.StartInfo.CreateNoWindow = false;
   process.Start();
   process.WaitForExit();
}

You can of course change the ASP.Net version to any other version by choosing a different directory.

Check if a TCP port is already in use by IIS6 using C#.Net

The following function checks if a port is already in use by the IIS. Such function can be used to validate ports before creating a website. The function simply attempts to open a connection to the specified port. In case there was an exception, that means that it is not used.


public static bool IsPortUsed(int port)
{
   try
   {
      TcpListener tcp = new TcpListener(port);
      tcp.Start();
      tcp.Stop();
      return true;
   }
   catch (SocketException)
   {
      return false;
   }
}

Get a Website Identifier from IIS6 using C#.Net

This function retrieves a website identifier from the IIS. Sometimes, you need a website identifier in order to connect to it and install something under it pragmatically. This function simply connects to the IIS and retrieve all the sub directories and then start searching for the desired website by its name and then return its identifier.


public static int GetWebSiteIdentifier(string server, string siteName)
{
   int siteIdentifier = 0;
   try
   {
     DirectoryEntry root = new DirectoryEntry("IIS://" + server + "/W3SVC");
     foreach (DirectoryEntry entry in root.Children)
     {
       if (string.Compare(entry.SchemaClassName, "IIsWebServer", true) == 0 &&      string.Compare(entry.Properties["ServerComment"].Value.ToString(), siteName, true) == 0)
       siteIdentifier = Int32.Parse(entry.Name);
     }
  }
  catch
  {
    throw new Exception("your message");
  }

  return siteIdentifier;

}

Creating an Application Pool on IIS6 using C#.Net

The following function creates an application pool on IIS6. The function creates an application pool and sets its identity with the specified user name and password.


public static void CreateAppPool(string serverName, string poolName, string userName, string password, bool enableRecylce)
{
  DirectoryEntry AppPool = null;
  DirectoryEntry root = null;
  try
  {
    root = new DirectoryEntry("IIS://" + serverName + "/W3SVC/AppPools");

    //create app pool
    AppPool = root.Invoke("Create", "IIsApplicationPool", poolName) as              DirectoryEntry;

   //set app pool identity
   AppPool.InvokeSet("AppPoolIdentityType", new Object[] {      AppPoolIdentityType.SpecificUser });
   AppPool.InvokeSet("WAMUserName", new Object[] { userName });
   AppPool.InvokeSet("WAMUserPass", new Object[] { password });
   AppPool.InvokeSet("AppPoolAutoStart", new Object[] { true });

   //set recycling options
   if (!enableRecylce)
     AppPool.InvokeSet("PeriodicRestartTime", new Object[] { 0 });

 

 

   AppPool.Invoke("SetInfo");
   AppPool.CommitChanges();
  }
  catch
  {
    throw new Exception("your message");
  }
  finally
  {
    AppPool.Dispose();
    root.Dispose();
  }
}

Check if a website exists on IIS6 using C#.Net

The following function checks if a website with the same name exists or not on the IIS. What it actually does, is that it connects to the IIS and retrieve all sub directories and then start searching for the specified website.


public static bool IsWebSiteExistsOnIIS(string serverName, string siteName)
{
   DirectoryEntry site = null;
   try
   {
      site = new DirectoryEntry("IIS://" + serverName + "/W3SVC");
      foreach (DirectoryEntry entry in site.Children)
      {
        if (entry.Properties["ServerComment"].Value != null &&
            entry.Properties["ServerComment"].Value.ToString() == siteName)
            return true;
      }
      return false;
   }
   finally
   {
      site.Dispose();
   }
}

Notice that the website name is saved in the “ServerComment” property and not the “name”. The “name” property holds the website Identifier.

Create website on IIS6 using C#.Net

The following function creates a website on IIS6 with C#.Net using directory services:

public static void CreateWebSiteOnIIS(string serverName, string siteName, int port, int? sslPort, string sitePath, string appPoolName, AuthTypes authenticationType)
{

   try
   {
      //Create website on IIS
      DirectoryEntry root = new DirectoryEntry("IIS://" + serverName + "/W3SVC");
      int newWebSiteID = (int)root.Invoke("CreateNewSite", new object[] { siteName,           new object[] { ":" + port.ToString() + ":" }, sitePath });
      DirectoryEntry newSite = new DirectoryEntry("IIS://" + serverName + "/W3SVC/"           + newWebSiteID);

      //Set SSL port
      if (sslPort != null)
      {
       newSite.Invoke("Put", new object[] { "SecureBindings", ":" + sslPort + ":" });
      }

      //update application pool
      newSite.Invoke("Put", new object[] { "AppPoolId", appPoolName });

      //update the authentication type of the website
      newSite.Invoke("Put", new object[] { "AuthFlags", authenticationType });
      newSite.Invoke("Put", new object[] { "AccessRead", true });

      //save changes
      newSite.Invoke("SetInfo");
      newSite.CommitChanges();
      root.CommitChanges();

      //Start the new site
      newSite.Invoke("Start", null);
      newSite.Dispose();
      root.Dispose();
   }
   catch
   {
      throw new Exception("Error");
   }
}

You can choose any other authentication type for your website by selecting a different Authentication type from the following enum


public enum AuthTypes
{
     AuthAnonymous = 1,
     AuthBasic = 2,
     AuthNTLM = 4,
     AuthMD5 = 16,
     AuthPassport = 64
}