0% found this document useful (0 votes)
132 views140 pages

Part 2

The document provides steps to configure the forgot password functionality in an ASP.NET web application using WebParts controls. It involves adding a WebPartManager and multiple WebPartZones to the default page. Various controls like labels, buttons, and dropdowns are added to the zones. SMTP settings are configured to send password reset emails. The document also describes how to test the forgot password feature and view the password reset email. Configuring an alias SMTP domain is needed to properly send and receive emails.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views140 pages

Part 2

The document provides steps to configure the forgot password functionality in an ASP.NET web application using WebParts controls. It involves adding a WebPartManager and multiple WebPartZones to the default page. Various controls like labels, buttons, and dropdowns are added to the zones. SMTP settings are configured to send password reset emails. The document also describes how to test the forgot password feature and view the password reset email. Configuring an alias SMTP domain is needed to properly send and receive emails.

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 140

D.

HARSHA VARDHAN

 Let us test this control whether it is working or not.


 Run the web site.

.NET 4.0 and Visual Studio 2010 Page 280 of 558


D. HARSHA VARDHAN

 Click on ―Forgot Password – Click here‖ option.


 Enter the username. Ex: satya

.NET 4.0 and Visual Studio 2010 Page 281 of 558


D. HARSHA VARDHAN

 Click on ―Submit‖.
 Then it shows the security question, which is given at the time of user registration.
 Enter the proper answer. Ex: green

.NET 4.0 and Visual Studio 2010 Page 282 of 558


D. HARSHA VARDHAN

 Click on ―Submit‖ button.


 In fact, an E-mail is automatically would be sent to the user, with the password
information.
 But now, it would not be sent properly. You will get this type of error message:

.NET 4.0 and Visual Studio 2010 Page 283 of 558


D. HARSHA VARDHAN

 To solve this problem, you have to configure the ―SMTP settings‖ in your web site. After
you configure, this control works properly.
 So, let us continue with configuring the SMTP Settings.
ASP.NET
 Close the browser and come back to the Visual Studio. Configuration
 Open Solution Explorer and select the web site name. (Click here)

 Click on ―ASP.NET Configuration‖ option.


 Then it displays ―ASP.NET Web Site
Administrative Tool‖.
 It‘s an inbuilt feature of ASP.NET, which is used
to customize the settings of the web site.

.NET 4.0 and Visual Studio 2010 Page 284 of 558


D. HARSHA VARDHAN

 Click on ―Application‖ tab.

.NET 4.0 and Visual Studio 2010 Page 285 of 558


D. HARSHA VARDHAN

 Click on ―Configure SMTP e-mail settings‖ option.


 Then it displays the following options:

.NET 4.0 and Visual Studio 2010 Page 286 of 558


D. HARSHA VARDHAN

 Then type the following details:


1. Server name: name of the SMTP server / localhost
2. Server Port: 25 (a fixed port no of SMTP protocol)
3. From: The e-mail address, from which the password recovery e-mail is to
be sent. For ex type [email protected].

.NET 4.0 and Visual Studio 2010 Page 287 of 558


D. HARSHA VARDHAN

 Click on ―Save‖ button.


 Then the above specified SMTP settings will be saved.

.NET 4.0 and Visual Studio 2010 Page 288 of 558


D. HARSHA VARDHAN

 Click on OK.
 Close the browser and come back to Visual Studio.
 Then the necessary changes will be made in the ―web.config‖ file.
 To see those changes, double click on ―web.config‖ file in the Solution Explorer.

.NET 4.0 and Visual Studio 2010 Page 289 of 558


D. HARSHA VARDHAN

 But still, it won‘t work, because the mail domain (peerstech.com), which you are using
in the above mentioned mail address doesn‘t exist actually.
 So that we have to create a alias domain (dummy domain), with the name of
―peerstech.com‖.
 To create it, click on ―Start‖ – ―Run‖.
 Then type ―inetmgr‖ and click on OK.

 Then it opens the ―Internet Information Services‖ (IIS) window.


 There, expand the local computer name.
 Expand ―Default SMTP Virtual Server‖.

.NET 4.0 and Visual Studio 2010 Page 290 of 558


D. HARSHA VARDHAN

 Select the option ―Domains‖.


 Then it shows existing list of domains, which are configured currently in the IIS server.
 Right click on ―Domains‖ – choose ―New‖ – ―Domain‖.

 Then select ―Alias‖.

.NET 4.0 and Visual Studio 2010 Page 291 of 558


D. HARSHA VARDHAN

 Click on Next.
 Specify the name as ―peerstech.com‖.

 Click on Finish.
 Then it will be added to the existing domains list.

.NET 4.0 and Visual Studio 2010 Page 292 of 558


D. HARSHA VARDHAN

 That‘s it. It‘s ready.


 Close the IIS window and come back to Visual Studio.
 Run the web site and test the ForgotPassword option. Now it works.
 After entering the correct username and correct answer for the question, it displays the
following message at run time.

.NET 4.0 and Visual Studio 2010 Page 293 of 558


D. HARSHA VARDHAN

 To find out the E-mail, open the following folder.


c:\Inetpub\mailroot\Drop
 There, you can find a file that contains the E-mail.

.NET 4.0 and Visual Studio 2010 Page 294 of 558


D. HARSHA VARDHAN

 Double click on that file.


 Then you can read the e-mail.

.NET 4.0 and Visual Studio 2010 Page 295 of 558


D. HARSHA VARDHAN

 If you configure the ―Outlook Express‖ properly, the e-mail will be sent automatically to
the Inbox of the user.
 Anyway, you can find the password, which is given as an encrypted value in the e-mail.
Ex: dgJfi^cdx=>d]h
 The user has to use this above password, to login. Of course, after next login, the user
can change the password.
 To test it, run the web site, and try to login with above given encrypted password (you
can copy the password and paste it directly in the password textbox, at the login page).
 After that try to change the password using ―Change Password‖ option.

.NET 4.0 and Visual Studio 2010 Page 296 of 558


D. HARSHA VARDHAN

WebParts Controls

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

Application 20: Demo on WebParts Controls

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Default.aspx‖ – Click on Add.
 Drag and drop the ―WebPartManager‖ control from the toolbox into the page (at the
top).

.NET 4.0 and Visual Studio 2010 Page 297 of 558


D. HARSHA VARDHAN

 Drag and drop the two or the ―WebPartZone‖ controls.

.NET 4.0 and Visual Studio 2010 Page 298 of 558


D. HARSHA VARDHAN

 Re-size the WebPartZone controls and set the auto-format styles, as per your desire.
 Rename the ―WebPartZone1‖ as ―FirstZone‖ using ID property.
 Rename the ―WebPartZone2‖ as ―SecondZone‖ using ID property.
 Rename the ―WebPartZone3‖ as ―ThirdZone‖ using ID property.

.NET 4.0 and Visual Studio 2010 Page 299 of 558


D. HARSHA VARDHAN

 Drag the drop any controls (like labels, buttons, textboxes, checkbox, calendars etc.) into
the web part zones.

.NET 4.0 and Visual Studio 2010 Page 300 of 558


D. HARSHA VARDHAN

(Continued…)

.NET 4.0 and Visual Studio 2010 Page 301 of 558


D. HARSHA VARDHAN

 Run the web site.


 You can observe ―Minimize‖ and ―Close‖ options for each control, at right side corner.

.NET 4.0 and Visual Studio 2010 Page 302 of 558


D. HARSHA VARDHAN

 Note: If you minimize any control, you can restore it later. If you close it, you can‘t
restore it again.
 Close the browser and come back to Visual Studio.
 Drag and drop a ―DropDownList‖ control.
 Select it and click on ―>‖ symbol. Click on ―Enable AutoPostBack‖ option.

.NET 4.0 and Visual Studio 2010 Page 303 of 558


D. HARSHA VARDHAN

 Set the Dropdownlist items as follows:

.NET 4.0 and Visual Studio 2010 Page 304 of 558


D. HARSHA VARDHAN

 Click on OK.
 Double click on the DropDownList1 control and write the code:

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;
}

 Run the web site.


 By default, you will be in ―Browse‖ mode.
 Select ―Design‖ mode from the Dropdownlist.
 Now, you can move any control from one WebPartZone to any other WebPartZone.

 This is the advantage of ―Design‖ mode.

.NET 4.0 and Visual Studio 2010 Page 305 of 558


D. HARSHA VARDHAN

State Management in ASP.NET


 This is to send some data values from one web page to another web page.
 For example, if you take any mailing web site, when you enter the user name and
password in the login page, that same user name is carried into the inbox page and
compose page etc.
 For another example, if you enter your question in the Google home page, that value can
be carried into the next page, which displays the search results.
 In this way, you require to transfer / share some data values among two or more pages
also.
 This is possible using ―State Management‖ concept.
 The state management concept can be implemented in many ways.
1. Using Query String
2. Using Cookies
3. Using Session State
4. Using Application State
5. Using View State

Transferring Information between Pages


With Query String

 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

.NET 4.0 and Visual Studio 2010 Page 306 of 558


D. HARSHA VARDHAN

Ex: http://localhost:portno/WebSiteName/WebPage.aspx?n1=140&n2=98

 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.

Application 21: Demo on State Management

 Create a new web site.


 Add the ―Default.aspx‖ page.
 Design the ―Default.aspx‖ page as shown:

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 307 of 558


D. HARSHA VARDHAN

Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
Response.Redirect("display1.aspx?uname=" + s);
}

 Add the ―display1.aspx‖ page.


 Design the ―display1.aspx‖ page as shown:

 Write the code:

display1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Params["uname"];
Label1.Text = "Welcome, " + s;
}

.NET 4.0 and Visual Studio 2010 Page 308 of 558


D. HARSHA VARDHAN

 Set the ―Default.aspx‖ as Start Page.


 Run the web site.

Limitations of Passing Information with Query String:

 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‖.

.NET 4.0 and Visual Studio 2010 Page 309 of 558


D. HARSHA VARDHAN

Implementation:
A. Assign value to the Cookie:
Create cookie object:
HttpCookie obj = new HttpCookie(―variable_name‖, ―value‖);
Assign the cookie object to Response:
Response.Cookies.Add(obj);
B. Get value from the Cookie:
Request.Cookies[―variable_name‖].Value

Demo:

 Open the previous demo web site.


 Add the ―Submit using Cookies‖ button in the Default.aspx as shown:

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 310 of 558


D. HARSHA VARDHAN

Default.aspx.cs
protected void Button2_Click(object sender, EventArgs e)
{
string s = TextBox1.Text;
HttpCookie ck = new HttpCookie("uname", s);
Response.Cookies.Add(ck);
Response.Redirect("display2.aspx");
}

 Add the ―display2.aspx‖ page.


 Design the ―display2.aspx‖ page as shown:

 Write the code:

display2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Request.Cookies["uname"].Value;
Label1.Text = "Welcome, " + s;
}

.NET 4.0 and Visual Studio 2010 Page 311 of 558


D. HARSHA VARDHAN

Limitations of “Cookies”
 Cookies will be stored in the form of text files during run time in the client system. Those
files can be easily visible by other users. It is easy to modify or delete the cookie files. It
is easy to hack the cookie files from remote systems also. So, cookies are not much
secured.
 Cookie files will not be deleted automatically. So that, it leads to waste of hard disk
memory.
 It doesn‘t supports to share ―objects‖ among multiple pages. It supports to share strings
or numerical values only.

Finally, now-a-days, cookies are out-dated. To overcome the limitations of cookies, we use
―Sessions‖.

.NET 4.0 and Visual Studio 2010 Page 312 of 558


D. HARSHA VARDHAN

Session State
 Whenever a client (browser) is connected, the ―Session‖ state will be created
automatically; and the session will be closed automatically whenever the client (browser)
is disconnected.
 Here, ―state‖ means some memory, at web server.
 For every client (browser), a separate session will be created. For example, your web site
is being opened by 100 users (from 100 browsers). That means there will be 100
sessions.
 Similar to Cookies, the ―Session state‖ is used to share values among multiple pages. For
example, between login and logout, the current user name, user id number and
password will be stored in the session state.
 Now-a-days, ―Cookies‖ are outdated. Instead of cookies, sessions are used.
 The main difference between cookies and session state is: a cookie will be saved on the
client system; and the session will be saved at web server.
 Sessions are more secured, when compared with ―Cookies‖, as sessions will be saved at
web server.
 Sessions will not be saved in the form of any files. Those are stored as logical objects in
the web server memory.
 Sessions are able to share values and objects also.
 Implementation of ―Session state‖ is easier, when compared with ―Cookies‖.
 To access the session state, you can use the implicit object called ―Session‖. That means
you don‘t require to create the ―Session‖ it is commonly available for all the web pages
by default.
 The ―Session‖ object always represents current session, in which the web page is being
executed.

Implementation:
A. Assign value to the Session:
Session[―name‖] = value;

.NET 4.0 and Visual Studio 2010 Page 313 of 558


D. HARSHA VARDHAN

B. Get value from the Session (gets the session variable value in “Object”
type):
Session[―name‖]
C. Clear all the values in the current session:
Session.Clear();

Demo:

 Open the previous demo web site.


 Add the ―Submit using Session State‖ button in the Default.aspx as shown:

.NET 4.0 and Visual Studio 2010 Page 314 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs
protected void Button3_Click(object sender, EventArgs e)
{
Session["uname"] = TextBox1.Text;
Response.Redirect("display3.aspx");
}

 Add the ―display3.aspx‖ page.


 Design the ―display3.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 315 of 558


D. HARSHA VARDHAN

 Write the code:

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;

.NET 4.0 and Visual Studio 2010 Page 316 of 558


D. HARSHA VARDHAN

B. Get value from the Application (gets the application state variable value in
“Object” type):
Application[―name‖]

C. Clear all the values in the Application state:


Application.Clear();

Demo:

 Open the previous demo web site.


 Add the ―Submit using Application State‖ button in the Default.aspx as shown:

.NET 4.0 and Visual Studio 2010 Page 317 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs
protected void Button4_Click(object sender, EventArgs e)
{
Application["uname"] = TextBox1.Text;
Response.Redirect("display4.aspx");
}

 Add the ―display4.aspx‖ page.


 Design the ―display4.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 318 of 558


D. HARSHA VARDHAN

 Write the code:

display4.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string s = Convert.ToString(Application["uname"]);
Label1.Text = "Welcome, " + s;
}

.NET 4.0 and Visual Studio 2010 Page 319 of 558


D. HARSHA VARDHAN

View State
 ―View State‖ is a state that keeps the current state of the web page, during post back.
 Post Backing: The web page gets re-loaded automatically, whenever the user performs
an event at run time. Here, the page will be submitted to the same page itself. This
process is called as ―Post Backing‖. For example, if the user clicks on a button, the page
will be posted back.
 At the time of post backing, the web page will be closed and the same web page will be
re-loaded. In fact, the textbox values / list box selections etc., would not be re-loaded, if
―View State‖ concept is not implemented.
 Because of ―View State‖, ASP.NET is able to get the web page to the previous state, as it
is submitted at the time of post back.
 As a part of this ―View State‖, at the time of Post Backing, ASP.NET automatically saves
the current values of the controls in a separate string temporarily. After re-loading the
page, the controls values will be re-stored to its previous state, based on the values in
view state string.
 In fact, the ―View State‖ is maintained automatically by ASP.NET, you don‘t require
implementing it manually.

Demo
 Open the previous demo web site.
 Add ―viewstatedemo.aspx‖ page and design it as shown.

.NET 4.0 and Visual Studio 2010 Page 320 of 558


D. HARSHA VARDHAN

 Open Solution Explorer; right click on ―viewstatedemo.aspx‖ and click ―View in Browser‖.
 Enter some values.

.NET 4.0 and Visual Studio 2010 Page 321 of 558


D. HARSHA VARDHAN

 Click on the button. Then the ―post backing‖ will be done. But the no values will be lost.

.NET 4.0 and Visual Studio 2010 Page 322 of 558


D. HARSHA VARDHAN

Global.asax
 This file contains the events, related to entire web site.
 Here is the list of events, written in global.asax file:
1. Application_Start: This event executes automatically, whenever the
―Application State‖ is created. The Application State will be created automatically,
whenever the web server is started.

2. Application_End: This event executes automatically, whenever the ―Application


State‖ is closed (erased). The Application State will be closed automatically,
whenever the web server is stopped.

3. Application_Error: This event executes automatically, whenever any type of


exception occurs, during the execution of any web page of the current web site.

4. Session_Start: This event executes automatically, whenever the ―Session


State‖ is created. The Session State will be created automatically, whenever the
user opens the web site on the browser. In other words, it executes when a new
client is connected.

5. Session_End: This event executes automatically, whenever the ―Session State‖


is closed. The Session State will be closed automatically, whenever the user
closes the web site on the browser. In other words, it executes when browser is
closed (disconnected).

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.

.NET 4.0 and Visual Studio 2010 Page 323 of 558


D. HARSHA VARDHAN

 Type the code as follows:

Global.asax
<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)


{
// Code that runs on application startup
Application["usercount"] = 0;
}

void Application_End(object sender, EventArgs e)


{
// Code that runs on application shutdown

void Application_Error(object sender, EventArgs e)


{
// Code that runs when an unhandled error occurs

.NET 4.0 and Visual Studio 2010 Page 324 of 558


D. HARSHA VARDHAN

Response.Redirect("errorpage.aspx");
}

void Session_Start(object sender, EventArgs e)


{
// Code that runs when a new session is started
int n = Convert.ToInt32(Application["usercount"]);
n++;
Application["usercount"] = n;
}

void Session_End(object sender, EventArgs e)


{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.

</script>

 Add ―usercountpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 325 of 558


D. HARSHA VARDHAN

 Write the code:

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.";
}

 Open Solution Explorer; right click on ―usercountpage.aspx‖ and click on ―View in


Browser‖.

.NET 4.0 and Visual Studio 2010 Page 326 of 558


D. HARSHA VARDHAN

 Copy the URL from the address bar; open another browser; and paste the URL.

.NET 4.0 and Visual Studio 2010 Page 327 of 558


D. HARSHA VARDHAN

Note: Every time you run the page, the user count will be incremented automatically.

 Come back to Visual Studio.


 Add ―errorpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 328 of 558


D. HARSHA VARDHAN

 Add ―errortestpage.aspx‖ and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 329 of 558


D. HARSHA VARDHAN

 Write the code:

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‖.

.NET 4.0 and Visual Studio 2010 Page 330 of 558


D. HARSHA VARDHAN

 Click on the button.


 Then it shows the ―errorpage.aspx‖ automatically, because of the code that you have
written in ―Application_Error‖ event at global.asax file.

.NET 4.0 and Visual Studio 2010 Page 331 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 332 of 558


D. HARSHA VARDHAN

Uniformity of the Content


 This concept target is to maintain uniformity (looks similar) for the content or controls.
 Suppose you have 10 main headings your web page. Which would the better one? Either
displaying all those 10 headings with different styles (fonts, colors, borders etc.); or
displaying all those with common and uniform style..?
 The correct answer is second option. That means it‘s a good and professional way, if you
plan to give the common styles for all the headings. Of course, not only for headings; for
textboxes, labels, list boxes, menu items etc., it is better to apply common styles only.
 At the this situation, this uniformity maintenance is possible in many ways:
1. CSS
2. Themes
3. Skins

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.

.NET 4.0 and Visual Studio 2010 Page 333 of 558


D. HARSHA VARDHAN

Implementation Models of CSS


1) Inline Styles: The styles are limited to the currently element (tag) only.
2) Internal Styles: The styles are limited to the tags, used in the same page.
3) External Styles: The styles can be applied to the tags, within the same web site
(multiple web pages).

Important CSS Attributes:

Attribute Possible Values


font-family any font name
font-size 1 to unlimited
font-weight normal / bold
text-align left / center / right / justify
vertical-align top / middle / bottom
text-decoration none / underline
text-transform none / lowercase / uppercase / capitalize
letter-spacing n (space between each character)
word-spacing n (space between each word)
line-height n (space between each line)
top pixels (Gap between the top margin to the current element)
left pixels (Gap between the left margin to the current element)
position relative / absolute
background-color any color
background any image path
background-repeat repeat / no-repeat
border-style none / solid / double / groove / inset / outset / dashed / dotted
border-color any color
border-width pixels
border-left-style none / solid / double / groove / inset / outset / dashed / dotted
border-left-color any color
border-left-width pixels
border-right-style none / solid / double / groove / inset / outset / dashed / dotted
border-right-color any color
border-right-width pixels
border-top-style none / solid / double / groove / inset / outset / dashed / dotted
border-top-color any color
border-top-width pixels
border-bottom-style none / solid / double / groove / inset / outset / dashed / dotted
border-bottom-color any color
border-bottom-width Pixels
default / pointer / wait / text / hand / crosshair / help / move, e-resize /
cursor
n-resize / ne-resize / nw-resize / s-resize, se-resize, sw-resize, w-resize
width pixels
height pixels
n (specifies the order of the element in rendering the content on the
z-index
page)

.NET 4.0 and Visual Studio 2010 Page 334 of 558


D. HARSHA VARDHAN

Implementation of CSS Styles


1) Inline Styles:
Syn: <tag Style=‖attribute1:value1; attribute2:value2;….‖>
Description: The CSS styles can be applied for the current tag only.

Ex:
<asp:TextBox ID="TextBox4" runat="server" Style="font-family:Broadway;
border-color:Red; text-align:right;" Text="hello"></asp:TextBox>

<h1 Style="font-family:Lucida Handwriting; font-size: 35px; font-weight:bold;


text-align:center; text-decoration:underline; text-transform:capitalize; letter-
spacing:5px; word-spacing:10px; line-height:2; background-color:lightgreen;
color:red; border-style: dotted; border-color:Red; border-width:10px; border-
bottom-style:dashed; border-top-style: groove; cursor: hand; width:
700px;">hello</h1>

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.

.NET 4.0 and Visual Studio 2010 Page 335 of 558


D. HARSHA VARDHAN

Ex:
<style type="text/css">
h2
{
color:Blue;
font-family: Tahoma;
font-size: 30px;
}
</style>

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.

.NET 4.0 and Visual Studio 2010 Page 336 of 558


D. HARSHA VARDHAN

Adding “.css” files to the Web Site

Click on ―Web Site‖ menu – ―Add New Item‖.


Select ―StyleSheet‖ option.
Enter the name of the css file. Ex: StyleSheet.css
Click on ―Add‖.
Then the css file will be added to the web site.

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;

.NET 4.0 and Visual Studio 2010 Page 337 of 558


D. HARSHA VARDHAN

font-size: 30px;
border-style: double;
}
</style>
</head>

Invoke the class:


<asp:TextBox ID="TextBox2" runat="server" CssClass="mytextbox"></asp:TextBox>

Application 22: Demo on Uniformity Maintenance

 Create a new web site.


 Add the ―cssdemo.aspx‖ page.
 Design the ―cssdemo.aspx‖ page as shown:

.NET 4.0 and Visual Studio 2010 Page 338 of 558


D. HARSHA VARDHAN

 Open Solution Explorer – right click on the web site name and click on ―Add New Item‖.
 Select ―Style Sheet‖.
 Enter the any file name. Ex: StyleSheet.css
 Click ―Add‖.
 Then the screen looks like this:

 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‖.

 Then it displays the following dialog box.

.NET 4.0 and Visual Studio 2010 Page 339 of 558


D. HARSHA VARDHAN

 Click on ―Class name‖ option and enter the any class name. Ex: MyTextBox.
 It automatically generates the Style rule preview as ―.MyTextBox‖ (as you know already
that, every CSS class name should start with . (dot)).

 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.

.NET 4.0 and Visual Studio 2010 Page 340 of 558


D. HARSHA VARDHAN

 Then it shows ―Modify Style‖ dialog box.


 Select any formatting effects that you want.

 Click on OK.
 Then it automatically generates the style sheet code as below:

.NET 4.0 and Visual Studio 2010 Page 341 of 558


D. HARSHA VARDHAN

 Come back to the ―cssdemo.aspx‖ page.


 Drag the ―StyleSheet.css‖ file from the Solution Explorer, into the page and drop it in the
page.
 Then it links the CSS file to the web page. That means, it generates the <link> tag
automatically in the code.
 Next, specify the following property for all the textboxes.
CssClass: MyTextBox
 Run the web site.
 Finally your page looks like this:

.NET 4.0 and Visual Studio 2010 Page 342 of 558


D. HARSHA VARDHAN

 This is how to apply CSS styles in ASP.NET.

.NET 4.0 and Visual Studio 2010 Page 343 of 558


D. HARSHA VARDHAN

Themes
 As you know in the previous concept, the CSS styles are used to apply common design
styles. But the limitation of CSS is, CSS styles are always executed at client level.
 The CSS styles can‘t be applied at sever level. So that, using CSS, you can set the
general properties like font styles, colors, cursors, borders etc., but you can‘t set the
special properties related to the server controls.
 For example, you can‘t set the ―ReadOnly‖ property of a textbox using CSS. In the same
way, you can‘t set the ―NavigateUrl‖ property of a hyperlink using CSS.
 In this case, to replace the usage of ―CSS styles‖, the ―Themes‖ are introduced.
 The advantage of themes is: those can set the any property of the server controls. For
example, you can do the above two examples using ―Themes‖.
 One more advantage is: you don‘t require setting any property like ―CssClass‖, if you are
using ―Themes‖. The style will be applied commonly for all the controls, that you have
mentioned in the skin file.
 The themes can be implemented in a ―skin file‖ (with .skin extension), and placed in the
―App_Themes‖ folder.
 When you create a theme, its skin file is placed in the ―App_Themes‖ folder.
 Note: The themes are completely dynamic. Its effect would not be displayed in the
―Design‖ view.

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‖ />

.NET 4.0 and Visual Studio 2010 Page 344 of 558


D. HARSHA VARDHAN

 To impose the theme in the required .aspx page, simply write the Theme=”theme
name” attribute the <%@ Page> directive.

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 the previous demo web site.


 Add the ―themesdemo.aspx‖ page and design it as shown:

 Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
 Select ―Skin File‖.

.NET 4.0 and Visual Studio 2010 Page 345 of 558


D. HARSHA VARDHAN

 Enter the file name as ―MyTheme.skin‖.


 Click on ―Add‖.
 It asks a confirmation, whether you want to place the skin file in the ―App_Themes‖
folder or not. You click on ―Yes‖.

 Then the screen looks like this:

 Delete all the commented code and type the code manually as follows:

.NET 4.0 and Visual Studio 2010 Page 346 of 558


D. HARSHA VARDHAN

MyTheme.skin
<asp:Label runat="server" Font-Bold="True" Font-Name="Tahoma" ForeColor="Green"
Font-Size="14px" />
<asp:TextBox runat="server" Font-Bold="True" Font-Name="Lucida Handwriting"
BackColor="DarkGreen" ForeColor="Yellow" Font-Size="14px" />
<asp:Button runat="server" Font-Bold="True" Font-Name="Comic Sans MS"
BackColor="DarkRed" ForeColor="Yellow" Font-Size="14px"/>

 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:

.NET 4.0 and Visual Studio 2010 Page 347 of 558


D. HARSHA VARDHAN

Limitations of Themes:
 As per the default nature of themes, for all the controls, common styles will be applied
automatically.
 Suppose if you want to apply one type of style for few controls on the page, and another
type of style for few other controls on the page, it not possible.
 Solution: Use ―Skins‖.

.NET 4.0 and Visual Studio 2010 Page 348 of 558


D. HARSHA VARDHAN

Skins
 Skins are similar to CSS classes.
 Similar to CSS class, the skin has a name.
 It can be written in the ―.skin‖ file.
 One skin file may contain any no. of skins.

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:

 Open the previous demo web site.


 Add the ―skinsdemo.aspx‖ page and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 349 of 558


D. HARSHA VARDHAN

 Open Solution Explorer; right click on the web site name and click on ―Add New Item‖.
 Select ―Skin File‖.
 Enter the file name as ―MyTheme2.skin‖.
 Click on ―Add‖.
 It asks a confirmation, whether you want to place the skin file in the ―App_Themes‖
folder or not. You click on ―Yes‖.
 Then the screen looks like this:
 Delete all the commented code and type the code manually as follows:

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" />

.NET 4.0 and Visual Studio 2010 Page 350 of 558


D. HARSHA VARDHAN

 Come back to the ―skinsdemo.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 ―MyTheme2‖ from the list.
 For the first five textboxes, set the following property:
SkinID: PinkAndRed
 For the remaining five textboxes, set the following property:
SkinID: BisqueAndBlue
 Then run the web site.
 At run time, the theme will be applied, and the page looks like this on the browser:

 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.

.NET 4.0 and Visual Studio 2010 Page 351 of 558


D. HARSHA VARDHAN

Web User Controls


 Similar to ―User Controls‖ in windows applications, you can develop user controls in the
web sites also.
 As you know already, the advantage of user controls is, those can be used in any web
page, and avoids designing repetitive content in multiple pages.
 That means you need to design the content once and you can use it any no. of times in
any page.

Implementation of Web User Controls

1. Add the User Control to the Web Site:


Click on ―Web Site‖ menu – ―Add New Item‖.
Select ―Web User Control‖.
Enter the name of the user control and click on ―Add‖.
Note: The file extension for web control file is ―.ascx‖. (Active Server Control
Extended).
Then the user control will be created with the following statement in the
―Source‖ view.
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %>

2. Design and Develop the User Control


Design the user control, as per on your requirement. Drag the required controls
from the toolbox, (just like web page) and write the code in the ―.ascx.cs‖ file if
needed.

3. Link the User Control with the Web Page


To do this, type the following tag in the ―Source‖ view, after ―<%@ Page>‖ tag.
<%@ Register Src="UserControlFileName" TagPrefix="xxxx" TagName="xxxx" %>

4. Invoke the User Control


To invoke the control in the page, use the following tag, whereever required.
<Tagprefix:TagName />

.NET 4.0 and Visual Studio 2010 Page 352 of 558


D. HARSHA VARDHAN

Demo:

Application 23: Demo on Web User Controls

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Default.aspx‖ – Click on Add.
 Design the ―Default.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 353 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Aboutus.aspx‖ – Click on Add.
 Design the ―Aboutus.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 354 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―Contactus.aspx‖ – Click on Add.
 Design the ―Contactus.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 355 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―registration.aspx‖ – Click on Add.
 Design the ―registration.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 356 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖ – Type the name as
―login.aspx‖ – Click on Add.
 Design the ―login.aspx‖ as follows:

 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:

.NET 4.0 and Visual Studio 2010 Page 357 of 558


D. HARSHA VARDHAN

 Come back to the ―Default.aspx‖.


 Drag the ―WebUserControl.ascx‖ and drop it into the page.
 Then the control will be added to the page.

.NET 4.0 and Visual Studio 2010 Page 358 of 558


D. HARSHA VARDHAN

 In the same way, drag and drop the ―WebUserControl.ascx‖ into all other pages also.
After designing the user control, the pages looks like this:

.NET 4.0 and Visual Studio 2010 Page 359 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 360 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 361 of 558


D. HARSHA VARDHAN

.NET 4.0 and Visual Studio 2010 Page 362 of 558


D. HARSHA VARDHAN

 Run the web site.

Note: To avoid the repetition of design like above example, you can use another concept called
as ―Master Pages‖.

.NET 4.0 and Visual Studio 2010 Page 363 of 558


D. HARSHA VARDHAN

Master Pages
 Similar to ―User Controls‖, the common design can be shared among multiple web pages
using ―Master Pages‖ concept.
 A master page is similar to web page, but it‘s not a web page.
 The master page file extension is ―.master‖.
 It also contains some design and code in the ―.cs‖ file.
 It can be executed on the browser directly.
 This is meant for re-usability only.
 That means the master page content can be re-usable by other web pages (.aspx
pages).

Implementation of Master Pages

1. Add the Master Page to the Web Site:


Click on ―Web Site‖ menu – ―Add New Item‖.
Select ―Master Page‖.
Enter the name of the master page and click on ―Add‖. Ex: MasterPage.master

2. Design and Develop the Master Page:


Design the required content in the master page before ―ContentPlaceHolder‖ tag,
and write the necessary code in the ―.master.cs‖ file.
The ―ContentPlaceHolder‖ tag represents the content in the other web pages. In
the master page, it should be empty.

3. Create a Web Page with the Reference of Master Page:


Click on ―Web Site‖ menu – ―Add New Item‖.
Select ―Web Form‖. Enter the name of the new web page.
Select the option ―Select Master Page‖.
Click on ―Add‖.
Then it displays the list of all available master pages in the project. Select the
master page name and click on ―OK‖.
In this content page, you design any content in the ―ContentPlaceHolder‖ tag.

.NET 4.0 and Visual Studio 2010 Page 364 of 558


D. HARSHA VARDHAN

Demo:

Application 24: Demo on Master Pages

 Create a new web site.


 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Master Page‖ – Type the name as
―MasterPage.master‖ – Click on Add.
 Design the ―MasterPage.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 365 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖.


 Type the name as ―Default.aspx‖.
 Select the option ―Select Master Page‖.
 Click on Add.
 Select ―MasterPage.master‖.
 Click on OK.
 Design it shows the screen like this:

 Design the new content in content place holder as follows:

.NET 4.0 and Visual Studio 2010 Page 366 of 558


D. HARSHA VARDHAN

 Click on ―WebSite‖ menu – ―Add New Item‖ – ―Web Form‖.


 Type the name as ―Aboutus.aspx‖.
 Select the option ―Select Master Page‖.
 Click on Add.
 Select ―MasterPage.master‖.
 Click on OK.
 Design it shows the screen like this:

.NET 4.0 and Visual Studio 2010 Page 367 of 558


D. HARSHA VARDHAN

 Design the new content in content place holder as follows:

.NET 4.0 and Visual Studio 2010 Page 368 of 558


D. HARSHA VARDHAN

 Run the web site.


 The common content, which you have designed in the master page, will be repeated in
―Aboutus‖ page and ―Default‖ page.
 Run the web site.

.NET 4.0 and Visual Studio 2010 Page 369 of 558


D. HARSHA VARDHAN

Caching
 Caching (pronounced as ―Cashing‖), is one of the most powerful concept of ASP.NET.
 This is introduced to reduce the stress on web server.
 If your application is being executed simultaneously from two or more browser windows
on the same system, or it is being executed simultaneously from two or more client
systems on the network, or it is being executed simultaneous from two or more web
clients on internet, on each post back of the page, a new request to the web server
would be passed. So that, the entire page is to be refreshed. That means the contents of
the web page would be re-loaded and the code will be executed every time. This causes
heavy stress on the web server.
 For example, there is a submit button on your web page. If the submit button is clicked
on one client, it is not a much stress on the web server. You suppose that the button is
clicked from 20 client systems at-a-time. So that 20 requests will be passed to the web
server. The web server should respond to the 20 clients. So this leads to slow-up the
execution, because of heavy stress on the web server.
 To avoid this kind of problems, ―Caching‖ concept is introduced.
 According to this, you can store the page and its output in the cache memory up to a
certain time.
 If any request is sent to the web server, within the time limitation, the page will not be
re-loaded / re-executed. No code will be executed. Simply the previously cached web
page will be sent to the client as response.
 After completion of the specified time limit, the cached page will be removed
automatically.
 If any request is sent to the web server after the time limit, the page will be re-loaded as
usual.
 Generally, it is recommended to store most frequently used web pages in the cache
memory, using ―Caching‖ concept.
 At this same time, it is not recommended to store the web pages in the cache memory,
which pages content can be frequently changed dynamically at run time. Ex: Inbox page,
cricket scores page, examination results page.

.NET 4.0 and Visual Studio 2010 Page 370 of 558


D. HARSHA VARDHAN

Types of Caching:
1. Output Caching:
The output of the web page will be stored in the cache memory, for a while (based
on the time limit that you have given).
Syntax: Write the following tag in the ―Source‖ view, after Page directive:
<%@ OutputCache Duration="seconds" VaryByParam="none" %>

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.

Application 25: Demo on Caching

 Create a new web site.


 Add ―Default.aspx‖ page and design it as shown:

.NET 4.0 and Visual Studio 2010 Page 371 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = DateTime.Now.ToLongTimeString();
}

 Open the ―Source‖ view.


 Type the <%@ OutputCache %> tag at the top, after <Page> directive as follows:

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>

.NET 4.0 and Visual Studio 2010 Page 372 of 558


D. HARSHA VARDHAN

 Run the web site.


 When you click the button for the web site, current system time will be displayed.
 But when you click the button every time, the time will not be displayed, because it
executes no code for the second time onwards.
 If you click on the button after 20 seconds, the time will be refreshed. Again, that output
will remain up to another 20 seconds.
 This is the effect of output caching.

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.

Fragment caching demo:

 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:

.NET 4.0 and Visual Studio 2010 Page 373 of 558


D. HARSHA VARDHAN

 Write the code:

WebUserControl.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}

 Open the ―Source‖ view.


 Type the <%@ OutputCache %> tag at the top, after <Control> directive as follows:

WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<%@ OutputCache Duration="30" VaryByParam="none" %>

.NET 4.0 and Visual Studio 2010 Page 374 of 558


D. HARSHA VARDHAN

 Add the ―fragmentcachingdemo.aspx‖ and design it as shown:

 Write the code:

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:

.NET 4.0 and Visual Studio 2010 Page 375 of 558


D. HARSHA VARDHAN

 Run the web site.


 Click on the Submit button. In fact, (if you are not implementing the caching feature),
when you click on the button, the complete page will be posted-back (re-loaded). That
means Page_Load() event also will be executed. At the same time, Page_Load() of Web
User Control also will be executed.
 But in the label, which you have designed in the web page, displays the latest system
time.
 But the user control will not be re-loaded. So that, in the label, which you have designed
in the WebUserControl, latest system time will not be displayed.
 This is the effect of ―fragment caching‖.

.NET 4.0 and Visual Studio 2010 Page 376 of 558


D. HARSHA VARDHAN

Data Caching Demo:

 To continue the demo application with ―Data caching‖, add the ―datacachingdemo.aspx‖
and design it as shown:

 Write the code:

datacachingdemo.aspx.cs
using System.Data.SqlClient;
using System.Data;

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


{
protected void Page_Load(object sender, EventArgs e)
{
//some code for loading the data...
if (Cache["mydata"] == null)
{
SqlConnection cn = new SqlConnection();

.NET 4.0 and Visual Studio 2010 Page 377 of 558


D. HARSHA VARDHAN

cn.ConnectionString = "data source=localhost;user id=sa;password=123;initial


catalog=demo";

SqlDataAdapter adp = new SqlDataAdapter("select * from customers", cn);


DataSet ds = new DataSet();
adp.Fill(ds);

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();
}
}

 Run the web site.


 When run the web page, it loads the data from database and it will be stored into the
cache memory.
 When you click on ―Show Data‖ button, instead of loading the data from database, the
data will be loaded from cache memory, and will be displayed in the GridView1 control.
 This is the effect of data caching.

.NET 4.0 and Visual Studio 2010 Page 378 of 558


D. HARSHA VARDHAN

Common Tasks in JavaScript

i. Displaying pop-up windows:


 Generally while you are browsing the web sites, sometimes, some ads will be
displayed in a separate window.
 That window can be called as popup window.

 To generate this type of popup windows, use the following syntax:


window.open("pagename.ext", "any_name",
"location=no,toolbar=no,menubar=no,width=xx,height=xx ");

Demo:

Application 26: Demo on Common Tasks in JavaScript

 Create a new web site.


 Add the ―popupdemo.aspx‖ and design it as follows:

.NET 4.0 and Visual Studio 2010 Page 379 of 558


D. HARSHA VARDHAN

 Add the ―myad.aspx‖ page and design it as follows with an image control:

.NET 4.0 and Visual Studio 2010 Page 380 of 558


D. HARSHA VARDHAN

 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>

 Come back to the ―popupdemo.aspx‖.


 Select the ―Show Popup Window‖ button and set the following property:
OnClientClick: javascript:window.open("myad.aspx", "popup1",
"location=no,toolbar=no,menubar=no,width=728px,height=
75px");

 Run the web site and click on the button. It shows the popup ad automatically.

.NET 4.0 and Visual Studio 2010 Page 381 of 558


D. HARSHA VARDHAN

ii. Displaying dialog boxes:


 JavaScript supports two types of dialog boxes:
1) Alert Boxes (Message Boxes):
Syntax: window.alert("message");

2) Confirmation Boxes:
Syntax: window.confirm("message");

Demo:

 Open the previous demo web site.


 Add the ―dialogboxes.aspx‖ and design it as follows:

.NET 4.0 and Visual Studio 2010 Page 382 of 558


D. HARSHA VARDHAN

 Set the button1 properties:


OnClientClick: javascript:window.alert("Hello, World!");
 Set the button2 properties:
OnClientClick: return window.confirm("Are you sure?");

 Add ―confirmationmessage.aspx‖ page and design it as follows:

.NET 4.0 and Visual Studio 2010 Page 383 of 558


D. HARSHA VARDHAN

 Come back to the ―dialogboxes.aspx‖.


 Double click on button2 and write the code:

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.

.NET 4.0 and Visual Studio 2010 Page 384 of 558


D. HARSHA VARDHAN

iii. Displaying Status Bar Messages on the Browser:


 Syntax:
window.status=‖message‖;

Demo:

 Open the previous demo web site.


 Add the ―statusbardemo.aspx‖ page and design it as follows:

 Open the page in ―Source‖ view.


 Change the <body> tag as follows:

<body onload="javascript:window.status='Move the mouse pointer on to the image...';">

 Change the <asp:Image> tag as follows:

.NET 4.0 and Visual Studio 2010 Page 385 of 558


D. HARSHA VARDHAN

<asp:Image ID="Image1" runat="server" ImageUrl="laptop.jpg"


onMouseOver="javascript:window.status='Click the Image';"
OnMouseOut="javascript:window.status='Move the mouse pointer on to the image...';"
onClick="javascript:window.alert('You have clicked in the image');" />

 Come back to the Design view.


 Run the web site and observe the status bar on the browser.

.NET 4.0 and Visual Studio 2010 Page 386 of 558


D. HARSHA VARDHAN

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.

The following example shows a small demo on LINQ:

Application 27: Demo on LINQ

 Create a new web site.


 Add the ―linqtoarraysdemo.aspx‖ page.
 Write the code:

.NET 4.0 and Visual Studio 2010 Page 387 of 558


D. HARSHA VARDHAN

protected void Page_Load(object sender, EventArgs e)


{
//data source
int[] numbers = { 2, 12, 10, 5, 15, 9, 99, 4, 62 };

//ling query
var result = from n in numbers where n < 10 select n;

//output
foreach (var x in result)
Response.Write(x + ", ");
}

 Run the web site.


 You get the output as follows:

 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:

from … in … let … where … orderby … select … group by …

.NET 4.0 and Visual Studio 2010 Page 388 of 558


D. HARSHA VARDHAN

 The above syntax consists of 7 clauses.


 from clause
 in clause
 let clause
 where clause
 orderby clause
 select clause
 group by clause

 Mandatory clauses:
 from clause
 in clause
 select clause

Clause: A part of the query.

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.

.NET 4.0 and Visual Studio 2010 Page 389 of 558


D. HARSHA VARDHAN

Note: The LINQ query returns the result in the form of IEnumerable<data type> type.
IEnumerable is an interface.

Library: System.Collections.Generic.IEnumerable

Demo on LINQ to Objects:

 Open the previous demo web site.


 Open the solution explorer; right click on the web site name and choose ―Add New
Item‖.
 Select ―Class‖.
 Enter the name as ―Student.cs‖.
 Click on ―Add‖.
 It asks for confirmation, whether you want to place the file in the ―App_Code‖ folder or
not. Click on ―Yes‖.
 Write the code:

Student.cs

public class Student


{
//fields
public int StudentID;
public string Name;
public string Course;
public int Marks;

//constructor
public Student(int StudentID, string Name, string Course, int Marks)
{
this.StudentID = StudentID;
this.Name = Name;
this.Course = Course;
this.Marks = Marks;
}
}

.NET 4.0 and Visual Studio 2010 Page 390 of 558


D. HARSHA VARDHAN

 Add the ―linqtoobjectsdemo.aspx‖ page.


 Write the code:

linqtoobjectsdemo.aspx.cs

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


{
protected void Page_Load(object sender, EventArgs e)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)
};

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>");

//linq query with compound where clause


var result2 = from s in stu where s.Name.EndsWith("a") && s.Marks >= 400 &&
s.Marks <= 600 select s;
Response.Write("<br>Students whose name ends with 'a', and marks is >=400 and
<=600:" + "<br>");
foreach (Student r in result2)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with let and where clauses


var result3 = from s in stu let avg = s.Marks / 10 where avg < 35 select s;
Response.Write("<br>Failed Students:" + "<br>");
foreach (Student r in result3)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with orderby clause


var result4 = from s in stu orderby s.Marks select s;
Response.Write("<br>Students (sort on marks):" + "<br>");
foreach (Student r in result4)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

.NET 4.0 and Visual Studio 2010 Page 391 of 558


D. HARSHA VARDHAN

//linq query with orderby clause (descending)


var result5 = from s in stu orderby s.Marks descending select s;
Response.Write("<br>Students (sort on marks - descending):" + "<br>");
foreach (Student r in result5)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with group clause


var result6 = from s in stu group s by s.Course;
Response.Write("<br>Students with grouping:" + "<br>");
foreach (var StuGrp in result6)
{
Response.Write(StuGrp.Key + ":" + "<br>");
foreach (Student r in StuGrp)
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:

.NET 4.0 and Visual Studio 2010 Page 392 of 558


D. HARSHA VARDHAN

LINQ with Lambda Expressions


 LINQ queries can be written in two syntaxes:
1) General Query Syntax
2) Lambda Expression Syntax
 The previously written linq queries are written with ―General Query Syntax‖.
 Syntax for Lambda Expression:
DataSource.Clause(range_variable_name => Expression)
 Ex:
stu.Where(s => s.Marks < 300)

goes to

.NET 4.0 and Visual Studio 2010 Page 393 of 558


D. HARSHA VARDHAN

Demo on LINQ with Lambda Expressions:

 Open the previous demo web site.


 Add the ―linqwithlambda.aspx‖ page.
 Write the code:

linqwithlambda.cs

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


{
protected void Page_Load(object sender, EventArgs e)
{
//data source
Student[] stu = { new Student(101, "Prakash", "MBA", 765),
new Student(102, "Pradeep", "MBA", 471),
new Student(103, "Pushpa", "Msc", 590),
new Student(104, "Purna", "MCA", 223),
new Student(105, "Purnima", "MCA", 450)
};

Response.Write("<font face=Tahoma>");

//linq query with where clause


var result1 = stu.Where(s => s.Course == "MCA");
Response.Write("MCA Students:<br>");
foreach (Student r in result1)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with compound where clause


var result2 = stu.Where(s => s.Name.EndsWith("a") && s.Marks >= 400 && s.Marks
<= 600);
Response.Write("<br>Students whose name ends with 'a', and marks is >=400 and
<=600: <br>");
foreach (Student r in result2)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with orderby clause


var result4 = stu.OrderBy(s => s.Marks);
Response.Write("<br>Students (sort on marks): <br>");
foreach (Student r in result4)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with orderby clause (descending)


var result5 = stu.OrderByDescending(s => s.Marks);

.NET 4.0 and Visual Studio 2010 Page 394 of 558


D. HARSHA VARDHAN

Response.Write("<br>Students (sort on marks - descending): <br>");


foreach (Student r in result5)
Response.Write(r.StudentID + ", " + r.Name + ", " + r.Course + ", " + r.Marks +
"<br>");

//linq query with group clause


var result6 = stu.GroupBy(s => s.Course);
Response.Write("<br>Students with grouping: <br>");
foreach (var StuGrp in result6)
{
Response.Write(StuGrp.Key + ":");
foreach (Student r in StuGrp)
Response.Write(" " + r.StudentID + ", " + r.Name + ", " + r.Course + ", " +
r.Marks + "<br>");
}

Response.Write("</font>");
}
}

.NET 4.0 and Visual Studio 2010 Page 395 of 558


D. HARSHA VARDHAN

LINQ to SQL
 This is to get the database data and perform LINQ queries on database data.

Demo on LINQ to SQL:

 Open SQL Server 2005.


 Create the ―Customers‖ table as follows:

 Enter some sample data:

.NET 4.0 and Visual Studio 2010 Page 396 of 558


D. HARSHA VARDHAN

 Create the ―Orders‖ table as follows:

.NET 4.0 and Visual Studio 2010 Page 397 of 558


D. HARSHA VARDHAN

 Enter some sample data:

.NET 4.0 and Visual Studio 2010 Page 398 of 558


D. HARSHA VARDHAN

 Right click on ―Database Diagrams‖ and click on ―New Database Diagram‖.


 It displays ―Add Table‖ dialog box.

 Select ―Customers‖ table and click on ―Add‖.

.NET 4.0 and Visual Studio 2010 Page 399 of 558


D. HARSHA VARDHAN

 Select ―Orders‖ table and click on ―Add‖.


 Click on ―Close‖.
 Drag the ―CustomerID‖ column from ―Customers‖ table and drop it on ―CustomerID‖
column in ―Orders‖ table.
 Click on OK.
 Click on OK.
 Save the diagram.

 Open Visual Studio 2010.


 Open the previous demo web site.
 Open the solution explorer; right click on the web site name and choose ―Add New
Item‖.
 Select ―LINQ to SQL Classes‖.
 Enter the file name as ―MyDB.dbml‖. (DBML stands for Database Markup Language).
 It asks for confirmation, whether you want to place the file in the ―App_Code‖ folder or
not. Click on ―Yes‖.
 Open the ―Server Explorer‖ by clicking on ―View‖ menu – ―Server Explorer‖.
 Right click on ―Data Connections‖ and click on ―Add Connection‖.
 Click on ―Change‖.
 Select the required database. Ex: ―Microsoft SQL Server‖.
 Enter the following details:
1. Server name: localhost
2. Use SQL Server Authentication:
 User name: sa
 Password: 123
3. Database name: demo
 Click on ―Test Connection‖. It displays connection succeeded message.
 Click on OK.
 Then a connection component will be created in the ―Server Explorer‖.
 Expand the ―demo‖ database in the server explorer.
 Expand ―Tables‖.
 Drag and drop the ―Customers‖ table into the DBML designer.
 In the same way, drag and drop the ―Orders‖ table into the DBML designer.

.NET 4.0 and Visual Studio 2010 Page 400 of 558


D. HARSHA VARDHAN

 Click on the plain area and observe the properties window.


 It shows the DataContext name, associated with this DBML file.
Ex: MyDBDataContext
 This is the class name, using which you can create the object while you write the code.
 Using with that object, you can access the ―Customers‖ and ―Orders‖ tables data.
 But you don‘t require writing any code for database connection and retrieving the data
from the database.
 Open the solution explorer; right click on the web site name and choose ―Add New
Item‖.
 Select ―Web Form‖.
 Enter the name as ―linqtosqldemo.aspx‖.
 Click on ―Add‖.
 Design the ―linqtosqldemo.aspx‖ as follows:

.NET 4.0 and Visual Studio 2010 Page 401 of 558


D. HARSHA VARDHAN

 Write the code:

linqtosqldemo.aspx.cs:

protected void LinkButton1_Click(object sender, EventArgs e)


{
MyDBDataContext db = new MyDBDataContext();
var customerslist = from c in db.Customers select c;

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 = "";
}

.NET 4.0 and Visual Studio 2010 Page 402 of 558


D. HARSHA VARDHAN

protected void LinkButton3_Click(object sender, EventArgs e)


{
MyDBDataContext db = new MyDBDataContext();
var customerslist = db.Customers.Where(c => c.Gender == "Female");

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);

.NET 4.0 and Visual Studio 2010 Page 403 of 558


D. HARSHA VARDHAN

var customerslist2 = db.Customers.Where(c => c.Amount >= 6000 && c.Amount <=
8000);

var customerslist = customerslist1.Union(customerslist2);

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);

var customerslist = customerslist1.Intersect(customerslist2);

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);

var customerslist = customerslist1.Except(customerslist2);

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 = "";
}

.NET 4.0 and Visual Studio 2010 Page 404 of 558


D. HARSHA VARDHAN

protected void LinkButton12_Click(object sender, EventArgs e)


{
MyDBDataContext db = new MyDBDataContext();
var Sum = db.Customers.Select(ct => ct.Amount).Sum();
var Avg = db.Customers.Select(ct => ct.Amount).Average();
var Min = db.Customers.Select(ct => ct.Amount).Min();
var Max = db.Customers.Select(ct => ct.Amount).Max();
var Count = db.Customers.Select(ct => ct.Amount).Count();

Label2.Text = "Sum: " + Sum + "<br>";


Label2.Text += "Average: " + Avg + "<br>";
Label2.Text += "Minimum: " + Min + "<br>";
Label2.Text += "Maximum: " + Max + "<br>";
Label2.Text += "Count: " + Count + "<br>";

GridView1.DataSource = null;
GridView1.DataBind();
}

 Run the web site and click on the link buttons.

.NET 4.0 and Visual Studio 2010 Page 405 of 558


D. HARSHA VARDHAN

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

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


<employees>
<emp>
<empid>101</empid>
<empname>Ram</empname>
<salary>8739</salary>
</emp>
<emp>
<empid>102</empid>
<empname>Sita</empname>
<salary>6782</salary>
</emp>
<emp>
<empid>103</empid>
<empname>Laxman</empname>
<salary>7832</salary>
</emp>
</employees>

.NET 4.0 and Visual Studio 2010 Page 406 of 558


D. HARSHA VARDHAN

Application 28: Demo on XML Usage in ASP.NET

 Create a new web site.


 Add the ―Default.aspx‖ page.
 Open the solution explorer; right click on the web site name and choose ―Add New
Item‖.
 Select ―XML File‖.
 Enter the file name as ―employees.xml‖.
 Type the code:

employees.xml

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


<employees>
<emp>
<empid>101</empid>
<empname>Ram</empname>
<salary>8739</salary>
</emp>
<emp>
<empid>102</empid>
<empname>Sita</empname>
<salary>6782</salary>
</emp>
<emp>
<empid>103</empid>
<empname>Laxman</empname>
<salary>7832</salary>
</emp>
</employees>

 Design the ―Default.aspx‖ page as follows:

.NET 4.0 and Visual Studio 2010 Page 407 of 558


D. HARSHA VARDHAN

 Write the code:

Default.aspx.cs

using System.Data;

protected void Page_Load(object sender, EventArgs e)


{
DataSet ds = new DataSet();
string filename = Request.PhysicalApplicationPath + "\\employees.xml";
ds.ReadXml(filename);
GridView1.DataSource = ds;
GridView1.DataBind();
}

 Note: The ReadXml() method reads the data from the xml file and stores it into dataset.
 Run the web site.

.NET 4.0 and Visual Studio 2010 Page 408 of 558


D. HARSHA VARDHAN

 Output:

.NET 4.0 and Visual Studio 2010 Page 409 of 558


D. HARSHA VARDHAN

Web Site Configuration


 For every application, some settings will be there.
 For example, for MS Word, there is an option called ―Word Options‖, where you can set
some settings related to MS Word software. For another example, for winamp also some
settings will be there like last opened play list, last played media file, last used theme,
status of ―Repeat‖ and ―Shuffle‖ options etc.
 For the ASP.NET web sites also, some settings are there.
 Those settings are written in a file called ―web.config‖.
 In fact, there are two files:
1. web.config
2. machine.config
 The above two are called as web configuration files in ASP.NET.

Sl. No web.config machine.config


1 Contains the configuration settings, related Contains the configuration settings,
to a single web site. related to entire server machine.
2 Located in the web site folder. Located in the following folder.
C:\WINDOWS\Microsoft.NET\Framework\
v4.0.30319\Config\machine.config

 Note: Both of those files can be written in XML language.


 To open the machine.config file, open the following folder.
C:\WINDOWS\Microsoft.NET\Framework\ v4.0.30319\Config
 Double click on ―machine.config‖ file.

.NET 4.0 and Visual Studio 2010 Page 410 of 558


D. HARSHA VARDHAN

 Strict Caution: Don‘t make any changes, without proper knowledge; because it makes
ASP.NET malfunction in your system.

Application 29: Demo on Web Site Configuration

Understanding the web.config file:


 Create a new web site.
 When you create the web site, automatically this file will be created.
 To open this, open Solution Explorer and double click on ―web.config‖ file.

.NET 4.0 and Visual Studio 2010 Page 411 of 558


D. HARSHA VARDHAN

 The xml document starts with XML prologue, which specifies the xml version.

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

 All other code can be written a root element called <configuration>.

<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.

.NET 4.0 and Visual Studio 2010 Page 412 of 558


D. HARSHA VARDHAN

 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>

 Open the ―Default.aspx‖ page and design it as follows:

 Write the code:

.NET 4.0 and Visual Studio 2010 Page 413 of 558


D. HARSHA VARDHAN

using System.Configuration;

protected void Page_Load(object sender, EventArgs e)


{
Label2.Text = ConfigurationManager.AppSettings["CompanyLocation"];
Label3.Text = "Ph: " + ConfigurationManager.AppSettings["PhoneNo"];
}

 Run the web site. The output will be like this:

 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:

.NET 4.0 and Visual Studio 2010 Page 414 of 558


D. HARSHA VARDHAN

<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.

.NET 4.0 and Visual Studio 2010 Page 415 of 558


D. HARSHA VARDHAN

 Write the code:

using System.Data.SqlClient;

protected void Button1_Click(object sender, EventArgs e)


{
SqlConnection cn = new SqlConnection();
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString;
cn.Open();
Label4.Text = "Connected Successfully!!";
cn.Close();
}

 The next thing you have to observe is <compilation> tag.


 This tag specifies the mode of debug (true / false).

<compilation debug="true">

.NET 4.0 and Visual Studio 2010 Page 416 of 558


D. HARSHA VARDHAN

 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.

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

 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:

.NET 4.0 and Visual Studio 2010 Page 417 of 558


D. HARSHA VARDHAN

<error statusCode="404" redirect="FileNotFound.htm" />

 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‖.

.NET 4.0 and Visual Studio 2010 Page 418 of 558


D. HARSHA VARDHAN

 Enter the file name as ―FileNotFound.htm‖.


 Click on ―Add‖.
 Design the ―FileNotFound.htm‖ page as follows:

 Change the <customErrors> mode as ―On‖.

<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">


<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

 Run the web site and enter the non-existing file name as follows:

.NET 4.0 and Visual Studio 2010 Page 419 of 558

You might also like