useful web config code asp.net

Task: Some useful web.config code. eg. URL Rewriting/ Remove Etag / Remove Server Header/ Enable Gzip and few more..


Description: Some Useful web-config code which used for URL Rewriting and do many more things.

1) Define database connection in web.config. the connectionStrings tag should be in <configuration> tag.
<connectionStrings>
<add name="ConnectNEw" connectionString="Data Source=APC\SQLEXPRESS;Initial Catalog=database_db;user id=user_8; pwd=Pass@L#7Mad87" providerName="System.Data.SqlClient"/>
</connectionStrings>


2) Define Execution timeout and max request length using <httpRuntime> tag. it should be in <system.web> tag. Here we can also define the session mode and its timeout value.
<system.web>
<httpRuntime enableVersionHeader="false"  executionTimeout="2400" maxRequestLength="20480" />
<sessionState mode="InProc" cookieless="false" timeout="80"></sessionState>
</system.web>



3) Etag and Server Header and other Redirect rule (Default page redirect, www redirect , https redirect)
<system.webServer>
    <rewrite>
      <outboundRules>
        <rule name="Remove ETag" >
          <match serverVariable="RESPONSE_ETag" pattern=".+" />
          <action type="Rewrite" value="" />
        </rule>
        <rule name="Remove Server header">
          <match serverVariable="RESPONSE_Server" pattern=".+" />
          <action type="Rewrite" value="" />
        </rule>
      </outboundRules>
      <rules>


 <!--<Redirect Without www to www> -->
        <rule name="Redirect to www" stopProcessing="true">
          <match url=".*" />
          <conditions trackAllCaptures="false">
            <add input="{HTTP_HOST}" pattern="^hemantrautela.blogspot.com$" />
          </conditions>
 <action type="Redirect" url="https://www.hemantrautela.blogspot.com/{R:0}" redirectType="Permanent"/>
        </rule>

 <!--<Redirect default.aspx to domain name> -->
        <rule name="default.aspx Redirect" stopProcessing="true">
          <match url="^(.*\/)*default\.aspx$"/>
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_METHOD}" negate="true" pattern="^POST$"/>
          </conditions>
          <action type="Redirect" url="{R:1}" redirectType="Permanent"/>
        </rule>

<!--<Redirect http to https - Non Secure to Secure page> -->
        <rule name="Redirect to https" stopProcessing="true" enabled="true">
          <match url="(.*)" />
          <conditions>
            <add input="{HTTPS}" pattern="off" ignoreCase="true" />
          </conditions>
          <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>



4)Add MIME type (A List for various mime type : https://www.sitepoint.com/web-foundations/mime-types-complete-list/)
<system.webServer>
 <staticContent>
     <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00"/>
      <remove fileExtension=".kml" />
      <mimeMap fileExtension=".kml" mimeType="application/vnd.google-earth.kml+xml" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".eot" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
    </staticContent>
</system.webServer>



5) Security Headers - X-Content-Type: nosniff & Other

<system.webServer>
<httpProtocol>
      <customHeaders>
        <remove name="Vary"></remove>
        <add name="Vary" value="Accept-Encoding"></add>
          <remove name="X-Powered-By"></remove>
          <add name="X-Frame-Options" value="SAMEORIGIN"></add>
          <add name="X-XSS-Protection" value="1; mode=block"></add>
          <add name="X-Content-Type-Options" value="nosniff "></add>
      </customHeaders>
    </httpProtocol>
</system.webServer>
 



6) Gzip Compression

<system.webServer>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
      <dynamicTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
      </dynamicTypes>
      <staticTypes>
        <add mimeType="text/*" enabled="true"/>
        <add mimeType="message/*" enabled="true"/>
        <add mimeType="application/javascript" enabled="true"/>
        <add mimeType="*/*" enabled="false"/>
      </staticTypes>
    </httpCompression>

    <urlCompression doStaticCompression="true" doDynamicCompression="true"/>
</system.webServer>




Combine ScriptResource ajaxcontroltoolkit script

Task: Combine the AjaxControlToolkit Script.

Description: Combine the AjaxControlToolkit Script. As we can see when we use AjaxControl on our webpage it load with several javascript resources (ScriptResource.axd). For SEO purpose we need to minimize the several request. So that we can combine these script in a single request.

First we need to know which script's are required for our webpage. for that we need to use ScriptReferenceProfiler (it is available in codeplex). So download it from codeplex and stored the dll in our 'Bin' Folder. And Use below code to find the several request.



<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="c1" %>
<%@ Register Assembly="ScriptReferenceProfiler" Namespace="ScriptReferenceProfiler"    TagPrefix="srp" %>

<html>
<head runat="server"></head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm1" runat="server">
</asp:ScriptManager>
<srp:ScriptReferenceProfiler ID="ScriptReferenceProfiler1" runat="server" />
<%-- Below will be all controls with ajax controls whatever.. --%>
</form>
</body>
</html>

Result (On Browser):


11 references found on this page:
        <asp:ScriptReference name="MicrosoftAjax.js"/>
        <asp:ScriptReference name="MicrosoftAjaxWebForms.js"/>
        <asp:ScriptReference name="AjaxControlToolkit.Compat.Timer.Timer.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.Compat.DragDrop.DragDropScripts.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.DragPanel.FloatingBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.RoundedCorners.RoundedCornersBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
        <asp:ScriptReference name="AjaxControlToolkit.DropShadow.DropShadowBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>

        <asp:ScriptReference name="AjaxControlToolkit.ModalPopup.ModalPopupBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>



Now we can combine the several Script request to one. For that we have to just copy the all found reference & use as below code .




<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="c1" %>

<html>
<head runat="server"></head>
<body>

<form id="form1" runat="server">

<asp:ScriptManager ID="sm1" runat="server">
<CompositeScript>
<Scripts>
      <asp:ScriptReference name="MicrosoftAjax.js"/>
      <asp:ScriptReference name="MicrosoftAjaxWebForms.js"/>
      <asp:ScriptReference name="AjaxControlToolkit.Compat.Timer.Timer.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.Common.Common.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.Compat.DragDrop.DragDropScripts.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.ExtenderBase.BaseScripts.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.DragPanel.FloatingBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.DynamicPopulate.DynamicPopulateBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.RoundedCorners.RoundedCornersBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.DropShadow.DropShadowBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
      <asp:ScriptReference name="AjaxControlToolkit.ModalPopup.ModalPopupBehavior.js" assembly="AjaxControlToolkit, Version=3.0.30930.28736, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e"/>
</Scripts>
</CompositeScript>
</asp:ScriptManager>
<%-- Below will be all controls with ajax controls whatever.. --%>
</form>
</body>
</html>


Now we can see in our browser the several ScriptResource combined in one request.

Create automated sitemap using asp.net

Task: Create automated sitemap dynamically using asp.net generic web handler.

Description: In E-Commerce website or blog we need to update sitemap regularly, instead of generating sitemap using third-party tool, we can generate sitemap dynamically using asp.net. Using "ashx" generic handler we can generate xml sitemap & using url rewriting we can rewrite "sitemap.ashx" for "sitemap.xml" request.


<%@ WebHandler Language="C#" Class="sitemap" %>

using System;
using System.Web;
using System.Text;
using System.Data;

public class sitemap : IHttpHandler {

    string currentTime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");
    public void ProcessRequest (HttpContext context) {

        context.Response.ContentType = "text/xml";
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        context.Response.Cache.SetAllowResponseInBrowserHistory(true);
        context.Response.Charset = "UTF-8";
        context.Response.Write("<?xml version='1.0' encoding='UTF-8'?><urlset xmlns='http://www.sitemaps.org/schemas/sitemap/0.9'>");
        context.Response.Write(sitemap());
        context.Response.Write("</urlset>");
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
    public string sitemap()
    {
        string weburl = "http://hemantrautela.blogspot.com/";
        System.Text.StringBuilder sitemap = new System.Text.StringBuilder();
        sitemap.Append(@"<url>
        <loc>" + weburl + @"</loc>
        <lastmod>"+currentTime+@"</lastmod>
        <priority>1.00</priority>
        </url>");
        // Append more url in your sitemap here using database
        return sitemap.ToString();
    }