Archives

Archives / 2006
  • Tool to generate strongly typed classes for configuration sections

    I wrote a simple tool to generate strongly typed classes for IIS configuration sections which can then be used with MWA to enable intellisense. This tool should be able to generate very logical intuitive type names in most cases. Generated code is similar to code samples in my earlier blog.

    Usage:
    genscode.exe <schemaFile> <optional section name>

    This tool dumps the code on the console. Redirect to save in a file.
    genscode.exe %windir%\system32\inetsrv\config\schema\IIS_Schema.xml system.webServer/httpCompression > HttpCompression.cs

    Omitting section name will make it generate classes for all sections defined in schema file.
    genscode.exe %windir%\system32\inetsrv\config\schema\IIS_Schema.xml > IISConfigSections.cs

    Compile the generated code to build a library.
    csc /t:library /r:Microsoft.Web.Administration.dll IISConfigSections.cs

    Add this library to your project references or just copy-paste the generated code in your code which is using MWA and start editing IIS sections without referring to schema. Here is how adding caching profiles will look like.

    using SystemwebServer;

    ServerManager
    sm = new ServerManager();

    CachingSection cs = (CachingSection)sm.GetApplicationHostConfiguration().GetSection(
        CachingSection.SectionName,
        typeof(CachingSection));
    cs.Profiles.Add(
        ".htm",
        EnumProfilesPolicy.CacheForTimePeriod,
        EnumProfilesKernelCachePolicy.CacheForTimePeriod,
        new TimeSpan(1000),
        EnumProfilesLocation.Downstream,
        "HEADER",
        "QUERYSTRING");

    ProfilesCollection profiles = cs.Profiles;
    ProfilesCollectionElement aspProfile = profiles.CreateElement();
    aspProfile.Extension = ".asp";
    aspProfile.Policy = EnumProfilesPolicy.CacheUntilChange;
    profiles.Add(aspProfile);

    sm.CommitChanges();

    Attached: GenSCodeInstall.zip (containing installer GenSCodeInstall.exe which will install genscode.exe and configschema.dll).

    View the original post

  • MWA and intellisense for configuration sections

    Microsoft.Web.Administration (MWA) returns generic ConfigurationSection, ConfigurationElementCollection, ConfigurationElement classes for dealing with different configuration sections. Using these classes directly requires you to remember attribute/collection/element names which needs to be passed to GetAttribute(), GetCollection(), GetChildElement(). MWA allows you to define your Section/Collection/Element types which can then be passed to GetSection, GetCollection, GetChildElement to get an instance of strongly typed class which makes dealing with sections very easy. Jan’s article on extending IIS7 schema talks about writing a strongly typed class to enable intellisense for simple sections.

    If the section contains a collection (or an element with one collection), you can define additional type which derives from ConfigurationElementCollectionBase and then use this type in call to GetCollection(). This class should implement Add(), Remove(), CreateNewElement(), this[keys] for handling elements specific to this collection.

    Taking example of system.webServer/httpErrors section, code for dealing with errors collection will look like this.

    public class HttpErrorsCollection : ConfigurationElementCollectionBase<HttpErrorsCollectionElement>
    {
        public HttpErrorsCollectionElement this[uint statusCode, int subStatusCode]
        {
            get
            {
                for (int i = 0; i < Count; i++)
                {
                    HttpErrorsCollectionElement element = base[i];
                    if ((element.StatusCode == statusCode) && (element.SubStatusCode == subStatusCode))
                    {
                        return element; 
                   
    }
                }

                return null;
            }
        }

        public HttpErrorsCollectionElement Add(
            uint statusCode,
            int subStatusCode,
            string prefixLanguageFilePath,
            string path,
            EnumHttpErrorsResponseMode responseMode)
        {
            HttpErrorsCollectionElement element = CreateElement();

            element.StatusCode = statusCode;
            element.SubStatusCode = subStatusCode;
            element.PrefixLanguageFilePath = prefixLanguageFilePath;
            element.Path = path;
            element.ResponseMode = responseMode;

            return Add(element);
        }

        protected override HttpErrorsCollectionElement CreateNewElement(string elementTagName)
        {
            return new HttpErrorsCollectionElement();
        }

       
    public void Remove(uint statusCode, int subStatusCode)
        {
            Remove(this[statusCode, subStatusCode]);
        }
    }

    public class HttpErrorsCollectionElement : ConfigurationElement
    {
        public uint StatusCode
        {
            get { return (uint)base["statusCode"]; }
            set { base["statusCode"] = (uint)value; }
        }

        public int SubStatusCode
        {
            get { return (int)base["subStatusCode"]; }
            set { base["subStatusCode"] = (int)value; }
        }

        public string PrefixLanguageFilePath
        {
            get { return (string)base["prefixLanguageFilePath"]; }
            set { base["prefixLanguageFilePath"] = (string)value; }
        }

        public string Path
        {
            get { return (string)base["path"]; }
            set { base["path"] = (string)value; }
        }

        public EnumHttpErrorsResponseMode ResponseMode
        {
            get { return (EnumHttpErrorsResponseMode)base["responseMode"]; }
            set { base["responseMode"] = (int)value; }
        }
    }

    public enum EnumHttpErrorsErrorMode
    {
        DetailedLocalOnly = 0,
        Custom = 1,
        Detailed = 2
    }

    public
    class HttpErrorsSection : ConfigurationSection
    {
        public static string SectionName = "system.webServer/httpErrors";
        public HttpErrorsCollection Errors
        {
            get { return (HttpErrorsCollection)GetCollection("error", typeof(HttpErrorsCollection)); }
        }
    }

    If the section/element schema has an <element> tag, you can define a type deriving from ConfigurationElement and then pass the type in GetChildElement. Taking example of request filtering section, code to handle requestLimits element will look like this. public class RequestFilteringSection : ConfigurationSection{
        public static string SectionName = "system.webServer/security/requestFiltering";

        public RequestLimitsElement RequestLimits
        {
            get { return (RequestLimitsElement)GetChildElement("requestLimits", typeof(RequestLimitsElement)); }
        }
    }

    Declaration of RequestLimitsElement looks similar to collection element class as in HttpErrorsCollectionElement.

    public
    class RequestLimitsElement : ConfigurationElement
    {
        public uint MaxAllowedContentLength
        {
            get { return (uint)base["maxAllowedContentLength"]; }
            set { base["maxAllowedContentLength"] = (uint)value; }
        }

        public uint MaxUrl
        {
            get { return (uint)base["maxUrl"]; }
            set { base["maxUrl"] = (uint)value; }
        }

        public uint MaxQueryString
        {
            get { return (uint)base["maxQueryString"]; } 
           
    set { base["maxQueryString"] = (uint)value; }
        }

        //
        // This element can further have collections.
        // HeaderLimitsCollection will look similar to
        // HttpErrorsCollection.
        //
        public HeaderLimitsCollection HeaderLimits
        {
            get { return (HeaderLimitsCollection)GetCollection("headerLimits", typeof(HeaderLimitsCollection)); }
        }
    }

    Checkout the tool to generate this code from schema definition here.

    View the original post

  • Response caching in IIS7

    Output cache module populates the IHttpCachePolicy intrinsic in BeginRequest stage if a matching profile is found. Other modules can still change cache policy for the current request which might change user-mode or kernel mode caching behavior. Output cache caches 200 responses to GET requests only. If some module already flushed the response by the time request reaches UpdateRequestCache stage or if headers are suppressed, response is not cached in output cache module. Output cache module only caches the response if some other module hasn't already cached it indicated by IHttpCachePolicy::SetIsCached. Also caching happens only for frequently hit content. Definition of frequently hit content is controlled by frequentHitThreshold and frequentHitTimePeriod properties defined in system.webServer/serverRuntime section. Default values define frequently hit content as ones which are requested twice in 10 seconds.

  • Feature delegation of custom module in UI

    I was at TechEd developers last week and one question that came up was what it takes for custom modules to show up in "Features Delegation" UI. I had image copyright walkthrough setup on the machine and in spite of having the custom schema xml and <section> entry in applicationHost.config, imageCopyright was not shown in "Features Delegation" UI. I did some more investigations on it and following is what it takes for UI to offer delegation to a custom module.

  • Sample forms authentication test in C#

    This sample test is doing the following:
    1. Sending request to a page which requires forms authentication. This results in 302 to login page.
    2. Send request to login page.
    3. Parse response from 2 and create response entity containing username/password to be used in next post request to login page.
    4. Do a POST to login page. If successful this should return a 302 with Set-Cookie and location header.
    5. Send request to location pointed to in last response (this is original page we requested in 1) with request cookie as returned in 4. Read more ...

    View the original post

  • Execution order of modules in IIS7

    Each request received by IIS 7.0 goes through multiple stages in the IIS request pipeline (read more about request pipeline here). In IIS, request processing move from one stage to the next stage in a fixed sequence. If any of the modules in system.webServer/modules section have subscribed to the event for the current stage then IIS calls each of those modules one by one before moving on to next stage. If there are multiple modules which subscribe to the same event (say RQ_BEGIN_REQUEST), module with higher priority is called first. Native modules can set execution priority for itself in RegisterModule using SetPriorityForRequestNotification. The following code snippet illustrates this for RQ_BEGIN_REQUEST. Read more ...

  • Changes to compression in IIS7

    Compression module provides IIS the capability to serve compressed responses to compression enabled clients. Clients which can accept compressed responses send Accept-Encoding header indicating compression schemes they can handle. If IIS can compress the response using a compression scheme which client can understand, IIS will send a compressed response with Content-Encoding response header indicating the scheme which was used to compress the response. Read more ...