Академический Документы
Профессиональный Документы
Культура Документы
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.
Let's Start
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
LocalPage.aspx.cs
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>
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;
}
}
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.
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).
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.
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).
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 %>" />
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.
Label3.Text = Resources.Resource.b1;
Label3.Text = GetLocalResourceObject("Button1.Text").ToString();
Label3.Text = GetGlobalResourceObject("resource", "color");
Example
Web page
.aspx page
Header
http://code.google.com/intl/fr/apis/language/transliterate/v1/getting_started.html
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.
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.
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.
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.
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#
VB.Net
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";
VB.Net
Imports System.Threading
Imports System.Globalization
Once the BasePage class is created, the next step is to inherit the BasePage class in the ASP.Net page.
C#
}
}
VB.Net
End Sub
End Class
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
HTML SPAN
The Multilingual ASP.Net website is now ready and we will now test it to make sure it works in the following
two cases
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.
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.
webusercontrol1.ascx
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>
</div>
</form>
</body>
</html>
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);
}
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
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.
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.
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.
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.
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.
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.
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).
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 Target location specify where to save your web application DLL file.
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.)
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.
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.
</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.
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.
</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")
The <customErrors> section of the Web.config file defines the settings for handling web
application errors. Below is the general syntax of this section:
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:
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.
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.
<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.
To get data from web.config file stored under connectionStrings tag, you need to write following
code
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.
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>
</appSettings>
<connectionStrings>
</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.
litText.Text = str;