Wednesday, July 16, 2014

ASP.NET Web.config File

ASP.Net Applications of XML have been integrated into such an extent that XML format for the exchange of data, it's also used to store configuration settings.
  1. A Web application can contain more than one Web.config file. The settings in a file apply to the directory in which it's located, and all child directories. Web.config files in child directories take precedence over the settings that are specified in parent directories.
  2. Web.config files are protected by IIS, so clients cannot get to them. If you try to retrieve an existing http://?????.com/Web.config file, you'll be presented with an "Access denied" error message.
  3. IIS monitors the Web.config files for changes and caches the contents for performance reasons. There's no need to restart the Web server after you modify a Web.config file.
Configuration settings for any of your ASP.NET Web applications can be stored in a simple text file. Presented in an easily understandable XML format, this file, called Web.config, can contain application-wide data such as database connection strings, custom error messages, and culture settings.

The Web.config is an XML file, it can consist of any valid XML tags, but the root element should always be <configuration>. Nested within this tag you can include various other tags to describe your settings. Since a Web.config file comes as a standard when you start to build a new Web application.
The default XML file generated by Visual Studio .NET:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation 
defaultLanguage="c#"
debug="true"
/>
<customErrors 
mode="RemoteOnly" 
/> 
<authentication mode="Windows" /> 
<authorization>
<allow users="*" />
</authorization>
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
<sessionState 
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false" 
timeout="20" 
/>
<globalization 
requestEncoding="utf-8" 
responseEncoding="utf-8" 
/>

</system.web>

</configuration>

The <configuration> tag has only one child tag, which we call section group, the <system.web> tag. A section group typically contains the setting sections, such as: compilation, customErrors, authentication, authorization, etc. The way this works is pretty straightforward: you simply include your settings in the appropriate setting sections. You want to use a different authentication mode for your Web application, you'd change that setting in the authentication section.

Apart from the standard system.web settings, you can define your own specific application settings, such as a database connection string, using the <appSettings> tag. Consequently, your most common Web.config outline would be:

<configuration>
<system.web>
<!— sections--> 
</system.web>
<appSettings>
<!— sections --> 
</appSettings >
</configuration>

Let's discuss the details of both section groups now.
The system.web Section Group
In this section group, you'll include configuration settings that, you'd have set up somewhere in the IIS administration console. At Microsoft's MSDN Library, you can find an overview of all the tags that the system.web section group understands, but, depending on the complexity of your site, you may not ever use even half of those options.

<authentication>
The authentication section controls the type of authentication used within your Web application, as contained in the attribute mode. You'll enter the value "None" if anyone may access your application. If authentication is required, you'll use "Windows", "Forms" or "Passport" to define the type of authentication. For example:

<authentication mode="Windows" />
<authorization>

To allow or deny access to your web application to certain users or roles, use <allow> or <deny> child tags.

<authorization>
<allow roles="Administrators,Users" />
<deny users="*" />
</authorization>

It's important to understand that ASP.NET's authorization module iterates through the sections, applying the first rule that corresponds to the current user. In this example, users carrying the role Administrators or Users will be allowed access, while all others (indicated by the * wildcard) will encounter the second rule and will subsequently be denied access.

<compilation>

Here, you can configure the compiler settings for ASP.NET. You can use loads of attributes here, of which the most common are debug and defaultLanguage. Set debug to "true" only if you want the browser to display debugging information. Since turning on this option reduces performance, you'd normally want to set it to "false". The defaultLanguage attribute tells ASP.NET which language compiler to use, since you could use either Visual Basic .NET or C# for instance. It has value vb by default.

<customErrors>

To provide your end users with custom, user-friendly error messages, you can set the mode attribute of this section to On. If you set it to RemoteOnly, custom errors will be shown only to remote clients, while local host users will see the ugly but useful ASP.NET errors -- clearly, this is helpful when debugging. Setting the mode attribute to Off will show ASP.NET errors to all users.

If you supply a relative (for instance, /error404.html) or absolute address (http://yourdomain.com/error404.html) in the defaultRedirect attribute, the application will be automatically redirected to this address in case of an error. Note that the relative address is relative to the location of the Web.config file, not the page in which the error takes place. In addition you can use <error> tags to provide a statusCode and a redirect attribute:

<customErrors mode="RemoteOnly" defaultRedirect="/error.html">
<error statusCode="403" redirect="/accessdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
</customErrors>

<globalization>

The globalization section is useful when you want to change the encoding or the culture of your application. Globalization is such an extensive subject that an entire article could be dedicated to the matter. In short, this section allows you to define which character set the server should use to send data to the client (for instance UTF-8, which is the default), and which settings the server should use to interpret and displaying culturally specific strings, such as numbers and dates.

<globalization requestEncoding="utf-8" responseEncoding="utf-8" 
culture="nl-NL" />

Encoding is done through the attributes requestEncoding and responseEncoding. The values should be equal in all one-server environments. In this example, the application culture is set to Dutch. If you don't supply a culture, the application will use the server's regional settings.

<httpRuntime>

You can use the httpRuntime section to configure a number of general runtime settings, two of which are particularly convenient.

<httpRuntime appRequestQueueLimit="100" executionTimeout="600" />

The first attribute specifies the number of requests the server may queue in memory at heavy-traffic times. In the example, if there are already 100 requests waiting to be processed, the next request will result in a 503 error ("Server too busy").

The executionTimeout attribute indicates the number of seconds for which ASP.NET may process a request before it's timed out.

<sessionState>

In this section of the Web.config file, we tell ASP.NET where to store the session state. The default is in the process self:

<sessionState mode="InProc" />

Session variables are very powerful, but they have a few downsides. Information is lost when the ASP.NET process crashes, and sessions are generally useless in the case of a Web farm (multiple Web servers). In that instance, a shared session server can solve your issues. It's beyond the scope of this article to expand on this topic, but it's worth a mention. More information on sessionState can be found in the MSDN Library online.

<trace>

Your application's trace log is located in the application root folder, under the name trace.axd. You can change the display of tracing information in the trace section.

The attributes you will look for initially are enabled: localOnly, and pageOutput.

<trace enabled="true" localOnly="true" pageOutput="false" />

Set localOnly to "false" to access the trace log from any client. If you set the value of pageOutput to "true", tracing information will be added to the bottom of each Web page.
The appSettings Section Group

Apart from the Website configuration settings I've been talking about in the preceding paragraphs, you'll know that a programmer frequently likes to use custom application-wide constants to store information over multiple pages. The most appealing example of such a custom constant is a database connection string, but you can probably think of dozens more from your own experience.

The common denominator of these constants is that you want to retrieve their values programmatically from your code. The Web.config file provides the possibility to do so, but as a security measure, these constants have to be included in the <appSettings> section group. Just like <system.web>, <appSettings> is a direct child tag of the Web.config's configuration root.

A typical custom section group would look something like this:

<appSettings>
<add key="sqlConn" value="Server=myPc;Database=Northwind" />
<add key="smtpServer" value="smtp.mydomain.com" />
</appSettings>

This example shows that keys and values can be included in the custom application settings via an <add> tag. The way to access such a value in any of your Web pages is illustrated below:

ConfigurationSettings.AppSettings("sqlConnection")
alternate


<configuration>
 <system.web>
  <!--  DYNAMIC DEBUG COMPILATION
          Set compilation debug="true" to enable ASPX debugging.  Otherwise, setting this value to
          false will improve runtime performance of this application.
          Set compilation debug="true" to insert debugging symbols (.pdb information)
          into the compiled page. Because this creates a larger file that executes
          more slowly, you should set this value to true only when debugging and to
          false at all other times. For more information, refer to the documentation about
          debugging ASP.NET files.
    -->
  <compilation defaultLanguage="c#" debug="true" />
  <!--  CUSTOM ERROR MESSAGES
          Set customErrors mode="On" or "RemoteOnly" to enable custom error messages, "Off" to disable.
          Add <error> tags for each of the errors you want to handle.
          "On" Always display custom (friendly) messages.
          "Off" Always display detailed ASP.NET error information.
          "RemoteOnly" Display custom (friendly) messages only to users not running
           on the local Web server. This setting is recommended for security purposes, so
           that you do not display application detail information to remote clients.
    -->
  <customErrors mode="RemoteOnly" />
  <!--  AUTHENTICATION
          This section sets the authentication policies of the application. Possible modes are "Windows",
          "Forms", "Passport" and "None"
          "None" No authentication is performed.
          "Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to
           its settings for the application. Anonymous access must be disabled in IIS.
          "Forms" You provide a custom form (Web page) for users to enter their credentials, and then
           you authenticate them in your application. A user credential token is stored in a cookie.
          "Passport" Authentication is performed via a centralized authentication service provided
           by Microsoft that offers a single logon and core profile services for member sites.
    -->
  <authentication mode="Windows" />
  <!--  AUTHORIZATION
          This section sets the authorization policies of the application. You can allow or deny access
          to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous
          (unauthenticated) users.
    -->
  <authorization>
   <allow users="*" /> <!-- Allow all users -->
   <!--  <allow     users="[comma separated list of users]"
                             roles="[comma separated list of roles]"/>
                  <deny      users="[comma separated list of users]"
                             roles="[comma separated list of roles]"/>
            -->
  </authorization>
  <!--  APPLICATION-LEVEL TRACE LOGGING
          Application-level tracing enables trace log output for every page within an application.
          Set trace enabled="true" to enable application trace logging.  If pageOutput="true", the
          trace information will be displayed at the bottom of each page.  Otherwise, you can view the
          application trace log by browsing the "trace.axd" page from your web application
          root.
    -->
  <trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
  <!--  SESSION STATE SETTINGS
          By default ASP.NET uses cookies to identify which requests belong to a particular session.
          If cookies are not available, a session can be tracked by adding a session identifier to the URL.
          To disable cookies, set sessionState cookieless="true".
    -->
  <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424"
            sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
           cookieless="false" timeout="20" />
  <!--  GLOBALIZATION
          This section sets the globalization settings of the application.
    -->
  <globalization requestEncoding="utf-8" responseEncoding="utf-8" />
  <!-- Disabling request validation for your application
   To disable request validation for your application, you must modify or create a Web.config file
   for your application and set the validateRequest attribute of the <PAGES /> section to false:
  <pages validateRequest="false" />
  -->
  <!-- HttpModule
 
   HttpModule Element:      
    <httpModules>
     <add type="classname,assemblyname" name="modulename"/>
     <remove name="modulename"/>
    <clear/>
    </httpModules>
   Example:
  <httpModules>
   <add type="Demos.Components.CSharpFriendsHttpModule,Demos" name="CSharpFriendsHttpModule" />
  </httpModules>
  -->
  <!-- HttpHander
   HttpHandler Element:
   <httpHandlers>
     <add verb="verb list"
       path="path/wildcard"
       type="type,assemblyname"
       validate="true|false"/>
     <remove verb="verb list"
       path="path/wildcard"/>
     <clear/>
   </httpHandlers>
   Example:
  <httpHandlers>
   <add verb="*" path="Salman/*.aspx" type="Demos.Components.MyHttpHandler,Demos" />
  </httpHandlers>
   -->
 </system.web>

</configuration>

Tuesday, July 15, 2014

Resize Image in C#

Step 1: Create a web page 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        div img { float: left; margin-bottom: 10px; }
        div span { float: left; font-size: 11px; font-family: Arial; padding-bottom: 20px; }
        .dv8 { float: left; width: 10px; padding: 20px; }
        .dv16 { float: left; width: 20px; padding: 20px; }
        .dv24 { float: left; width: 30px; padding: 20px; }
        .dv32 { float: left; width: 40px; padding: 20px; }
        .orig { border: 1px solid lightgray; padding: 2px; }
       
        .dvpart1 { float: left; padding-right: 50px; }
        .dvpart2 { float: left; }
        .dvpart2 .btn { float: left; font-size: 11px; font-family: Arial; }
        .clear { clear: both; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="dvpart1">
        <div class="dv8">
            <span>8*8</span>
            <asp:Image CssClass="orig" runat="server" ID="img8to8" />
            <asp:Image runat="server" ID="img16to8" />
            <asp:Image runat="server" ID="img24to8" />
            <asp:Image runat="server" ID="img32to8" />
        </div>
        <div class="dv16">
            <span>16*16</span>
            <asp:Image runat="server" ID="img8to16" />
            <asp:Image CssClass="orig" runat="server" ID="img16to16" />
            <asp:Image runat="server" ID="img24to16" />
            <asp:Image runat="server" ID="img32to16" />
        </div>
        <div class="dv24">
            <span>24*24</span>
            <asp:Image runat="server" ID="img8to24" />
            <asp:Image runat="server" ID="img16to24" />
            <asp:Image CssClass="orig" runat="server" ID="img24to24" />
            <asp:Image runat="server" ID="img32to24" />
        </div>
        <div class="dv32">
            <span>32*32</span>
            <asp:Image runat="server" ID="img8to32" />
            <asp:Image runat="server" ID="img16to32" />
            <asp:Image runat="server" ID="img24to32" />
            <asp:Image CssClass="orig" runat="server" ID="img32to32" />
        </div>
    </div>
    <div class="clear"></div>
    <div class="dvpart2">
        <div>
            <asp:Button CssClass="btn" Text="Upload and resize" runat="server" ID="btnResize" OnClick="btnResize_Click" />
            <asp:FileUpload CssClass="btn" runat="server" ID="updImage" />
        </div>
         <div class="clear"></div>
        <div class="dv8">
            <span>8*8</span>
            <asp:Image runat="server" ID="imgCustomTo8" />
        </div>
        <div class="dv16">
            <span>16*16</span>
            <asp:Image runat="server" ID="imgCustomTo16" />
        </div>
        <div class="dv24">
            <span>24*24</span>
            <asp:Image runat="server" ID="imgCustomTo24" />
        </div>
        <div class="dv32">
            <span>32*32</span>
            <asp:Image  runat="server" ID="imgCustomTo32" />
        </div>
    </div>
    </form>
</body>
</html>



Step 2: paste blow code in code behind 


/// <summary>
    /// Creates the thumbnail.
    /// </summary>
    /// <param name="maxWidth">The maximum width.</param>
    /// <param name="maxHeight">The maximum height.</param>
    /// <param name="path">The path.</param>
    /// <returns>The path of new resized image</returns>
    public string CreateThumbnail(int maxWidth, int maxHeight, string path)
    {

        var image = System.Drawing.Image.FromFile(path);
        var ratioX = (double)maxWidth / image.Width;
        var ratioY = (double)maxHeight / image.Height;
        var ratio = Math.Min(ratioX, ratioY);
        var newWidth = (int)(image.Width * ratio);
        var newHeight = (int)(image.Height * ratio);
        var newImage = new Bitmap(newWidth, newHeight);
        Graphics thumbGraph = Graphics.FromImage(newImage);

        thumbGraph.CompositingQuality = CompositingQuality.HighQuality;
        thumbGraph.SmoothingMode = SmoothingMode.HighQuality;
        //thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

        thumbGraph.DrawImage(image, 0, 0, newWidth, newHeight);
        image.Dispose();

        string fileRelativePath = "newsizeimages/" + maxWidth + Path.GetFileName(path);
        newImage.Save(Server.MapPath(fileRelativePath), newImage.RawFormat);
        return fileRelativePath;
    }

    /// <summary>
    /// Handles the Click event of the btnResize control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    protected void btnResize_Click(object sender, EventArgs e)
    {
        if (updImage.HasFile)
        {
            try
            {
                updImage.SaveAs(Server.MapPath("uploadedimage/" + updImage.FileName));
                imgCustomTo8.ImageUrl = CreateThumbnail(8, 8, Server.MapPath("uploadedimage/" + updImage.FileName));
                imgCustomTo16.ImageUrl = CreateThumbnail(16, 16, Server.MapPath("uploadedimage/" + updImage.FileName));
                imgCustomTo24.ImageUrl = CreateThumbnail(24, 24, Server.MapPath("uploadedimage/" + updImage.FileName));
                imgCustomTo32.ImageUrl = CreateThumbnail(32, 32, Server.MapPath("uploadedimage/" + updImage.FileName));
            }
            catch
            {

            }
        }
    }



3. Use blow namespace

using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;