Upload
anon167470467
View
70
Download
7
Embed Size (px)
Citation preview
ASP.NET
- A technology from Microsoft for web and mobile based development- A web application is made of certain forms called as Web Forms- Each web form is a class inherited from System.Web.UI.Page class- We can use a language of choice to build the web application even same web
application can have different pages in different languages- Single web page can only one language- If no language is defined the default is Visual Basic- Different kind of pages used in ASP.NET
o .aspx For presentation
o .aspx.cs For logic
o .master For master pages
o .ascx For Custom Web Controls
o .asmx For Web Service
o .css For Cascading Style Sheets
o .htm For HTML Files
o .asax For Global Application Class
o .resx For resource file
Create a Web Application
File New Project… Select language as Visual C# and them ASP.NET Web Application
- It has a project file and solution file
Creating a website
- A website is collection of web pages and do not have the project file and solution file
o File New Website- To open a website we always need to go
o File Open Website
Development modes of Website/ Web Application1. Two Page or Code Behind model
a. Two files get created asi. .aspx
ii. .aspx.csb. Both get combined using Page directive with CodeFile attributec. It is by default
2. Single Page modela. All tags and program code get merged into single file .aspxb. While adding a new web form remove the checkbox
i. [ ] Place code in separate fileii. Website Add New Item… Web Form
Note: Visual Studio Provides in build server called as ASP.NET Development Server to run a web application for development purpose only.
To deploy a web project we need another server called IIS (Internet Information Server)
Components of an ASP.NET Page
1. Directivesa. Provides directions to the compilerb. Starts with <%@ and ends with %>
i. Pageii. Import
iii. Registeriv. OutputCachev. Etc.
1. <%@ Page Language="C#" %>2. <%@ Import Namespace="System.Data.SqlClient" %>
2. HTML Tags3. ASP.NET or Server Side Tags
a. Special tags provided by ASP.NET which are object of certain classb. <asp:Button ID="Button1" runat="server" Text="Button" />
4. Scriptletsa. Language code merged directly into HTML using <% and %> delimiters
<% int n = 5; for (int i = 1; i <= 10; i++) Response.Write(i * n + "<br>"); %>
5. Expressionsa. Used to display some value or expression or variable on the screenb. Use <%= and %> delimiters<%for (int i = 1; i <= 6; i++)
{%> <h<%=i%>>This is heading <%=i%> </h<%=i%>>
<%} %>
6. Intrinsic or pre-defined Objects a. Requestb. Response
i. Write()ii. Redirect()
iii. End()c. Sessiond. Servere. Applicationf. ViewState
Working with controls
Label controlText
TextBox control- To create single line text, password field and mutliline text
o Texto ToolTipo AccessKey – to make the hotkeyo TextModeo MaxLengtho ReadOnly
Button control- To create a push button
o Text
LinkButton control- To create a button as hyperlink
o Text
ImageButton control- To use an image as button
o ImageUrl
HyperLink control- To navigate to some URL
o Texto ImageUrlo NavigateUrlo Target
Storing Connection string inside Web.Config (Web Configuration File)
- Use <connectionStrings> section
<connectionStrings> <add connectionString="Data Source=.;Integrated Security=true;Database=batch02" name="cs" providerName="System.Data.SqlClient"/> </connectionStrings>
- To read the connection string in any web form use WebConfigurationManager class of System.Web.Configuration nmaespaces
using System.Web.Configuration;
cn.ConnectionString = WebConfigurationManager.ConnectionStrings["cs"].ConnectionString;
05.04.2010
Using Data Source Controls
- Special controls for database programming with very less codeo SqlDataSource – to work with sql server, oracle, db2 etc.o AccessDataSource – only access fileso XmlDataSource – on xml fileso ObjectDataSource – with collectionso SitemapDataSource – To create a sitemap in websiteo LinqDataSource- use with LINQ (Language Integrated Query)
- All these controls provides some properties and methodso InsertQueryo UpdateQueryo DeleteQueryo SelectQueryo Insert()o Update()o Delete()
- To view data from database ASP.NET provides different controlso GridViewo ListViewo Repeater
o DetailsViewo FormView
Every ASP.NET control provides Smart Tag for quick access of important properties of the control
Test Case
Create a table as CategoryMaster having category code and category name. Write a web form to insert, update, delete and select the different category names.
Data Binding with GridView
Method 1: Using a Data Source Control
- Provide DataSourceId propertyo Gridview1.DataSourceId=SqlDataSource1
- We can also define the primary key usingo DataKeyNames
Method 2: Using DataTable or DataView
- Use DataSource with DataBind() methodo GridView1.DataSource=dt;o GridView1.DataBind();
protected void Button1_Click(object sender, EventArgs e) { SqlConnection cn = MyClass.GetConnection(); string sql = "Select * from categorymaster"; SqlCommand cmd = new SqlCommand(sql, cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); cn.Close();
GridView1.DataSource = dt; GridView1.DataBind(); }
Creating Dropdown list
- Allows to select only one item- It provides Items collection
o Use Add() method to add the itemso It needs an object of ListItem class
- SelectedValueo Gives only the value
- SelectedItemo Texto Value
ExampleDropDownList1.Items.Add(new ListItem("United Kingom", "uk"));
Note: When adding elements on form load, and click on any button, re-load occurs. To avoid addition of items again and again, check for PostBack of the form using IsPostBack roperty of the Page class
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DropDownList1.Items.Add(new ListItem("United Kingom", "uk")); } }
Binding data with DropDownList
Method 1: Using Data Source control
Define properties- DataSourceId=”data source id name”- DataTextField=”fieldname to display data”- DataValueField=”fieldname to use the value”
Method 2: Using ADO.NET- DataSource=datatable or dataview- DataTextField=”fieldname to display data”- DataValueField=”fieldname to use the value”- DataBind()
Test Case
Create a web form to input data into a Product Table having Product Id, Product Name, Product Unit Price, Category Id, Quantity Available, Minimum Order Level
Here Category Id is a foreign key
09.04.2010
Intrinsic objects
1. Requesta. Formb. QueryStringc. ServerVariablesd. Cookies
2. Responsea. Cookiesb. Write()c. Redirect()d. End()
3. Session4. Server5. Application6. ViewState
Response object
- To send the response to the cliento Write(data)
- Also used to redirect the control to some other URLo Redirect(url)
- We can stop sending data to the cliento End()
- We can create a cookie on the client using Cookies collection
Test Case
Write a program to check the login and password and redirect the control to Main.aspx file if the security information is validated.
Sample : Users Table (login,password, username)
Using Login control- UserName- Password- FailureText
Session object
- Used to manage some information accessible in all the web forms for the current user
o Session[“variable”]=valueo Variable=Session[“variable”]
- Use Abandon() method to remove all session variableso Session.Abandon()
Test Case- In last example, if the user login is success then pass the user name
to other web form Main.aspx
Server object
- To give information about the server, files and folder on the server- To helps in transferring control from one page to another of the
websiteo Server.MapPath(“folder or file”)o Server.Transfer(“page name”)
Difference between Redirect and Transfer1. Redirect can transfer control to any URL while Transfer sends control
to some page of same website
2. Transfer carries data from one page to another page automatically when Redirect do not
3. Transfer is faster than redirection
Uploading files on server
- Use FileUpload control- To upload the files selection the file using FileUpload control- Use FileName property of FileUpload control to get the current
file name- Use Server.MapPath() to get full path of the folder on the website- Use SaveAs() method of FileUpload control to save the file on
server
12.04.2010
Application object- To manage some information accessible in all the pages for all users
o Application[“variable”]=value- Use Lock() and UnLock() method while updating Application variables
Application.Lock();Application[“variable”]=value;Application.UnLock();
Test Case
Create a visit counter on the home page
<% int counter; if (Application["vc"] == null) counter = 0; else counter = Convert.ToInt32(Application["vc"]);
counter++; Application.Lock(); Application["vc"] = counter; Application.UnLock(); %>You are vistor number # : <%=counter %>
ViewState object- To manage some information between different calls of a web
form- It works with current page only
o ViewState[“variable”]=value- A hidden variable get used to manage the information _ViewState
Test Case
Create a web form to get a login and password. It user makes three makes then disable the login button and say a method Your Account is Blocked.
protected void Button1_Click(object sender, EventArgs e) { if (txtLogin.Text == "abc" && txtPassword.Text == "xyz") Response.Redirect("frmMain.aspx"); else {
if (ViewState["ec"] == null) ec = 0; else ec = Convert.ToInt32(ViewState["ec"]);
ec++;
ViewState["ec"] = ec;
if (ec == 3) { Button1.Enabled = false; lblMessage.Text = "Sorry! Your Account is Blocked"; } else { lblMessage.Text = "Invalid Authentication"; }
}
Other methods to manage data 1. Cookies2. Hidden Variables
Cookies
- Some information managed at the client side- Use Cookies collection of Response object to send the cookie the
client - Use HttpCookie class to create a cookie- To read the cookie from the client use Request object’s Cookies
collection- Can be of two types
o Temporary Cookies (default)o Persistent Cookie
- Use Expires property to define the expiry date of the cookie- Use Methods from DateTime.Now with methods AddSecond(),
AddMonth(), AddYear() etc.
Test Case
Create a web form to create a cookie and read it to manage last visit time
protected void Button1_Click(object sender, EventArgs e) { HttpCookie c = new HttpCookie("lv"); c.Value = DateTime.Now.ToString(); c.Expires = DateTime.Now.AddSeconds(10); Response.Cookies.Add(c); }
protected void Button2_Click(object sender, EventArgs e) { if (Request.Cookies["lv"] == null) { Response.Write("Welcome new user"); } else { HttpCookie c=Request.Cookies["lv"]; Response.Write("Dear User Your Last Visit was : " + c.Value); } }
Hidden Variables
- Special variables that are kept inside the web page in hidden form- They are not visible on the screen- They are used to carry data from one to another page- Use HiddenField control to manage such information
Test Case
Create three web forms where first form inputs Name and Age and Second form Org name and designation. Show all for details on third web form.
Page1.aspxPage2.aspxPage3.aspx
14.04.2010
Merging contents of one file to a web form
- Use the following command anywhere in the web form
<!-- #include file="filename" -->
Test Case
Create an html page to footer from Project Add New Item … HTML page
Now add another web form and merge the page contents at the bottom of the page
<!-- #include file="footer.htm" -->
Creating and Using Web User Controls- Used merge the contents after some processing- They are used as custom tag inside a web form
To create a web user control add it fromProject Add New Item… Web User Control
A file get created with .ascx extension
Test Case
Write a control as Table control to get a number as attribute and print the table of that number with heading
e.g. Table.ascx
The directive <%@ Control %> indicates that it is a control and not web form
Define the properties to be used as an attributeGo to design view to build the look and feel of the controlBuild it
Using a web user control
- To use the control in a web form we need to register it- Use register directive to register a control with the web form
<%@ Register Src="~/Table.ascx" TagName="Table" TagPrefix="bps" %>
- While using such controls always use runat=”server” to denote a server control
<bps:Table Number="6" runat="server" ID="t1" />
Working with Master Pages
- Special page that has common items used on many pages like image, flash animation, menus etc.
- It defines the look and feel for many web pages- We need to add some control called as ContentPlaceHolder to insert data later
on from Content Page
Creating Master Page
- Project Add New Item… Master Page- A file get added with .master extension- Define the look and feel and Add the Content Place Holder control to add
information from Content page
Creating a content page
Select the Master on which a content page to be created.Project Add Content Page
Note: 1. To define the size of a content place holder place it inside a Panel2. To define the fix location of a control choose
a. Format Position Absolute
b. Now drag and drop the control to any position
Using Cascading Style Sheet (CSS)
- A fixed set of code to enhance power of HTMLo color: color name or codeo background-color: color name or color codeo background-image: url(filename)o font-family:font nameo font-size: number unit (units can be cm, mm, in, pt, px etc)
5in 5 inch 12pt 12 points
o text-decoration:underline|none
CSS can be applied using three ways
1. Inline (Tag Level)2. Internal (Page Level)3. External (Web Application Level)
Inline CSS means applying CSS code directly on a tag using STYLE attribute of the tag. Can be applied only on HTML tag but not on ASP.NET tags
<p style="text-align:center;background-color:Blue;color:White;font-weight:bold;font-size:40pt">Hello</p>
Internal CSS means applying effect on all tags of current web page or web form using <STYLE></STYLE> tag under <HEAD> section. Not supported by ASP.NET controls
<style type="text/css" > A {text-decoration:none} A:hover {text-decoration:underline;color:Red} </style>
Creating Named Styles
- We can define the styles with names using two techniqueso ID basedo CLASS based
- When using ID based styles use # before the style name- When using CLASS based styles using . before the style name
For .NET use CLASS based syntax. Use CssClass property to define the class name
.abc{color:White;background-color:Maroon} #xyz {color:White;background-color:Maroon}
<asp:TextBox ID="TextBox1" runat="server" CssClass="abc" style="top: 111px; left: 175px; position: absolute; height: 22px; width: 128px"></asp:TextBox> </div> <p> <h1 id="xyz">Hello to all</h1>
External CSS
- We need to create separate file having a set of classes and tag effects as .css- Use <LINK> tag to give reference of that file in any web page or web form
o <LINK href=”filename.css” rel=”stylesheet”>
Creating a CSS file from Visual Studio
- Project Add New Item Style Sheet
19.04.2010
Working with Themes and Skins
- A theme is a folder having a set of .skin files- All such themes are stored in special folder App_Themes- Each skin file contains the look and feel of a control - The skin file will have same name as controls class name
Prjoect App_Themes
themename (folder) classname.skin
- To apply the theme on a page use Theme property of Page class or Page Directive- Use SkinId property to define the SkinId of a control if a control more than one look
and feels
Using Validation controls
- Used to apply validation rules on the controls- There are 5+1 validation controls- There are five validations and one is summary control
o RequiredFieldValidatoro CompareValidatoro RangeValidator
o RegularExpressionValidatoro CustomValidatoro ValidationSummary
- Each validation control provides some propertieso ControlToValidateo ErrorMessageo Display – static/dynamic/noneo SetFocusOnError=true/false
Compare Validator
- ContolToValidate- ControlToCompare- ValueToCompare- Operator- Type
RegularExpressionValidator- To check the patterns
o \d{6}o \d{10,12}
Range Validator
- Type- MimumValue- MaximumValue
Custom Validator- To define the custom rules- Select the control and double click on- IsValid property of Page class manages the validations. It is a read only property- Use EventArgs object to the validation status with IsValid property
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { char ch = txtEmpId.Text.ToUpper()[0]; if (!(ch == 'D' || ch == 'B' || ch == 'C')) { args.IsValid = false; }
}
protected void Button3_Click(object sender, EventArgs e) { if (Page.IsValid) { Response.Write("Done"); } }
Validation Summary
- To show all message at one place on the web form or inside a dialog- Place the ValidationSummary control somewhere on page- Set Display property as None for validations controls if using Validation Summary
o ShowSummaryo ShowMessagBox
Using ValidationGroups
- If using multiple operations on same form create Validation Groups using ValidationGroup property
Stopping the validation process on a control
- Set CausesValidation property as false to disallow the volition process on click of some button
21.04.2010
Web Service- Special classes that reside on some web server and serve different kind of clients in
any kind of applications and any kind of device- Such classes contains special methods called as Web Methods- To make a method as Web Method use [WebMethod] attribute above the methods- It uses XML as transfer mode hence also known as XML Web Service- A class to be called as web service must inherit from
System.Web.Services.WebService class
Creating a web Service
File New Website ASP.NET Web Service
A service contains files with .asmx extension
If using database, it does not support Integrated Security mode.
Test Case
Write a web service having a method GetResult() which takes a rollno as parameter
using System;using System.Linq;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;
using System.Xml.Linq;using System.Data.SqlClient;
[WebService(Namespace = "[email protected]")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService]public class Service : System.Web.Services.WebService{ public Service () {
//Uncomment the following line if using designed components //InitializeComponent(); }
[WebMethod] public int GetMarks(int rollno) { SqlConnection cn = new SqlConnection(); try { string sql = "Select marks from result where rollno=@rollno"; cn.ConnectionString = "Data Source=.;Integrated Security=true;database=batch02"; cn.Open();
SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.AddWithValue("@rollno", rollno); int marks = Convert.ToInt32(cmd.ExecuteScalar()); return marks;
} catch (Exception ex) { throw ex; } finally { cn.Close(); } } }
Consuming or using a Web Service
- To use a web service in any kind of application first create a URL of it- On local machine create a virtual directly to test a web service using IIS
o Start the IIS Default Website New Virtual Directory
Example
http://localhost:90/ws02/service.asmx
- to use the web service inside a project give reference of ito Website/Project Add Service Reference…
- Give your web service URL and the namespace name for your classes of web service- Create an object of SOAP client (Simple Object Access Protocol) and invoke the
required method
Test Case
Create a windows application to show the result of a student using a web service.
private void button1_Click(object sender, EventArgs e) { int rollno = int.Parse(txtRollno.Text);
bpsharma.ServiceSoapClient c = new bpsharma.ServiceSoapClient(); txtResult.Text = c.GetMarks(rollno).ToString(); }
Creating and using the web proxy
- We convert the web service classes into a dynamic link library (DLL) using a tool WSDL.EXE (Web Service Description Language)
- Use the following syntax to convert a Web service URL into a .cs file
WSDL <url>?wsdl
Example
wsdl http://localhost:90/ws02/service.asmx?wsdlCSC /t:library Service.cs Service.dll
- Now use this DLL in place of web URL- Give reference of another DLL of .NET Framework System.Web.Services.dll
Example
private void button1_Click(object sender, EventArgs e) { int rollno = int.Parse(txtRollNo.Text); Service s = new Service(); int marks = s.GetMarks(rollno); MessageBox.Show("Resulst is " + marks); }
23.04.2010
AJAX (Asynchronous Java Script and XML)
- A client side technology from Google- It allows interacting with server side technologies like ASP, ASP.NET, PHP, JSP etc.- Certain classes are used at the client side to invoke methods from JavaScript that get
response from server side technology- It provides different classes in different browser
o XmlHttpReader class Found in Opera, Chrome, Firefox etc.
o MSXml2.XmlHttp Latest versions of IE
o Microsoft.XmlHttp Older Version of IE
Creating an object of such classes in JavaScript
var x=new XmlHttpReader();
var y=new ActiveXObject("MsXml2.XmlHttp");
var z= new ActiveXObject("Microsoft.XmlHttp");
Create a URL to send the request on some server
- Open the connection with the server from client using open() method- Use send() method to send your request- Use readyState property to get the current status of the request
o 0 not initializedo 1 process initializedo 2 request sendo 3 under processingo 4 process completed
- Use OnReadyStateChange event for program code- Use responseText property to get the response send by server
Test Case
Create a html form to valid a login id from server using AJAX without submitting the form.
Solution
Create an HTML form having a field as login
<html>
<head><meta http-equiv="Content-Language" content="en-us"><meta http-equiv="Content-Type" content="text/html; charset=windows-1252"><title>Login</title><script>
function checkLogin(){
var login=document.f.login.value;if(login=="")
return;var x=new ActiveXObject("MsXml2.XMLHTTP");var url="LoginCheck.aspx?login="+login;x.open("get",url,true);x.send();x.onreadystatechange=function(){
if(x.readyState==4){
if(x.responseText=="yes"){
errMessage.innerHTML="Sorry! This id already exist";return;
}}
}}
</script></head>
<body>
<form method="post" action="CreateUser.aspx" name="f"><p>Login : <input type="text" name="login" size="20" onkeyup="checkLogin()"> <span
id="errMessage" style="color:red"></span></p><p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
http://localhost/LoginCheck.htm
Contents of LoginCheck.aspx
<%@ Page Language="C#" %><%@ Import Namespace="System.Data.SqlClient" %>
<%
string login=Request["login"];SqlConnection cn=new SqlConnection();cn.ConnectionString="Data Source=.;User Id=sa;Password=pass;Database=batch02";cn.Open();string sql="Select * from Users where login=@login";
SqlCommand cmd=new SqlCommand(sql,cn);cmd.Parameters.AddWithValue("@login",login);SqlDataReader dr=cmd.ExecuteReader();string ans="";if(dr.HasRows)
ans="yes";else
ans="no";cn.Close();Response.Write(ans);
%>
For server side controls use Attributes collection to add them HTML events
txtLogin.Attributes.Add("onKeyUp","checkLogin()");
26.04.2010
Using Reporting Controls
1. Repeater2. DataList3. GridView4. DetailsView
Repeater control
- Creates the reports based on templateso HeaderTemplateo FooterTemplateo ItemTemplateo AlternateItemTemplateo SeparatorTemplate
- Use special delimiters <%# %> with Eval() method to get data from some data source or data source id
o Method 1 DataSourceId=<data source control name>
o Methods 2 DataSource=<datatable or data view> DataBind()
- It can show only record per row. There is no paging concept.
Test Case
- Use the MS Access Sample database FPNWIND.mdb provided with MS Office- Add this file to App_Data folder of the ASP.NET Application- Use AccessDataSource control to use the Access Files
<asp:Repeater ID="Repeater1" runat="server"> <ItemTemplate> <tr><td><%#Eval("CustomerId") %> </td><td> <%#Eval("CompanyName") %></td><td> <%#Eval("City") %></td><td> <%#Eval("Country") %></td></tr> </ItemTemplate> <AlternatingItemTemplate> <tr><td><%#Eval("CustomerId") %> </td><td> <%#Eval("CompanyName") %></td><td> <%#Eval("City") %></td><td> <%#Eval("Country") %></td></tr> </AlternatingItemTemplate> <HeaderTemplate> <h1>Customer Report</h1> <table border="1"></HeaderTemplate> <FooterTemplate></table></FooterTemplate> </asp:Repeater>
protected void Page_Load(object sender, EventArgs e) { OleDbConnection cn = new OleDbConnection(); cn.ConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\Batches2010\02\26.04\Batch02_2604\Batch02_2604\App_Data\FPNWIND.MDB"; cn.Open();
DataTable dt = new DataTable();
string sql = "Select * from Customers";
OleDbDataAdapter da = new OleDbDataAdapter(sql,cn); da.Fill(dt); cn.Close();
Repeater1.DataSource = dt; Repeater1.DataBind(); }
DataList control
- Used to show multiple records in one rowo DataSourceIdo DataSourceo DataBind()
o RepeatColumnso RepeatDirection
- It also has templates- It also provides styles on different templates- Use <%# and %> delimiters with Eval() method
Details View control
- Used to show the current record only
Creating Scrollable reports
- Use Panel control with Scrolling
GridView control
- to show one record per row - Allows the paging as well
o AllowPagingo AllowSortingo PageSizeo PagerSettingso SelectedRow
- Use Columns Collection- To use the program code for Selection use Select command button from
Columns collection
28.04.2010
Creating Master/Table Reports
- Creating a combo box having master informationo DataSourceIdo DataTextFieldo DataValueField
Caching
- To hold data in client’s browser cache memory and serve the data in same data was asked based
- Caching can be of three types
o Full Page Cachingo Field based cachingo Control Based caching
- Use OutputCache Directive to define the cache duration and type of cachingo Duration will be define in secondso VaryByControlo VaryByParam
Example 1:
Full Page Caching<%@ OutputCache Duration="3600" VaryByParam="none" %>
Example 2: Control Based Caching
<%@ OutputCache Duration="3600" VaryByControl="DropDownList1" %>
Creating HyperLinkField in GridView control
- Select the Columns collection- Add HyperLinkField control- Use Properties
o DataNavigateUrlField Defines the field name to merge the data in dynamic URL
generationo DataNavigateUrlFormatString
Define the format for URL Example
ShowCustomer.aspx?cid={0}
What is Crystal Report?
- A reporting tool from Seagate company to create advance reports- Allow to export in different formats- Add a new crystal report from
o Project Add New Item… Reporting Crystal Reporto A file get created as .rpt
Using Crystal Report in ASP.NET- Add a new web form- Add CrystalReportSource control and select the report file name- Now Add CrystalReportViewer control and select the CrystalReportDataSource-
30.04.2010
Resource Files
- Special files with .resx extension that contain data that can be used dynamically on different web forms
- Such files contain data using key/value relationship- Add a resource file from
o Project Add new item… Resource File
protected void Page_Load(object sender, EventArgs e) { lblName.Text = MyResources.lblName; cmdSave.Text = MyResources.cmdSave; }
Internationalization (I18N)
- .NET provides different classes for international way of programming- It is divided in two parts
o Globalizationo Localization
- Globalization deals with the specific information of a country like Currency, Date Format, and Time Format etc.
- Localization deals with the specific language in different regions of the country- Use System.Globalization namespace with CultureInfo class to define the
information related with a country- Every country has fixed code defined by IETF (Internet Engineering Task Force) and
every language defined in the country also has a unique code.
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) {
DropDownList1.DataSource = CultureInfo.GetCultures(CultureTypes.SpecificCultures); DropDownList1.DataTextField = "DisplayName"; DropDownList1.DataValueField = "Name"; DropDownList1.DataBind(); } }
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { Response.Write(DropDownList1.SelectedValue); }
Example
hi-IN Hindi – Indiafr-FR Frenchde-DE Germanyen-US US English
Sample Case
Create a web form and display the current date in different countries – India, France, Germany and US
CultureInfo fr = new CultureInfo("fr-FR");lblFrance.Text = DateTime.Now.ToString(fr);
Note: To change the Page items specific to country to automatically when a country get selected use Page.Culture Property
Page.Culture = DropDownList1.SelectedValue;
Localization
- Every country specific language code has its own resource file having country code associate with it
- First resource is the default resource and other are specific to countryo MyResources.resx
Default Resource Fileo MyResources.de.resx
For Germamo MyResources.fr.resx
For france
- Use UICulture property of Page class to define the current country language code-
SecurityGDI+Remoting