Professional Documents
Culture Documents
Material IMP PDF
Material IMP PDF
And
ASP.NET
Duration: 47 Hours
Hour 6 ASP.NET Introduction and Advantages, Getting started with ASP.NET Page 46
Hour 7 Inpage Technique and Code behind Technique, Page Definition Syntax Page 62
Hour 8 Implicit Objects , Page Execution Life Cycle, Page Events Page 64
Hour 9 Client controls (vs) Server Controls; HTML Server Controls, Post Backing Page 70
Hour 10 Standard Controls Page 76
Hour 11 Tables Designing, Absolute Positioning Page 93
Hour 12 Wizard and AdRotator Controls Page 100
Web Server
Web Site
Web Client 1
Browser
Request
Response
Web Site:
It‘s a collection of web pages.
In other words, it‘s named memory location on the web.
Every company purchases some amount of memory space on the web server. In that
space, some web pages will be uploaded. Then that memory space is called as ―web
site‖.
Every web site is a folder in the web server memory, in which all the web pages can
be stored.
URL:
Every web site is associated with an address.
That address of the web site is called as ―URL‖ (Uniform Resource Locator).
The client can open the web site using the URL only.
In simple, when you are browsing any web site on internet, the address displayed in
the address bar of the browser, is called as ―URL‖.
Ex: http://www.google.co.in
Web Server:
A system, which serves one or more web sites on internet.
Web Client:
Every system, which has internet connection, can be called as ―Web Client‖.
Suppose you have internet connection in your system, then your system can be
called as ―Web Client‖.
In the web client, browser should be there.
Browser:
In the client system, to open the web sites, a software should be there.
That software is called as ―Browser‖.
As you know, there are so many browsers are available in the market.
Every browser should able to execute the following code:
HTTP:
It is the protocol, in which all the web sites are maintained.
The applications that run under HTTP protocol can be called ―web applications‖.
Web Page:
It‘s a part of the web site.
It contains some information.
That information can be called as ―Content‖.
The content may be in different formats (headings, text matter, images, links, tables,
controls like textboxes, buttons etc.)
Every page is a file. Ex:
page1.html
page2.asp
page3.aspx
page4.php
page5.jsp
etc.
In order to develop your own web site, you have to follow 3 stages:
I. Page Designing Stage
II. Client Side Programming Stage
III. Server Side Programming Stage
It‘s a designing language; it‘s not a programming language. That means it doesn‘t
contains any programming concepts such as data types, variables, operators, control
statements, arrays etc. It contains some design concepts only.
Its syntax is written in the form of tags. The tag name is to be written within the < and
> symbols.
Def of Tag: A keyword, which is written inside of < and > symbols is called as ―Tag‖.
The tags are two types in html.
1. Paired tags: These tags contain starting tag and ending tag.
<tag>
some content
</tag>
2. Unpaired tags: These tags contain only single tag. No starting / ending
tag.
<tag>
<html>
<head>
<title>any title</title>
</head>
<body>
some content
</body>
</html>
The <html> tag specifies the starting and ending point of the html program.
3) Link tags:
<A>
4) List Tags:
<OL>
<UL>
<LI>
5) Multi-media tags:
<IMG>
<HR>
<BGSOUND>
<MARQUEE>
7) Form tags:
<FORM>
<INPUT>
<TEXTAREA>
<SELECT>
<OPTION>
Note: All of these tags are described in the ―HTML beginners guide‖ file, which is attached to
this material. If you don‘t have an idea about all of these tags, a try to learn those from that
―HTML beginners guide‖ text book.
Demo.html
<html>
<head>
<title>Demo on HTML tags</title>
</head>
<body bgcolor="lightyellow">
<a name="top">
<h1 align="center">
HTML Demo Page</h1>
<h2 align="center">
(Hypertext Markup Language)
</h2>
<p align="justify">
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-
requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET. HTML is one
of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of ASP.NET.
HTML is one of the pre-requirements of ASP.NET. HTML is one of the pre-requirements of
ASP.NET. </p>
<hr>
<p align="justify">
<font size="4" face="Century Gothic">
<font color="green">
.NET Framework latest version 4.0. .NET Framework latest version
4.0. .NET Framework latest version 4.0. .NET Framework latest version 4.0. .NET
Framework latest version 4.0. .NET Framework latest version 4.0. </font> <font
color="red">.NET Framework latest version 4.0. .NET Framework latest version 4.0. .NET
Framework latest version 4.0. .NET Framework latest version 4.0. .NET Framework latest
version 4.0. .NET Framework latest version 4.0. .NET Framework latest version 4.0. .NET
Framework latest version 4.0. .NET Framework latest version 4.0. .NET Framework latest
version 4.0.</font>
</font>
</p>
<hr>
<div align="right">
This is normal text.<br>
<hr>
<center>
<img src="c:\earth.gif">
<img src="c:\earth.gif" width="50px" height="40px" alt="The globe is
moving around the sun!">
</center>
<hr>
<marquee>
C#.NET is the No. 1 language today!
</marquee>
<marquee direction="right">
C#.NET is the No. 1 language today!
</marquee>
<hr>
<center>
<marquee behavior="alternate" width="270px">
<img src="c:\globe2.jpg">
</marquee>
</center>
<hr>
<bgsound src="c:\josh.mp3">
<a href="sample.html">
Click here for first example...</a><br>
<br>
<a href="c:\globe2.jpg">
<img src="c:\globe2.jpg" width="100px" height="100px">
</a>
<br><br>
<a href="c:\josh.mp3">
Click here to listen the music</a><br><br>
<br>
<a href="#top">
Top..</a><br>
</font>
<font face="Tahoma">
<hr>
<tr bgcolor="bisque">
<th>Student ID</th>
<th>Student Name</th>
<th>Marks</th>
</tr>
<tr>
<td>101</td>
<td>Ashok Kumar</td>
<td>78</td>
</tr>
<tr>
<td>102</td>
<td bgcolor="pink">Kiran</td>
<td>53</td>
</tr>
<tr>
<td>103</td>
<td>Kiranmayi</td>
<td>47</td>
</tr>
<tr>
<td>104</td>
<td>Joji</td>
<td>96</td>
</tr>
</table>
</font>
</body>
</html>
(Continued…)
registration.html
<html>
<head>
<title>Forms demo</title>
</head>
<body>
<form>
<center>
Student Name:
<input type="text"><br>
Age:
<input type="text" size="3"><br>
Password:
<input type="password"><br>
Confirm Password:
<input type="password"><br>
Gender:
<input type="radio" name="gen">Male
<input type="radio" name="gen">
Female<br>
Marital Status:
<input type="radio" name="mar">
Single
<input type="radio" name="mar">
Married
<input type="radio" name="mar">
Divorced<br>
Resume Attachment:
<input type="file">
Select Coursetype:
<select>
<option>Normal Track</option>
<option>Fast Track</option>
<option>Super Fast Track</option>
</select><br><br>
<hr>
<input type="submit">
<input type="reset">
<hr>
</center>
</form>
</body>
</html>
<html>
<head>
<title>any title</title>
<script language=”javascript”>
//some js code
</script>
</head>
<body>
some content
</body>
</html>
The <script> tag specifies starting and ending point of the JS code.
You can‘t write the html tags directly in the <script> tag. You can write only JS code.
registration.html
<html>
<head>
<title>Forms demo</title>
</head>
<body>
<form>
<center>
<h1>ABC Technical Training Institute</h1>
<h2>Hyderabad</h2>
<h2>Student Registration Form</h2>
<hr>
Student Name:
<input type="text"><br>
Age:
<input type="text" size="3"><br>
Password:
<input type="password"><br>
Gender:
<input type="radio" name="gen">Male
<input type="radio" name="gen">
Female<br>
Marital Status:
<input type="radio" name="mar">
Single
<input type="radio" name="mar">
Married
<input type="radio" name="mar">
Divorced<br>
Resume Attachment:
<input type="file">
<input type="button" value="Add">
<br>
Select Coursetype:
<select>
<option>Normal Track</option>
<option>Fast Track</option>
<option>Super Fast Track</option>
</select><br><br>
<hr>
<input type="submit">
<input type="reset">
<hr>
</center>
</form>
</body>
</html>
Note: At run time, in the browser, java script code will be blocked, because of some protection
features of browser. At that time, the following message will be appeared.
To activate java script code, you click on the above message, and choose ―Allow Blocked
Content‖. Click ―Yes‖ for confirmation. Then java script code will be activated.
Observation:
In the above example, when you click on ―Submit‖ button, the ―validate()‖ function will
be called automatically.
The ―validate()‖ function is a user-defined function, which contains some code for
validating the age value, whether it is in the range of 18 and 60.
Note: To understand more better about JavaScript, refer to ―HTML beginners guide‖ book, which
is attached to this material.
//implement some
server side operations
<html>
<head>
<title>Login</title>
</head>
<body bgcolor="beige">
<center>
<form name="f1" action="http://localhost/loginserver.asp"
method="post">
<h1>Login</h1><hr>
Username:
<input type="text" name="txt1"><br>
Password:
<input type="password" name="txt2"><br>
<hr>
<input type="submit">
<input type="reset">
</form>
</center>
</body>
</html>
C:\Inetpub\wwwroot\loginserver.asp
(save this file in the specified folder only, otherwise it won‘t run)
<html>
<head>
<title>Login Server</title>
</head>
<body>
<center>
<h1>
<%
'Get the values from the client page
Dim s1,s2
s1 = Request.Form("txt1")
s2 = Request.Form("txt2")
To run this application, double click on ―loginclient.html‖. Enter the user name and
password.
If you enter the correct user name and password (system and manager), it opens the
server page and shows ―You are successfully Logged in…‖ message, otherwise it shows
―Invalid Username / Password‖ message.
In the client page, you have to design a html form compulsory. In that <form> tag, you
have to give the address of the server page, to which it is to be submitted.
Syn: http:/servername/pagename.asp
When you click on ―Submit‖ button, the server page will be opened, based on the given
URL.
At the time of submission, the parameter values (username and password) will be sent to
the server page.
In the server page (loginserver.asp) code, the ―Dim‖ statement (Dim stands for
Dimension) declares two variables for storing user name and password.
After that we retrieve the values from the client page using the control‘s names (txt1 and
txt2).
Then we check the values whether those are correct or not, using If statement.
Then we give the response message to the client using ―Response.Write()‖ statement.
Note: This much knowledge on ASP 3.0 is enough, before entering into ASP.NET.
IIS
Web Site
port
Finally, ASP is supported in IIS only; and ASP.NET is supported in IIS and ASP.NET
Development Server also.
If you find the above type of screen, then you can understand as IIS is working on your
system.
If you find the following error page, then you can understand as IIS is not working
properly on your system (or) IIS is not installed on your system.
If you want to stop the services, you can do so, by right clicking on the ―Default Web
Site‖ option, and by clicking on ―Stop‖.
So now you can understand that the part of the URL, http://myserver represents
―wwwroot‖ folder in the ―myserver‖ computer.
To have accessibility for client pages and server pages from the client computers, we
have to store both these types of pages in the ―wwwroot‖ folder only.
Requirements of ASP.NET:
Web Page Designing Language: HTML
Client Side Scripting Language: JavaScript
Programming Language: C#.NET / VB.NET
Web Server: IIS / ASP.NET Development Server
//implement some
server side operations
Form
Submit
Postback
Automatic Generation of Designer Code: While you are designing the web pages in
ASP.NET, it generates the necessary tags automatically. So don‘t require to type tags
manually.
Post-backing: This feature reduces no. of web pages in your web site. Because of this
feature, you can write the application logic just like the windows applications. That
means you can implement the necessary events at server side.
Master Pages: To avoid the repetition of designing the common content among
multiple pages.
Data Controls: To display the database data better with / without the writing the code
manually.
Validation Controls: Avoids the usage of ―JavaScript‖ for implementing the validations.
Login Controls: To implement the common login / logout features, without writing any
code.
Crystal Reports: There is no other server side programming language, which supports
―Crystal reports‖ in the web sites.
Themes and Skins: To have uniformity in the controls, designed in all the web pages;
and finally to make the web page as a good looking page.
Support of Multiple Cultures: You can display the contents of the web pages, in
different regional languages like English / French / Arabic / Telugu / Tamil etc.
Security: It supports several security models like Windows based security, Forms based
security, Passport based security, Role based security etc.
Caching: To store the output of the page temporarily in the cache memory, and make
the web site to be executed faster.
Multiple Languages: You can write the functionality related code in any of the .NET
languages (Visual C#.NET or Visual Basic.NET), that you want.
WebParts: To personalize the web site, for every user. The user can modify the page
contents right from the browser.
AJAX: To make the web site executed faster, and to attract the user with better
functionality.
Web Services: To implement some interaction between one web site to another web
site.
The next thing is you have to add the web pages to your web site.
Note: In ASP.NET Web Sites, we use ―Server Pages‖ (Web Forms) only; Very rarely only
we use HTML pages; because in the server page, we can implement html code, JavaScript
and also some server side concepts.
3. Split View: It shows the design view and source view at-a-time; so that you can
observe modify the content easier.
So, we are maintaining two inter-linked for every page, as above (one is for
designing purpose and other one is for programming purpose). This type of maintenance is called
as “Code behind Technique”. This model is the comfortable and recommend model to avoid
clumsiness of the code; because if you write the design code and programming code within a
single file, it may not be understandable clearly and the code will be lengthy. In the earlier
versions of ASP.NET, they have introduced another technique called “In-page technique”.
According that ―In-page technique‖, we maintain the designer code and programmer
code within a single file (.aspx file). This is not recommend. Anyway, we can implement that
technique also now, just for having an idea.
Click on ―Add‖.
Click on ―Design‖ view.
Drag and drop a button control.
Double click on that and see where the Button1_Click event will be generated.
It will be generated in the ―.aspx‖ file only, instead of ―.aspx.cs‖ file.
For ASP.NET web page, the following objects are commonly available. That means, you
don‘t require creating these objects.
1) Request:
3) Session:
4) Application:
Whenever the client sends a request (opens the web page), the following life cycle will
be executed at server side.
Client Server
filename.aspx
(class)
Browser
Create an object
Initialize
Render
Unload
Ex:
Event Description
Default.aspx.cs
The above is not offered by HTML; it‘s offered by ASP.NET; so that it can be called as
―ASP.NET Server side tag‖.
Next, you drag a button control from ―HTML‖ category. It generates the following tag.
<input id="Button1" type="button" value="button" />
The above is offered by HTML; so that it can be called as ―HTML Client side tag‖.
The next thing is, you just double click the server button. It generates the
―button1_click‖ event in the C# syntax. There, you can write the server side code.
protected void Button1_Click(object sender, EventArgs e)
{
After that, you just double click the client button. It generates the ―button2_onclick‖
event in the JavaScript syntax. There, you can write the client side code only using
JavaScript.
<script language="javascript" type="text/javascript">
function Button2_onclick()
{
}
</script>
Note: Drag the ―Server button‖ from ―Standard‖ category; and ―Client button‖ from ―HTML‖
category.
Default.aspx.cs
Default.aspx
When you click the server button, it shows the output on the page as shown in the above
screen.
When you click the client button, it shows the output message in the dialog box.
One more difference you need to observe in this case. When you click the server button,
the page will be ―posted-back‖. Then you can observe a progress bar displayed in the
status bar in the browser. But when you click the client button, the page will not be
posted-back; simply the JavaScript code will be executed at the client side.
PostBack: The page will be submitted to itself. As a part of this, the page will be closed
and re-opened.
IMP Note: You can‘t access the client controls in server code.
For example, you try to do like this. Take a new web site and a web page; Drag and drop
―Text‖ control from ―HTML‖ category. Its name will be ―Text1‖.
Then drag a server side Button control from ―Standard‖ category.
Next, you try to write the following code in ―Button1_Click‖ event.
Text1.Value = DateTime.Now.ToString();
That above statement can‘t be accepted, because basically ―Text1‖ is the HTML control.
But there is a provision to access the HTML controls in the server code also.
To do this, open the page in ―Source‖ view, and add runat=”server” attribute in the
<input> tag. Then the code looks like this:
<input id="Text1" type="text" runat="server" />
Then above code will work. In fact, when you write the runat=‖server‖ attribute for the
<input> tag, even though the textbox is a HTML control, it is identified and accessible in
the server code. This type of special HTML controls are called as “HTML Server
Controls”.
Finally, the application looks like this:
Note: Drag the ―Text1‖ control from ―HTML‖ category; and ―Button‖ from ―Standard‖ category.
v. Login Controls:
It includes with some controls, which implement login / logout related concepts,
without writing any code.
Properties of Button
Property Description
ID Specifies the name of the control.
Text Specifies the visible text of the control.
BackColor Specifies the background color.
ForeColor Specifies the foreground color.
Font Specifies the font settings like font name, bold, italic, size etc.
BorderWidth Specifies the border size in the form of pixels.
Specifies the style of the border. (None / Dotted / Dashed / Solid /
BorderStyle
Double / Groove / Ridge / Inset / Outset)
BorderColor Specifies the color of the border.
Width Specifies the width (in pixels).
Height Specifies the height (in pixels).
Specifies the tooltip message, which can be displayed whenever
Tooltip
you move the mouse pointer on the control.
TabIndex Specifies the index in the tab order.
Enables / disables the control. ―True‖ means the control is enabled.
Enabled It responds for the user. ―False‖ means the control is disabled. The
control will not respond for the user.
Displays / Hides the control. ―True‖ means the control is visible
Visible (displayed on the screen). ―False‖ means the control is hidden. The
control will not be displayed on the screen.
Events of Button
Event Description
Click Executes on clicking on the control.
Properties of Label
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Events of Label
No Events.
Properties of TextBox
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Enables / Disables automatic post backing, whenever the user
AutoPostBack
performs an action that causes an event.
Specifies the maximum characters length, which can be entered in
MaxLength
the textbox.
ReadOnly Enables / Disables the read-only for the textbox.
TextMode SingleLine / MultiLine / Password
Wrap Enables / Disables automatic wrapping nature in the textbox.
Events of TextBox
Event Description
TextChanged Executes on changing the textbox text.
Properties of Image
Property Description
ID, BackColor, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip, TabIndex, Visible
ImageUrl Specifies the url of the image to be displayed.
Events of Image
No Events.
Properties of Hyperlink
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Specifies the url, which is to be opened, whenever the hyperlink is
NavigateUrl
clicked.
ImageUrl Specifies the url of the image to be displayed.
6. LinkButton: Looks like a hyperlink, and offers button functionality. That means
whenever it is clicked, ―Click()‖ event will be executed.
Properties of LinkButton
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible
Specifies the url, which is to be opened, whenever the hyperlink is
NavigateUrl
clicked.
Events of LinkButton
Event Description
Click Executes on clicking on the control.
7. ImageButton: Looks like an image control, but offers button functionality. It executes
―Click()‖ event, whenever it is clicked.
Properties of ImageButton
Property Description
ID, BackColor, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip, TabIndex, Visible
ImageUrl Specifies the url of the image to be displayed.
Events of ImageButton
Event Description
Click Executes on clicking on the control.
Properties of CheckBox
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible, AutoPostBack
Events of CheckBox
Event Description
CheckedChanged Executes on checking / un-checking the checkbox.
9. RadioButton: This is to display few options on the page. At least 2 or more radio
buttons are to be placed. The user can select any one of the radio buttons.
Properties of RadioButton
Property Description
ID, Text, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height,
Tooltip, TabIndex, Enabled, Visible, AutoPostBack
Represents the current status of the radio button, whether it is checked or
Checked
un-checked. (true / false)
TextAlign Left / Right
Used to group-up the radio buttons. You have to give same group name
GroupName
for all the radio buttons in the group.
Events of RadioButton
Event Description
CheckedChanged Executes on checking / un-checking the radio button.
Properties of CheckBoxList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.
TextAlign Left / Right
RepeatDirection Vertical / Horizontal
Events of CheckBoxList
Event Description
SelectedIndexChanged Executes on clicking on any check box in the list.
Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently checked or
Items[index].Selected
not (true / false).
11. RadioButtonList: Contains multiple radio buttons as items. It offers automatic grouping
nature of all the radio buttons, without specifying the ―GroupName‖ property.
Properties of RadioButtonList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.
TextAlign Left / Right
RepeatDirection Vertical / Horizontal
Events of RadioButtonList
Event Description
SelectedIndexChanged Executes on clicking on any radio button in the list.
Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently checked or
Items[index].Selected
not (true / false).
12. ListBox: Displays multiple items as options, so that the user can select any one (or
more) items.
Properties of ListBox
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Events of ListBox
Event Description
SelectedIndexChanged Executes on clicking on any item in the list.
Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently selected or
Items[index].Selected
not (true / false).
13. DropDownList: Displays multiple items as options, so that the user can select any one
of the items. It is same as ―Combo box‖ in windows applications.
Properties of DropDownList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, AutoPostBack
Items Specifies the list of items, which is to be displayed in the control.
Events of DropDownList
Event Description
SelectedIndexChanged Executes on clicking on any item in the drop down.
Property Description
SelectedIndex Represents index of the currently selected item.
SelectedItem.Text Represents index of the currently selected item.
Items.Count Represents total count of the items.
Items[index].Text Represents the text value of the item, based on given index.
Gets the status of the given item, whether currently selected or
Items[index].Selected
not (true / false).
Properties of Table
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Specifies the collection or rows, which are to be displayed in the table. It
contains the inner property called ―Cells‖, which specifies the cells
collection. First, click on ―Rows‖ property. There, add the required no. of
Rows
rows. Then select the required to row and click on ―Cells‖ option to add the
cells to the selected row. There, add the required no. of cells. Specify the
actual cell text, in the ―Text‖ property.
BackImageUrl Specifies the background image path.
Caption Specifies a title for the table.
Specifies the position of the caption in the table. (Top / Bottom / Left /
CaptionAlign
Bottom)
GridLines None / Horizontal / Vertical / Both
HorizontalAlign Left / Center / Right / Justify
Events of Table
No Events
15. Literal: Displays the output of given html code. It supports all the html tags.
Properties of Literal
Property Description
ID, Text, Visible
Events of Literal
No Events
16. Calendar: Displays a calendar. The user can switch to previous / next month.
Properties of Calendar
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
SelectedDate Specifies the currently selected date in the calendar control.
Caption Specifies a title for the calendar.
Specifies the position of the caption in the control. (Left / Right / Top /
CaptionAlign
Bottom)
ShowGridLines Enables / disables the grid lines.
Event Description
SelectionChanged Executes on selecting any date in the calendar.
Property Description
SelectedDate Represents currently selected date value in the calendar.
Note: ―AutoFormat‖ option is available for this control. To change the auto format style,
right click on the calendar control and choose ―Auto Format‖ option.
17. Panel: Acts as container for other controls. You can drag any other controls into the
panel.
Properties of Panel
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible, HorizontalAlign
Scrollbars None, Horizontal, Vertical, Both, Auto
Events of Panel
No Events
18. BulletedList: Used to display few items with bullets or numbering. It is similar to <OL>
and <UL> tags in HTML.
Properties of BulletedList
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Numbered, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman, Disc,
BulletStyle
Circle, Square, CustomImage
To specify the path of the CustomImage, to be displayed as bullet for
BulletImageUrl
every item.
Events of BulletedList
Event Description
Click Executes on clicking the control.
Properties of FileUpload
Property Description
ID, BackColor, ForeColor, Font, BorderWidth, BorderStyle, BorderColor, Width, Height, Tooltip,
TabIndex, Enabled, Visible
Methods of FileUpload
Method Description
The file will be uploaded (copied) from the original location, into
SaveAs(―destination the specified destination location, based on the given destination
file path‖) path. Generally you need to give the destination file path as server
root directory. (c:\Inetpub\wwwroot\filename.ext)
Events of FileUpload
No Events
Default.aspx
(Continued…)
Label2: TextBox2
Text: Registration Form :
Font: Century Gothic, Large Font: Arial
ForeColor: #FF3300
.NET 4.0 and Visual Studio 2010 Page 87 of 558
Label5: Label10:
Text: Password: Text: Gender:
Font: Arial Font: Arial
TextBox3: RadioButton1:
TextMode: Password Text: Male
Font: Arial GroupName: g1
Font: Arial
Label6:
Text: Confirm Password: RadioButton2:
Font: Arial Text: Female
GroupName: g1
TextBox4: Font: Arial
TextMode: Password
Font: Arial Label11:
Text: Marital Status:
Label7: Font: Arial
Text: Address:
Font: Arial RadioButtonList
1:
TextBox5: Items: Single, Married,
TextMode: Multiline Divorced
Width: 218px RepeatDirection: Horizontal
Height: 85px Font: Arial
Font: Arial
Label12:
Label8: Text: Preferable Timings:
Text: DateOfJoining Font: Arial
Font: Arial
CheckBoxList1:
Calendar1: Items: Morning, Afternoon,
AutoFormat: Colorful2 Evening
CheckBox1: RepeatDirection: Horizontal
Text: Documents Submitted? Font: Arial
Font: Arial Label13:
CheckBox2: Text: Resume Attachment:
Text: Is Already Registered? Font: Arial
AutoPostBack True CheckBox1:
: Text: Documents
Font: Arial Submitted?
Label9: Font: Arial
Text: Existing Registration FileUpload1:
Number: Font: Arial
Visible: False
Font: Arial Label14:
Text: Course Type:
TextBox6: Font: Arial
Visible: False
Font: Arial DropDownList1:
.NET 4.0 and Visual Studio 2010 Page 88 of 558
Items: Normal Track, Fast
Track, Super Fast
Track
LinkButton1: Hyperlink5:
Text: Show Duration Details Text: Contact Us
Font: Arial Font: Arial
NavigateUrl: mailto:customercare
Table1: @abcd.com
Rows: Add 4 rows and 2 cells in
each row. Type the text as LinkButton2:
shown. Text: Hide the globe
Font: Arial Font: Arial
Visible: False
Hyperlink6:
Label15: ImageUrl: globe2.jpg
Text: Course: (Copy the image into
Font: Arial the web site folder)
NavigateUrl: globe.jpg
ListBox1: (Copy the image into
Items: .NET 4.0, Java, Share the web site folder)
Point, Oracle, Sql Server,
Silver Light Panel1:
Font: Arial BackColor: #33CCFF
Button1: Label16:
Text: Submit Text: Search:
Font: Arial Font: Arial
Image1: TextBox7:
ImageUrl: earth.gif Font: Arial
(Copy the image into the
web site folder) ImageButton1:
ImageUrl: search_button.gif
Hyperlink1: (Copy the image into
Text: About Us the web site folder)
NavigateUrl: aboutus.aspx
Font: Arial Label17:
Text: (null)
Hyperlink2: Font: Arial
Text: Google Search ForeColor: #400040
NavigateUrl: http://www.google.co.in
Font: Arial Literal1:
Text: <h3><marquee
Hyperlink3: bgcolor="lightpink">A
Text: Click to listen audio ll Rights Reserved.
NavigateUrl: josh.mp3 Copy Right ©
(Copy the audio file into 2010</marquee></h
the web site folder) 3>
Font: Arial
Hyperlink4:
Text: Click to view video
NavigateUrl: SilverJubilee.wmv
(Copy the video file into
.NET 4.0 and Visual Studio
the web site folder)2010 Page 89 of 558
Font: Arial
Default.aspx.cs
preferrable_timings = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
preferrable_timings = preferrable_timings + CheckBoxList1.Items[i].Text + ", ";
}
resume_file = FileUpload1.FileName;
coursetype = DropDownList1.SelectedItem.Text;
course = ListBox1.SelectedItem.Text;
string outputmsg = "<h1>Your data has been submitted successfully! The submitted
data is:</h1><h2>";
Response.Write(outputmsg);
}
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
Label9.Visible = true;
TextBox6.Visible = true;
TextBox6.Focus();
}
else
{
Label9.Visible = false;
TextBox6.Visible = false;
}
}
In the previous example, you may feel like, the ―the alignment of controls‖ was not good.
Yes, we have not concentrated on making the controls alignment good there.
Now, concentrate on that.
You can maintain the controls positions better, in two ways:
1. With HTML Tables
2. With Absolution Positioning
You don‘t require to write the code for ―Step1‖, ―Step 2‖ link buttons and ―Previous‖,
―Finish‖ buttons.
The only thing is, you need to design the contents, directly in the required step.
This is control features ―Auto Format‖ option also.
Steps:
First, drag and drop the ―Wizard‖ control into the page.
Click on ―OK‖.
Then the screen looks like this:
Second Step:
Third Step:
Final Step:
Then double click on ―Add‖ button and ―Multiply‖ button, and write the following code.
Steps:
First, you need to collect the ad images. Just for practice purpose, you can download the
ads from internet (from various web sites).
Then take a new web site.
Open Solution Explorer. Right click on the web site and choose ―New Folder‖.
In the above syntax, <?xml version="1.0"?> tag is called as XML prologue, which
specifies that, the current document is a XML document and it also specifies about the
XML version, that we are using currently. The current XML version is 1.0.
The <Advertisements> tag is called as root element, which specifies starting point and
closing point the advertisement descriptions. The ―xmlns‖ specifies the XML schema file
reference. A XML schema decides or describes what tags can be written in an ―.xml‖ file.
Next, each ad is to be described in individual <Ad> tags. So that, you can write multiple
<Ad> tags. Each <Ad> tag may contain the following inner elements.
1. <ImageUrl>: Specifies the path and file name of the image file, which is to be
displayed at run time.
Note: In the above code, the tilde character ―~‖ represents the current working web site
path. For example, your web site is stored in the ―c:\Inetpub\wwwroot‖ folder. Your web
site name is ―WebSite1‖. Then the current directory (c:\Inetpub\wwwroot\WebSite1) can
be represented as ―~‖ character.
The next thing is, you take a new web page and drag and drop the ―AdRotator‖ control.
Select the following property for the ―AdRotator1‖ control.
AdvertisementFile: ~/ads.xml
The design some other controls that you need as follows:
Click on ―Save‖ button to save the table. Then it asks for the table name. Enter
the desired table name.
2. DROP
drop table tablename;
3. ALTER
alter table tablename add columnname datatype(width);
alter table tablename drop column columnname;
DML:
1. SELECT
select * from tablename;
select column1, column2, .. from tablename;
select * from tablename where condition;
select column1, column2, … from tablename where condition;
2. INSERT
insert into tablename values(value1, value2,…);
3. DELETE
delete from tablename;
delete from tablename where condition;
4. UPDATE
update tablename set column1=value1, column2=value2;
update tablename set column1=value1, column2=value2 where
condition;
use master
drop database test
GO
use test
GO
select * from Products where price not between 2000 and 8000
Functions:
create function functionname(@variable datatype(width),…)
returns returndatatype
as begin
declare @variable datatype(width)
…….
…….
return returnvalue
end
Note: The procedure can’t return any value; and a function should return any value. For every
variable in T-SQL, we have to prefix “@” symbol without fail.
Procedure:
GO
execute ShowSquare 5
Function:
GO
select dbo.GetCube(5)
Note: Here, the driver acts as mediator between the frontend application and backend
databases. The driver can also be called as ―Provider‖. This provider may be released by Backend
Company or Frontend Company.
Note: Just for separation of the individual values, we are using ―;‖.
ADO.NET Library
To perform above mentioned database operations, ADO.NET technology offers some pre-
defined classes, organized in the form of namespaces.
Library: System.Data
DataSet
DataTable
DataRow
DataColumn
SqlClient OleDb
SqlConnection OleDbConnection
SqlCommand OleDbCommand
SqlDataReader OleDbDataReader
SqlDataAdapter OleDbDataAdapter
SqlParameter OleDbParameter
ADO.NET NameSpaces:
1) System.Data
Contains necessary classes and namespaces to manipulate the databases.
2) System.Data.SqlClient
Contains necessary classes, used to interact with the SQL Server database.
3) System.Data.OleDb
Contains necessary classes, used to interact with any other databases. Of course,
the OleDb namespace also supports to connect with SQL server database, but
we won‘t use it for SQL Server, because ―SqlClient‖ namespace is especially
available for that.
1) Connection:
Maintains the connection with the database.
2) Command:
Executes a query statement (select statement), non-query statement (insert
statement / delete statement / update statement) or a stored procedure /
function at backend.
3) DataReader:
It acts as a buffer, which holds the data, after execution of a query statement at
backend.
4) DataAdapter:
Executes a query statement at backend.
5) Parameter:
Sends a parameter (argument) value to a backend stored procedure / function.
6) DataSet:
Acts as a buffer, which holds multiple tables at-a-time.
7) DataTable:
Acts as a buffer, which holds a single table (collection of rows and columns).
8) DataRow:
Acts as a buffer, which holds a single row.
9) DataColumn:
Acts as a buffer, which holds a single column.
Note: All of above are the classes; you need to create object(s) for those classes.
Connection
ConnectionStrin
g
Open()
Close()
ConnectionString: This property contains the connection string, used for the
connection.
Open(): This method opens the database connection.
Close(): This method disconnects the database connection.
1) Insertion Command:
To insert a new row into the table.
SQL statement: insert into tablename values(value1, value2,…)
2) Deletion Command:
To delete one or more rows from the table.
SQL statement: delete from tablename where condition
3) Updation Command:
To update (modify) the table data.
SQL statement: update tablename set column1=value1, column2=value2
where condition
4) Select Command:
To retrieve the data from the database table, into the frontend application.
SQL statement: select * from tablename
Connection Command
ConnectionStrin CommandText
g Connection
Open() CommandType
Close() Parameters
ExecuteNonQuery()
ExecuteReader()
c) CommandType: This property specifies the type of the command that you want
to execute. It is of two types:
Text: (default) This is used for any SQL statement (insertion statement /
deletion statement / updation statement / select statement)
StoredProcedure: This is used for Stored Procedure / Function only.
Insertion.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(5,'Arun','Male',8000)";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
cn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
//Connection impl
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial
catalog=demo";
cn.Open();
string gen;
if (RadioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into customers values(" + TextBox1.Text + ", ' " +
TextBox2.Text + " ' , ' " + gen + " ' , " + TextBox3.Text + ")";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
//presentation logic
if (n > 0)
Label8.Text = n + " Row Inserted.";
else
Label8.Text = "Insertion failed.";
cn.Close();
}
Note: While you are preparing the CommandText with user-entered values, to remember the
concatenation syntax in the above example, remember the following syntax:
Deletion.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "delete from customers where customerid=" + TextBox1.Text
+ " ";
cmd.Connection = cn;
int n = cmd.ExecuteNonQuery();
//presentation logic
if (n > 0)
Label3.Text = n + " Row Deleted.";
else
Label3.Text = "Deletion failed.";
cn.Close();
}
Updation.aspx.cs
using System.Data.SqlClient;
string gen;
if (RadioButton1.Checked == true)
gen = "Male";
else
gen = "Female";
//presentation logic
if (n > 0)
Label6.Text = n + " Row Updated.";
else
Label6.Text = "Updation failed.";
cn.Close();
}
Connection
.NET
Application
Note: Here, to execute the select statement, you have to use ―ExecuteReader()‖ method of
command class. After execution of the statement, it returns the entire data, i.e. retrieved from
the database, in the form of ―DataReader‖ class object. So that we have to receive it into an
instance of ―DataReader‖ class.
Connection
ConnectionStrin
g
Open()
Close()
Command
CommandText
Connection
CommandType
Parameters
ExecuteNonQuery()
ExecuteReader()
DataReader
Read()
[“column name”]
[index]
Close()
a) Read(): This method moves the record pointer, to the next record. For the first
time call of this method, the record pointer point-outs the first record. After that,
for every call it jumps to next record. If the next record is found, then it returns
―true‖; if the next record is not found, that means whenever it is reached end of
the data, then it returns ―False‖.
Ex:
dr.Read();
(true)
(true)
dr.Read();
(true)
dr.Read();
(true)
dr.Read();
(false)
c) [index]: This indexer gets the value, at the specified column index, in the
current row, which is currently pointed-out by the record pointer. The column
index always starts from ―0‖.
d) Close(): This method closes the buffer. At the end of your code, you can close
it.
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as
―DataReaderDemo.aspx‖. Click on ―Add‖.
Properties of ―HyperLink5‖:
Text: View Data using Data Reader
NavigateUrl: ~/DataReaderDemo.aspx
DataReaderDemo.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();
dr.Close();
cn.Close();
}
Sometimes, you may need to display the records based on the user-entered value. For
example, when the user enters the customer id, then you need to display the respective
customer details. We take a demonstration like that:
Add the hyperlink called ―View Data using Data Reader – Conditional Data‖ as shown
below:
DataReaderDemo_ConditionalData.aspx.cs
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select customername,gender,amount from customers where
customerid=" + TextBox1.Text + " ";
cmd.Connection = cn;
//DataReader impl
SqlDataReader dr;
dr = cmd.ExecuteReader();
dr.Close();
cn.Close();
}
Library:
Connection: Maintains the connection with database.
DataAdapter: Sends a sql statement and executes it at backend. It‘s just like Command
class, in the connection oriented model. The difference between Command class and
DataAdapter class is, the ―Command‖ class is used to execute any type of statement
(insert statement, delete statement, update statement and select statement). But
adapter executes select statement only.
The ―DataReader‖ works only when the connection is closed. But the ―DataTable‖ works
even though the database is disconnected.
The ―DataReader‖ buffer supports record travelling only once in its lifetime. But the
―DataTable‖ buffer supports record travelling any no. of times in its life time.
The ―DataReader‖ buffer supports only forward record travelling. It doesn‘t supports
backward or random record travels. But ―DataTable‖ supports forward, backward and
random record travels.
―DataReader‖ supports sequential records travels only. It doesn‘t supports to pick-up a
record directly with its index. But ―DataTable‖ supports to pick-up a record directly with
its index.
―DataReader‖ supports only column indexing. ―DataTable‖ supports both column and row
indexing.
―DataReader‖ data can‘t be assigned to ―DataGridView‖ control. But the ―DataTable‖ data
can be assigned to the ―DataGridView‖ control.
Connection
DataSet
DataTable
0
1
2
3
.NET DataRow
Application 0 1 2
Connection
ConnectionString
Open()
Close()
DataAdapter
DataAdapter(“select statement”,
connection_object)
Fill(dataset_object)
DataSet
Tables[table_index]
Clear()
DataTable
Rows.Count
Rows[row_index]
Columns.Count
Columns[column_index]
DataRow
[column_index]
[“column name”]
Clear(): Clears all the tables, and makes the dataset empty.
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the page name as
―DataSetDemo.aspx‖. Click on ―Add‖.
Properties of ―HyperLink7‖:
Text: View Data using Data Set
NavigateUrl: ~/DataSetDemo.aspx
DataSetDemo.aspx.cs
using System.Data;
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from customers";
cmd.Connection = cn;
dr.Close();
cn.Close();
}
Sometimes, you may need to display the records one-by-one in flexible manner, depending on
the clicked buttons like ―First‖, ―Previous‖, ―Next‖, ―Last‖. We take a demonstration like that:
Add the hyperlink called ―View Data using Data Set – Flexible Records Presentation‖ as
shown below:
DataSetDemo_FlexibleRecords.aspx.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//DataTable impl
dt = ds.Tables[0];
if (Page.IsPostBack == false)
{
//display first record
RowIndex = 0;
Display();
}
Label6.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
//display first record
RowIndex = 0;
Display();
}
protected void Button2_Click(object sender, EventArgs e)
{
//display previous record
RowIndex--;
Using with the DataTable buffer, it is possible to display the data in the ―GridView‖ control (or
in any other ―Data Controls‖). In other words, the dataset data can be assigned into ―GridView‖
control programmatically. The ―GridView‖ control is one of the major famous controls, which
displays the data in a table format. It is easy to use it. To assign the data into this ―GridView‖
control, write the following statement:
GridView1.DataSource = datatable_obj;
GridView1.DataBind();
Here, the ―DataBind()‖ method displays the data on the screen. By default, when you assign the
―DataSource‖ property, that source of the data only be applied. But the data will not be displayed
on the screen. When you call the DataBind() method, then only the data will be rendered on the
output.
Add the hyperlink called ―View Data using Data Set - GridView‖ as shown below:
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the form name as
―DataSetDemo_GridView.aspx‖. Click on ―Add‖.
Properties of ―HyperLink9‖:
Text: View Data using Data Reader
NavigateUrl: ~/DataSetDemo_GridView.aspx
[Drag and drop the ―GridView‖ control from the ―Data‖ category at the toolbox].
DataSetDemo_DataGridView.aspx.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//DataTable impl
DataTable dt;
dt = ds.Tables[0];
//grid logic
GridView1.DataSource = dt;
GridView1.DataBind();
}
For example, in your project you want to perform 2 insertions, 3 deletions at various
tables. If you implement the code with previous concepts, you require large code and moreover
at run time 5 database calls will be sent. That means the execution flow goes to the backend,
executes one statement and comes back. For all of these, it takes much time. So the application
will be executed slower. If the application is running multiple client systems simultaneously, it will
be slower. It that time, this ―Stored Procedure Calling‖ concept is recommended. As an
advantage of this, those 5 transactions would be performed with a single database call.
Connection
Command
(provider, data (procedure / .NET
db Source, user id, function name,
parameters) Application
password)
Demo:
StoredProcedureDemo.aspx.cs
using System.Data;
using System.Data.SqlClient;
//Command impl
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "calculategrades";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
cn.Close();
}
Click on ―WebSite‖ menu – ―Add New Item‖. Enter the page name as
―StoredProcedureDemo_MultipleTables.aspx‖. Click on ―Add‖.
Properties of ―HyperLink11‖:
Text: Stored Procedure Demo – Multiple Tables
NavigateUrl: ~/StoredProcedureDemo_MultipleTables.aspx
StoredProcedureDemo_MultipleTables.aspx.cs
using System.Data;
using System.Data.SqlClient;
//DataAdapter impl
SqlDataAdapter adp = new SqlDataAdapter("getdata", cn);
//DataSet impl
DataSet ds = new DataSet();
adp.Fill(ds);
//grid logic
GridView1.DataSource = dt1;
GridView1.DataBind();
GridView2.DataSource = dt2;
GridView2.DataBind();
}
These controls are used to display the database data in various formats.
Instead of using the regular standard controls like labels, textboxes etc., it is better to
use these ―Data controls‖. For example, we have already used a data control called
―GridView‖, which presents the data in a table format.
In this way, we have to discuss about other data controls also.
The following are all the important data controls in ASP.NET 4.0:
AccessDataSource
SqlDataSource
GridView
DetailsView
FormView
ListView
Chart
One more thing that you need to remember that, these controls supports the database
connections in two models:
1. Programming Model:
We have to write all the code for database connections, for retrieving the
data from the database and for performing insertions, deletions,
updations etc., just like we have implemented the code in the previous
ADO.NET examples.
It takes much time.
But it is better to perform any type of database manipulations.
2. Non-Programming Model
We don‘t need to write any code for database connections, retrievals,
insertions etc.; simply we have drag and drop the ―data source‖ controls
such as AccessDataSource, SqlDataSource etc., and we have to
configure those controls properly. These data source controls can
interact with the database and can serve the data to the other data
controls like GridView, DetailsView etc.
Click on OK.
Then type the table structure as follows:
Of course, you can do something, whenever the ―Select‖ button is clicked. You have to
write some code for that.
To do so, double click on the GridView control. Then it generates
―SelectedIndexChanged‖ event. That event will be executed automatically, whenever the
user selects any row, by clicking on ―Select‖ link button at run time.
For a demonstration, drag one Label control (below the grid control) and write the
following code:
In this way, you are able to implement ―Paging‖, ―Sorting‖, ―Editing‖, ―Deleting‖ and
―Selection‖ features in the GridView control. But ―Insertion‖ feature is not supported in
this control. But insertion feature is also available in other controls like ―DetailsView‖,
―FormView‖ etc.
Note: Remember that all the above practiced concepts are supported in any other databases
also, like Access, Oracle etc.; not only for SQL Server.
Now, the DetailsView and FormView controls are looking almost all same.
But you can change the design of FormView control. To do so, click on ―>‖ button and
choose ―Edit Templates‖ option.
Then the control looks like this:
Now, let us use the ―Chart‖ control. This ―Chart‖ control is introduced in ASP.NET 2010
version. It‘s not available in the older versions.
In this way, we can display the same data in various models, using different data
controls.
Ex:
Server name: classroom
User ID:sa
Password: 123
Database: sample
Click on ―Finish‖.
Then the ―OLE DB (ADO)‖ dialog box will be closed and the focus will be come back to
―Standard Report Creation Wizard‖ dialog box. And now, the ―OLE DB (ADO)‖ option
will be expanded.Expand the database name and select the table name, which you
want. (Ex: students).
Click on ―>‖ button to add the selected table into the right side list.
Click on ―Next‖.
Expand the table name. Then the list of columns will be displayed.
Now you have to add the require column(s), into the right side list, which you want to
display in the crystal report.
To change any font / border / alignment / colors / paragraph of the objects, right click
on the require object and choose the ―Format Object‖ option.
To add new objects, right click on the empty area and choose ―Insert‖, where you can
select ―Special Field‖ / ―Text Object‖ / ―Summary‖ / ―Line‖ / ―Box‖ / ―Chart‖ /
There, select the ―studentsreport.rpt‖ file from the drop down list.
Enter the password as ―123‖ (or the password according to your system) and click on ―Log on‖.
The validation controls are meant for performing client side validations.
Def of Validation: The ―Validation‖ is a process, that checks the user input values,
whether those are correct or not. According to this, whenever the user clicks on ―submit‖
button on the client system, the user-input values will be validated first. If all of those
values are valid, then the page will be submitted to the web server. Otherwise, an error
message will be displayed to the user and the page will not be submitted to the web
server.
Advantage of Validation: As an advantage of validation, invalid values containing
pages would not be submitted to the web server. So that we can avoid the stress on web
server.
In older days, the client side validations are performed by using the code written in ―java
script‖ language. But in newer age of web development like ASP.NET, validation controls
are introduced to replace the role of ―java script validations‖.
Advantage of Validation Controls: Validation controls are very much easy to use. You
don‘t require to write even single line of code also to use them. So that we can avoid
―java script‖ usage. In order to perform different kinds of validations, ASP.NET offers
different types of validation controls.
Functionality of Validation Controls: A validation control performs a particular type
of validation on input / selection based controls like textbox, checkbox, checkboxlist,
radiobuttonlist, listbox, dropdownlist etc. At run time, whenever the user clicks on
―Submit‖ button it validates the particular control. If the given value is valid, it allows the
page to be submitted. Otherwise, it stops the submition of the page and displays an error
message on the page. By default, its forecolor is set to ―red‖.
1. RequiredFieldValidator: Checks for the value entry in a particular control, and makes
it as mandatory control. That means the user should enter the value in the specified
field. Otherwise, it stops the submition of the page to the server.
Properties of RequiredFieldValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
Properties of RangeValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
Properties of RegularExpressionValidator
Property Description
Contains the reference of the control (textbox, checkbox,
ControlToValidate
radiobutton etc.), that is be validated.
Contains the message, which is to be appeared automatically, on
ErrorMessage
entering the invalid value.
true / false. Whenever it is true, the focus will be moved to that
SetFocusOnError
control, whenever the invalid value is found.
ValidationExpression Specifies the format, to be checked.
Design regExpValidatoryEMail
ControlToValidate: txtEMail
lblValidationDemo ErrorMessage: Enter a Valid E-Mail address.
lblName ValidationExpression: Internet e-mail address.
txtName lblCourse
ReqValidatorName rbListCourse
ControlToValidate: txtName Items: C, C++, Java, .NET
ErrorMessage: Please enter any name. reqValidatorCourse
SetFocusOnError: true ControlToValidate: rbListCourse
lblAge ErrorMessage: Select any course.
txtAge lblCity
rngValidatoryAge txtCity
ControlToValidate: txtAge comValidatorCity
ErrorMessage: Age should be between 18 ControlToValidate: txtCity
and 60. ErrorMessage: “Vijayawada” is not allowed.
MinimumValue: 18 ValueToCompare: Vijayawada
MaximumValue: 60 Type: String
Type: Integer Operator: NotEqual
lblPhone lblPassword
txtPhone txtPassword
regExpValidatorPhone TextMode: Password
ControlToValidate: txtPhone
ErrorMessage: Enter a Valid Phone
Number.
ValidationExpression: U.S. Phone Number
lblEMail
txtEMail
Default.aspx
success.aspx
Then click on ―>‖ button and select ―Edit Menu Items‖ option.
Then it displays Menu Item Editor dialog box.
To add the child items, you have to use second ―+‖ symbol, which is called ―Add a child
item‖.
For example, click on ―Products‖ and click on ―Add a child item‖ option. Then it creates a
child item inside of ―Products‖ item. Specify the following properties:
1. Text: Consumer Products
2. NavigateUrl: ConsumerProducts.aspx
Again, select ―Products‖ item and click on ―Add a child item‖ option. Specify the following
properties:
1. Text: Home Appliances
2. NavigateUrl: HomeAppliances.aspx
Then select ―Services‖ item and click on ―Add a child item‖ option. Specify the following
properties:
1. Text: Prepaid
At run time, the ―LoginName‖ control displays the currently logged-in user name
automatically.
Run the web site and test it.
Next, If you want to offer ―Change Password‖ option in your site, add a hyperlink into the
―mainpage.aspx‖ and set the following properties:
1. Text: Change Password
2. NavigateUrl: changepassword.aspx
Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―changepassword.aspx‖ – Click on Add.
Drag and drop the ―ChangePassword‖ control from the toolbox.
Set the following properties for the ―ChangePassword1‖ control:
1. ContinueDestinationPageUrl: mainpage.aspx
Click on Finish.
Then it will be added to the existing domains list.
The WebParts controls allow the user to change the web page content dynamically at run
time, though the browser.
This is a concept of personalization, which remembers your settings automatically, based
your login information (username and password). If you run the web site later (after few
days or months also), the same settings will be loaded.
Important WebParts Controls:
1. WebPartManager
2. WebPartZone
Default.aspx.css
using System.Web.UI.WebControls.WebParts;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 0)
WebPartManager1.DisplayMode = WebPartManager.BrowseDisplayMode;
else
WebPartManager1.DisplayMode = WebPartManager.DesignDisplayMode;
}
The query string is the string attached to URL, which is displayed in the browser‘s
address bar. The query string starts with ―?‖ symbol.
When you want to pass one or more values from one page to another page as
arguments, you can send them with the ―Query String‖, in the following format.
Syn: http://localhost:portno/WebSiteName/WebPage.aspx?parameter=value
Ex: http://localhost:portno/WebSiteName/WebPage.aspx?n=100
When you want to pass multiple values with the query string, use the following format:
Syn: http://localhost:portno/WebSiteName/WebPage.aspx?parameter1=value1&
parameter2=value2
To get the parameter value in the next page, use this syntax:
Syn: Request.Params[―parameter name‖]
Ex: Request.Params[―n‖]
The above syntax gets the value of the given parameter, in string format.
display1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Params["uname"];
Label1.Text = "Welcome, " + s;
}
No security is available, because the argument names and values will be displayed in the
browser‘s title bar. You can‘t pass the values in hidden mode.
The values can be sent from one page to another page only. But, the values can‘t be
retrieved from other pages, forwarded from the second page.
You can share only string values or numerical values among multiple pages. Of course,
even though you pass the numerical values, it treats the value as a string value only.
Anyhow, you can‘t pass ―objects”.
Note: To overcome the above first two limitations, ―Cookies‖ concept is introduced.
Cookies
A cookie can be used to share values among two or multiple web pages.
Cookies are stored at client system only.
A cookie will be created as a text file in the ―c:\Documents And
Settings\Username\Cookies‖ folder on the client system. These files will be created
dynamically at run time.
When compared with ―Query String‖, the advantage of cookies is, it doesn‘t display the
values in the address bar. The value can be passed in hidden mode.
Another advantage of ―Cookies‖ is, cookies alive among multiple web pages, not only
between one page to another page. That means you can access the values stored in the
cookies from any other pages, navigated from the current page.
According to the OOP standards in ASP.NET, every cookie is an object for a pre-defined
class called ―HttpCookie‖.
Demo:
display2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Cookies["uname"].Value;
Label1.Text = "Welcome, " + s;
}
Finally, now-a-days, cookies are out-dated. To overcome the limitations of cookies, we use
―Sessions‖.
Implementation:
A. Assign value to the Session:
Session[―name‖] = value;
Demo:
Default.aspx.cs
protected void Button3_Click(object sender, EventArgs e)
{
Session["uname"] = TextBox1.Text;
Response.Redirect("display3.aspx");
}
display3.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Session["uname"]);
Label1.Text = "Welcome, " + s;
}
Application State
Another state available in ASP.NET is ―Application‖ state. Similar to ―Session state‖, the
―Application state‖ holds the data values or objects among multiple web pages in the
web site.
Similar to ―Session state‖, the ―Application state‖ also will be stored at web server. It
offers much security.
The only difference between ―Session‖ and ―Application‖ states is: ―The Session state
data will be lost automatically whenever the browser is closed. But the Application state
data will not be lost even after the browser is closed. It will remain until you stop the
web server‖.
In other words, the session is limited to single client. Individual sessions are created for
every client. But for all the clients, ―Application‖ state is accessible.
Conclusion: When you want to store any data value, that is related one user, you
prefer to use ―Session‖ state. Whenever your data value is to be accessible from other
users also, then you prefer ―Application‖ state.
Implementation:
A. Assign value to the Application:
Application[―name‖] = value;
Demo:
Default.aspx.cs
protected void Button4_Click(object sender, EventArgs e)
{
Application["uname"] = TextBox1.Text;
Response.Redirect("display4.aspx");
}
display4.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Application["uname"]);
Label1.Text = "Welcome, " + s;
}
Demo
Open the previous demo web site.
Add ―viewstatedemo.aspx‖ page and design it as shown.
Demo
Open the previous demo web site.
Open Solution Explorer. Right click on the web site name and click on ―Add New Item‖ –
select ―Global Application Class‖ – Click on ―Add‖.
It generates the following events automatically.
Global.asax
<%@ Application Language="C#" %>
<script runat="server">
</script>
usercountpage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
int n = Convert.ToInt32(Application["usercount"]);
Label1.Text = "This web site is viewed by " + n + " users.";
}
errortestpage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
int[] a = { 10, 20, 30, 40 };
int x = a[5];
Response.Write(x);
}
Open Solution Explorer; Right click on ―errortestpage.aspx‖ and select ―View in Browser‖.
CSS
(Cascading Style Sheets)
This is to overcome the limitations of HTML and also to apply common style among
several controls on the same or different web pages.
This can also be called as ―DHTML‖ (Dynamic Hypertext Markup Language).
DHTML offers better designing features, which are not supported by classic HTML.
This also used to implement common design styles among different types of controls.
It contains no new tags. It contains several attributes for better designing.
In fact, CSS is not only related to ASP.NET. It is the generalized web page designing
concept, which is available in PHP and J2EE etc., also.
In ASP.NET, these styles can be applied for both HTML tags and ASP.NET controls also.
Ex:
<asp:TextBox ID="TextBox4" runat="server" Style="font-family:Broadway;
border-color:Red; text-align:right;" Text="hello"></asp:TextBox>
2) Internal Styles:
Syn:
<head>
<style type=‖text/css‖>
tag
{
attribute1:value1; attribute2:value2;….
}
</style>
</head>
Description: The CSS styles can be applied for every instance of the specified
tag in the current page.
Invoke it:
<h2>hello</h2>
3) External Styles:
Syn: (“xxxxxx.css” file)
tag
{
attribute1:value1; attribute2:value2;….
}
Description: The CSS styles can be applied for every instance of the specified
tag in every page, that is linked with the ―.css‖ file.
To link the ―.css‖ file, write the following tag in the page.
<head>
<link href=‖css file path‖ rel=‖Stylesheet‖ type=‖text/css‖ />
</head>
Instead, you also drag and drop the ―.css‖ file from Solution Explorer into the
web page. Then Visual Studio automatically generates the above ―<link>‖ tag in
the ―<head>‖ tag automatically.
CSS Classes
In the ―Internal Styles‖ and ―External Styles‖, common styles will be applied for every
instance of particular tag. Instead, you can have a choice for applying the CSS styles for
the required instances only, with the concept called ―CSS classes‖.
Finally, the ―CSS Classes‖ concept can be used in two situations:
1) To apply common CSS styles for selective instances of a tag.
2) To apply common CSS styles for selective instances of multiple tags.
To create a CSS class, follow the syntax:
.classname
{
attribute1:value1; attribute2:value2;….
}
To apply the CSS style for the required html tag, follow the syntax:
<tag class=‖classname‖>
To apply the css style for the required server tag, follow the syntax:
<asp:tag CssClass=‖classname‖>
Ex:
<head runat="server">
<style type="text/css">
.mytextbox
{
color:Red;
font-family: Tahoma;
Remove that body tag and make file empty, because we don‘t require it now.
On the screen, you can observe ―Style Sheet‖ toolbar.
If you don‘t find it, click on ―View‖ menu – ―Toolbars‖ – ―Style Sheet‖ option. Then the
toolbar will be there.
Then click on the first button called ―Add Style Rule‖.
Click on OK.
Then it generates CSS class syntax in the code.
Then click on the class name (MyTextBox) and click on ―Build Style‖ option in the toolbar.
Click on OK.
Then it automatically generates the style sheet code as below:
Implementation of Themes:
First, add a skin file by clicking on ―Web Site‖ menu – ―Add New Item‖ – ―Skin File‖.
Enter the name of the theme. Ex: MyTheme.skin
Click on ―Add‖.
It asks a confirmation, to create ―App_Themes‖ folder. Click on ―Yes‖.
Then the skin file will be created as follows:
In the skin file, you can write the tags for server controls like <asp:Label> etc., along
with few properties. The tag should contain runat=server attribute.
Ex: <asp:Label runat=‖server‖ BackColor=‖Pink‖ />
Note: If the property values are clashed between the control and the theme, the theme
properties only be applied at run time.
Note: To disable the themes for a specific tag instance, simply use EnableTheming=”false”
attribute for the required tag.
Demo:
Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
Select ―Skin File‖.
Delete all the commented code and type the code manually as follows:
IMP Note: While you are typing the above code, no help
can be given by Visual Studio. You have to take care about
casing and all other things. If you don‘t type it in proper
casing, it won‘t work. It causes some errors.
Come back to the ―themesdemo.aspx‖ page.
Open the properties window and choose ―DOCUMENT‖
option from the list, which is displayed at the top of the
properties window.
Select the ―Theme‖ property as ―MyTheme‖ from the list.
Select the ―Label3‖ and set the following property:
EnableTheming: False
Then run the web site.
At run time, the theme will be applied, and the page looks
like this on the browser:
Implementation:
Create the tag designs with “SkinID” attribute (in the skin file):
<tag runat=‖server‖ property=‖value‖ SkinID=‖skin name‖ />
Access the Skin with “SkinID” attribute (in the aspx page):
<tag runat=‖server‖ SkinID=‖skin name‖ />
Demo:
MyTheme2.skin
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="Pink" ForeColor="Red" Font-Size="20px" SkinID="PinkAndRed" />
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="Bisque" ForeColor="Blue" Font-Size="20px" SkinID="BisqueAndBlue" />
Note: If you don‘t apply the SkinID property, no style will be applied.
So finally, we have few textboxes with one style, and few other textboxes with another
style.
This is possible using Skins.
Open solution explorer; right click on the web site name and choose ―Add New Item‖.
Select ―Web User Control‖.
Enter any name. Ex: WebUserControl.ascx
Note: ascx stands for Active Server Control Extended.
Click on ―Add‖.
Design it as shown:
Note: To avoid the repetition of design like above example, you can use another concept called
as ―Master Pages‖.
2. Fragment Caching:
This is also one kind of output caching.
But instead of storing the full page output in the cache memory, partial page (part of
the page) output only be stored.
To implement this, you have to implement the ―OutputCache‖ in the Web User
Control.
After that, drag and drop the ―WebUserControl‖ into the web page.
That‘s all. Then finally it will be fragment caching.
3. Data Caching:
This is used to store the frequently used database data, in the cache memory.
For the first time, when the user opens the web page, you connect with the database
and get the data from the database; and store it in the cache memory.
Later, you can get the cached data on the same page or another page also, without
contacting the database.
Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
Note: The attribute ―VaryByParam‖ can be used for the pages, having the parameters in the
query string. When you want to use this, you write it as VaryByParam=”*”. Whenever you
write like this, separate copies will be created in the cache for the page, having different query
strings. If there are no changes in the query string, then cached output will be given as response
to the user.
To continue the demo application with ―Fragment caching‖, open the solution explorer,
right click on the web site name and choose ―Add New Item‖.
Select ―Web User Control‖.
Enter the name as ―WebUserControl.ascx‖.
Click on ―Add‖.
Design the ―WebUserControl.ascx‖ as shown:
WebUserControl.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>
fragmentcachingdemo.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
Drag and drop the ―WebUserControl.ascx‖ from solution explorer, into the page.
Then the screen looks like this:
To continue the demo application with ―Data caching‖, add the ―datacachingdemo.aspx‖
and design it as shown:
datacachingdemo.aspx.cs
using System.Data.SqlClient;
using System.Data;
DataTable dt;
dt = ds.Tables[0];
Cache["mydata"] = dt;
Label1.Text = "Data Loaded from Database";
}
else
{
Label1.Text = "Data Loaded from Cache";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//some code for displaying the data...
DataTable dt = (DataTable)Cache["mydata"];
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Demo:
Add the ―myad.aspx‖ page and design it as follows with an image control:
Select the ―DOCUMENT‖ properties in the ―properties window‖ and set the following
property:
Title: Ad
Type the <body> tag as follows:
<body leftmargin=0 rightmargin=0 topmargin=0 bottommargin=0>
Run the web site and click on the button. It shows the popup ad automatically.
2) Confirmation Boxes:
Syntax: window.confirm("message");
Demo:
dialogboxes.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("confirmationmessage.aspx");
}
Note: When the user clicks on ―OK‖ button at run time, the ―confirmationmessage.aspx‖ page
will be displayed, because the confirm() method returns ―true‖ value. Otherwise, no action will be
done, because the confirm() method returns ―false‖ value.
Demo:
LINQ
LINQ (pronounced link) stands for ―Language Integrated Query‖.
This concept is introduced in .NET Framework 3.5.
This is a ―query writing technology‖.
This is most useful while working large amount of data in the live projects.
Introduction:
In relational database system, data is organized in the form of tables, on which you can
write SQL queries to retrieve the required data according to the requirement in the
application.
In the modern world, the data sources are not only the databases. The application can
access the data from various other data sources like XML files, SAP, CSV (Comma
Separated Values) files etc.
But you can‘t write a query on the non-database data, which in the form of objects, XML
etc. There, you can write the queries using the new concept called ―LINQ‖.
You can write queries on arrays, objects, tables, xml using LINQ.
Note: Before writing the LINQ queries, you should import the ―System.Linq‖ namespace.
//ling query
var result = from n in numbers where n < 10 select n;
//output
foreach (var x in result)
Response.Write(x + ", ");
}
In the above application, the array contains few numbers. After executing the query, you
got only the numbers, which are less than 10. In this manner, you can write the queries
on various data sources.
LINQ Syntax:
Mandatory clauses:
from clause
in clause
select clause
Understanding Clauses:
1. from clause: This is used to specify the range variable name. At run time, the one-by-
one element (in a loop) will be assigned to this range variable and based on this range
variable other clauses like where, let, order by etc., will be executed..
2. in clause: This is used to specify the data source for the query, from where data comes
to execute the query.
3. let clause (optional): This is used to declare a new identifier with a value, that is to be
used during the query execution.
4. where clause (optional): This is most frequently used optional clause, using which
you can specify the condition in the query.
5. orderby clause (optional): This is used to specify the sorting expression if required. It
supports to have both ascending and descending order.
6. select clause: This is used to specify the object, which is required in the query results.
In general, we give
7. group by (optional): This is similar to ―group by‖ clause in SQL. This retrieves grouped
data, based on a column.
Note: The LINQ query returns the result in the form of IEnumerable<data type> type.
IEnumerable is an interface.
Library: System.Collections.Generic.IEnumerable
Student.cs
//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}
linqtoobjectsdemo.aspx.cs
Response.Write("<font face=Tahoma>");
//linq query with where clause
var result1 = from s in stu where s.Course == "MCA" select s;
Response.Write("MCA Students:" + "<br>");
foreach (Student r in result1)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");
Response.Write("</font>");
}
}
Run the web site and the output will be like this:
goes to
linqwithlambda.cs
Response.Write("<font face=Tahoma>");
Response.Write("</font>");
}
}
LINQ to SQL
This is to get the database data and perform LINQ queries on database data.
linqtosqldemo.aspx.cs:
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton2_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from c in db.Customers where c.Gender == "Female" select c;
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton4_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.OrderBy(c => c.Amount);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton5_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.OrderByDescending(c => c.Amount);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton6_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Take(2);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton7_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Skip(2);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton8_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Amount >= 4000 && c.Amount <=
5000);
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton9_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Gender == "Male");
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton10_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist1 = db.Customers.Where(c => c.Gender == "Male");
var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
protected void LinkButton11_Click(object sender, EventArgs e)
{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from cust in db.Customers
join ord in db.Orders
on cust.CustomerID equals ord.CustomerID
select new { cust.CustomerID, cust.CustomerName, cust.Gender,
cust.Amount, ord.OrderID, ord.ProductID, ord.Price, ord.OrderDate };
GridView1.DataSource = customerslist;
GridView1.DataBind();
Label2.Text = "";
}
GridView1.DataSource = null;
GridView1.DataBind();
}
XML
XML stands for ―Extensible Markup Language‖.
It is also a markup language, just like HTML, which contains tags.
But unlike HTML, the XML contains no pre-defined tags. It contains only user-defined
tags.
This xml code can be written in a file with ―.xml‖ file.
This is used to describe the data in a structured format.
The xml files can be used as ―secondary databases‖.
Generally, xml documents are portable, in order to share the data among two projects
developed in different languages.
Ex: employees.xml
employees.xml
Default.aspx.cs
using System.Data;
Note: The ReadXml() method reads the data from the xml file and stores it into dataset.
Run the web site.
Output:
Strict Caution: Don‘t make any changes, without proper knowledge; because it makes
ASP.NET malfunction in your system.
The xml document starts with XML prologue, which specifies the xml version.
<configuration>
………..
</configuration>
The next important section is <appSettings>. This is used to store or configure the
application settings, which are related to entire web site. For example, you want to
display the company‘s phone number in several web pages. So that, if you write the
phone number in each page it will be much difficult to change it later, because you
require to change it in all the required pages.
Instead, you try to store it (write it) in the web.config file, at the <appSettings> section.
Then later if you want to change it, you can change it easily, without changing any code
in all the pages.
To take a demonstration, change the <appSettings/> tag as follows:
<appSettings>
<add key="CompanyLocation" value="Hyderabad"/>
<add key="PhoneNo" value="040-23923020"/>
</appSettings>
using System.Configuration;
That means, at run the opens the web.config file automatically, then the company
location and phone number will be taken from <appSettings> tag and will be displayed
in the labels.
Suppose, you want to the change the company location and phone number now. Where
we need to change? You have to change in the <appSettings> tag; and no changes in
your code of the page.
Just for a demo, change the company location and phone number in the web.config file
as follows:
<appSettings>
<add key="CompanyLocation" value="Banglore"/>
<add key="PhoneNo" value="9993999790"/>
</appSettings>
Run the web site. These values will be affected in the output directly.
In the similar way, you are strongly recommended to store the connection strings in the
web.config file, at <connectionStrings> tag; because there may be some changes in the
connection string in future.
<connectionStrings>
<add name="MyConn" connectionString="data source=localhost;user
id=sa;password=123;initial catalog=demo"/>
</connectionStrings>
Come back to Default.aspx and add a button called ―Connect to SQL Server‖ as shown.
using System.Data.SqlClient;
<compilation debug="true">
When it is set to ―true‖, it shows the code, when the exceptions occur; break points also
work.
When it is set to ―false‖, it shows a default error message page, when the exceptions
occur; break points won‘t work.
By default, when you create the web site, it will be ―false‖. After you run the web site for
the first time, it will be automatically changed as ―true‖.
It is recommended to set it as ―true‖, when the development process in under progress.
It is recommended to set it as ―false‖, before you publish it on the internet; because you
won‘t show the code to the user, when an exception occurs.
The next thing you have to observe is <authentication> tag.
This tag specifies the mode of ASP.NET security. The modes are:
A. None
B. Windows
C. Forms
D. Passport
The default mode is ―Windows‖.
<authentication mode="Windows"/>
We discuss more about this ASP.NET Security concepts and authentication modes later.
The next thing you have to observe is <customErrors> tag.
CustomError means customized errors.
Note: By default, the above code will be under commented mode. You have to un-
comment it, by moving the --> tag to up.
These custom errors are used to display required web pages, when some special type of
error occurs at run time.
For example, whenever the user tries to open a non-existing filename, there will be one
type of error at server. That error code is ―404‖.
Observe the following tag:
According to the above tag, whenever 404-error occurs, ASP.NET automatically redirects
the execution flow to the above specified html page called ―FileNotFound.htm‖.
To test this functionality, do like this:
Run the web site as follows:
In the above screen, the user has tried to open the ―abc.aspx‖ page, which is not there
in our web site. So that ASP.NET is showing the default error message as above.
In the above screen, you can observe the error code as ―HTTP 404‖.
Anyway, using <customErrors> tag, you can display another page, at this case.
To do so, close the browser and come back to Visual Studio.
Open the Solution Explorer; right click on the web site name and choose ―Add New
Item‖.
Select ―HTML Page‖.
Run the web site and enter the non-existing file name as follows:
When you try to open the ―abc.aspx‖ (or any non-existing file name), it shows the
―FileNotFound.htm‖ page as above.
In the similar way, when the user is not having proper permission to open the web site,
it raises ―403‖ error. At this error, it shows ―NoAccess.htm‖ page.
Custom Error Modes:
A. On: Custom errors always work.
B. Off: Custom errors won‘t work.
C. RemoteOnly: Custom errors won‘t work in the server system, in which the web
site is stored. Those work from other client systems only.
For all other types of errors, a common page is maintained; i.e. ―GenericErrorPage.htm‖.
To test it, add the ―GenericErrorPage.htm‖ page and design it as shown:
Open the web.config file and change the connection string wrongly (Ex: change the
password as 456).
Right click on ―Default.aspx‖ and click on ―View in Browser‖.
Click on ―Connect to SQL Server‖ button.
Then it shows ―GenericErrorPage.htm‖ page as follows:
Next, observe the <pages> tag. Here, you can specify ―theme‖ attribute as follows:
<pages theme="any_theme_name">
If you specify any theme as above, that theme will be applied for all the web pages
commonly.
Note: In the other sections of the web.config file like <httpHandlers>, <httpModules>,
<compilers>, <system.webServer>, <runtime> etc., we don‘t require to change anything
particularly.
<sessionState mode="InProc">
</sessionState>
1) Off: Session state is not activated. That means, in your web site session state will not
work.
2) InProc: Session state will be maintained in the memory, which is allocated for original
ASP.NET process that is called as ―aspnet_wp.exe‖ file.
3) StateServer: The session state will be maintained as a separate process, by a separate
server called ―ASP.NET State Server‖.
4) SQLServer: The session state will be maintained in the SQL Server database.
sessiontest.aspx.cs
display.aspx.cs
<sessionState mode="Off">
</sessionState>
Now, run the ―sessiontest.aspx‖ page. When you enter any name in the textbox and click
on Submit button, it won‘t work; because currently session state is disabled in this web
site.
Open the web.config file and change the <sessionState> tag as follows:
<sessionState mode="StateServer">
</sessionState>
Now, run the ―sessiontest.aspx‖ page. It won‘t work properly; because you have
specified that session state is to be maintained as a separate process, by ASP.NET State
Server. But by default, that server is not started. You have to start it manually.
To do so, open Control Panel – Administrative Tools – Services.
Right click on ―ASP.NET State Services‖ and click on ―Start‖.
<sessionState mode="SQLServer">
</sessionState>
Now, run the ―sessiontest.aspx‖ page. It won‘t work properly; because you have
specified that session state is to be maintained in SQL Server database. But by default,
that SQL Server is not configured to store the sessions. You have to configure it
manually.
To do so, open the following folder:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
To add a new application setting, click on ―Create new application setting‖ option.
Enter the name and value of the application setting.
Click on ―Save‖.
Click on OK.
It adds the value to the list; immediately, ―web.config‖ file also will be updated.
Come ―Back‖ to ―Application‖ tab.
Configure SMTP E-mail settings: This is to be configured, when you want to send
automatic e-mails from your web site.
Note: Already we know how to configure the SMTP E-mail settings, in the previous
sessions.
Application Status: It should be always ―online‖ only. It should not be offline. If it is
offline, it won‘t work on the browser.
To test it, click on ―Take application offline‖ and try to run any page. It won‘t run. Again
come back to this web site administrative tool and click on ―Take application online‖.
Then it works normally.
Debugging and Tracing – Configure debugging and tracing: This is to enable or
disable the debugging and tracing.
If you uncheck the ―Enable debugging‖ option, then the <compilation> tag will be
modified as:
<compilation debug="false">
</compilation>
If you check the ―Enable debugging‖ option, then the <compilation> tag will be modified
as:
<compilation debug="true">
</compilation>
The other options in this screen are related to ―tracing‖ concept. We will discuss more
about this ―tracing‖, in the further sessions later.
Click on ―Back‖.
Debugging and Tracing – Define default error page: This is used to change the
generic error page (default error page which is to be displayed on occurrence of any type
of error in the web site). For more information, recollect the knowledge of
<customErrors> tag from previous sessions.
Here, you can select any other page, which acts as default error page.
Click on ―Save‖.
Provider: Always, it should be ―AspNetSqlProvider‖ only.
This is all about working with the ―ASP.NET Web Site Administrative Tool‖.
Close the browser and come back to Visual Studio.
Note: When you change any setting in the ―ASP.NET Web Site Administrative Tool‖, the
necessary changes would be made in the web.config file automatically.
Tracing
Using this tracing, the developer can get more technical information about the page
execution at run time.
To enable this feature, first option required page and set the following property of the
DOCUMENT object:
Trace: true
<system.web>
<trace enabled="true" pageOutput="true"/>
</system.web>
Now, if you run any page in the web site, tracing will be by default activated.
To disable the tracing feature, simply delete the <trace> tag (or) set it as
enabled=”false”.
For this demo, create 3 users named ―ram‖, ―sita‖ and ―laxman‖.
<authentication mode="Windows">
</authentication>
<authorization>
<allow users="localhost\ram"/>
<allow users="localhost\sita"/>
<deny users="*"/>
</authorization>
Now, if you login as ―ram‖ or ―sita‖, the web site can be accessed normally.
If other users logged-in, the web site is inaccessible. If you try to open the web site,
while you are in other user name (other than ram and sita), then it shows the following
type of message on the browser:
<authentication mode="Forms">
<forms loginUrl="Default.aspx"></forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Right click on ―guest‖ folder and click on ―Add New Item‖. Select ―Web Form‖. Enter the
file name as ―guestwelcome.aspx‖. Click on ―Add‖. Then the page will be added in
―guest‖ folder.
Design the ―guestwelcome.aspx‖ page as follows:
Make sure that few users are registered or not. If not, run the web site and register few
users. Ex: satya, syam, sridhar.
Open the solution explorer. Select the web site name. Click on ―ASP.NET Configuration‖
option.
Click on ―Security‖.
Now, you have to select the users, under the ―admin‖ role. For example, let us imagine
as ―satya‖ is the administrator.
So click on ―All‖.
It shows all the available user names.
Then check the checkbox for ―satya‖ user only. It will be saved immediately.
Click on ―Back‖.
Click on ―Manage‖ option, which is at right side of ―guest‖ role.
Now, you have to select the users, under the ―guest‖ role. For example, let us imagine as
―syam‖ and ―sridhar‖ are the guests.
So click on ―All‖.
It shows all the available user names.
Then check the checkbox for ―syam‖ and ―sridhar‖ users only. It will be saved
immediately.
Click on ―Back‖. All the roles are created and the necessary users are mapped with the
user roles.
Now, you have to continue with mapping our web site folder structure, with the user
roles. That means you have to specify which folders are accessible for which user roles.
To do so, come back to ―Security‖ option.
Click on ―Create Access Rules‖ option. Click on ―SecurityDemo‖ (web site name). Select
―All Users‖ – Select ―Allow‖. Click on OK.
Click on ―Create Access Rules‖ option again. Click on ―admin‖ folder in the tree structure.
Select ―admin‖ role – Select ―Allow‖. Click on OK.
Click on ―Create Access Rules‖ option again. Click on ―admin‖ folder in the tree structure.
Select ―guest‖ role – Select ―Deny‖. Click on OK.
Click on ―Create Access Rules‖ option again. Click on ―guest‖ folder in the tree structure.
Select ―admin‖ role – Select ―Deny‖. Click on OK.
Click on ―Create Access Rules‖ option again. Click on ―guest‖ folder in the tree structure.
Select ―guest‖ role – Select ―Allow‖. Click on OK.
Default.aspx.cs
In the above output screen, you can observe the date & time formats, currency styles,
number forms in English-US Format.
Suppose, you want to display those in Chinese format.
To do so, you close the browser and come back to Visual Studio.
Open the Properties window; select the ―DOCUMENT‖ option.
Specify the following property:
Culture: zh-SG Chinese (Simplified, Singapore)
Now, you can observe the date and time formats, currency style, calendar etc., in
Chinese language.
In this way, you can select any culture. All major cultures from all the countries are
displayed in the ―Culture‖ property of DOCUMENT object.
For example, again change the culture as:
Culture: te-IN Telugu (India)
Run the web site. Output:
Now, you can observe the output in telugu language, by following the Indian date & time
formats and currency formats.
This concept is called as ―Localization‖.
The user also can change the culture straightaway from the browser, using ―Tools‖ –
―Internet Options‖ – ―Languages‖ option at run time.
But being a programmer, you have to allow it. Then only the contents will be displayed in
user-selected language.
To do so, first, take one more web page called ―UserSelectedCulture.aspx‖ and design it
just like ―Default.aspx‖.
UserSelectedCulture.aspx.cs
Click on OK.
Move the culture to up; because top culture only be considered in the list.
Click on OK.
Click on OK.
Click on ―Refresh‖.
Then the contents will be displayed in Tamil language.
Globalization:
Globalization means, displaying all the pages in a common culture.
So that instead of specifying the culture in each web page individually, you specify the
culture in web.config file, so that it will be applied for all the pages commonly.
To do so, open the web.config file and type the following tag:
<globalization culture="fr-CA"/>
(or)
<globalization culture="auto:fr-CA"/>
Implementation Code:
Default.aspx.cs
using System.Net.Mail;
Important Note: Here, we are using the local domain called peerstech.com for
demonstration. (peerstech.com domain has been created in the previous chapters. For
more information, read the chapter called ―Configuring E-Mail Server‖). Remember that,
the same code works for real internet e-mail addresses also. Suppose, if you send the e-
mail to your friend‘s gmail id, your friend has to open the gmail web site and has to
check it in the inbox. So, the same example code works for all the mail addresses on
Internet. No issues in that. But, if you are giving an E-mail ID, which really exist on
Internet, you require the Internet connection with your system, for sure.
The previous example is a simple demo, to send the e-mails. Sometimes, you require
sending the e-mails with attachments also. At that time, you require knowledge on
―MailMessage‖ class.
MailMessage
MailMessage(“from”, “to”, “subject”, “message
body”)
Attachments
EMailsWithAttachmentsDemo.aspx.cs
using System.Net.Mail;
mail.Attachments.Add(att1);
mail.Attachments.Add(att2);
sc.Send(mail);
Label8.Text = "E-Mail Sent Successfully!!";
}
Example:
Let us imagine there is a software company called ―A‖.
It is developing a web site called ―Online shopping‖.
In this online shopping web site, the list of available products will be presented to the
customer.
After that, if the customer clicks on a product, then it displays the additional details about
that product like product manufacturing date, expiry date, price etc.
Finally, if the customer wants to buy the product, he/she has to enter the credit card
number for payment.
Then the credit card number is to be validated.
At the time of this validation, being a programmer, you have to check whether the
entered credit card number is correct or not and it is actually issued by the bank or not
and also you have to check for the available balance in the related bank account.
But here is the problem. The entire information about the bank customers and credit
cards related information is only available at bank database only. The bank can‘t give its
database to outsiders for security reasons.
But you are working in a software company, so that you can‘t connect to the bank
database directly, because the bank‘s database server is not available in your software
company.
In this case, web services are used to solve the problem; and indirectly the web service
allows you to get connected with the bank database and also to perform necessary
validations.
Web Method:
A web method is a method, which can be called from any other web site.
It can be executed directly on the web.
It can receive arguments.
It should return any value.
It should be defined as ―public‖ method only.
Just for a trail, write the following method in the ―Service‖ class.
[WebMethod]
public int GetRandomNumber(int min, int max)
{
Random r = new Random();
int n = r.Next(min, max);
return (n);
}
Click on the web method name, which you want to execute. Ex:
GetRandomNumber.
Then enter the values for the arguments (for min and max).
Click on ―GO‖.
Then it displays
the ―service.asmx‖
page.
After that, you
have to enter the
web reference
name. Ex: MyRef
A web reference
acts as
representation for
web service.
Finally click on ―Add Reference‖.
Then the web service will be linked with your web site; and the necessary files will be
copied into the web site folder.
Default.aspx.cs
using MyRef;
WCF
(Windows COMMUNICATION Foundation)
Since the introduction of the .NET Framework 3.0, Microsoft has made available
a new way to build Web services. Until the .NET Framework 3.0 came out, it was not a simple
task to build components that were required to communicate a message from one point to
another because Microsoft offered more than one technology that you could use for such an
action.
For instance, you could have used ASP.NET Web services (as just seen), MSMQ
(Microsoft Message Queue), .NET Remoting, and even the System.Messaging namespace. Each
technology has its own pros and cons. ASP.NET Web Services (also known as ASMX Web
Services) provided the capability to easily build interoperable Web services. The WSE enabled
you to easily build services that took advantage of some of the WS-* message protocols. MSMQ
enabled the queuing of messages, making it easy to work with solutions that were only
intermittently connected. .NET Remoting was a fast way to move messages from one .NET
application to another. Moreover, these are Microsoft options only. This does not include all the
options available in other environments, such as the Java world.
Using the WCF, you will be able to take advantage of all the items that make
distribution technologies powerful. WCF is the answer and the successor to all these other
message distribution technologies.
Looking back, you can see the gradual progression to the service-oriented
architecture model. In the 1980s, the revolution arrived with the concept of everything being an
object. When object-oriented programming came on the scene, it was enthusiastically accepted
as the proper means to represent entities within a programming model. The 1990s took that one
step further, and the component-oriented model was born. This enabled objects to be
encapsulated in a tightly coupled manner. It was only recently that the industry turned to a
service-oriented architecture because developers and architects needed to take components and
have them distributed to other points in an organization, to their partners, or to their customers.
This distribution system needed to have the means to transfer messages between machines that
were generally incompatible with one another. In addition, the messages had to include the
ability to express the metadata about how a system should handle a message.
If you ask 10 people what an SOA is, you‘ll probably get 11 different answers,
but there are some common principles that are considered to be foundations of a service-
oriented architecture:
❑ Boundaries are explicit: Any datastore, logic, or entity uses an interface to expose its data
or capabilities. The interface provides the means to hide the behaviors within the service, and the
interface front-end enables you to change this behavior as required without affecting
downstream consumers.
❑ Services are autonomous: All the services are updated or versioned independently of one
another. Thus, you do not upgrade a system in its entirety; instead, each component of these
systems is an individual entity within itself and can move forward without waiting for other
components to progress forward. Note that with this type of model, once you publish an
interface, that interface must remain unchanged. Interface changes require new interfaces
(versioned, of course).
❑ Services are based upon contracts, schemas, and policies: All services developed
require a contract regarding what is required to consume items from the interface (usually done
through a WSDL document). Along with a contract, schemas are required to define the items
passed in as parameters or delivered through the service (using XSD schemas). Finally, policies
define any capabilities or requirements of the service.
❑ Service compatibility that is based upon policy: The final principle enables services to
define policies (decided at runtime) that are required to consume the service. These policies are
usually expressed through WS-Policy.
If your own organization is considering establishing an SOA, the WCF is a framework that works
on these principles and makes it relatively simple to implement. The next section looks at what
the WCF offers. Then you can dive into building your first WCF service.
WCF Overview
As stated, the Windows Communication Foundation is a means to build
distributed applications in a Microsoft environment. Although the distributed application is built
upon that environment, this does not mean that consumers are required to be Microsoft clients
or to take any Microsoft component or technology to accomplish the task of consumption. On the
other hand, building WCF services means you are also building services that abide by the
principles set forth in the aforementioned SOA discussion and that these services are vendor
agnostic — thus, they are able to be consumed by almost anyone.
You can build WCF services using Visual Studio 2008. Note that because this is a
.NET Framework 3.0 component, you are actually limited to the operating systems in which you
can run a WCF service. Whereas the other Microsoft distribution technologies mentioned in this
chapter do not have too many limitations on running on Microsoft operating systems, an
application built with WCF can only run on Windows XP SP2, Windows Vista, or Windows Server
2008.
When you build a WCF project in this manner, the idea is that you build a
traditional class library that is compiled down to a DLL that can then be added to another project.
The separation of code and project is a powerful division on larger projects. That said, you can,
however, just as easily build a WCF service directly in your .NET project, whether that is a
console application or a Windows Forms application. The approach taken for the examples in this
chapter show you how to build a WCF service that is hosted in a console application. Keep in
mind that for the services you actually build and deploy, it is usually better to build them directly
as a WCF Service Library project and use the created DLL in your projects or in IIS itself.
Before we jump into building a WCF service, first consider what makes up a
service built upon the WCF framework.
Microsoft as the ABC of WCF. Each letter of WCF means something in particular in the WCF
model, including the following:
Basically, you can think of this as follows: ‗‗A‘‘ is the where, ‗‗B‘‘ is the how, and ‗‗C‘‘ is the what.
Finally, a hosting environment is where the service is contained. This constitutes an application
domain and process. All three of these elements (the service, the endpoints, and the hosting
environment) are put together to create a WCF service offering, as depicted.
The next step is to create a basic service using the WCF framework.
To build your service, prior to hosting it, you must perform two main steps. First,
you need to create a service contract. Second, you must create a data contract. The service
contract is really a class with the methods that you want to expose from the WCF service. The
data contract is a class that specifies the structure you want to expose from the interface.
Once you have a service class in place, you can host it almost anywhere. When
running this from Visual Studio 2010 / 2008, you will be able to use the same built-in hosting
mechanisms that are used by any standard ASP.NET application. To build your first WCF
application, select File – New - Web Site from the Visual Studio menu and call the project
WCFService1. The example this chapter will run through here demonstrates how to build the WCF
service by building the interface, followed by the service itself.
Click on OK.
Then it creates the WCF Service project.
Open the ―App_Code\IService.cs‖ file using Solution Explorer.
Write the code:
IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
int Add(int a, int b);
[OperationContract]
int Subtract(int a, int b);
[OperationContract]
int Multiply(int a, int b);
[OperationContract]
int Divide(int a, int b);
[OperationContract]
CompositeType GetSquareAndCube(int n);
// Use a data contract as illustrated in the sample below to add composite types to service
operations.
[DataContract]
public class CompositeType
{
int square_val;
int cube_val;
[DataMember]
public int Square
{
get { return square_val; }
set { square_val = value; }
}
[DataMember]
public int Cube
{
get { return cube_val; }
set { cube_val = value; }
}
}
Service.cs
return (a * b);
}
Default.aspx.cs
AJAX
(Asynchronous JavaScript and XML)
-------------------------- Request
-------------------------- (XmlHttpRequest)
--------------------------
Execute some Server Code
--------------------------
-------------------------- Response
-------------------------- (XmlHttpResponse)
Previously, in post-backing web sites, the ―HttpRequest‖ will be sent and ―HttpResponse‖
will be received. Here in AJAX, ―XmlHttpRequest‖ will be sent and ―XmlHttpResponse‖ will
be received. In other words, the client side values would be passed to the web server in
XML format, in AJAX technology. In this way, you require ―XML‖ usage in AJAX.
To send and receive the ―XmlHttpRequest‖ and ―XmlHttpResponse‖, you require to write
some code in a language. That language is ―JavaScript‖. In this way, you require
―JavaScript‖ usage in AJAX.
To develop ASP.NET web sites with AJAX technology, you are supposed to work with two
types of controls.
A. AJAX Extension Controls
B. AJAX Toolkit Controls
II. UpdatePanel:
This control contains the content, which is to be updated in AJAX model, on the post
back.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
The <ContentTemplate> tag contains the actual content. In this tag, you drag and
drop the controls, that you want.
If any control in the UpdatePanel requires post back, the entire page would not be
re-loaded. Just the required content would be updated with the support of call-back.
So, this feature improves the execution speed of the page.
ajaxdemo1.aspx.cs
Run the web site and test it. It works perfectly. The problem here is, when you click
on ―Add‖ button especially, you can observe a small blink in you page contents.
That‘s because of post-back. The entire page will be re-loaded. In fact, it is enough
to submit the ―a‖ and ―b‖ values here and get the result in the third textbox. So that,
you can implement AJAX here.
To do so, open toolbox; drag and drop the ―ScriptManager‖ control into the page at
the top (as shown on the screen).
Drag and drop the UpdatePanel control. It‘s like a normal panel control. You drag
and drop the necessary labels and textboxes, into the UpdatePanel (as shown the
screen).
That‘s it. Run the web site and test it directly on the browser. Now also, the output
will be displayed correctly, when you click on ―Add‖ button. But the thing is, the page
will not be posted-back; instead, ―call-back‖ will be performed.
Let‘s take one demo on AJAX.
Add the ―ajaxdemo2.aspx‖ page and design it as shown:
ajaxdemo2.aspx.cs
Run the web site and test it. Now, when you click on the first button the time will be
refreshed, without a post-back; because the button is inside of ―UpdatePanel‖
control. When you click on the second button, post-back will be performed as usual,
because it is not inside of ―UpdatePanel‖ control.
III. UpdateProgress:
This control is helpful, if it is taking much time to execute large amount of code,
while a call-back is being performed in an UpdatePanel.
This control contains the content, which is to be displayed while the page is getting
call back.
This improves the user-friendly nature.
This is useful, when you have large amount of code in the UpdatePanel.
By default, it contains some link with the UpdatePanel control.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
</ProgressTemplate>
</asp:UpdateProgress>
Demo on UpdateProgress:
ajaxdemo3.aspx.cs
Run the web site and test it. Now, it takes 3 seconds, to refresh the time.
In these 3 seconds of duration, no indication is given to the user. So, at this time,
the user may be in dynamo, whether the site is working properly or not.
To solve this problem, drag and drop the ―UpdateProgress‖ control into the same
page and design it as shown:
Now, run the web site and test it. When you click on ―Refresh‖ button now, the
―loading…‖ message and the hour glass image will be displayed for that 3 seconds of
duration.
IV. Timer:
This control is same as ―Timer‖ control in Windows Applications.
It executes certain process repetitively at every completion of certain interval time.
When you drag the control, you can see the following tag in the ―Source‖ view.
<asp:Timer ID="Timer1" runat="server">
</asp:Timer>
Demo on Timer:
ajaxdemo3.aspx.cs
AJAXControlToolKit
Demo:
Open the previous demo web site.
Add the ―AjaxToolkitDemo.aspx‖ page.
Download the ―AjaxControlToolkit.dll‖ file from
Microsoft‘s web site.
URL: http://www.asp.net/ajax
Right click on the toolbox and select ―Add Tab‖.
A new tab will be created in the toolbox. Enter a
meaningful name of the new tab. Ex: ―AJAX
Toolkit‖.
Right click on ―AJAX Toolkit‖ tab and select
―Choose Items‖.
Click on Browser and select the
―AjaxControlToolkit.dll‖ file from the download
location.
Click on OK.
Then automatically all the controls will be added to
that tab.
In this session, we are covering most important
controls of this toolkit, which may be generally
used in the now-a-days live projects development.
Note: Most of the AJAX toolkit controls are
extenders. The extender controls works depending
on other controls.
Continued…
If you are using AjaxControlToolkit.dll v3.5 or higher, drag and drop the
―ToolKitScriptManager‖ control from the toolbox, on to the top of the page (as shown on
the screen). If you are using older version of AjaxControlToolkit.dll (v2.0, v3.0 etc.) then
use ―ScriptManager‖ control, because ―ToolKitScriptManager‖ control is not available.
Select the ―First Name‖ textbox and click on ―>‖ symbol.
Click on ―Add Extender‖ option.
Select ―DropShadowExtender‖ option.
Click on OK.
That‘s all. A shadow will be displayed at run time, under the ―first name‖ textbox.
Output:
Click on OK.
Run the web site. Click on ―Submit‖ button, without entering the first name.
Then the validation message will be displayed like this:
Click on OK.
Set the properties of TextBox3:
WatermarkText: mm/dd/yyyy
WatermarkCssClass: mywater
Add ―StyleSheet.css‖ file.
Type the code:
StyleSheet.css
.mywater
{
background-color: Gray;
color: Silver;
}
Run the web site and observe the date of birth textbox. The watermark text will be
displayed in specified CSS style. Output:
Click on OK.
Run the web site and observe the ―date of joining‖ textbox. It displays the calendar, and
then the cursor enters into the textbox. Click on any date. Then the selected date will be
displayed in the textbox.
Output:
Click on OK.
Run the web site and observe the ―password‖ textbox. While you type the password in the
textbox, it displays the strength of it (Low / Very Low / Average / Strong / Excellent /
Unbreakable etc.).
Output:
Click on OK.
Run the web site. It allows you to type few characters, to quickly select the medicine
names in the dropdown list.
Output:
Click on OK.
Run the web site. Even though you scroll the web page, the image always will be
displayed on the screen.
Output:
WPF
(Windows Presentation Foundation)
XAML
Extensible Application Markup Language (XAML) is an XML syntax used to define the
hierarchical structure of the user interface.
In the following line, you can see the declaration of a button named button1 with the
content ―Click Me!‖.
The <Button> element specifies the use of the Button class:
<Button Content=”Click Me!” Background=”LightGreen” />
There‘s always a .NET class behind an XAML element.
With attributes and child elements, you set the value of properties.
Click on OK.
Then the Visual Studio window will be appeared like this:
Note: Every WPF window contains two files.
1. Windowname.xaml
2. Windowname.xaml.cs
Properties
The XAML language supports the properties to be written in two ways.
1. Properties as Attributes:
The properties can be written as attributes.
Ex: <Button Content=‖Click Me!‖ Background=‖LightGreen‖ />
2. Properties as Elements:
Ex:
<Button>
<Button.Background>
LightGreen
</Button.Background>
Click Me!
</Button>
WPF Controls
Sl.
Control Description
No
1 Button Responds for Click event.
2 CheckBox Can be checked or un-checked.
3 RadioButton Can be checked or un-checked with grouping nature.
4 TextBox Used to take input values.
Used to develop the text editing applications with better features
5 RichTextBox
than TextBox.
6 PasswordBox Used to take passwords.
7 ScrollBar Can be scrolled by the user.
8 Slider Same as TrackBar in windows forms applications.
9 ProgressBar Displays the progress of a particular task.
10 Label Displays a static message.
11 Menu Displays a menu bar.
12 ContextMenu Displays a context menu, whenever you right click on a control.
13 TabControl Contains multiple tabs.
14 TreeView Contains several tree nodes.
15 Border Displays a border around the specified area.
16 Grid Contains the controls in the form of rows and columns.
17 Image Displays an image.
18 Rectangle Displays a rectangle.
19 Ellipse Displays an ellipse or circle.
20 Canvas Similar to Panel control in windows forms applicationn.
21 WrapPanel Similar to FlowLayoutPanel control windows forms applications.
Window1.xaml.cs
Shapes
Line
<Line X1="xxx" Y2=" xxx" X2=" xxx" Y2=" xxx" Stroke="xxx" StrokeThickness="xxx" />
Rectangle
<Rectangle Name="xxx" Top="xx" Left="xx" Width="xx" Height="xx" Stroke="xxx" />
Ellipse
<Ellipse Name="xxx" Top="xx" Left="xx" Width="xx" Height="xx" Stroke="xxx" />
Path (Curve)
<Path Stroke="xxx" StrokeThickness="xx" Data="xxx" />
Window1.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Canvas>
<Ellipse Canvas.Left="50" Canvas.Top="50" Width="100" Height="100"
Stroke="Blue" StrokeThickness="4" Fill="Yellow" />
<Ellipse Canvas.Left="60" Canvas.Top="65" Width="25" Height="25"
Stroke="Blue" StrokeThickness="3" Fill="White" />
<Ellipse Canvas.Left="70" Canvas.Top="75" Width="5" Height="5"
Fill="Black" />
<Path Stroke="Blue" StrokeThickness="4"
Data="M 62,125 Q 95,122 102,108" />
<Line X1="124" X2="132" Y1="144" Y2="166" Stroke="Blue"
StrokeThickness="4" />
<Line X1="114" X2="133" Y1="169" Y2="166" Stroke="Blue"
StrokeThickness="4" />
<Line X1="92" X2="82" Y1="146" Y2="168" Stroke="Blue"
StrokeThickness="4" />
<Line X1="68" X2="83" Y1="160" Y2="168" Stroke="Blue"
StrokeThickness="4" />
</Canvas>
</Grid>
</Window>
Transformation
1. RotateTransform
<ControlName.LayoutTransform>
<RotateTransform Angle=‖xx‖ />
</ControlName.LayoutTransform>
2. SkewTransform
<ControlName.LayoutTransform>
<SkewTransform AngleX=‖xx‖ AngleY=‖xx‖ />
</ControlName.LayoutTransform>
Window1.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Button Margin="-113,45,-139,0" Name="button1" Height="44"
VerticalAlignment="Top">
<Button.LayoutTransform>
<RotateTransform Angle="40" />
</Button.LayoutTransform>
Rotate Transformation Button
</Button>
<Button HorizontalAlignment="Left" Margin="35,100,0,58" Name="button2"
Width="170">
<Button.LayoutTransform>
<SkewTransform AngleX="3" AngleY="28" />
</Button.LayoutTransform>
Skew Transformation Button
</Button>
</Grid>
</Window>
Brushes in WPF
The brushes can be used for backgrounds / foregrounds for any control. Use the
following syntaxes within <ControlName.Background> or <ControlName.Foreground>
tags.
SolidColorBrush
<SolidColorBrush>xxxx</SolidColorBrush>
LinearGradientBrush
<LinearGradientBrush StartPoint=‖xx,xx‖ EndPoint=‖xx,xx‖>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
<GradientStop Color=‖xx‖ Offset=‖xx‖></GradientStop>
</LinearGradientBrush>
RadialGradientBrush
<RadialGradientBrush Center=‖xx,xx‖ GradientOrigin=‖xx,xx‖ RadiusX=‖xx‖
RadiusY=‖xx‖ SpreadMethod=‖xx‖>
<GradientStop Color=‖xx‖ Offset=‖xx‖ />
<GradientStop Color=‖xx‖ Offset=‖xx‖ />
<GradientStop Color=‖xx‖ Offset=‖xx‖ />
</RadialGradientBrush>
DrawingBrush
<DrawingBrush>
<DrawingBrush.Drawing>
<GeometryDrawing Brush=‖xxx‖>
<GeometryDrawing.Geometry>
<GeometryGroup>
<EllipseGeometry RadiusX=‖xx‖ RadiusY=‖xx‖ Center=‖xx,xx‖ />
<EllipseGeometry RadiusX=‖xx‖ RadiusY=‖xx‖ Center=‖xx,xx‖ />
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen>
<Pen.Brush>xxx</Pen.Brush>
</Pen>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
ImageBrush
<ImageBrush ImageSource=‖xxxxx‖ />
VisualBrush
<VisualBrush>
<VisualBrush.Visual>
<StackPanel Background=‖xxx‖>
<Rectangle Width=‖xx‖ Height=‖xx‖ Fill=‖xxx‖ Margin=‖xx‖ />
<Ellipse Width=‖xx‖ Height=‖xx‖ Fill=‖xxx‖ Margin=‖xx‖ />
<Button Margin=‖x‖>xxx</Button>
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
Window1.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Width="403" Height="352">
<Button Margin="21,14.5,0,0" HorizontalAlignment="Left" Width="127" Height="30"
VerticalAlignment="Top">
<Button.Background>
<SolidColorBrush>Yellow</SolidColorBrush>
</Button.Background>
Solid Color
</Button>
<Button Margin="21,86,0,0" HorizontalAlignment="Left" Width="127" Height="35.5"
VerticalAlignment="Top">
<Button.Background>
<LinearGradientBrush StartPoint="0,0"
EndPoint="0.5,1.2">
</Button.Background>
<Button.Foreground>White</Button.Foreground>
Image Brush
</Button>
<Button Margin="0,0,77,45" Height="78" HorizontalAlignment="Right"
VerticalAlignment="Bottom" Width="108">
<Button.Background>
<VisualBrush >
<VisualBrush.Visual>
<StackPanel Background="White">
<Rectangle Width="25" Height="25" Fill="LightCoral" Margin="2" />
<Ellipse Width="65" Height="20" Fill="Aqua" Margin="5" />
<Button Margin="2">A Button</Button>
</StackPanel>
</VisualBrush.Visual>
</VisualBrush>
</Button.Background>
Visual Brush
</Button>
<Button Margin="0,86,62,146.139" HorizontalAlignment="Right" Width="138">
<StackPanel>
<Border x:Name="reflected">
<Border.Background>Yellow</Border.Background>
<StackPanel>
<Label>Visual Brush 2</Label>
<Rectangle Width="70" Height="15" Margin="2"
Fill="BlueViolet" />
</StackPanel>
</Border>
<Rectangle Height="30">
<Rectangle.Fill>
<VisualBrush Opacity="0.35" Stretch="None"
Visual="{Binding ElementName=reflected}">
<VisualBrush.RelativeTransform>
<TransformGroup>
Click on OK.
Click on OK.
Then the Visual Studio window will be appeared like this:
ASP.NET 4.0
Frequently
Asked
Questions
(FAQ’s)
ASP.NET FAQ's
What is view state and use of it?
The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within
the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted
(sent to the server), which allows you to program accordingly.
User Controls:
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control.
An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The
ASP.NET page framework compiles a user control on the fly to a class that derives from the
System.Web.UI.UserControl class.
Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
CachingOutput Caching: Caches the dynamic output generated by a request. Some times it
is useful to cache the output of a website even for a minute, which will result in a
better performance. For caching the whole page the page should have OutputCache
Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical
to cache the entire page, in such cases we can cache a portion of page <%@ OutputCache Duration="120"
VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching asp.net provides a cache object for
eg: cache["States"] = dsStates;
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included
only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control:Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be
included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more
than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @
Import Namespace="System.web" %>
@Implements: Indicates that the current page or user control implements the specified .NET framework
interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in custom server control
syntax. <%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes
and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly
Src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control
contained in a page
<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None"
Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should be dynamically
compiled and linked against the page in which this directive is declared.
How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't
use code-behind?
Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you
want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug
Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe
doesn't appear in the list,check the "Show system processes" box.) Click the Attach button to attach to
aspnet_wp.exe and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET
to build debug executables by placing a <%@ Page Debug="true" %> statement at the top of an ASPX
file or a <COMPILATION debug="true" />statement in a Web.config file.
What is the transport protocol you use to call a Web service SOAP
HTTP with SOAP
True or False: To test a Web service you must create a windows application or Web application to
consume this service?
False.
The idea is to pass a method in the invocation of the web method. When the webmethod has finished it will
call this callback function to process the result
2. Synchronous Call
Application has to wait until execution has completed.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by
uncommenting the line in the <HTTPHANDLERS>section of Machine.config that maps *.vsdisco to
System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET user account permission
to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because
they could represent a threat to Web server security.
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this
example, it prevents caching of a Web page that shows the current time.
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM
components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves
the performance of calls that the page places to apartment- threaded COM objects by ensuring that the
page (actually, the thread that processes the request for the page) and the COM objects it creates share an
apartment. AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If
those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the
same STAs as the threads that created them. Without AspCompat="true," request threads run in a
multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when
it's marshaled across apartment boundaries. Do not set AspCompat to true if your page uses no COM
objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered
ThreadingModel=Free or ThreadingModel=Both.
How do I provide information to the Web Service when the information is required as a SOAP Header?
The key here is the Web Service proxy you created using wsdl.exe or through Visual Studio .NET's Add
Web Reference menu option. If you happen to download a WSDL file for a Web Service that requires a
SOAP header, .NET will create a SoapHeader class in the proxy source
file. Using the previous example:
What is WSDL?
WSDL is the Web Service Description Language, and it is implemented as a specific XML vocabulary. While
it's very much more complex than what can be described here, there are two important aspects to WSDL
with which you should be aware. First, WSDL provides instructions to consumers of Web Services to describe
the layout and contents of the SOAP packets the Web Service intends to issue. It's an interface description
document, of sorts. And second, it isn't intended that you read and interpret the WSDL. Rather, WSDL should
be processed by machine, typically to generate proxy source code (.NET) or create dynamic proxies on the
fly (the SOAP Toolkit or Web Service Behavior).
What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
Windows service is an application that runs in the background. It is equivalent to a NT service. The
executable created is not a Windows application, and hence you can't just click and run it. It needs to be
installed as a service, VB.Net has a facility where we can add an installer to our program and then use a
utility to install the service; whereas this is not the case with standard exe