Detailed description of C # Operations IIS full parsing (graphics)

Source: Internet
Author: User
Tags hosting silverlight
Recently in the implementation of a tool for the company, Silverlight deployment is already a pro, but for non-technical staff is a headache, when the implementation of the site to meet the customer situation is also different, need a similar system backup "one-click tool" quickly implement application deployment and Database Association. Online on this aspect of resources is also more chaotic, which for IIS programming impact factors, operational skills to refine the summary.





A: Version Issue



This is a practical problem that you have to consider before you start programming. Because the IIS version is different in that it is basically a completely different approach to programming. Learn more about the ISS version in the operating system specific requirements.






The ISS6.0 era mainly takes the DirectoryEntry object under the using System.DirectoryServices space as programmatic access to a main carrier. But as ISS7.0 publishes. NET, the Web program begins to transition from ISS6.0 to version 7.0. In addition to the newly added Microsoft.Web.Administration namespaces in the programming control ISS, several objects are proposed for managing operations and accessing ISS, making the operation of ISS more streamlined and efficient.



B: What are we going to do?



The actual user operating environment mainly in the Windows xp/2000/2003 operating system, which led to the ISS version is mainly between 5.0/5.1/6.0, so this demo code programming instance is the ISS7.0 version of the following (not including Iss7.0).



For demonstration purposes, we are now in demand: To successfully deploy a Silverlight application on the hard disk to the local machine ISS. and support access over LAN. The demand is very simple is a sentence, in fact, when entering the actual programming because the customer's LAN environment is unpredictable, which also led to the impact of deploying Silverlight program to ISS many unknown factors. So to make Silverlight applications successful in programming, we have to take advantage of programming in addition to controlling ISS to control other major factors affecting the ISS.



C: Enter programming



Now that we've made the demand, we're probably sure of a solution:






Create a virtual directory hosting Silverlight application under the default site, the new virtual directory runs in a stand-alone application pool, support for local LAN anonymous access is actually a control of access rights, in order to directly make the changed application effective requires multiple restarts of the ISS service, This requires programmatic control of the ISS service.



Acquisition of the <1>iss version



Before entering the customer environment, we first detect the presence of ISS installed, and the ISS version to get hints, there are two main ways to obtain the ISS version, the first method is to traverse the DirectoryEntry entity directory The second way is by getting the registry of ISS modified version value [ Tested this way to get version instability].


public static void GetIssVersionByDri (string domainname)
    2:      {       
    3: try
    4: {
    5: if (string.IsNullOrEmpty (domainname))
    6: {
    7: // If empty, it defaults to the local machine
    8: domainname = "LOCALHOST";
    9:                }
   10: DirectoryEntry getEntity = new DirectoryEntry ("IIS: //" + domainname + "/ W3SVC / INFO");
   11: string Version = getEntity.Properties ["MajorIISVersionNumber"]. Value.ToString ();
   12: MessageBox.Show (Version);
   13:}
   14: catch (Exception se)
   15: {
   16: // Explanation: there is no (int) entry.Properties ["MajorIISVersionNumber"]. Value; property in IIS5.0, an exception will be thrown and the version is 5.0
   17: MessageBox.Show ("Getting ISS version is an exception message:" + se.Message);
   18:}
   19:}


Get the ISS version value from the system registry: [Test found unstable]


1: public static string GetIssVersion ()
    2:  {
    3: // RegistryKey represents an item-level node in the Windows registry. This class is a registry wrapper
    4: string issversion = string.Empty;
    5: RegistryKey getkey = Registry.LocalMachine.OpenSubKey ("software \\ microsoft \\ inetstp");
    6: if (getkey! = Null)
    7: {
    8: issversion = Convert.ToInt32 (getkey.GetValue ("majorversion", -1)). ToString ();
    9: MessageBox.Show (issversion.ToString ());
   10:}
   11: return issversion;
   12:}
  <2> Create a virtual directory


Each Internet service can be published from more than one directory, and each directory can be located on a local drive or network by specifying a directory with a universal naming convention (UNC) name, a user name, and a password for access, and a virtual directory may be a host program. This published action directory is the virtual directory. Take a look at the steps and properties of the virtual directory that you created in ISS6.0.






To create a new virtual directory:


1: /// <summary>
   2: /// add a virtual directory
   3: /// </ summary>
   4: public void CreateVirtualDir (string virtualdirname, string logicDir)
   5: {
   6: // If there are duplicates, delete the virtual directory directly
   7: if (IsExitesVirtualDir (virtualdirname))
   8: DeleteVirtualDir (virtualdirname);
   9:   
  10: DirectoryEntry rootEntry;
  11: rootEntry = new DirectoryEntry ("IIS: // localhost / W3SVC / 1 / root");
  12:
  13: DirectoryEntry newVirDir;
  14: newVirDir = rootEntry.Children.Add (virtualdirname, "IIsWebVirtualDir");
  15: newVirDir.Invoke ("AppCreate", true);
  16:
  17: newVirDir.CommitChanges ();
  18: rootEntry.CommitChanges ();
  19:
  20: newVirDir.Properties ["AnonymousPasswordSync"] [0] = true;
  21: newVirDir.Properties ["Path"] [0] = logicDir; // + @ "virtualdirentry \ virtualname \";
  twenty two:   
  23: // Set port binding data
  24: //_newVirDir.Properties["ServerBindings"].Value = AppEntitys.WebAppInfor.HostIp + AppEntitys.WebAppInfor.HostProt + AppEntitys.WebAppInfor.AppDesc;
  25:
  26: // Set starting default page:
  27: newVirDir.Properties ["EnableDefaultDoc"] [0] = true;
  28: newVirDir.Properties ["DefaultDoc"] [0] = "Default.aspx";
  29:
  30: // _ newVirDir
  31: newVirDir.CommitChanges ();
  32:}





This method is created with two parameters, one is the new virtual directory name, and the other is the physical path of the Silverlight application to deploy. The path to the ISS needs to be established when acquiring the root program. ISS path format such as: Iis://computername/service/website/directory






Add a new virtual directory after locating the root directory. Set the parameter to schema-refers to the type of each node: iisvirtualdir:--virtual directory Iiswebdir:--Normal directory, after adding the "AppCreate" method in ADSI to create the directory. Commit to save through the root directory and new directory after creation is complete .



<3> Directory property settings



The Directoryentity virtual Directory property can be said to be very much, at the time of programming I do a way to differentiate between attributes to go through the entire set of properties PropertyCollection. Then jump out of the usual important attributes into the assignment settings. Because the properties on the virtual directory are not directly mentioned in the API on MSDN, especially for virtual directory access control, very important attributes, and so on. The local common properties are described first:






For example, modify the program start page:


1: // Set starting default page:
    2: newVirDir.Properties ["EnableDefaultDoc"] [0] = true;
    3: newVirDir.Properties ["DefaultDoc"] [0] = "Default.aspx, Index.Html, index.asp";
    4: newVirDir.CommitChanges ();


The DefaultDoc option supports multiple but selective sorting. The general modification of the directory properties is done by the CommitChanges () method to commit the save, but sometimes you will find that I have modified the properties without saving them. This is because some of the property settings in ISS require that the ISS service be restarted to take effect. This time we need to control the ISS service.



<4>iss Service Control



About ISS Service control Microsoft provides a namespace system.serviceprocess provides the ability to quickly manipulate the local System Services API. For ISS Service control Our most common use is to restart the current settings to take effect. When setting up the service, I first find the service name, open Computer Management and open the service under the service and application directory.






We can see that the ISS service naming is: Issadmin we control by encoding: Start ISS.





1: // Get IIS Serivcer control statement. The parameter is the server's short name for identifying the service in the system.
    2: ServiceController getservicecon = new ServiceController ("IISADMIN");
    3: getservicecon.Start ();


Restart/pause/stop ISS service:





1: if (getservicecon.Status == ServiceControllerStatus.Running)
    2:       {
    3: // stop service
    4: getservicecon.Stop ();
    5: // suspend service
    6: getservicecon.Pause ();
    7: // Restart the service
    8: // Process provides access to local and remote processes and enables you to start and stop local system processes
    9: // Using the Start method call: Start (or reuse) the process resource specified by the StartInfo property of this Process component and associate it with the component
   10: // true if a process resource is started; false if a new process resource is not started (for example, if an existing process is reused)
   11: // Start the process resource by specifying the name of the document or application file, and associate the resource with the new Process component
   12: Process.Start ("iisreset");
   13:}


As above, it is easy to use programming to control the operation status of ISS service effectively.



<5> Application pool creation and control



An ISS application pool is a configuration that links one or more applications to one or more worker process collections. Because applications in an application pool are separated from other applications by worker process boundaries, applications in one application pool are not affected by the problems that are caused by applications in other application pools, and when we create a new application, sometimes we cannot clear the forecast of the client environment. To minimize the external factors that affect ISS Setup, we put the new virtual directory in a separate application pool.



When you create a virtual directory, you also create a program pool where you put the virtual directory:


1: /// <summary>
   2: /// Associate the corresponding application and virtual directory after the program pool is established
   3: /// </ summary>
   4: public static void SetAppToPool (string appname)
   5: {
   6: // Get directory
   7: DirectoryEntry getdir = new DirectoryEntry ("IIS: // localhost / W3SVC");
   8: foreach (DirectoryEntry getentity in getdir.Children)
   9:            {
  10: if (getentity.SchemaClassName.Equals ("IIsWebServer"))
  11: {
  12: // Set the application pool. Get the application first. Set the application pool.
  13: // Test the root directory for the first time
  14: foreach (DirectoryEntry getchild in getentity.Children)
  15: {
  16: if (getchild.SchemaClassName.Equals ("IIsWebVirtualDir"))
  17: {
  18: // Find the specified virtual directory.
  19: foreach (DirectoryEntry getsite in getchild.Children)
  20: {
  21: if (getsite.Name.Equals (appname))
  twenty two:                                {
  23: // [Test passed successfully]
  24: getsite.Properties ["AppPoolId"]. Value = appname;
  25: getsite.CommitChanges ();
  26:}
  27:}
  28:}
  29:}
  30:}
  31:}
  32:}


The idea is as follows: First obtain the ISS root directory namely iss://localhost/w3svc. Gets the node type by schemaClassName after success. Isswebserver Common directory Isswebvirturaldir virtual directory. Gets the name of the secondary application pool through the property parameter AppPoolId by obtaining the specified virtual directory through the name unique name of the virtual directory. Then commit the save.



In fact, through the application we can clearly see the relationship between the various directories in the ISS. The above is to modify one that has been stored in the application pool, how to create:


1: public static bool CreateAppPool (string metabasePath, string appPoolName, string Username, string Password)
   2:        {
   3: bool issucess = false;
   4: try
   5: {
   6: if (metabasePath.EndsWith ("/ W3SVC / AppPools"))
   7: {
   8: if (MyIISHelper.AppPoolExist (appPoolName))
   9:                    {
  10: // already exists delete this AppPool first
  11: //MessageBox.Show("The program pool currently named after the site name already exists! ");
  12: DeleteRepPool (appPoolName);
  13:}
  14:
  15: // Create a new program pool
  16: DirectoryEntry newpool;
  17: DirectoryEntry apppools = new DirectoryEntry (metabasePath);
  18: newpool = apppools.Children.Add (appPoolName, "IIsApplicationPool");
  19:
  20: // Set properties Access username and password Generally adopt the default method
  21: newpool.Properties ["WAMUserName"] [0] = Username;
  22: newpool.Properties ["WAMUserPass"] [0] = Password;
  23: newpool.Properties ["AppPoolIdentityType"] [0] = "3";
  24: newpool.CommitChanges ();
  25:}
  26: return issucess;
  27:}
  28: catch /// (Exception ex)
  29: {
  30: return false;
  31:}
  32:}


Basically the same as creating a directoryentity but note that the specified schome type is iisapplicationpool used to identify an application pool that was created. Of course, the creation can be deleted as follows:





 1:  DirectoryEntry appPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
   2:   foreach (DirectoryEntry getdir in appPool.Children)
   3:     {
   4:         if (getdir.Name.Equals(appname))
   5:            {
   6:              getdir.DeleteTree();//删除
   7:            }
   8:     }


About application Pools If you do not make any settings, they are added to Defaultpool in ISS, but sometimes the default program pool settings environment does not necessarily meet the current program requirements, such as the most common ones. NET version of the control. Where application settings for version 3.0 and 3.5 require re-registration of the 3.5. NET FrameWork. Some components this involves a. NET version issue.



<6>. NET version Issues



In the case of ISS control there are also a variety of problems, on the one hand because the Test XP 2003 system environment, need to control too much, of course, it is worth mentioning is about the entire application pool. NET version issue. Let's take a look at the multiple versions under ISS settings:






If our application uses version 3.0 or 3.5 then there is no corresponding in the application pool. NET version. When the application runs, it prompts an HTTP error 404.17 NotFound:






In fact, when the ISS is working on the. NET version of the application pool, net3.0\3.5 does not have a handler aspnet_isapi.dll, which is why we do not see the. net3.0\3.5 version when you specify the Web site framework for IIS. The most straightforward method of re-registering. NET 3.5 is hosted by. NET 2.0: At this point we need to execute a CMD command:






Switch the application pool. NET version from new to. NET 2.0. Also implement. NET 3.0/3.5 hosting.



<7> usage environment and test conditions



Both the application and the code are passed on Windows 7./xp2/windows Server 2003. The corresponding ISS version ranges from iss5.0/5.1 to ISS 6.0/7.0. Contains ISS7.0. Limited space, the actual operation of the ISS there are a lot of details of the problem can not be exhaustive, I just picked it I think the basis or several important issues focused on writing, in fact, there are many other factors on ISS, so for this aspect of control programming Can only compromise the purpose of choosing the effect you want to do. Don't Tantaiqiuquan. Because the process of controlling itself is a complex process. The customer environment is also not as unified.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.