Microsoft.Web.Administration (MWA) を使用した構成セクションへのアクセス

発行日 : 2007 年 11 月 23 日 (作業者 : saad(英語))
更新日 : 2008 年 2 月 26 日 (作業者 : saad(英語))

要約

この記事では、Microsoft.Web.Administration API を使用して、プログラムによって IIS 7.0 構成ファイル (applicationHost.config および web.config) の構成セクションにアクセスする方法について説明します。ここでは、ネストした要素やコレクションを含む複雑なセクションを扱います。例では、IIS_schema.xml ファイルに定義されている実際の IIS 7.0 構成セクションを使用します。この記事では、Microsoft.Web.Administration によって提供されている基本クラスを使用してこれらのセクションにアクセスおよび操作する一般的な方法について説明します。また、厳密に型指定されたクラスを使用してこれらのセクションを表す方法についても説明します。

はじめに

この記事では、Microsoft.Web.Administration API を使用して、プログラムによって IIS 7.0 構成セクションにアクセスする例を示します。ここでは、ネストした要素 (system.webServer/asp) やコレクション (system.webServer/security/isapiCgiRestriction) を含むセクションを扱います。最初に、Microsoft.Web.Administration によって提供される汎用基本クラスを使用してこれらのセクションを操作する方法を説明し、次に、これらのセクションを表す、厳密に型指定されたラッパー クラスの使用例を示します。

ネストした要素やコレクションを含むセクションのスキーマ

ネストした要素を含むセクション

ネストした要素を含むセクションの例として、system.webServer/asp セクションが挙げられます。そこでは、"session" 要素が "asp" セクション内に定義されています。このセクションのスキーマは次のとおりです。他にもスキーマ内のプロパティや入れ子になった要素がありますが、この例では示されていません。

<sectionSchema name="system.webServer/asp"> 
      <attribute name="appAllowClientDebug" type="bool" defaultValue="false" /> 
      <attribute name="appAllowDebugging" type="bool" defaultValue="false" /> 
      <!-- Omitted to simplify --> 
      <element name="session"> 
        <attribute name="allowSessionState" type="bool" defaultValue="true" /> 
        <attribute name="keepSessionIdSecure" type="bool" defaultValue="true" /> 
      </element> 
    </sectionSchema> 

コレクションを含むセクション

次に、キーでインデックス付けされた要素のコレクションを含むセクションの例として、system.webServer/security/isapiCgiRestriction セクションを取り上げます。このセクションのスキーマは次のとおりです。

    <sectionSchema name="system.webServer/security/isapiCgiRestriction"> 
      <collection addElement="add" clearElement="clear" removeElement="remove"> 
        <attribute name="path" type="string" expanded="true" required="true" isUniqueKey="true" validationType="nonEmptyString" /> 
          <attribute name="allowed" type="bool" required="true" defaultValue="false" /> 
          <attribute name="groupId" type="string" required="false" /> 
          <attribute name="description" type="string" /> 
      </collection> 
      <attribute name="notListedIsapisAllowed" type="bool" defaultValue="false" /> 
      <attribute name="notListedCgisAllowed" type="bool" defaultValue="false" /> 
    </sectionSchema> 

セクションへの一般的なアクセス

Microsoft.Web.Administration は、構成システムのさまざまなコンポーネントを表す汎用基本クラスをいくつか提供しています。

  • Configuration : 単一の構成ファイルを表します (applicationHost.config、またはサイトやアプリケーションの web.config ファイル)。
  • ConfigurationElement : 構成ファイル内の要素を表すために使用される汎用エンティティです。これは、構成セクション、コレクション エントリ、セクション内のネストした要素などの基本クラスです。
  • ConfigurationAttribute : ConfigurationElement 内のプロパティを表します。
  • ConfigurationSection : ConfigurationElement から派生し、IIS スキーマ ファイル内に定義されるセクションを表します。これを使って、セクションのさまざまなプロパティにアクセスします。
  • ConfigurationElementCollection : ConfigurationElement から構成されるコレクション クラスです。これも ConfigurationElement から派生します。

次の例は、system.webServer/asp セクション内のネストした要素にアクセスする方法を示しています。

    static void Main(string[] args) {  
    ServerManager serverManager = new ServerManager();  
    Configuration config = serverManager.GetApplicationHostConfiguration();  
          ConfigurationSection section = config.GetSection("system.webServer/asp");  
          ConfigurationElement element = section.GetChildElement("session"); 
  Console.Write("allowSessionState attribute value: ");  
          Console.WriteLine(element.GetAttributeValue("allowSessionState"));  
          Console.WriteLine("Set allowSessionState value to false"); 
  element.SetAttributeValue("allowSessionState", false); 
  Console.Write("allowSessionState attribute value: ");  
          Console.WriteLine(element.GetAttributeValue("allowSessionState"));  
  serverManager.CommitChanges();  
    } 

ServerManager クラスは、各種サーバー設定にアクセスするためのエントリ ポイントです。ここでは applicationHost.config ファイル内のプロパティを設定していますが、個々のサイトやアプリケーションの web.config ファイル内のこれらのプロパティにもアクセスしたり変更したりすることができます。CommitChanges 呼び出しによって、設定の変更を保存します。

次の例は、コレクションの要素全体を反復する方法、およびコレクションに要素を追加する方法を示しています。

    static void Main(string[] args) {         
          ServerManager serverManager = new ServerManager();     
  Configuration config = serverManager.GetApplicationHostConfiguration();         
ConfigurationSection section = 
      config.GetSection("system.webServer/security/isapiCgiRestriction");
    ConfigurationElementCollection collection = section.GetCollection(); 

      // Iterating through the elements in the collection foreach (ConfigurationElement element in collection) 
 { 
  Console.Write("Path: " + element.GetAttributeValue("path")); 
Console.WriteLine(" Allowed: " + element.GetAttributeValue("allowed")); 
        } 
       // Adding a new element to the collection        ConfigurationElement newElement = collection.CreateElement(); 
      newElement.SetAttributeValue("path", @"%SystemDir%\someDll.dll"); 
      newElement.SetAttributeValue("allowed", false); 
      collection.Add(newElement); 
      serverManager.CommitChanges();             
    } 

厳密に型指定されたクラスによるセクションへのアクセス

汎用基本クラスから派生した、厳密に型指定されたクラスを使用することで、プロパティへのアクセスをより簡単かつ直感的に行うことができます。これは特に、さまざまな操作で同じセクションに何回もアクセスする必要がある場合に役立ちます。また、これらのクラスを使用すると、コンパイル時にプロパティの型がチェックされます。さらには、GetChildElement や GetAttributeValue のような回りくどいメソッド呼び出しを回避することもできます。

次の例は、system.webServer/asp セクション、およびそのセクションの session 要素のラッパーを示しています。このスニペットには、このセクションのすべてのプロパティは含まれていません。

    public sealed class AspSection : ConfigurationSection { 
   private AspSession _session; 
    public AspSection() 
    { 
    } 

    public AspSession Session 
    {          
        get 
    { 
        if (_session == null) 
         {             
              _session = (AspSession)GetChildElement("session", 
typeof(AspSession)); 
         } 
       return _session; 
    }         
 }         
   } 

    public sealed class AspSession : ConfigurationElement { 
    public AspSession() 
    { 
    } 
     public bool AllowSessionState 
     { 
        get { 
       return (bool)base["allowSessionState"]; 
          } 
         set 
    { 
           base["allowSessionState"] = value; 
         } 
      } 
    } 

上記の例の GetChildElement 呼び出しは、構成要素内のネストした要素にアクセスするために使用されています (セクション、コレクション要素など)。base[...] の呼び出しは GetAttributeValue クラスと SetAttributeValue クラスをラップし、これらの属性の値を取得、および設定します。

次の例は、厳密な型指定の方法によって、ネストした要素のプロパティにアクセスする方法を示しています。

    static void Main(string[] args) { 
      ServerManager serverManager = new ServerManager(); 
      Configuration config = serverManager.GetApplicationHostConfiguration(); 
      AspSection section = (AspSection)config.GetSection("system.webServer/asp", 
        typeof(AspSection)); 
      Console.WriteLine(section.Session.AllowSessionState); 
      section.Session.AllowSessionState = false; 
      serverManager.CommitChanges(); 
    }         

config.GetSection の呼び出しに注目してください。セクションのパスと作成するセクションの型が指定されています。既定では、config.GetSection を呼び出すと、ConfigurationSection が作成されます。厳密に型指定されたラッパーのインスタンスを取得するため、型を渡す必要があります。

次に、コレクションを持つセクション用に、厳密に型指定されたクラスを作成する方法を示します。この例では、system.webServer/security/isapiCgiRestriction セクションを使用しています。このスニペットには、このセクションに存在するすべてのプロパティは含まれていません。

    public sealed class IsapiCgiRestrictionSection : ConfigurationSection {  
    private IsapiCgiRestrictionCollection _collection;             
    public IsapiCgiRestrictionSection() { 
      }         
    public IsapiCgiRestrictionCollection IsapiCgiRestrictions { 
        get { 
          if (_collection == null) { 
            _collection = 
              (IsapiCgiRestrictionCollection)GetCollection(typeof(IsapiCgiRestrictionCollection)); 
          } 
        return _collection; 
        } 
      } 
    }             

基本クラス (ConfigurationElement) の GetCollection メソッドを使用して、対象の要素の既定のコレクションにアクセスしています。

次の例は、コレクション自体、およびコレクション内の要素用の厳密に型指定されたクラスを示しています。

   public sealed class IsapiCgiRestrictionCollection : ConfigurationElementCollectionBase<IsapiCgiRestrictionElement> { 
   public IsapiCgiRestrictionCollection() {  
      } 
   public new IsapiCgiRestrictionElement this[string path] {  
        get { 
          for (int i = 0; i< Count; i++) { 
            IsapiCgiRestrictionElement restriction = base[i]; 
            if (String.Equals=(Environment.ExpandEnvironmentVariables(restriction.Path),  
              Environment.ExpandEnvironmentVariables(path), StringComparison.OrdinalIgnoreCase)) {  
              return restriction; 
            } 
          } 
        return null; 
      } 
    } 
    public IsapiCgiRestrictionElement Add(string path, bool allowed) { 
        IsapiCgiRestrictionElement element = CreateElement(); 
        element.Path = path; 
        element.Allowed = allowed; 
        return Add(element); 
    } 
    protected override IsapiCgiRestrictionElement CreateNewElement(string elementTagName) { 
        return new IsapiCgiRestrictionElement(); 
      } 
    } 
    public sealed class IsapiCgiRestrictionElement : ConfigurationElement { 
  public IsapiCgiRestrictionElement() { 
      } 
     public bool Allowed { 
      get { 
        return (bool)base["allowed"]; 
      } 
      set { 
        base["allowed"] = value; 
      } 
    }         
     public string Path { 
      get { 
        return (string)base["path"]; 
      } 
      set { 
        base["path"] = value; 
      } 
     } 
   }           

厳密に型指定されたコレクション クラスでは、コレクション キー (この例では path 属性) を使用してコレクションのインデックスを指定する機能がとても便利です。Add メソッドのパラメーターには、その要素で必要なプロパティを指定します。この例では、Add に path 属性のみを指定することもできます。その場合、allowed 属性は既定値になります。

次に、厳密に型指定されたクラスを使用してコレクションの全エントリを反復する例、およびコレクションに要素を追加する例を示します。

    static void Main(string[] args) { 
      ServerManager serverManager = new ServerManager();             
      Configuration config = serverManager.GetApplicationHostConfiguration(); 
      IsapiCgiRestrictionSection section =  
        (IsapiCgiRestrictionSection)config.GetSection("system.webServer/security/isapiCgiRestriction", typeof(IsapiCgiRestrictionSection));
      // Iterating through the elements in the collection 
      foreach (IsapiCgiRestrictionElement element in section.IsapiCgiRestrictions) { 
        Console.Write("Path: " + element.Path); 
        Console.WriteLine(" Allowed: " + element.Allowed); 
      } 
      // Adding a new element to the collection 
      section.IsapiCgiRestrictions.Add(@"%SystemDir%\someDll.dll", false); 
      serverManager.CommitChanges(); 
    }