Вы находитесь на странице: 1из 51

What is Globalization and Localization in

ASP.Net

Globalization is the process of designing the application in such a way that it can be used by users
from across the globe (multiple cultures).

Localization, on the other hand, is the process of customization to make our application behave as per
the current culture and locale. These two things go together.

To do globalization we need to use Resource Files.

Let's Start

To add Resource Files to our project:

1. Right-click on the Root Folder Add New Item.


2. Select Resource File from the above Templates.
3. Name it "Resource.resx"
4. You need other Resource Files for storing data depending on the Culture
5. Add another file with the following names of each resource, such as "Resource.en-GB.resx"
else you can give a different name but after the (Dot ) because they are sub-files of
"Resource.resx".

o For English you can add "Resource.en-GB.resx"


o For Marathi you can add "Resource.mr-IN.resx"
o For Hindi you can add "Resource.hi-IN.resx"
o For Arabic you can add "Resource.ar-SA.resx"
1. Let us add some data in these files; open "Resource.resx"

Add a name under the "Resource.resx" Filename Column and keep the Value column blank as in the
following:
Save And Close Resource.resx

2. Open "Resource.en-GB.resx"

 Add a name under the "Resource.en-GB.resx" Filename and the value that you want to display
in the value field.
3. Open Resource.hi-IN.resx

 Add a name under the "Resource.hi-IN.resx" Filename and the Value that you want to display
in the value field.

4. Open "Resource.mr-IN.resx"
 Add a name under the "Resource.mr-IN.resx" Filename and the Value that you want to display
in the value field.

5. Open "Resource.ar-SA.resx"

 Add a name under the "Resource.ar-SA.resx" Filename and the Value that you want to display
in the value field.
 Add a new page and name it "LocalPage.aspx"
 Add a DropDownList in the "LocalPage.aspx"

On LocalPage.aspx

<asp:DropDownList ID="DrpLanguages" AutoPostBack="true"


runat="server" Width="200px"
OnSelectedIndexChanged="DrpLanguages_SelectedIndexChanged">
<asp:ListItem Text="Select Languages" Value="0"></asp:ListItem>
<asp:ListItem Text="English" Value="en-GB"></asp:ListItem>
<asp:ListItem Text="Hindi" Value="hi-IN"></asp:ListItem>
<asp:ListItem Text="arabic" Value="ar-SA"></asp:ListItem>
</asp:DropDownList>

LocalPage.aspx.cs

protected void DrpLanguages_SelectedIndexChanged(object sender,EventArgs e)


{
Session["Culture"] = DrpLanguages.SelectedValue;
Response.Redirect("Runpage.aspx");
}

 Add another page name ("Runpage.aspx")


 Add a Label to this "Runpage.aspx"
Add two Labels

For accessing the resource file you need to add syntax like this:

Text="<%$Resources:Resource,AccCode%>"
"<%$Resources:Your Main Resource file Name, Add Name Of Resource field which you want to
display %>"
<asp:Label ID="lblresdisplay" Font-
Size="Large" runat="server" Text="<%$Resources:Resource,AccCode%>"></asp:Label>

<asp:Label ID="Label1" Font-


Size="Large" runat="server" Text="<%$Resources:Resource,AccCode%>"></asp:Label>

To accomplish this, what we need to do is to override the InitializeCulture function and set the
UICulture to the user selected language.

Runpage.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Globalization;
using System.Threading;

public partial class Runpage : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

protected override void InitializeCulture()


{
base.InitializeCulture();
System.Threading.Thread.CurrentThread.CurrentCulture
= new System.Globalization.CultureInfo(Session["Culture"].ToString());
System.Threading.Thread.CurrentThread.CurrentUICulture
= newSystem.Globalization.CultureInfo(Session["Culture"].ToString());

}
}

Final Output
Globalization and Localization in C#

Globalization is the process of designing and developing applications that function for
multiple cultures.

Localization is the process of customizing your application for a given culture and locale.

Cultures and Locales

The language needs to be associated with the particular region where it is spoken, and
this is done by using locale (language + location). For example: fr is the code for French
language. fr-FR means French language in France. So, fr specifies only the language
whereas fr-FR is the locale. Similarly, fr-CA defines another locale implying French
language and culture in Canada. If we use only fr, it implies a neutral culture (i.e.,
location neutral).

Set culture information

Application level -In web.config file


<configuration>
<system.web>
<globalization culture="fr-FR" uiCulture="fr-FR"/>
</system.web>
</configuration>

Resource Files

1. A resource file is an XML file that contains the strings that you want to translate
into different languages or paths to images.
2. The resource file contains key/value pairs. Each pair is an individual resource. Key
names are not case sensitive.

e.g. A resource file might contain a resource with the key Button1 and the value Submit
Resource files in ASP. NET have an .resx extension. At run time, the .resx file is compiled
into an assembly.

Global Resource Files

1. You create a global resource file by putting it in the reserved folder


App_GlobalResources at the root of the application.
2. Any .resx file that is in the App_GlobalResources folder has global scope.
Local Resource Files

A local resources file is one that applies to only one ASP. NET page or user control (an
ASP. NET file that has a file-name extension of .aspx, .ascx, or .master).

Implicit Localization with Local Resources

1. If you have created local resource files for a specific page, you can use implicit
localization to fill the property values for a control from the resource file. In
implicit localization, ASP.NET reads a resource file and matches resources to
property values.
2. To use implicit localization, you must use a naming convention for resources in
the local resource file that uses the pattern: meta:resourcekey

Explicit Localization

1. Alternatively, you can use explicit localization, where you use a resource
expression. Unlike implicit localization, you must use a resource expression for
each property that you want to set.
<asp:Button ID="Button1" runat="server" Text="Button" Text="<%$Reso
urces:WebResources, Button1Caption %>" />

Localizing Static Text

1. If a page includes static text, you can use ASP.NET localization by including it in a
Localize control, and then using explicit localization to set the static text. The
Localize control renders no markup; its only function is to act as a placeholder for
localized text.
2. The Localize control can be edited in Design view, not only in the property grid.
At run time, ASP.NET treats the Localize controlas a Literal control.

<asp:Localize ID="l1" runat="server" Text="Welcome!" meta:resourcekey="button1


" />

Get Resource value programmetically

Label3.Text = Resources.Resource.b1;
Label3.Text = GetLocalResourceObject("Button1.Text").ToString();
Label3.Text = GetGlobalResourceObject("resource", "color");

Example

Create a Multi-Lingual Site with Localization

Web page

Step 1 Drag a button and Label


Step 2 Right click on web site- Add ASP.NET Folder - Add App_Local Resource -Select -
Step 3 Right click on Add New item - Resource File - Name (Default.aspx.resx)- Name
(Button1.Text)- Ok / Label1.Text-English-Copy the RESX file and Paste it
Step 4 Rename it - (Deafult.aspx.fr.resx)- edit it..(Button1.Text)- Namaste /
Label1.Text- French.

.aspx page

<asp:Button meta:resourcekey="button1" />


<asp:Label meta:resourcekey="label1" />

Header

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" Culture="A


uto:en-US" UICulture="Auto" %>
Next.. Right cilck on web site- Add ASP.NET Folder - Add App_GlobalResources - Add
Resource - Name and Value
copy and paste and rename (Resource.fr.resx)-

Now drag a new label :- label id(name)-renamecopypaste- expression - text - expression


type=resource- expression property=class key=resource
Resource key-welcome

FOR LANG TRANSLATION

http://code.google.com/intl/fr/apis/language/transliterate/v1/getting_started.html

ASP.Net Multilingual website: Support and display Multiple


Languages (English French) in ASP.Net

Here has explained with an example, how to create a multilingual website in


ASP.Net using Globalization and Localization i.e. a website that supports and
displays multiple languages such as English and French in ASP.Net using C#
and VB.Net.
In this article I will explain with an example, how to create a multilingual website in ASP.Net
using Globalization and Localization i.e. a website that supports and displays multiple languages such as
English and French in ASP.Net using C# and VB.Net.

What is Globalization and Localization?

Globalization is a process of designing applications intended for users of different languages across the Globe
while Localization is a process of designing the application so that it can display contents in the language of the
user.

What is Language and Locale?

Language means the broader category of spoken languages i.e. English, French, etc. Now English is spoken in
United Kingdom as well as United States but these both countries have their own vocabulary of English
language which is known as Locale.

The Culture name for United Kingdom English is en-GB while for United States is en-US.
ASP.Net Global and Local Resources

ASP.Net has two set of Resource files i.e. Global and Local Resource files.

Global Resources

These resource files can be accessed on all pages throughout the applications.

Local Resources

These resource files are unique to each page and can be used only on that particular page.

You can read more about the Global and Local resource files in this MSDN article.

Building a Multilingual ASP.Net website

Let’s start working in building the multilingual application in ASP.Net. This article will explain how to develop
a multilingual application using Global Resources.

Adding a Global Resource file

The very first thing is to add two Global Resource files one for English and one for French with the following
names.

English - Resource.resx

French – Resource.fr.resx

As soon as you add the first Resource file you will get the following prompt from Visual Studio asking to create
a folder named App_GlobalResources. You need to click Yes.
Once both the Resource files are added, the App_GlobalResources folder in the Solution Explorer should look
as shown below.

Next you will need to add sets of Name and Values to the Resource files of both English and French.

English Resource file

French Resource file

Master Page

Now add a Master Page to your project and add a DropDownList above the ContentPlaceHolder with two items
with Language name in the Text part and the Language Culture name in the value part.

This DropDownList will be used to switch between the English and French languages.

Language:
<asp:DropDownList ID="ddlLanguages" runat="server" AutoPostBack="true">
<asp:ListItem Text="English" Value="en-us" />
<asp:ListItem Text="French" Value="fr" />
</asp:DropDownList>
<hr />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>

You will need to import the following Namespace in the Master Page.

C#

using System.Globalization;

VB.Net

Imports System.Globalization

Inside the Page Load event of the Master Page, the Language DropDownList’s selected item is set based on the
name of the Current Culture.

C#

protected void Page_Load(object sender, EventArgs e)


{
if (!this.IsPostBack)
{
if (ddlLanguages.Items.FindByValue(CultureInfo.CurrentCulture.Name) != null)
{
ddlLanguages.Items.FindByValue(CultureInfo.CurrentCulture.Name).Select
ed = true;
}
}
}

VB.Net

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load


If Not Me.IsPostBack Then
If ddlLanguages.Items.FindByValue(CultureInfo.CurrentCulture.Name) IsNot Noth
ing Then
ddlLanguages.Items.FindByValue(CultureInfo.CurrentCulture.Name).Select
ed = True
End If
End If
End Sub
Base Class

Now add a new Class named BasePage to the project which will be inherited by all pages in the project.

As soon as you add the Class file you will get the following prompt from Visual Studio asking to create a folder
named App_Code. You need to click Yes.

The BasePage class will be inherited by all the pages in the application and hence it inherits the
ASP.Net Page class.

The BasePage class overrides the InitializeCulture event of the page and inside the event handler, first the
User’s default language is detected and if the language is not selected using from the DropDownList then the
default Language is set as Current Culture.

If the language is selected using the Language DropDownList then the Current Culture is set using the selected
value of the DropDownList which is fetched from theRequest.Form collection.

C#

using System.Threading;
using System.Globalization;

///<summary>
/// Summary description for BasePage
///</summary>
public class BasePage : System.Web.UI.Page
{
protected override void InitializeCulture()
{
string language = "en-us";

//Detect User's Language.


if (Request.UserLanguages != null)
{
//Set the Language.
language = Request.UserLanguages[0];
}

//Check if PostBack is caused by Language DropDownList.


if (Request.Form["__EVENTTARGET"] != null && Request.Form["__EVENTTARGET"
].Contains("ddlLanguages"))
{
//Set the Language.
language = Request.Form[Request.Form["__EVENTTARGET"]];
}

//Set the Culture.


Thread.CurrentThread.CurrentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(language);
}
}

VB.Net

Imports System.Threading
Imports System.Globalization

Public Class BasePage


Inherits System.Web.UI.Page
Protected Overrides Sub InitializeCulture()
Dim language As String = "en-us"

'Detect User's Language.


If Request.UserLanguages IsNot Nothing Then
'Set the Language.
language = Request.UserLanguages(0)
End If
'Check if PostBack is caused by Language DropDownList.
If Request.Form("__EVENTTARGET") IsNot Nothing AndAlso Request.Form("__EVENT
TARGET").Contains("ddlLanguages") Then
'Set the Language.
language = Request.Form(Request.Form("__EVENTTARGET"))
End If

'Set the Culture.


Thread.CurrentThread.CurrentCulture = New CultureInfo(language)
Thread.CurrentThread.CurrentUICulture = New CultureInfo(language)
End Sub
End Class

Inheriting the BasePage class in the ASP.Net Page

Once the BasePage class is created, the next step is to inherit the BasePage class in the ASP.Net page.

C#

public partial class _Default : BasePage


{
protected void Page_Load(object sender, EventArgs e)
{

}
}

VB.Net

Partial Class _Default


Inherits BasePage

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load

End Sub
End Class

Displaying content using Resource files

The following HTML Markup consists of an ASP.Net Label control and an HTML SPAN element. The
ASP.Net Label has been assigned the Greetings Resource while the HTML SPAN element has been assigned
the Introduction Resource.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<asp:Label ID="Label1" Text="<%$Resources:Resource, Greetings %>" runat="server" Font-
Bold="true" />
<br />
<br />
<span><%=Resources.Resource.Introduction %></span>
</asp:Content>

Below are the syntaxes for assigning Resource file to an ASP.Net Control and an HTML element.

ASP.Net Control

<asp:Label ID="Label1" Text="<%$Resources:Resource, <Resource Name> %>" runat="server" Fo


nt-Bold="true" />

HTML SPAN

<span><%=Resources.Resource.<Resource Name> %></span>

Multilingual ASP.Net website in action

The Multilingual ASP.Net website is now ready and we will now test it to make sure it works in the following
two cases

1. Loading the Default User Language from Browser

In order to test whether the Multilingual ASP.Net website detects and loads the default user language, you will
need open Internet Options window from the Tools menu of the Internet Explorer browser and then click
on Languages button and finally add and make French language as default.
Now run the website and it will display the contents in French Language and also the DropDownList will
display the French Language as selected.

2. Switching between the Languages using DropDownList

When a language is selected from the DropDownList, the content is displayed for the selected language.
Web User Control in ASP.NET

In this blog you will learn how to create a Web user control in asp.net4.

Step 1: Open visual studio

Take new web applicarion

Step 2: Add Web user control


Step 3: Add control

webusercontrol1.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs"


Inherits="article.WebUserControl1" %>
<asp:TextBox ID="txtvalue" runat="server"></asp:TextBox>
<asp:Button ID="btnClick" runat="server" OnClick="btnClick_Event" Text="Click" />

Step 4: Create an event,

webusercontrol1.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace article
{
public delegate void click(String str);
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public event click clickEvent;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Event(object sender, EventArgs e)
{
clickEvent(txtvalue.Text);
}
}
}

Step 5: Rebuild our application then add a web form and drag and drop created user control to our
new web form web form aspx pge webform.aspx

</head>
<body>
<form id="form1" runat="server">
<div>

<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />


<br />
<br />
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="true"></asp:TextBox>

</div>
</form>
</body>
</html>

Call event function in our application

web form aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace article
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.WebUserControl11.clickEvent += new click(WebUserControl11_clickEvent);
}

void WebUserControl11_clickEvent(string str)


{
TextBox1.Text = str;
}
}
}

Diffrences Between Custom Control and User Control:

Custom Control

1. You can create a Custom control when it is going to be used across different
applications.
2. Custom controls don't a visual interface.
3. Custom controls however can be added to your tool box and used in different
applications without re-compiling.
4. It's a .dll

User Control

1. If the control you are going to create is only for a particular website then User
Control is the best option.
2. User controls have a visual interface.
3. User control will not appear in tool box and it will not have design support and
loaded at runtime.
4. It's a .ascx

Beginner’s Guide: How IIS Process ASP.NET Request

Introduction
When request come from client to the server a lot of operation is performed before sending
response to the client. This is all about how IIS Process the request. Here I am not going to
describe the Page Life Cycle and there events, this article is all about the operation of IIS
Level. Before we start with the actual details, let’s start from the beginning so that each and
everyone understand it's details easily.

What is Web Server ?


When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET Engine
is responsible to execute all kind of asp.net requests and responses. The process name
is "WebDev.WebServer.Exe" which actually takw care of all request and response of an web
application which is running from Visual Studio IDE.

Now, the name “Web Server” come into picture when we want to host the application on a
centralized location and wanted to access from many locations. Web server is responsible for
handle all the requests that are coming from clients, process them and provide the responses.
What is IIS ?
IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is
used to host your ASP.NET Web application. IIS has it's own ASP.NET Process Engine to handle
the ASP.NET request. So, when a request comes from client to server, IIS takes that
request and process it and send response back to clients.

Request Processing :

Hope, till now it’s clear to you that what is Web server and IIS is and what is the use of them. Now
let’s have a look how they do things internally. Before we move ahead, you have to know about
two main concepts
1. Worker Process
2. Application Pool

Worker Process: Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is
responsible to manage all the request and response that are coming from client system. All the
ASP.Net functionality runs under the scope of worker process. When a request comes to the
server from a client worker process is responsible to generate the request and response. In a
single word we can say worker process is the heart of ASP.NET Web Application which runs on
IIS.

Application Pool: Application pool is the container of worker process. Application pools is used
to separate sets of IIS worker processes that share the same configuration. Application pools
enables a better security, reliability, and availabilityfor any web application. The worker process
serves as the process boundary that separates each application pool so that when one worker
process or application is having an issue or recycles, other applications or worker processes are
not affected. This makes sure that a particular web application doesn't not impact other web
application as they they are configured into different application pools.

Application Pool with multiple worker process is called “Web Garden”.

Now, I have covered all the basic stuff like Web server, Application Pool, Worker process. Now
let’s have look how IIS process the request when a new request comes up from client.

If we look into the IIS 6.0 Architecture, we can divided them into Two Layer

1. Kernel Mode
2. User Mode
Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a
request comes from Client to Server, it will hit HTTP.SYS First.
Now, HTTP.SYS is Responsible for pass the request to particular Application pool. Now here is one
question, How HTTP.SYS comes to know where to send the request? This is not a random pickup.
Whenever we creates a new Application Pool, the ID of the Application Pool is being generated
and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web
application, it checks for the Application Pool and based on the application pool it send the
request.

So, this was the first steps of IIS Request Processing.

Till now, Client Requested for some information and request came to the Kernel level of IIS
means at HTTP.SYS. HTTP.SYS has been identified the name of the application pool where to
send. Now, let’s see how this request moves from HTTP.SYS to Application Pool.
In User Level of IIS, we have Web Admin Services (WAS) which takes the request from HTTP.SYS
and pass it to the respective application pool.

When Application pool receive the request, it simply pass the request to worker process
(w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the
correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different
resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds
the mapping into IIS.

Note : Sometimes if we install IIS after installing asp.net, we need to register the extension with
IIS using aspnet_regiiscommand.

When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry
point of an application.HTTPRuntime is a class which calls the ProcessRequest method to start
Processing.

When this methods called, a new instance of HTTPContext is been created. Which is accessible
usingHTTPContext.Current Properties. This object still remains alive during life time of object
request. Using HttpContext.Current we can access some other objects like Request, Response,
Session etc.

After that HttpRuntime load an HttpApplication object with the help


of HttpApplicationFactory class.. Each and every request should pass through the corresponding
HTTPModule to reach to HTTPHandler, this list of module are configured by the HTTPApplication.

Now, the concept comes called “HTTPPipeline”. It is called a pipeline because it contains a set of
HttpModules ( For Both Web.config and Machine.config level) that intercept the request on its
way to the HttpHandler. HTTPModules are classes that have access to the incoming request. We
can also create our own HTTPModule if we need to handle anything during upcoming request
and response.
HTTP Handlers are the endpoints in the HTTP pipeline. All request that are passing through the
HTTPModule should reached to HTTPHandler. Then HTTP Handler generates the output for the
requested resource. So, when we requesting for any aspx web pages, it returns the
corresponding HTML output.

All the request now passes from httpModule to respective HTTPHandler then method and the
ASP.NET Page life cycle starts. This ends the IIS Request processing and start the ASP.NET Page
Lifecycle.

Conclusion
When client request for some information from a web server, request first reaches to HTTP.SYS of
IIS. HTTP.SYS then send the request to respective Application Pool. Application Pool then
forward the request to worker process to load the ISAPI Extension which will create an
HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the
ASP.NET Page LifeCycle events starts.

How to host asp.net application on the web server (IIS)

Introduction
In general hosting part of the application is not done by developer however in some scenario
where the team size is small or we need to host the application on the local server, we developer
does all the work. In this article, I am going to show how to host an asp.net application on IIS 7.5
in Windows 7 Home Premium Operating System.

Step 1
Open the IIS either from the Start Menu by writing the "inetmgr" command in the search box or
at the command window (you must have the administrative priviledge).

You can also achieve the same by going to Control Panel and clicking on Administrative Tools >
Internet Information Services (IIS) Manager as displayed in the picture below.
If you are not able to see the Internet Information Service (IIS) Manager, your computer might
not have IIS installed. To install the IIS, follow below steps.

Installing IIS on Windows 7


Go to Control Panel > Programs > Turn Windows Features on or off as displayed in the picture
below.
Ensure that from the Tree View, the Checkboxes against the Internet Information Services (IIS) is
checked, even explore the depth of this root folder and check almost all checkboxes as displayed
in the picture below. Checking almost all checkboxes will install more than enough (extra
components as well that is not required for web hosting) component to get started and you may
not use all the components. However later on you can uncheck to un-install those.
I have written hundreds of .NET How to's solution (ebook + source code + video) series
based on real time project problems, click here to get it.

Step 2

Once you have opened the Internet Information Service (IIS) Manager, your screen should look
like below (displayed the left panel in the below picture).

Now, right click the Sites and select Add Web Site ... and your screen should look like below
Enter the Site Name (in my case its SampleWebSite), select the physical folder where you have
kept your website files (this may be your Visual Studio solution folder if you are setting it up at
your local machine or the unpackaged folder path or the root folder of the website or web
application). Now you can click on the OK button.

Clicking OK button may give you above alert box, complaining about the port you are going to
use as by default port 80 is used for the default website of your IIS so you might want to change
it. Click on No button at above alert box and change the port. I have changed the port to 8123 as
displayed below and clicked on OK button.
Clicking OK should give you a screen something similar to below picture where you will have a
SampleWebSite created (notice at the left panel).

Step 3
Now, you may click on the Advance Settings ... from the right panel and modify some settings
that you want to modify. In general it is not needed and you can keep it default.
Step 4
Now, your website is ready to be browsed, you can right click on the website name
(SampleWebSite in my case) and go to Manage Web Site > Browse and you should have an
Internet Explorer window open displaying the default page of your website or web application.
Below is the screenshot of the default page of my SampleWebSite.

Step 5 (Optional)
Notice: Your website may not work if you have developed your it Visual Studio 2010 as your
web.config file may have some tags that is not identified by the IIS. This is becuase creating the
website the way we created just now will host your website in its own application pool that will
have .NET Framework version 2 as target version. So you will need to change to the .NET
Framework 4.0 version.
Click on Application Pools from the left panel and double click the Application pool for your
webiste (generally application pool for your website is your website name so in my case
SampleWebSite) and you should see a dialogue box similar to above. Select .NET Framework
v4.xxx from the .NET Framework version dropdown and click OK. Now follow the Step 4 above
again and your should see the default page.

The Advance Settings dialogue box has many settings and if you look at it carefully, you will feel
that it is self explanatory. Also it gives you description of each settings at the bottom of the
dialogue (above the Ok and Cancel buttons).

Just few of them that is important to focus normally are


1. Application Pool - you will be able to change the application pool if you want.
2. ID : ID of the website, not important for you, used to log files and trace files
3. Physical Path - Physical root path of your application
4. .. Logon credentials .. - in case your physical path is at remote locations etc.
5. Start Automatically - if you want to start the the website automatically when IIS starts.
6. Connection Limits - Maximum number of seconds a connection can remain active
7. Max. Bandwidth - To control the bandwidth consumption of your website
8. Max. Concurrent Connections - Maximum number of concurrent connections your website can
accepts
9. Enable Protocols - Helps you to setup the protocol used to access your website (useful when
you want to host your wcf services on IIS - WAS), for example you can mention "http,net.tcp" in
this case your website will be accessible over http as well as net.tcp connection.
10. Rest three are related with tracing of your web site in case of failure.

Deploy ASP.Net Website on IIS in Our Local


Machine
First open your ASP.Net web application in Visual Studio.

Now in the top we have the option Build. Click on that and under Build you will find Publish
Website.
Click on Publish Website. Now open the publish web pop-up.

For Publish method select File System.

For Target location specify where to save your web application DLL file.

Then click on publish.

Go to the target folder and in that location you will see your web application DLL file.
Now open IIS manager. (Type inetmgr in the run command.)

Right-click on Default Application and Add Application.

Enter Alias name then select an Application pool and Physical path.
Now Double-click on default document.

And add a start page of your web application. Here my application start page is
EstimationSlip.aspx.
Now right-click on your application and browse.

See your application without Visual Studio.


If you want to place a textbox on the page, type tb and press Tab. Wow… You will see something
like this..

<asp:TextBox ID="TextBox1" runat="server"/>

Type req and press Tab. Boom…

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Contro


lToValidate="TextBox1" ErrorMessage="errormessage"></asp:RequiredFieldValidato
r>

About Web.Config Files

The ASP.NET Web.config file is used to define the configuration settings for an ASP.NET
application. ASP.NET and the .NET Framework use .config files to define all configuration options.
The .config files, including the ASP.NET Web.config file, are XML files.

Server-wide configuration settings for the .NET Framework are defined in a file called
Machine.config. The settings in the Machine.config file can be changed and those settings affect
all .NET applications on the server.

Different ASP.NET applications might need different application settings, that’s why defining
those settings in the Machine.config file, is usually not practical. The solution for this problem is
the ASP.NET Web.config file.

The ASP.NET application configuration settings can be changed by creating a file called
Web.config and saving it in the root folder of the application. But what if the Machine.config file
defines different settings than the ones defined in your Web.config file? The good news is that
the settings in the Web.config file override the settings in the Machine.config file.

This is how the minimal Web.config file should look like:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<system.web>

</system.web>
</configuration>

The first line of the Web.config file is the same as the first line for any .config file and specifies
that this is an XML document with utf-8 character encoding type.

There are 2 important characteristics of the Web.config file. The first one is that if you change
your Web.config file, you don’t need to re-compile your ASP.NET application.
The second one is that the Web.config file cannot be viewed in directly in a browser.

How can we use the ASP.NET Web.config file?


<appSettings> Web.config section

The ASP.NET Web.config file is a perfect place to store your ASP.NET application configuration
settings. For example you can store your database connection string in Web.config file and
access them easily from your ASP.NET application. Why would you want to keep your database
connection strings in the Web.config file? The reason is simple – easier maintenance and
deployment. Imagine that you have a huge ASP.NET application, with several hundreds pages
connecting and interacting with a database. If all those pages have the database connection
string hard-coded in them, it will be a nightmare to change all those strings in case you are
changing database servers. Using the Web.config file to store the database connection strings
will allow you to change the connection string only once, and you don’t have to even re-compile
the whole application. Of course you can keep any application wide settings in your Web.config
file, not only database connection strings.

Consider the Web.config example below:

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
<appSettings>

<add key="sConnectionString" value="Provider=SQLOLEDB;DataSource=Yo


ur_Server_Name;Initial Catalog=Your_Database_Name;User Id=Your_Username;Passwo
rd=Your_Password;" />

</appSettings>
<system.web>

</system.web>
</configuration>

As you can see, we have added a new section in our Web.config called <appSettings>.
The <appSettings> section defines custom ASP.NET application settings. The <add> child
element of the <appSettings> ads a key/value pair, which is accessible from your applications,
with the following code:

ConfigurationSettings.AppSettings("sConnectionString")

<customErrors> Web.config section

The <customErrors> section of the Web.config file defines the settings for handling web
application errors. Below is the general syntax of this section:

<customErrors defaultRedirect="YourDefaultURL" mode="On|Off|RemoteOnly">


<error statusCode="ErrorStatusCode" redirect="YourRedirectURL"/>
</customErrors>

The attribute mode defines how custom error handling works and can be one of the following 3
options:

On: Enabled
Off: Disabled
RemoteOnly: Enabled only for remote clients (requests coming from the local machine are not
handled by these custom error settings).

You can use the <customErrors> Web.config section to define how to handle particular error
codes. Here is an example of custom handling of 404 error (File Not Found):

<customErrors mode="On">
<error statusCode="404" redirect="Nice-FileNotFound-Page.aspx"/>
</customErrors>
<identity> Web.config section

The <identity> Web.config section defines what identity (Windows account) to use when
accessing the ASP.NET application. Here is the generic syntax of the <identity> section of the
Web.config:

<identity impersonate="true|false" userName="username" password="password"/>

Impersonation is the concept whereby an application executes under the context of the identity
of the client that is accessing the application. This is achieved by using the access token provided
by IIS.

By default the ASPNET Windows account is used to access ASP.NET resources through the
Aspnet_wp.exe process. This account is less powerful, compared to the IUSR_ machinename guest
Internet account used by classic ASP for example. In certain situations you might want to use the
anonymous IUSR_ machinename account, as the account accessing your ASP.NET application and
you can do that by using the following code in your Web.config file:

<system.web>
<identity impersonate="true" />
</system.web>

In this case we use impersonation. In short impersonation is the act of ASP.NET executing code in
the context of an authenticated client (Windows account).

If you want you can specify a particular account Windows account to be used instead of the
ASPNET Windows account. You can do it like this:

<system.web>
<identity impersonate="true" userName="WindowsDomain\YourUserName" password="Y
ourPassword" />
</system.web>

The ASP.NET Web.config file can control many more settings like Session State, Tracing and
Authentication & Authorization for example.

Getting connectionStrings / appSettings values from


web.config file

I am going to show how to get connectionStrings / appSettings values from web.config file. This
article also contains how to get get the connectionString value at .aspx page in case you are
using DataSource control like SqlDataSource.
Introduction
In many cases, we need to use some data string throughout the application, database connection
string is the best example of it. Instead of writing the connection string wherever we are creating
a connection, its good practice (and easy to maintain too) to store it into web.config file and get
it at desired place.

Places to store data into Web.Config file


There are two places where we can store data into our web.config file. These are appSettings and
connectionStrings. Following is the code snippet from the web.config file where we can store
data and retrieve at later point of time.

<configuration>
<appSettings>
<add key="ConnStr" value="Data Source=.\SQLEXPRESS;AttachDbFilename=C:\MyData\App_
Data\Database.mdf;Integrated Security=True;User Instance=True"/>
</appSettings>
<connectionStrings>
<add name="ConnStr" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:
\MyData\App_Data\Database.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
</configuration>

Here appSettings is meant for any data string that can be stored while connectionString is meant
for storing the database connection strings only.

How to Get data from Web.Config


Getting data from web.config file is simple. If you want to get data from appSettings tag then you
need to write following code

string connStr = System.Configuration.ConfigurationManager.AppSettings["ConnStr"].


ToString();

To get data from web.config file stored under connectionStrings tag, you need to write following
code

string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["Conn


Str"].ToString();
Getting connectionStrings value into .aspx page
If for some reason you want to access the string stored in connectionStrings tag into .aspx page
(You may need this while using SqlDataSource control), you need to write following code (Notice
the code in the pink color <%$ ConnectionStrings:ConnStr %>).

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ Connec


tionStrings:ConnStr %>'
SelectCommand="Select * FROM SampleForTutorials ORDER BY [Name]" DataSourceMode="D
ataSet">
</asp:SqlDataSource>

Conclusion
Web.Config file is the best place to store small and simple string that can be used throught the
application. UsingSystem.Configuration.ConfigurationManager class that exists
in System.Configuration namespace, we can retrive them wherever we need.

Reading appSettings and connectionStrings from


web.config file in asp.net

In this tutorials, I am going to explain how to read appSettings and connectionStrings values
from the web.config file.
To do so, lets add one appSettings and connectionStrings into our web.config file like this

<appSettings>

<add key="AppKey" value="Value in AppSetting key"/>

</appSettings>

<connectionStrings>

<add name="ConnStr" connectionString="server=localhost;databas


e=mydatabase;uid=uid;pwd=pwd;"/>

</connectionStrings>

In the code behind file, you will have to use System.Configuration namespace. So add it at the
top of the .cs file like

using System.Configuration;

Now, write the following code to retrieve the values from the web.config appSettings and
connectionStrings.

string str = "connectionStrings value: " + ConfigurationManager.ConnectionStri


ngs["ConnStr"].ToString();

str += "<br />appSetting value: " + ConfigurationManager.AppSettings["


AppKey"].ToString();

litText.Text = str;