Enable Bandwidth throttling programmatically using WMI in C#
- From: "AL" <astpc.net@xxxxxxxxx>
- Date: 12 Apr 2006 01:38:24 -0700
Hi,
Does anybody has the script to add Bandwidth throttling and Website
Connections to a website on creation?
This is the code that i've been using to create the website.
thanks
using System;
using System.ComponentModel;
using System.Management;
using System.DirectoryServices;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespaceTest.Net
{
/// <summary>
/// Creates a new IIS website
/// </summary>
/// <remarks>
/// This component is used to create a new IIS website on a
remote
server specified by <see cref="IIsServerName">IIsServerName</see>
/// <para>Internally, it uses WMI to manage the remote
server</para>
/// <para>There is one method <see
cref="CreateSite">CreateSite</see>
that handles creation of the new website, however there are a few
required properties that must be set prior to the method call. They
are:</para>
/// <para><see cref="Description">Description</see>, <see
cref="HomeDirectory">HomeDirectory</see>, <see
cref="TCPPort">TCPPort</see>, <see
cref="IIsServerName">IIsServerName</see>, <see
cref="IIsServerUsername">IIsServerUsername</see>, and <see
cref="IIsServerPassword">IIsServerPassword</see></para>
/// </remarks>
[Description("Creates a new IIS website"),
DefaultProperty("Description")]
public class IIsWebSiteCreator :
System.ComponentModel.Component
{
#region Constructor
/// <overloads>Instantiates a new instance of the <see
cref="IIsWebSiteCreator">IIsWebSiteCreator</see> component</overloads>
/// <summary>
/// Instantiates a new instance of the <see
cref="IIsWebSiteCreator">IIsWebSiteCreator</see> component, using
System.ComponentModel.IContainer
/// </summary>
/// <param name="container"></param>
public
IIsWebSiteCreator(System.ComponentModel.IContainer container)
{
//
// Required for Windows.Forms Class Composition
Designer support
//
container.Add(this);
InitializeComponent();
}
/// <summary>
/// Instantiates a new instance of the <see
cref="IIsWebSiteCreator">IIsWebSiteCreator</see> component
/// </summary>
public IIsWebSiteCreator()
{
//
// Required for Windows.Forms Class Composition
Designer support
//
InitializeComponent();
}
/// <summary>
/// Instantiates a new instance of the <see
cref="IIsWebSiteCreator">IIsWebSiteCreator</see> component, using
default values for <see cref="Description">Description</see>, <see
cref="HomeDirectory">HomeDirectory</see>, <see
cref="LogFileDirectory">LogFileDirectory</see>, and <see
cref="IIsServerName">IIsServerName</see>, also, the <see
cref="AnonymousUserName">AnonymousUserName</see> property will be set
to "WEB\guest_web"
/// </summary>
/// <param name="description"></param>
/// <param name="homeDirectory"></param>
/// <param name="logFileDirectory"></param>
/// <param name="serverName"></param>
public IIsWebSiteCreator(string description, string
homeDirectory,
string logFileDirectory, string serverName)
{
//
// Required for Windows.Forms Class Composition
Designer support
//
InitializeComponent();
_description = description;
_homeDirectory = homeDirectory;
_logFileDirectory = logFileDirectory;
_IIsServerName = serverName;
//Other defaults
_AnonymousUserName = @"WEBSITE\guest_web";
_AnonymousUserPassword = @"test";
}
#endregion
#region Fields
private System.ComponentModel.Container components =
null;
string _description = "";
string _IPAddress = "";
int _TCPPort = 80; //Default is port 80
string[] _hostHeader;
string _homeDirectory = "";
ExecutePermissions _permissions =
ExecutePermissions.ScriptsOnly;
AuthenticatedAccess _authentication =
AuthenticatedAccess.Basic;
bool _enableAnonymousAccess = true;
string _AnonymousUserName = "";
string _AnonymousUserPassword = "";
string _logFileDirectory = "";
bool _enableFrontPage = false;
string _IIsServerName = "";
string _IIsServerUsername = "";
string _IIsServerPassword = "";
string _UNCUsername = "";
string _UNCPassword = "";
string _internalServerName = ""; //eg
"W3SVC/1273343373"
ServerState _state = ServerState.Stopped;
FrontPageExtensionTypes _FrontPageExtensionType =
FrontPageExtensionTypes.None;
WindowsImpersonationContext impContext = null;
#endregion
#region Properties
/// <summary>
/// Gets or sets website description - usually the
domain name (eg.
del9.com)
/// </summary>
[Description("Gets or sets website description -
usually the domain
name (eg. del9.com)"),
Category("Required")]
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Gets or sets IP address of website (leave blank to
use default of
"All Unassigned")
/// </summary>
[Description("Gets or sets IP address of website (leave
blank to use
default of \"All Unassigned\")")]
public string IPAddress
{
get
{
return _IPAddress;
}
set
{
_IPAddress = value;
}
}
/// <summary>
/// Gets or sets TCP Port of website - default is 80.
Must be an
integer value between 1 and 65535
/// </summary>
[Description("Gets or sets TCP Port of website -
default is 80. Must
be an integer value between 1 and 65535"),
DefaultValue(80),
Category("Required")]
public int TCPPort
{
get
{
return _TCPPort;
}
set
{
if (value < 1 || value > 65535)
{
throw new Exception("TCP port
must be an integer value between 1
and 65535");
}
else
{
_TCPPort = value;
}
}
}
/// <summary>
/// Gets or sets the Host Header value - should be set
to domain name
/// </summary>
/// <remarks>
/// This property takes a string array allowing
multiple host headers
to be specified
/// <para>At a minimum, the default domain name should
be specified
eg. "del9.com". It is also recommended that
"www.del9.com" should be specified as well</para>
/// </remarks>
/// <example>
/// The following example shows how to set this
property
/// <code>
/// 'Instantiate a new object (this is done
automatically when using
the visual designer in VS.NET & by dragging the component onto the
design surface)
/// Dim WebSite1 As New IIsWebSiteCreator
///
/// 'Set HostHeader property
/// WebSite1.HostHeader = new String() {"del9.com",
"www.del9.com"}
///
/// 'Set required properties
/// ...
///
/// 'Call CreateSite() to create new site
/// Dim returnValue As Integer = WebSite1.CreateSite()
/// </code>
/// </example>
[Description("Gets or sets Host Header values - should
be set to
domain name (so the same as Name)")]
public string[] HostHeader
{
get
{
return _hostHeader;
}
set
{
_hostHeader = value;
}
}
/// <summary>
/// Gets or sets full path to home directory for site,
eg
"C:\Temp\NewSite" or "\\server\share$\newsite"
/// </summary>
[Description(@"Gets or sets full path to home directory
for site, eg
C:\Temp\NewSite or \\server\share$\newsite"),
Category("Required")]
public string HomeDirectory
{
get
{
return _homeDirectory;
}
set
{
_homeDirectory = value;
}
}
/// <summary>
/// Gets or sets the execute permissions type for site,
default is
"Scripts only"
/// </summary>
[Description("Gets or sets the execute permissions type
for site,
default is \"Scripts only\""),
DefaultValue(ExecutePermissions.ScriptsOnly)]
public ExecutePermissions Permissions
{
get
{
return _permissions;
}
set
{
_permissions = value;
}
}
/// <summary>
/// Gets or sets site authentication method, default is
"Basic"
/// </summary>
[Description("Gets or sets site authentication method,
default is
\"Basic\""),
DefaultValue(AuthenticatedAccess.Basic)]
public AuthenticatedAccess Authentication //TODO:
Change
Authentication to an array object to hold multiple values?
{
get
{
return _authentication;
}
set
{
_authentication = value;
}
}
/// <summary>
/// Gets or sets value indicating whether anonymous
access should be
enabled, default is true
/// </summary>
[Description("Gets or sets value indicating whether
anonymous access
should be enabled, default is true"),
DefaultValue(true)]
public bool EnableAnonymousAccess
{
get
{
return _enableAnonymousAccess;
}
set
{
_enableAnonymousAccess = value;
}
}
/// <summary>
/// Gets or sets the user account name for anonymous
access, eg
"WEB\guest_web"
/// </summary>
[Description("Gets or sets the user account for
anonymous access, eg
\"WEB\\guest_web\"")]
public string AnonymousUserName //AnonymousUserName
property in WMI
documentation
{
get
{
return _AnonymousUserName;
}
set
{
_AnonymousUserName = value;
}
}
/// <summary>
/// Gets or sets the user account password for
anonymous access
/// </summary>
[Description("Gets or sets the user account password
for anonymous
access")]
public string AnonymousUserPassword
{
get
{
return _AnonymousUserPassword;
}
set
{
_AnonymousUserPassword = value;
}
}
/// <summary>
/// Gets or sets the log file directory
/// </summary>
[Description("Gets or sets the log file directory")]
public string LogFileDirectory //WMI
IIsWebServer.LogFileDirectory
property
{
get
{
return _logFileDirectory;
}
set
{
_logFileDirectory = value;
}
}
/// <summary>
/// Gets or sets whether FrontPage extensions should be
enabled for
site, default is false
/// </summary>
[Description("Gets or sets whether FrontPage extensions
should be
enabled for site, default is true"),
DefaultValue(false)]
public bool EnableFrontPage
{
get
{
return _enableFrontPage;
}
set
{
_enableFrontPage = value;
}
}
/// <summary>
/// Gets or sets the FrontPage extension type (<see
cref="FrontPageExtensionTypes">FrontPageExtensionTypes</see>) to
create, default is None
/// </summary>
[Description("Gets or sets the FrontPage extension type
to create,
default is None"),
DefaultValue(FrontPageExtensionTypes.None)]
public FrontPageExtensionTypes FrontPageExtensionType
{
get
{
return _FrontPageExtensionType;
}
set
{
_FrontPageExtensionType = value;
}
}
/// <summary>
/// Gets or sets the name of the IIS server that site
resides on
/// </summary>
[Description("Gets or sets the name of the IIS server
that site
resides on"),
Category("Required")]
public string IIsServerName
{
get
{
return _IIsServerName;
}
set
{
_IIsServerName = value;
}
}
/// <summary>
/// Gets or sets the domain username to use when
connecting to the
IIS server, eg. "WEB\Administrator"
/// </summary>
[Description("Gets or sets the domain username to use
when connecting
to the IIS server, eg. \"WEB\\Administrator\""),
Category("Required")]
public string IIsServerUsername
{
get
{
return _IIsServerUsername;
}
set
{
_IIsServerUsername = value;
}
}
/// <summary>
/// Gets or sets the password to use with the
IIsServerUsername
account
/// </summary>
[Description("Gets or sets the password to use with the
IIsServerUsername account"),
Category("Required")]
public string IIsServerPassword
{
get
{
return _IIsServerPassword;
}
set
{
_IIsServerPassword = value;
}
}
/// <summary>
/// Gets or sets the UNC username to use for connecting
to the
network directory path when site root resides on a network share
/// </summary>
[Description("Gets or sets the UNC username for
connecting to the
network directory path when site root resides on a network share")]
public string UNCUsername
{
get
{
return _UNCUsername;
}
set
{
_UNCUsername = value;
}
}
/// <summary>
/// Gets or sets the UNC password to use for connecting
to the
network directory path when site root resides on a network share
/// </summary>
[Description("Gets or sets the UNC password for
connecting to the
network directory path when site root resides on a network share")]
public string UNCPassword
{
get
{
return _UNCPassword;
}
set
{
_UNCPassword = value;
}
}
#endregion
#region Methods
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Creates a new website
/// </summary>
/// <returns>One of the following return codes: 0 - new
site creation
failed (may already exist); 1 - site creation successful; 2 - site
configuration successful; 3 - server starting; 4 - server started; 5 -
server stopping; 6 - server stopped; 7 - server pausing; 8 - server
paused; 9 - server continuing</returns>
/// <exception cref="System.Exception">Thrown when
required
properties are not specified, and when a duplicate site already
exists</exception>
public int CreateSite()
{
int returnCode = 0;
// Check for required properties before
creating site, throw
exceptions
CheckRequiredProps();
// -- end checks ----
ConnectionOptions oConn = new
ConnectionOptions();
oConn.Authentication
=AuthenticationLevel.PacketPrivacy;
if (_IIsServerName.ToUpper() ==
Environment.MachineName.ToUpper())
{
//Need to impersonate on local machine
string domain = "";
string username = "";
if (_IIsServerUsername.IndexOf(@"\") !=
-1)
{
domain =
_IIsServerUsername.Substring(0,
_IIsServerUsername.IndexOf(@"\"));
username =
_IIsServerUsername.Substring(_IIsServerUsername.IndexOf(@"\") + 1);
}
else
{
domain = "";
username = _IIsServerUsername;
}
impContext =
NetworkSecurity.ImpersonateUser(
domain,
username,
_IIsServerPassword,
LogonType.LOGON32_LOGON_NETWORK,
LogonProvider.LOGON32_PROVIDER_DEFAULT);
oConn.Impersonation =
ImpersonationLevel.Impersonate;
oConn.EnablePrivileges = true;
}
else
{
oConn.Username = _IIsServerUsername;
oConn.Password = _IIsServerPassword;
}
ManagementPath myPath = new ManagementPath();
myPath.Server = _IIsServerName;
ManagementScope scope = null;
ObjectQuery oq = null;
// Create virtual root if it doesn't exist --
Need to check if we
are using UNC shares or not
bool dirExists = false;
if (_homeDirectory.StartsWith(@"\\")) // UNC
share
{
//HACK: Creating folders on UNC shares
on remote machine doesn't
seem to work?.. so this must be done b4 call is made to this method
// //Use impersonation just in case UNC
share has denied ACL
permissions for calling ASP.NET user
// if (impContext == null)
// {
// string domain =
_IIsServerUsername.Substring(0,
_IIsServerUsername.IndexOf(@"\"));
// string username =
_IIsServerUsername.Substring(_IIsServerUsername.IndexOf(@"\") + 1);
//
// try
// {
// impContext =
NetworkSecurity.ImpersonateUser(
// domain,
// username,
//
_IIsServerPassword,
//
LogonType.LOGON32_LOGON_NETWORK,
//
LogonProvider.LOGON32_PROVIDER_DEFAULT);
// }
// catch (ApplicationException ex)
// {
// throw ex;
// }
// }
//
// if (Directory.Exists(_homeDirectory))
dirExists = true;
}
else //Not UNC share so need to use WMI to
determine if it exists
{
myPath.NamespacePath = @"root\CIMV2";
scope = new ManagementScope(myPath,
oConn);
oq = new ObjectQuery("select Name from
Win32_Directory where Name =
'" + _homeDirectory.Replace(@"\", @"\\") + "'");
using (ManagementObjectSearcher os =
new
ManagementObjectSearcher(scope, oq))
{
if (os.Get().Count > 0)
//It exists!
{
dirExists = true;
}
}
}
if (!dirExists)
{
//Create it
if
(!CreateHomeDirectory(_homeDirectory, oConn))
throw new Exception("Cannot
create website home directory at \"" +
_homeDirectory + "\" on " + _IIsServerName);
}
//----
myPath.NamespacePath = @"root\MicrosoftIISv2";
myPath.RelativePath =
"IIsWebService.Name='W3SVC'";
scope = new ManagementScope(myPath, oConn);
// Check if site already exists first
oq = new ObjectQuery("select ServerComment from
IIsWebServerSetting
where ServerComment = '" + _description + "'");
using (ManagementObjectSearcher os = new
ManagementObjectSearcher(scope, oq))
{
if (os.Get().Count > 0)
throw new Exception("Site with
same description already exists");
}
// --------------
string ret = "";
using (ManagementObject nac = new
ManagementObject(scope, myPath,
null))
{
// create ServerBinding WMI objects for
each host header
ManagementBaseObject[] ServerBindings;
if (_hostHeader.Length > 0)
{
ServerBindings = new
ManagementBaseObject[_hostHeader.Length];
for (int i = 0; i <
_hostHeader.Length; i++)
{
ManagementObject
Bindings = CreateServerBindingInstance(oConn,
_IIsServerName);
Bindings["IP"] =
_IPAddress;
Bindings["Hostname"] =
_hostHeader[i];
Bindings["Port"] =
_TCPPort;
Bindings.Put(); //to
commit the new instance.
ServerBindings[i] =
Bindings as ManagementBaseObject;
}
}
else
{
ManagementObject Bindings =
CreateServerBindingInstance(oConn,
_IIsServerName);
Bindings["IP"] = _IPAddress;
Bindings["Hostname"] = "";
Bindings["Port"] = _TCPPort;
Bindings.Put(); //to commit the
new instance.
ServerBindings = new
ManagementBaseObject[1];
ServerBindings[0] = Bindings as
ManagementBaseObject;
}
// create the site using the new
bindings
try
{
ret = CreateNewSite(nac,
_homeDirectory, ServerBindings,
_description);
}
catch (Exception ex)
{
nac.Dispose();
throw ex;
}
}
// Configure the new web server
if (ret.Length > 0)
{
// Check to see if site created
successfully..
if (ret.IndexOf("IIsWebServer=") == -1)
{
throw new Exception("Error
creating site: " + ret);
}
returnCode = 1; //Site created
successfully
// From the return string, we need to
parse out just the server
name, eg W3SVC/1273343373
_internalServerName =
ret.Replace("IIsWebServer='",
"").TrimEnd(Convert.ToChar("'"));
if (_internalServerName.Length > 0)
{
// Configure using
IIsWebServerSetting (ie server level)
myPath.RelativePath =
"IIsWebServerSetting.Name='" +
_internalServerName + "'";
using (ManagementObject
oWebServerSetting = new
ManagementObject(new ManagementScope(myPath, oConn), myPath, null))
{
oWebServerSetting["ServerAutoStart"] = true;
oWebServerSetting["AccessRead"] = true;
switch (_permissions)
{
case
ExecutePermissions.None: //Nothing to do here
break;
case
ExecutePermissions.ScriptsOnly:
oWebServerSetting["AccessScript"] = true;
break;
case
ExecutePermissions.ScriptsAndExecutables:
oWebServerSetting["AccessScript"] = true;
oWebServerSetting["AccessExecute"] = true;
break;
}
if
(_logFileDirectory.Length > 0)
{
oWebServerSetting["LogFileDirectory"] = _logFileDirectory;
}
else
{
oWebServerSetting["DontLog"] = true;
}
if
(_enableAnonymousAccess)
{
if
(_AnonymousUserName.Length == 0)
{
oWebServerSetting.Dispose();
throw
new Exception("When anonymous access is enabled, the
AnonymousUserName property must be specified");
}
oWebServerSetting["AuthAnonymous"] = true;
oWebServerSetting["AnonymousUserName"] = _AnonymousUserName;
if
(_AnonymousUserPassword.Length > 0)
oWebServerSetting["AnonymousUserPass"] =
_AnonymousUserPassword;
}
switch
(_authentication)
{
case
AuthenticatedAccess.Basic:
oWebServerSetting["AuthBasic"] = true;
break;
case
AuthenticatedAccess.Digest:
oWebServerSetting["AuthMD5"] = true;
break;
case
AuthenticatedAccess.Integrated:
oWebServerSetting["AuthNTLM"] = true;
break;
case
AuthenticatedAccess.Passport:
oWebServerSetting["AuthPassport"] = true;
break;
}
// Commit changes
oWebServerSetting.Put();
returnCode = 2;
}
// Configure using
IIsWebVirtualDirSetting (ie site root directory
level) after server has started
myPath.RelativePath =
"IIsWebVirtualDirSetting.Name='" +
_internalServerName + "/ROOT'";
using (ManagementObject
oVirtualDirSetting = new
ManagementObject(new ManagementScope(myPath, oConn), myPath, null))
{
oVirtualDirSetting["AppFriendlyName"] = "Default Application";
if (_UNCUsername.Length
0){
oVirtualDirSetting["UNCUserName"] = _UNCUsername;
oVirtualDirSetting["UNCPassword"] = _UNCPassword;
}
// Commit
oVirtualDirSetting.Put();
}
//Start the server!
myPath.RelativePath =
"IIsWebServer.Name='" + _internalServerName
+"'";
using (ManagementObject
oWebServer = new ManagementObject(new
ManagementScope(myPath, oConn), myPath, null))
{
// first must check the
state
if
((int)oWebServer["ServerState"] == 4 ||
(int)oWebServer["ServerState"] == 6) //ie. stopped or paused
{
// Start it via
async call
oWebServer.InvokeMethod("Start", null);
// Wait 1 sec
for changes to take place
System.Threading.Thread.Sleep(1000);
}
}
// Check the state
using (ManagementObject
oWebServer = new ManagementObject(new
ManagementScope(myPath, oConn), myPath, null))
{
_state =
IIsManager.SetServerState((int)oWebServer["ServerState"]);
}
//We need to add 3 to account
for previous return values
returnCode = 3 + (int)_state;
// Try to setup FrontPage
extensions only if the following
conditions are met:
// Server state = Running
// EnableFrontPage = true
// FrontPageExtensionType =
FPE2002
// HomeDirectory is not a UNC
share (ie starts with "\\")
if (_state ==
ServerState.Running && _enableFrontPage &&
_FrontPageExtensionType == FrontPageExtensionTypes.FPE2002 &&
!_homeDirectory.StartsWith(@"\\"))
{
myPath.RelativePath =
"IIsWebServerSetting.Name='" +
_internalServerName +"'";
using (ManagementObject
oWebServer = new ManagementObject(new
ManagementScope(myPath, oConn), myPath, null))
{
//FrontPage
extensions
oWebServer["FrontPageWeb"] = true;
// Commit
oWebServer.Put();
}
IIsManager oManager =
new IIsManager(_IIsServerName,
_IIsServerUsername, _IIsServerPassword);
int identifier =
Int32.Parse(_internalServerName.Replace("W3SVC/", ""));
oManager.CreateFrontPageExtensions(FrontPageExtensionTypes.FPE2002,
identifier);
}
}
}
//Undo impersonation
if (impContext != null)
impContext.Undo();
return returnCode;
}
/// <summary>
/// Creates a new website
/// </summary>
/// <param name="isWin2k">Boolean value indicating
whether or not
server is running Windows 2000</param>
/// <returns>One of the following return codes: 0 - new
site creation
failed (may already exist); 1 - site creation successful; 2 - site
configuration successful; 3 - server starting; 4 - server started; 5 -
server stopping; 6 - server stopped; 7 - server pausing; 8 - server
paused; 9 - server continuing</returns>
/// <exception cref="System.Exception">Thrown when
required
properties are not specified, and when a duplicate site already
exists</exception>
/// <remarks>This method differs to the CreateSite()
method in that
it doesn't check for the existance of the directory and tries to create
it, so you must create the home directory first before using this on a
Win2k server (similar to UNC shares)</remarks>
public int CreateSite(bool isWin2k)
{
CheckRequiredProps();
if (isWin2k) //Have to use ADSI
{
int returnCode = 0;
//Need to impersonate on local machine
string domain = "";
string username = "";
if (_IIsServerUsername.IndexOf(@"\") !=
-1)
{
domain =
_IIsServerUsername.Substring(0,
_IIsServerUsername.IndexOf(@"\"));
username =
_IIsServerUsername.Substring(_IIsServerUsername.IndexOf(@"\") + 1);
}
else
{
domain = "";
username = _IIsServerUsername;
}
string rootDirPath = "IIS://" +
_IIsServerName + "/W3SVC";
int newWebID = 0;
using (DirectoryEntry webServer = new
DirectoryEntry(rootDirPath,
_IIsServerUsername, _IIsServerPassword, AuthenticationTypes.Secure |
AuthenticationTypes.ServerBind))
{
//Search thru all existing
sites & find highest identifier
foreach (DirectoryEntry website
in webServer.Children)
{
if
(website.SchemaClassName == "IIsWebServer")
{
if
(Int32.Parse(website.Name) > newWebID)
newWebID = Int32.Parse(website.Name);
}
}
//Increment the ID
newWebID++;
//Now create site
using (DirectoryEntry
newWebsite =
webServer.Children.Add(newWebID.ToString(), "IIsWebServer"))
{
newWebsite.Properties["ServerComment"].Insert(0, _description);
//ServerBindings
if (_hostHeader.Length
0){
for (int i = 0;
i < _hostHeader.Length; i++)
{
newWebsite.Properties["ServerBindings"].Insert(i, _IPAddress +
":" + _TCPPort.ToString() + ":" + _hostHeader[i]);
}
}
else
{
newWebsite.Properties["ServerBindings"].Insert(0, _IPAddress +
":" + _TCPPort.ToString() + ":");
}
//ServerAutoStart
newWebsite.Properties["ServerAutoStart"].Insert(0, true);
//LogFileDirectory
if
(_logFileDirectory.Length > 0)
{
newWebsite.Properties["LogFileDirectory"].Insert(0,
_logFileDirectory);
}
else
{
newWebsite.Properties["DontLog"].Insert(0, true);
}
//AnonymousAccess
if
(_enableAnonymousAccess)
{
if
(_AnonymousUserName.Length == 0)
{
throw
new Exception("When anonymous access is enabled, the
AnonymousUserName property must be specified");
}
newWebsite.Properties["AuthFlags"].Insert(0,
0x00000001); //AuthAnonymous
newWebsite.Properties["AnonymousUserName"].Insert(0,
_AnonymousUserName);
if
(_AnonymousUserPassword.Length > 0)
newWebsite.Properties["AnonymousUserPass"].Insert(0,
_AnonymousUserPassword);
}
newWebsite.CommitChanges();
newWebsite.RefreshCache();
returnCode = 1; //Site
created successfully
//Site root directory
settings
using (DirectoryEntry
virtRoot = newWebsite.Children.Add("ROOT",
"IIsWebVirtualDir"))
{
//Home
directory
virtRoot.Properties["Path"].Insert(0, _homeDirectory);
if
(_UNCUsername.Length > 0)
{
virtRoot.Properties["UNCUserName"].Insert(0, _UNCUsername);
virtRoot.Properties["UNCPassword"].Insert(0, _UNCPassword);
}
//Permissions
virtRoot.Properties["AccessFlags"].Insert(0,
0x00000001); //AccessRead
switch
(_permissions)
{
case
ExecutePermissions.None: //Nothing to do here
break;
case
ExecutePermissions.ScriptsOnly:
virtRoot.Properties["AccessFlags"].Insert(0,
0x00000201); //AccessRead | AccessScript
break;
case
ExecutePermissions.ScriptsAndExecutables:
virtRoot.Properties["AccessFlags"].Insert(0,
0x00000205); //AccessRead | AccessScript | AccessExecute
break;
}
switch
(_authentication)
{
case
AuthenticatedAccess.Basic:
if (_enableAnonymousAccess)
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000003); //AuthAnonymous | AuthBasic
else
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000002); //AuthBasic
break;
case
AuthenticatedAccess.Digest:
if (_enableAnonymousAccess)
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000017); //AuthAnonymous | AuthMD5
else
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000016); //AuthMD5
break;
case
AuthenticatedAccess.Integrated:
if (_enableAnonymousAccess)
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000005); //AuthAnonymous | AuthNTLM
else
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000004); //AuthNTLM
break;
case
AuthenticatedAccess.Passport:
if (_enableAnonymousAccess)
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000065); //AuthAnonymous | AuthPassport
else
virtRoot.Properties["AuthFlags"].Insert(0,
0x00000064); //AuthPassport
break;
}
//DirBrowseFlags
virtRoot.Properties["DirBrowseFlags"].Insert(0,
0x4000003E); //All except for EnableDirBrowsing
virtRoot.CommitChanges();
virtRoot.Close();
}
newWebsite.CommitChanges();
newWebsite.RefreshCache();
webServer.CommitChanges();
returnCode = 2; //Site
configured successfully
newWebsite.Close();
} //newWebSite
webServer.Close();
} //webServer
//Reconnect to setup the application
root
using (DirectoryEntry appRoot = new
DirectoryEntry(rootDirPath +
"/" + newWebID + "/ROOT", _IIsServerUsername, _IIsServerPassword,
AuthenticationTypes.Secure | AuthenticationTypes.ServerBind))
{
if (appRoot != null)
{
appRoot.Invoke("AppCreate", new object[] {true});
appRoot.CommitChanges();
appRoot.Properties["AppFriendlyName"].Value = "Default
Application";
appRoot.Properties["AppIsolated"].Value = 2;
appRoot.CommitChanges();
}
appRoot.Close();
}
//Try to start the server!
using (DirectoryEntry newWebsite = new
DirectoryEntry(rootDirPath +
"/" + newWebID, _IIsServerUsername, _IIsServerPassword,
AuthenticationTypes.Secure | AuthenticationTypes.ServerBind))
{
if (newWebsite != null)
{
//Start the server!
newWebsite.Invoke("Start", null);
System.Threading.Thread.Sleep(1000);
newWebsite.CommitChanges();
newWebsite.RefreshCache();
//Check state
_state =
IIsManager.SetServerState(Convert.ToInt32(newWebsite.Properties["ServerState"].Value));
returnCode = 3 +
(int)_state;
// Try to setup
FrontPage extensions only if the following
conditions are met:
// Server state =
Running
// EnableFrontPage =
true
//
FrontPageExtensionType = FPE2000
// HomeDirectory is not
a UNC share (ie starts with "\\")
if (_state ==
ServerState.Running && _enableFrontPage &&
_FrontPageExtensionType == FrontPageExtensionTypes.FPE2000 &&
!_homeDirectory.StartsWith(@"\\"))
{
//FrontPage
extensions
newWebsite.Properties["FrontPageWeb"].Insert(0, true);
newWebsite.CommitChanges();
newWebsite.RefreshCache();
IIsManager
oManager = new IIsManager(_IIsServerName,
_IIsServerUsername, _IIsServerPassword);
oManager.CreateFrontPageExtensions(FrontPageExtensionTypes.FPE2000,
newWebID);
}
}
newWebsite.Close();
}
return returnCode;
}
else
{
return CreateSite();
}
}
private void CheckRequiredProps()
{
if (_homeDirectory.Length == 0)
throw new Exception("Site home
directory not specified");
if (_IIsServerName.Length == 0)
throw new Exception("IIS server not
specified");
if (_IIsServerUsername.Length == 0 ||
_IIsServerPassword.Length ==
0)
throw new Exception("Credentials used
for logging on to IIS server
not specified");
if (_description.Length == 0)
throw new Exception("Site description
not specified");
if (_TCPPort < 1 || _TCPPort > 65535)
throw new Exception("TCPPort must be an
integer between 1 and
65535");
if (_enableAnonymousAccess &&
_AnonymousUserName.Length == 0)
throw new Exception("When anonymous
access is enabled,
AnonymousUserName must be specified");
}
// Create ref to ServerBinding class
private ManagementObject
CreateServerBindingInstance(ConnectionOptions oConn, string server)
{
ManagementScope mScope = null;
ManagementPath mPath = new ManagementPath();
mPath.ClassName = "ServerBinding";
mPath.NamespacePath = "root\\MicrosoftIISv2";
mScope = new ManagementScope(mPath, oConn);
mScope.Path.Server = server;
return new ManagementClass(mScope, mPath,
null).CreateInstance();
}
// Create new site
private string CreateNewSite(ManagementObject nac,
string
PathOfRootVirtualDir, ManagementBaseObject[] ServerBindings, string
ServerComment)
{
ManagementBaseObject inP = null;
inP = nac.GetMethodParameters("CreateNewSite");
inP["PathOfRootVirtualDir"] =
PathOfRootVirtualDir;
inP["ServerBindings"] = ServerBindings;
inP["ServerComment"] = ServerComment;
ManagementBaseObject outP =
nac.InvokeMethod("CreateNewSite", inP,
null);
return
System.Convert.ToString(outP.Properties["ReturnValue"].Value);
// Returns something like:
IIsWebServer='W3SVC/1273343373'
// this can be used to further
configure/customize the webserver
}
// Create site home directory, returns true if
successful otherwise,
false.
private bool CreateHomeDirectory(string fullpath,
ConnectionOptions
oConn)
{
bool flag = false;
ManagementPath mpath = new ManagementPath();
mpath.Server = _IIsServerName;
mpath.ClassName = "Win32_Process";
mpath.NamespacePath = @"root\CIMV2";
ManagementScope scope = new
ManagementScope(mpath, oConn);
using (ManagementClass process = new
ManagementClass(scope, mpath,
null))
{
string commandLine =
"C:\\createfolder.cmd \"" + fullpath + "\"";
ManagementBaseObject inParams = null;
inParams =
process.GetMethodParameters("Create");
inParams["CommandLine"] = commandLine;
inParams["CurrentDirectory"] = null;
inParams["ProcessStartupInformation"] =
null;
ManagementBaseObject outParams =
process.InvokeMethod("Create",
inParams, null);
int retVal =
Convert.ToInt32(outParams.Properties["ReturnValue"].Value);
inParams.Dispose();
outParams.Dispose();
}
//Wait 1 sec
System.Threading.Thread.Sleep(1000);
//Find out if directory was created
successfully
if (fullpath.StartsWith(@"\\")) //UNC
share
{
if (Directory.Exists(fullpath))
flag = true;
}
else //Use WMI to search
{
mpath.ClassName = "Win32_Directory";
ManagementScope scope2 = new
ManagementScope(mpath, oConn);
ObjectQuery oq = new
ObjectQuery("select Name from Win32_Directory
where Name = '" + fullpath.Replace(@"\", @"\\") + "'");
using (ManagementObjectSearcher os =
new
ManagementObjectSearcher(scope2, oq))
{
if (os.Get().Count > 0)
flag = true;
}
}
return flag;
}
#endregion
#region Child objects
/// <summary>
/// Handler class for asynchronous callback
/// </summary>
internal class ObserverHandler
{
bool isComplete = false;
/// <summary>
/// Specifies that async operation is done
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Done(object sender,
CompletedEventArgs e)
{
isComplete = true;
}
/// <summary>
/// Indicates whether or not async call is
complete
/// </summary>
public bool IsComplete
{
get
{
return isComplete;
}
}
}
#endregion
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not
modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new
System.ComponentModel.Container();
}
#endregion
}
.
- Prev by Date: Re: Inconsistent WMI results using multiple asynchronous queries
- Next by Date: Re: WMI in VC++, Access Denied
- Previous by thread: Re: Bind the TCP/IP protocol to adapter
- Next by thread: How to determine if permissions are inherited
- Index(es):
Relevant Pages
|