ASP - Net Notes Final
ASP - Net Notes Final
ASP.NET
www.enosislearning.com
course@enosislearning.com
ASP.NET
Contents
1. Introduction to ASP.NET
What is Web Application? ................................................................................................................... 5
Front-End and Back-End Development ............................................................................................... 6
Introducing ASP?................................................................................................................................... 6
Problem with ASP……….…….................................................................................................................... 6
What is ASP.NET?................................................................................................................................... 7
Advantages of ASP.NET…….................................................................................................................... 8
ASP.NET Execution Cycle........................................................................................................................8
3. Web Server
What is Web Server?........................................................................................................................... 17
What is IIS?...............................………….................................................................................................18
Request Process on IIS..........................................................................................................................18
Worker Process ………............................................................................................................................18
Application Pool………...........................................................................................................................19
4. ASP.NET Controls
Controls in Web Development.............................................................................................................20
HTML Controls..........................…………................................................................................................20
ASP.NET Controls………..........................................................................................................................26
ASP.NET HTML Server Controls............................................................................................................26
ASP.NET Web Server Controls..............................................................................................................28
www.enosislearning.com Page 2
ASP.NET
6. GridView Control
Overview ……………………………...............................................................................................................44
How to use Gridview Control? ..…………................................................................................................45
7. Repeater Control
Overview ……………………………...............................................................................................................46
How to use Repeater Control? ..…………................................................................................................47
9. State Management
Overview……………………………..................................................................................................................59
Client Side State Management ..…………................................................................................................59
View State…………………....…………................................................................................................60
Control State……………....…………................................................................................................61
Hidden Fields ……………....…………................................................................................................63
Cookies ……………………....…………................................................................................................64
Query String ……………....…………................................................................................................69
10. Caching
Introducing Caching ……………….............................................................................................................77
www.enosislearning.com Page 3
ASP.NET
12. Ajax
Overview ………………………………............................................................................................................104
What is Ajax? …………….. ......................................................................................................................104
What does asynchronous refer to? .....................................................................................................104
Ajax Advantages ….…..………………..........................................................................................................105
Ajax Disadvantages …..…….…….............................................................................................................106
Update Panel ……………..……………..........................................................................................................107
Example on Update Panel …..…….……...................................................................................................111
www.enosislearning.com Page 4
ASP.NET
Chapter 1
INTRODUCTION
What is Web Application?
Web application or web app is a client-server program which run on web browser.
Example: - online shopping website.
Web application uses a combination of server-side scripts i.e php, ASP etc to handle the storage
and retrieval of the information and client-side scripts i.e JavaScript and HTML to present
information to users.
Web Application can be static (no processing is required) or dynamic (which required server side
processing).
www.enosislearning.com Page 5
ASP.NET
What is ASP?
There are many problems with ASP if you think of needs for Today's powerful Web applications.
www.enosislearning.com Page 6
ASP.NET
What is ASP.NET?
www.enosislearning.com Page 7
ASP.NET
Advantages of ASP.NET
A request for an .aspx file causes the ASP.NET runtime to parse the file for code that can be
compiled.
It then generates a page class that instantiates and populates a tree of server control instances.
This page class represents the ASP.NET page.
Now an execution sequence is started in which, for example, the ASP.NET page walks its entire
list of controls, asking each one to render itself.
The controls paint themselves to the page. This means they make themselves visible by
generating HTML output to the browser client.
www.enosislearning.com Page 8
ASP.NET
Chapter 2
The following table describes the stages of the ASP.NET application life cycle.
STAGE DESCRIPTION
User requests The life cycle of an ASP.NET application starts with a request sent by a browser to
an application the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI
resource from
the Web extension under the Web server. When a Web server receives a request, it examines
server. the file name extension of the requested file, determines which ISAPI extension
should handle the request, and then passes the request to the appropriate ISAPI
extension. ASP.NET handles file name extensions that have been mapped to it, such
as .aspx, .ascx, .ashx, and .asmx.
Note
If a file name extension has not been mapped to ASP.NET, then ASP.NET will not
receive the request. This is important to understand for applications that use
ASP.NET authentication. For example, because .htm files are typically not mapped
to ASP.NET, ASP.NET will not perform authentication or authorization checks on
requests for .htm files. Therefore, even if a file contains only static content, if you
want ASP.NET to check authentication, create the file using a file name extension
mapped to ASP.NET, such as .aspx.
Note
If you create a custom handler to service a particular file name extension, you must
map the extension to ASP.NET in IIS and also register the handler in your
application's Web.config file.
ASP.NET When ASP.NET receives the first request for any resource in an application, a class
receives the named ApplicationManager creates an application domain. Application domains
www.enosislearning.com Page 9
ASP.NET
first request for provide isolation between applications for global variables and allow each
the application. application to be unloaded separately. Within an application domain, an instance of
ASP.NET also compiles the top-level items in the application if required, including
application code in the App_Code folder. For more information, see "Compilation
Life Cycle" later in this topic.
ASP.NET core After the application domain has been created and the HostingEnvironment object
objects are instantiated, ASP.NET creates and initializes core objects such as HttpContext,
created for
each request. HttpRequest, and HttpResponse. The HttpContext class contains objects that are
specific to the current application request, such as the HttpRequest and
HttpResponse objects. The HttpRequest object contains information about the
current request, including cookies and browser information. The HttpResponse
object contains the response that is sent to the client, including all rendered output
and cookies.
An After all core application objects have been initialized, the application is started by
HttpApplication
creating an instance of the HttpApplication class. If the application has a Global.asax
object is
www.enosislearning.com Page 10
ASP.NET
assigned to the file, ASP.NET instead creates an instance of the Global.asax class that is derived from
request the HttpApplication class and uses the derived class to represent the application.
Note
www.enosislearning.com Page 11
ASP.NET
The request is The following events are executed by the HttpApplication class while the request is
processed by processed. The events are of particular interest to developers who want to extend
the
HttpApplication the HttpApplication class.
pipeline.
1. Validate the request, which examines the information sent by the browser
and determines whether it contains potentially malicious markup. For more
information, see ValidateRequest and Script Exploits Overview.
2. Perform URL mapping, if any URLs have been configured in the
UrlMappingsSection section of the Web.config file.
3. Raise the BeginRequest event.
4. Raise the AuthenticateRequest event.
5. Raise the PostAuthenticateRequest event.
6. Raise the AuthorizeRequest event.
7. Raise the PostAuthorizeRequest event.
8. Raise the ResolveRequestCache event.
9. Raise the PostResolveRequestCache event.
10. Based on the file name extension of the requested resource (mapped in the
application's configuration file), select a class that implements IHttpHandler
to process the request. If the request is for an object (page) derived from
the Page class and the page needs to be compiled, ASP.NET compiles the
page before creating an instance of it.
11. Raise the PostMapRequestHandler event.
12. Raise the AcquireRequestState event.
13. Raise the PostAcquireRequestState event.
14. Raise the PreRequestHandlerExecute event.
15. Call the ProcessRequest method (or the asynchronous version
BeginProcessRequest) of the appropriate IHttpHandler class for the request.
For example, if the request is for a page, the current page instance handles
the request.
16. Raise the PostRequestHandlerExecute event.
17. Raise the ReleaseRequestState event.
18. Raise the PostReleaseRequestState event.
www.enosislearning.com Page 12
ASP.NET
During the application life cycle, the application raises events that you can handle and calls
particular methods that you can override. To handle application events or methods, you can
create a file named Global.asax in the root directory of your application.
If you create a Global.asax file, ASP.NET compiles it into a class derived from the HttpApplication
class, and then uses the derived class to represent the application.
An instance of HttpApplication processes only one request at a time. This simplifies application
event handling because you do not need to lock non-static members in the application class
when you access them. This also allows you to store request-specific data in non-static members
of the application class. For example, you can define a property in the Global.asax file and assign
it a request-specific value.
ASP.NET automatically binds application events to handlers in the Global.asax file using the
naming convention Application_event, such as Application_BeginRequest. This is similar to the
way that ASP.NET page methods are automatically bound to events, such as the page's
Page_Load event.
TheApplication_Start and Application_End methods are special methods that do not represent
HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not
for each HttpApplication instance.
www.enosislearning.com Page 13
ASP.NET
•Raised at the appropriate time in the application life cycle, as listed in the application
life cycle table earlier in this topic.
•Application_Error can be raised at any phase in the application life cycle.
•Application_EndRequest is the only event that is guaranteed to be raised in every
request, because a request can be short-circuited. For example, if two modules handle
the Application_BeginRequest event and the first one throws an exception, the
Application_event
Application_BeginRequest event will not be called for the second module. However,
the Application_EndRequest method is always called to allow the application to clean
up resources.
• Called once for every instance of the HttpApplication class after all modules
have been created.
Init
• Called before the application instance is destroyed. You can use this method to
manually release any unmanaged resources.
Dispose
• Called once per lifetime of the application before the application is unloaded.
Application_End
www.enosislearning.com Page 14
ASP.NET
The requesting of an ASP.NET page triggers a sequence of events that encompass the page life
cycle. The Web browser sends a post request to the Web server. The Web server recognizes the
ASP.NET file extension for the requested page and sends the request to the HTTP Page Handler
class. The following list is a sampling of these events, numbered in the order in which they are
triggered.
PreInt
Unload Init
SaveState
Complete ASP.NET InitComplete
PreRender Load
Load
Complete
www.enosislearning.com Page 15
ASP.NET
PreInt: This is the entry point of the ASP.NET page life cycle - it is the pre-initialization, so you
have access to the page before it is initialized. Controls can be created within this event. Also,
master pages and themes can be accessed. You can check the IsPostBack property here to
determine if it is the first time a page has been loaded.
Init: This event fires when all controls on the page have been initialized and skin settings have
been applied. You can use this event to work with control properties. The Init event of the page
is not fired until all control Init events have triggered - this occurs from the bottom up.
InitComplete: This event fires once all page and control initializations complete. This is the last
event fired where ViewState is not set, so ViewState can be manipulated in this event.
PreLoad: This event is triggered when all ViewState and Postback data have been loaded for the
page and all of its controls - ViewState loads first, followed by Postback data.
Load: This is the first event in the page life cycle where everything is loaded and has been set to
its previous state (in the case of a Postback). The page Load event occurs first followed by the
Load event for all controls (recursively). This is where most coding is done, so you want to check
the IsPostBack property to avoid unnecessary work.
LoadComplete: This event is fired when the page is completely loaded. Place code here that
requires everything on the page to be loaded.
PreRender: This is the final stop in the page load cycle where you can make changes to page
contents or controls. It is fired after all Postback events and before ViewState has been saved.
Also, this is where control databinding occurs.
PreRenderComplete: This event is fired when PreRender is complete. Each control raises this
event after databinding (when a control has its DataSourceID set).
SaveStateComplete: This is triggered when view and control state have been saved for the page
and all controls within it. At this point, you can make changes in the rendering of the page, but
those changes will not be reflected on the next page Postback since view state is already saved.
Unload: This event fires for each control and then the page itself. It is fired when the HTML for
the page is fully rendered. This is where you can take care of cleanup tasks, such as properly
closing and disposing database connections.
www.enosislearning.com Page 16
ASP.NET
Chapter 3
WEB SERVER
When we run our ASP.NET Web Application from visual studio IDE, VS Integrated ASP.NET
Engine is responsible to execute all kind of asp.net requests and responses. The process name is
"WebDev.WebServer.Exe" which actually take care of all request and response of an web
application which is running from Visual Studio IDE.
Now, the name “Web Server” come into picture when we want to host the application on a
centralized location and wanted to access from many locations. Web server is responsible for
handle all the requests that are coming from clients, process them and provide the responses.
Server Recieved
The Request
Process The
Request and Send
Back To Client
www.enosislearning.com Page 17
ASP.NET
What is IIS?
IIS (Internet Information Server) is one of the most powerful web servers from Microsoft that is
used to host your ASP.NET Web application. IIS has its own ASP.NET Process Engine to handle
the ASP.NET request. So, when a request comes from client to server, IIS takes that
request and process it and send response back to clients.
Worker Process
Worker Process (w3wp.exe) runs the ASP.Net application in IIS.
This process is responsible to manage all the request and response that are coming from client
system.
All the ASP.Net functionality runs under the scope of worker process.
When a request comes to the server from a client worker process is responsible to generate the
request and response. In a single word we can say worker process is the heart of ASP.NET Web
Application which runs on IIS.
www.enosislearning.com Page 18
ASP.NET
Application Pool
Application pool is the container of worker process.
Application pools is used to separate sets of IIS worker processes that share the same
configuration.
Application pools enables a better security, reliability, and availability for any web application.
The worker process serves as the process boundary that separates each application pool so that
when one worker process or application is having an issue or recycles, other applications or
worker processes are not affected. This makes sure that a particular web application doesn't not
impact other web application as they are configured into different application pools.
If we look into the IIS 6.0 Architecture, we can divided them into Two Layer
Kernel Mode
User Mode
Now, Kernel mode is introduced with IIS 6.0, which contains the HTTP.SYS. So whenever a request
comes from Client to Server, it will hit HTTP.SYS First.
www.enosislearning.com Page 19
ASP.NET
Chapter 4
ASP.NET CONTROLS
HTML Controls
Basic Tags
<head></head> Sets off the title and other information that isn’t
displayed on the web page itself
Body Attributes
<body bgcolor="pink"> Sets the background color, using name or hex value
<body text="black"> Sets the text color, using name or hex value
<body link="blue"> Sets the color of links, using name or hex value
www.enosislearning.com Page 20
ASP.NET
<body vlink="#ff0000"> Sets the color of followed links, using name or hex value
<body ondragstart="return false" Disallows text selection with the mouse and keyboard
onselectstart="return false">
Text Tags
Links
www.enosislearning.com Page 21
ASP.NET
<a href="#NAME"></a> Links to that target location from elsewhere in the document
Formatting
<div align="left"> A generic tag used to format large blocks of HTML, also
used for stylesheets
<imgsrc="name" align="left"> Aligns an image: left, right, center; bottom, top, middle
www.enosislearning.com Page 22
ASP.NET
Tables
<th></th> Sets off the table header (a normal cell with bold,
centered text)
Table Attributes
<table cellpadding="1"> Sets amount of space between a cell’s border and its
contents
<tr align="left"> or <td align="left"> Sets alignment for cell(s) (left, center, or right)
<tr valign="top"> or <td valign="top"> Sets vertical alignment for cell(s) (top, middle, or
bottom)
<tdnowrap> Prevents the lines within a cell from being broken to fit
Frames
www.enosislearning.com Page 23
ASP.NET
Frames Attributes
<frame marginwidth="value"> Defines the left and right margins for the frame; must be
equal to or greater than 1
<frame marginheight="value"> Defines the top and bottom margins for the frame; must
be equal to or greater than 1
<frame scrolling="value"> Sets whether the frame has a scrollbar; value may equal
“yes,” “no,” or “auto.” The default, as in ordinary
documents, is auto.
Forms
For functional forms, you’ll have to run a script. The HTML just creates the appearance of a form.
www.enosislearning.com Page 24
ASP.NET
<select multiple name="NAME" size=?></select> Creates a scrolling menu. Size sets the number
of menu items visible before you need to
scroll.
<textarea name="NAME" cols=40 Creates a text box area. Columns set the
rows=8></textarea name> width; rows set the height.
<input type="radio" name="NAME" value="x"> Creates a radio button. Text follows tag
<input type="text" name="NAME" size=20> Creates a one-line text area. Size sets length,
in characters.
HTML 5 adds a few (and HTML5 seems to not use some of the ones above as well):
<audio src=url>
<button formaction=url>
<command icon=url>
<embed src=url>
<html manifest=url>
<input formaction=url>
<source src=url>
<video poster=url> and <video src=url>
www.enosislearning.com Page 25
ASP.NET
In addition, the style attribute can contain css declarations with one or several urls. For example: <div
style="background: url(image.png)">
ASP.NET Controls
Server Controls are the tags that are understood by the server. There are basically three types of
server controls
www.enosislearning.com Page 26
ASP.NET
Note: All HTML server controls must be within a <form> tag with the runat="server" attribute. The
runat="server" attribute indicates that the form should be processed on the server. It also indicates
that the enclosed controls can be accessed by server scripts.
www.enosislearning.com Page 27
ASP.NET
www.enosislearning.com Page 28
ASP.NET
www.enosislearning.com Page 29
ASP.NET
To prevent this, you have to set the CausesValidation property for the control to False.
www.enosislearning.com Page 31
ASP.NET
The RequiredFieldValidator server control makes sure that the user enters something into the
field that it is associated with in the form. You need to tie the RequiredFieldValidator to each
control that is a required field in the form.
www.enosislearning.com Page 32
ASP.NET
The CompareValidator server control compares the value entered into the form field to another
field, a database value, or other value that you specify. When comparing against data types, you
just set the Operator—DataTypeCheck. After that is done, you can set the Type attribute to
String, Integer, Double, Date, or Currency in the CompareValidator control to make sure that the
user's input into the field is the specified type.
Using the CompareValidator server control, you can make comparisons between different
controls within a form on your ASP.NET page. For example, if you want to compare what the
user enters in the Password field to the entry in the Confirm Password field to see whether they
are the same, you can use the CompareValidator server control.
<p>
Password<br>
<asp:TextBox id="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
<asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="Passwords
do not match!" ControlToValidate="TextBox2" ControlToCompare="TextBox1"></asp:Compa
reValidator>
</p>
<p>
Confirm Password<br>
www.enosislearning.com Page 33
ASP.NET
You can also use the CompareValidator server control to make sure that the value typed into the
form field by a user is valid when compared against a constant, some dynamic value that you
retrieve, or that it adheres to a specific data type. Listing 7 shows an example of this.
Age:
<asp:TextBox id="TextBox1" runat="server" MaxLength="3"></asp:TextBox>
<asp:CompareValidator id="CompareValidator1" runat="server"
ErrorMessage="You must enter a number" ControlToValidate="TextBox1" Type="Integer"
Operator="DataTypeCheck"></asp:CompareValidator>
In this example, the user must enter an integer in the text box; otherwise, the CompareValidator
server control fires and displays an error message on the page. By giving the Type property of
the CompareValidator server control a value of Integer, you ensure that the value entered in the
text box conforms to this .NET Framework data type.
You also have the option of not only comparing values against specific data types, but also
ensuring that values are valid when compared against certain constants (see Listing 8).
Age:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
www.enosislearning.com Page 34
ASP.NET
18 to join" Type="Integer">
</asp:CompareValidator>
The RangeValidator server control is similar to the CompareValidator server control, but the
RangeValidator server control compares what is entered into the form field with two values and
makes sure that what was entered by the user is between these two specified values.
Marks:
<asp:TextBoxID="txtMarks"runat="server"/>
<asp:RangeValidatorID="rvMarks"runat="server"
Type="Integer"MinimumValue="0"MaximumValue="100"/>
For instance, imagine that you have a text box where you want end users to enter their ages
Age:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator id="RangeValidator1" runat="server"
ControlToValidate="TextBox1" Type="Integer"
ErrorMessage="You must be between 30 and 40"
MaximumValue="40" MinimumValue="30"></asp:RangeValidator>
www.enosislearning.com Page 35
ASP.NET
In this case, the user should enter a value between 30 and 40 in the text box. If some number is
entered that is outside of this range, the RangeValidator server control fires an error message
and considers the form submission invalid.
The Type property enables you to make comparisons against many different .NET Framework
types, such as String, Integer, Double, Date, and Currency. These choices enable you to do a
number of range comparisons. You can also use the Date value for the Type property to make
sure that the entry is between specific date ranges.
For example, if the user is entering her last name, and you want only people with last names
starting with M and P to proceed, you can easily do this by using the RangeValidator server
control, as illustrated in Listing 10.
Last name:
ControlToValidate="TextBox1"
MaximumValue="Q" MinimumValue="M"></asp:RangeValidator>
In the example in Listing 10, the value is being checked against a range that is specified by using
the MaximumValue and MinimumValue properties. In this example, that the Type property is
not specified. In this case, it doesn't need to be specified because the default value of the Type
property is String.
Age:
<asp:TextBoxid="TextBox4"runat="server"></asp:TextBox>
www.enosislearning.com Page 36
ASP.NET
<asp:RangeValidatorid="RangeValidator1"runat="server"
ControlToValidate="TextBox4"Type="Integer"
MaximumValue="40"MinimumValue="30"></asp:RangeValidator>
<br/>
Last name:
<asp:TextBoxid="TextBox5"runat="server"></asp:TextBox>
<asp:RangeValidatorid="RangeValidator2"runat="server"
ControlToValidate="TextBox5"
MaximumValue="Q"MinimumValue="M"></asp:RangeValidator>
The RegularExpressionValidator server control is a validation control that enables you to check
the user's input based on a pattern defined by a regular expression. In the past, these kinds of
validations took a considerable amount of JavaScript coding. The RegularExpressionValidator
control with ASP.NET saves coding time.
www.enosislearning.com Page 37
ASP.NET
For an example of using the RegularExpressionValidator server control to make sure that a value
entered in a text box is an e-mail address, look at Listing 11.
<asp:RegularExpressionValidator id="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox1"
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
To use an image instead of text for your error messages, you use an HTML string that points to
the image that you want to display for the value of the ErrorMessage property (see Figure 7).
Validation Expressions
www.enosislearning.com Page 39
ASP.NET
Phone ^[01]?[- .]?(\([2-9]\d{2}\)|[2- (425) 555-0123 Validates a U.S. phone number. It must
Number 9]\d{2})[- .]?\d{3}[- .]?\d{4}$ 425-555-0123 consist of 3 numeric characters, optionally
425 555 0123 enclosed in parentheses, followed by a set
1-425-555-0123 of 3 numeric characters and then a set of 4
numeric characters.
<asp:RegularExpressionValidator ID="RegularExpressionValidator2"
runat="server" ErrorMessage="Please Enter Valid Email ID"
ValidationGroup="vgSubmit" ControlToValidate="txtEmail"
CssClass="requiredFieldValidateStyle"ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
www.enosislearning.com Page 40
ASP.NET
Chapter 5
Overview
The upload process is quite simple. There are always two parts, the client and server sides, that
communicate with each other through HTTP requests and responses. Let’s consider the usual
upload scenario:
A user visits a web page and chooses files to upload.
The client application packs these files to a POST request and sends it to the server.
The server parses the request, handles it (for example, saves files on a hard disk),
and sends a response to the client side.
FileUpload allows a user to choose a file to be uploaded via the Browse button. The control
doesn’t automatically save a selected file to the server, but it exposes the SaveAs method to
perform this. Deploying FileUpload in your web application is very easy.
<html>
<head>
<title>Upload Files</title>
</head>
www.enosislearning.com Page 41
ASP.NET
<body>
<br/>
OnClick="UploadButton_Click"
<br/>
</form>
</body>
</html>
After running this page, you will see the following interface:
www.enosislearning.com Page 42
ASP.NET
if (FileUpload1.HasFile)
try
FileUpload1.SaveAs(Server.MapPath("~/uploads/") +
FileUpload1.FileName);
FileUpload1.PostedFile.FileName + "<br>" +
else
This event handler checks if any file has been specified, tries to save it to the uploads folder, and
displays a message indicating whether the file has been saved successfully.
Note: - The FileUpload1 name is similar to the FileUpload id attribute in the client form discussed
above.
www.enosislearning.com Page 43
ASP.NET
Chapter 6
GRIDVIEW CONTROL
GridView control is used to display whole table data on web page. In GridView control each
column define a filed or title, while each rows represents a record or data.
The GridView control display data with rows and columns wise, we can display whole table in
GridView and we also display only required columns from table in GridView control in asp.net.
In GridView control we can easily do sorting, paging and inline editing.
Also we can perform editing and deleting operation on displayed data with GridView control.
GridView Example:
Step 1 – Open the Visual Studio –> Create a new empty Web application.
Step 3 – Drag and drop GridView Control on web page from toolbox.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
www.enosislearning.com Page 44
ASP.NET
using System.Data;
}
protected void btnview_Click(object sender, EventArgs e)
{
SqlConnection SQLConn = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial
Catalog='Blog';Integrated Security=True");
SqlDataAdapter SQLAdapter = new SqlDataAdapter("Select * from UserMst", SQLConn);
DataTable DT = new DataTable();
SQLAdapter.Fill(DT);
GridView1.DataSource = DT;
GridView1.DataBind();
}
www.enosislearning.com Page 45
ASP.NET
Chapter 7
REPEATER CONTROL
A Repeater is a Data-bound control. Data-bound controls are container controls. It creates a link
between the Data Source and the presentation UI to display the data. The repeater control is
used to display a repeated list of items.
A Repeater has five inline templates to format it:
<HeaderTemplate>
<AlternatingItemTemplate>
<Itemtemplate>
<SeperatorTemplate>
<FooterTemplate>
<HeaderTemplate>
Displays Header text for a Data Source collection and applies a different style for the Header
text.
<AlternatingItemTemplate>
Changes the background color or style of alternating items in a Data Source collection.
<Itemtemplate>
It defines how the each item is rendered from the Data Source collection.
<SeperatorTemplate>
It will determine the separator element that separates each item in the item collection. It will be
a <br> or <Hr> HTML element.
<FooterTemplate>
www.enosislearning.com Page 46
ASP.NET
Table Query
Complete Program
Repeter_Control_Example.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
SqlCommand cmd;
www.enosislearning.com Page 47
ASP.NET
SqlDataAdapter da;
DataSet ds;
Info=True;User ID=sa;Password=****");
if (!IsPostBack)
RepeterData();
}
protected void btnSubmit_click(object sender, EventArgs e)
try
{
con.Open();
values(@userName,@subject,@comment,@date)", con);
cmd.ExecuteNonQuery();
con.Close();
txtName.Text = string.Empty;
txtSubject.Text = string.Empty;
txtComment.Text = string.Empty;
RepeterData();
www.enosislearning.com Page 48
ASP.NET
catch(Exception ex)
{
txtComment.Text= ex.Message;
}
}
public void RepeterData()
{
con.Open();
cmd = new SqlCommand("Select * from Comment Order By Post_Date desc", con);
da.Fill(ds);
RepterDetails.DataSource = ds;
RepterDetails.DataBind();
}
}
Repeter_Control_Example.aspx
Inherits="Repeter_Control_Example" %>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</head>
<body>
<form id="form1" runat="server">
www.enosislearning.com Page 49
ASP.NET
<table>
<tr>
<td>Enter Name:</td>
<td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Enter Subject:</td>
</tr>
<tr>
<td valign="top">Enter Comments:</td>
TextMode="MultiLine"></asp:TextBox></td>
</tr>
<tr>
<td></td>
/></td>
</tr>
</table>
</div>
<div>
<asp:Repeater ID="RepterDetails" runat="server">
<HeaderTemplate>
<table style="border:1px solid #0000FF; width:500px" cellpadding="0">
</td>
</tr>
www.enosislearning.com Page 50
ASP.NET
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color:#EBEFF0">
<td>
<td >
Subject:
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblComment" runat="server" Text='<%#Eval("CommentOn") %>'/>
</td>
</tr>
<tr>
<td>
<tr>
<td >Post By: <asp:Label ID="lblUser" runat="server" Font-Bold="true" Text='<%#Eval("UserName")
%>'/></td>
<td >Created Date:<asp:Label ID="lblDate" runat="server" Font-Bold="true"
Text='<%#Eval("Post_Date") %>'/></td>
</tr>
</table>
</td>
</tr>
www.enosislearning.com Page 51
ASP.NET
<tr>
<td colspan="2"> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
www.enosislearning.com Page 52
ASP.NET
Chapter 8
2) Save this website in you local file system and give it a name. Choose C# as your development
language for this website
4) Right-click on this folder and add a new item. From all the items available select a Web User control.
Also choose C# as the devlopment language and tick the option Place code in a seperate file.Name the
control Address.ascx
5) Switch to the Source view of the Address.ascx control.Have a look at the first line.
Notice that even though this directive looks a lot like a page directive it starts with @ Control
6) Open the Address.ascx.cs file.Your newly create class does not inherit from
theSystem.Web.UI.Page but from
The classes System.Web.UI.Page and System.Web.UI.UserControl have lots in common since they both
inherit from another class,TemplateControl class
www.enosislearning.com Page 53
ASP.NET
7) Let’s work on our new user control. Insert a table in your “Address.ascx” page. This table should have
4 rows and 2 columns.
8) Add 4 label web server controls on the first 4 rows of the first column. Set their IDproperty as you
like(AddressLabel1,AddressLabel2,AddressLabel3,PostCodeLabel). Set their text property like this
Address1
Address2
Address3
PostCode
9) Add 4 textbox web server controls on the 4 rows of the second column.Set their IDproperty like this
10) In order to add this newly created web user control to the Default.aspx page just drag and drop it
from the Solution Explorer onto the .aspx page
11) Look in the source view of the Default.aspx page and notice this line
This is how the user control is registered with the .aspx page. You will also see this
12) We can add new server controls to our user control. If we wanted to have a label control as a header
we must select the Address.ascx and just above the table to insert a new label.Name this
label headingLabel.
One can set the Text property of this new header label control and make it apparent to the end use that
we talk about Shipping Address. But as I mentioned before we need to use this user control in many
places in our website. So we do not want to have a fixed Textproperty but one we can set its value
accordingly.
section you will see thatheadingLabel is not exposed as a property. It cannot be accessed from our
page.
www.enosislearning.com Page 54
ASP.NET
So we must add a new public property on this UserControl_Address class.This is the same with every
other normal class.
13) Now you can go back to the Default.aspx page (Source View) and add theHeader=Shipping Address
14) It is very easy to handle events in a user control.Add a button to the user control. This means that
you go to the Address.ascx file and drop a button under the table. Set the IDproperty to be txtNext and
the Text property to be Next. Add another .aspx page to your website and call it Checkout.aspx. Double
click on the button and you have the empty event handling routine.
14 ) Let’s see now, how we can create an event in the user control. First we need to define an event.
When we define an event we must define the signature of the event handler method. We do that by
choosing a delegate type.We also must give a name to our event. We will call itConfirmed event.
So we know now that our user control class will raise an event and we must write some code to actually
cause this event to be raised.
www.enosislearning.com Page 55
ASP.NET
When the user clicks the button, the Confirmed event will be raised.
Select the Default.aspx page and in the Source View locate the
and change it to
We just added the event handler in the user control.We do that by entering the name of the event and
the name of the event handling routine we will add shortly.
Run the application and you will see the event raised and handled (the text “The event has been
handled” will be printed in the Default.aspx page)
15) Let’s assume that we need 2 instances of our user contol in the Default.aspx page (e.g one for
shipping address and one for billing address).Select the Default.aspx and add a new user control. Go to
the Source View and add a Header property e.g Billing Address. Also set the ID property to
“Billing_Address“. You should have something like this
We need to copy all the fields entered in our Shipping address to the Billing address fields.
So we must access the text properties of the Shipping_Address user control and copy them to
the Billing_Address user control.
www.enosislearning.com Page 56
ASP.NET
You will see that it is impossible to access these textbox values directly fromShippingAdress_Confirmed
event handler in the Default.aspx.cs class, because these text properties are protected and thus invisible
to the event handling routine.
16) Select the Default.aspx.cs file and inside the ShippingAddress_Confirmed event handling routine,
comment out the ( Response.Write(“The event has been handled”);) and type
Billing_Address.Address1 = Shipping_Address.Address1;
Billing_Address.Address2 = Shipping_Address.Address2;
www.enosislearning.com Page 57
ASP.NET
Billing_Address.Address3 = Shipping_Address.Address3;
Billing_Address.PostCode = Shipping_Address.PostCode;
Run your application. Type some address data into the first user control and then click the button. You
will see the entered data copied in the second user control.
www.enosislearning.com Page 58
ASP.NET
Chapter 9
STATE MANAGEMENT
State Management
HTTP is a stateless Protocol.
A client open a connection and request some information. The server respond with a requested
resources if available. After, closing the connection, the server does not remember any
information about the client. So, server considers the next request from the same client as a
fresh request, with no relation to the previous request.
State management means to preserve state of a control, web page, object/data, and user in the
application explicitly because all ASP.NET web applications are stateless, i.e., by default, for each
page posted to the server, the state of controls is lost.
Types of State Management:-
www.enosislearning.com Page 59
ASP.NET
View State
ViewState is an approach to saving data for the user.
Because of the stateless nature of web pages, regular page member variables will not maintain
their values across postbacks. ViewState is the mechanism that allows state values to be
preserved across page postbacks and by default, EnableViewState property will be set to true.
Stores values per control by key name, like a Hashtable.
Tracks changes to a View State value's initial state.
Serializes and Deserializes saved data into a hidden form field on the client.
Automatically restores View State data on postbacks.
View State
Pros Cons
Easy to use
can't store large values
Encrypted
Required computational efforts on server
Having good security
Can be used within a page
Fast to retrive and use
Sample:
Here is a simple example of using the "ViewState" property to carry values between
postbacks.
www.enosislearning.com Page 60
ASP.NET
Code Example:
publicintSomeInteger {
get {
object o = ViewState["SomeInteger"];
if (o != null) return (int)o;
return 0;
//a default
}
set { ViewState["SomeInteger"] = value;
Control State
The purpose of the control state repository is to cache data necessary for a control to properly
function. ControlState is essentially a private ViewState for your control only, and it is not
affected when ViewState is turned off. ControlState is used to store small amounts of critical
information. Heavy usage of ControlState can impact the performance of application because it
involves serialization and deserialization for its functioning.
There are two methods you have to implement in your custom control.
Load Control State
Save Control State
Control State
Pros
No Server resorces required
Cons
Reliability Progrmming is reqired
Versatility
www.enosislearning.com Page 61
ASP.NET
Code Example:
publicclassControlStateWebControl : Control
{
#region Members
privatestring _strStateToSave;
#endregion
#region Methods
protectedoverridevoidOnInit(EventArgs e)
{
Page.RegisterRequiresControlState(this);
base.OnInit(e);
}
protectedoverrideobjectSaveControlState()
{
return _strStateToSave;
}
protectedoverridevoidLoadControlState(object state)
{
if (state != null)
{
_strStateToSave = state.ToString();
}
}
#endregion
}
www.enosislearning.com Page 62
ASP.NET
Hidden Fields
A Hidden control is the control which does not render anything on the web page at client
browser but can be used to store some information on the web page which can be used on the
page. Hidden fields are used to store data at the page level. These fields are not rendered by the
browser, rather it's just like a standard control for which you can set its properties. If you use
hidden fields, it is best to store only small amounts of frequently changed data on the client.
Hidden Fields
Pros Cons
Potential security risk
No server resorces required
Simple storage architecture
Widespread support
Performance consideration
Simple Implementation
Storage Limitations
Sample:
//Declaring a hidden variable
protectedHtmlInputHiddenhidNickName;
Code Example:
protectedvoidPage_Load(object sender, EventArgs e)
{
if(!IsPostBack)|
Label1.Text = string.Format("Clicked {0} times", HiddenField1.Value);
}
www.enosislearning.com Page 63
ASP.NET
Cookies
A cookie is a small amount of data which is either stored at client side in text file or in memory
of the client browser session.
Cookies are always sent with the request to the web server and information can be retrieved
from the cookies at the web server. Every time a user visits a website, cookies are retrieved
from the user machine and help identify the user.
Cookies are useful for storing small amounts of frequently changed information on the client.
The information is sent with the request to the server.
Cookies
Pros Cons
Confugirable expiration rules
User Configured refusal
No server resources are required
Potential security risk
Simplicity
Size Limitations
Data Persistence
Sample:
// Creating a cookie
myCookie.Values.Add("muffin", "chocolate");
myCookie.Values.Add("babka", "cinnamon");
www.enosislearning.com Page 64
ASP.NET
Code Example:
//Storing value in cookie
HttpCookie cookie = new HttpCookie("NickName");
cookie.Value = "David";
Response.Cookies.Add(cookie);
Response.Redirect("Page2.aspx");
//Retrieving value in cookie
if (Request.Cookies.Count> 0 && Request.Cookies["NickName"] != null)
lblNickName.Text = "Welcome" + Request.Cookies["NickName"].Value.ToString();
else
lblNickName.Text = "Welcome Guest";
www.enosislearning.com Page 65
ASP.NET
Response.Cookies["StudentCookies"].Value = TextBox1.Text;
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["StudentCookies"]["RollNumber"] = TextBox1.Text;
Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu";
Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar";
Response.Cookies["StudentCookies"]["LastName"] = "Vatsa";
Response.Cookies["StudentCookies"]["TotalMarks"] = "499";
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1);
Reading/Getting Cookies
In the above code, I have used many ways to write or create cookies so I need to write here
using all the above ways separately.
For Way 1
For Way 2
For Way 3
string roll;
roll = Request.Cookies["StudentCookies"]["RollNumber"];
roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"];
www.enosislearning.com Page 66
ASP.NET
Deleting Cookies
In the above code, I have used many ways to create or read cookies. Now look at the code given
below which will delete cookies.
if (Request.Cookies["StudentCookies"] != null)
{
Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(-1);
Response.Redirect("Result.aspx"); //to refresh the page
}
www.enosislearning.com Page 67
ASP.NET
Limitations of Cookies
There are following limitations for cookies:
o Size of cookies is limited to 4096 bytes.
o Total 20 cookies can be used on a single website; if you exceed this browser will delete
older cookies.
o End user can stop accepting cookies by browsers, so it is recommended to check the
users’ state and prompt the user to enable cookies.
Sometimes, the end user disables the cookies on browser and sometimes browser has no such
feature to accept cookies. In such cases, you need to check the users’ browser at the home page
of website and display the appropriate message or redirect on appropriate page having such
message to enable it first. The following code will check whether the users’ browser supports
cookies or not. It will also detect if it is disabled too.
if (Request.Browser.Cookies)
Else
www.enosislearning.com Page 68
ASP.NET
Query String:
A Query string is used to pass the values or information form one page to another page. They
are passed along with URL in clear text. Query strings provide a simple but limited way of
maintaining some state information. When surfing the internet you should have seen weird
internet addresses such as:
http://www.localhost.com/Webform2.aspx?name=ABC&lastName=XYZ
This HTML address uses a QueryString property to pass values between pages.
Query String
Pros Cons
Widespread Support Potential Security Risk
No Server resources are required Limited Capacity
Simple Implementation Size Limitations
Syntax:
Request.QueryString(variable)[(index)|.Count]
Code Example:
using System;
usingSystem.Web.UI;
publicpartialclass_Default : Page
{
protectedvoidPage_Load(object sender, EventArgs e)
{
www.enosislearning.com Page 69
ASP.NET
string v = Request.QueryString["param"];
if (v != null)
{
Response.Write("param is ");
Response.Write(v);
}
string x = Request.QueryString["id"];
if (x != null)
{
Response.Write(" id detected");
}
}
}
Application State:
Application State is used to store information which is shared among users of the ASP.Net web
application. Application state is stored in the memory of the windows process which is
processing user requests on the web server. Application state is useful in storing a small amount
of often-used data. If application state is used for such data instead of frequent trips to the
database, then it increases the response time/performance of the web application.
In classic ASP, an application object is used to store connection strings. It's a great place to store
data that changes infrequently.
Application State
Pros Cons
Simple Implementation Resources Requirement
Application Scope Limited durability of data
www.enosislearning.com Page 70
ASP.NET
Code Example 1:
Code Example 2:
Session State:
ASP.NET Session state provides a place to store values that will persist across page requests.
Values stored in Session are stored on the server and will remain in memory until they are
explicitly removed or until the Session expires. It is defined as the period of time that a unique
user interacts with a Web application. Session state is a collection of objects, tied to a session
stored on a server.
Session State
Pros
Sesssion specific events
Data Persistence
Cons
Platform scalability Performance Consideration
cokkisless Support
Extensibility
Sample:
www.enosislearning.com Page 71
ASP.NET
Code Example:
objectsessionObject = Session["someObject"];
if (sessionObject != null)
{
myLabel.Text = sessionObject.ToString();
}
Profile Properties:
ASP.NET provides a feature called profile properties, which allows you to store user-specific
data. It is similar to session state, except that unlike session state, the profile data is not lost
when a user's session expires. The profile properties feature uses an ASP.NET profile, which is
stored in a persistent format and associated with an individual user. In this each user has its own
profile object.
Profiler Properties
Pros Cons
DataPersistence Performance Consideration
Platform Scalability Additonal Configuration requirements.
Extensibility Data Maintainence
Sample:
<profile>
<properties>
<add item="item name" />
www.enosislearning.com Page 72
ASP.NET
</properties>
</profile>
Code Example:
Global.asaxfile:
Global.asax file is ASP.NET application file. Global.asax is extension of Global Application Class.
Global.asax file resides in the IIS virtual root of an ASP.NET application. It is used to declare
application level variable. There are many events in Global.asax file which are as follows:
www.enosislearning.com Page 73
ASP.NET
Application_Init •Fires when the application initializes for the first time.
Example :
HIT counter
Solution Explorer->Right click->add->new item->Global application class (Global.asax)->add likes
below image.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
www.enosislearning.com Page 74
ASP.NET
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.SessionState;
namespace Application
{ publicclassGlobal : System.Web.HttpApplication
{
protectedvoidApplication_Start(object sender, EventArgs e)
{
Application["hits"] = 0;
}
protectedvoidSession_Start(object sender, EventArgs e)
{
Application["hits"] = Int32.Parse(Application["hits"].ToString()) + 1;
}
protectedvoidApplication_BeginRequest(object sender, EventArgs e)
{
}
protectedvoidApplication_AuthenticateRequest(object sender, EventArgs e)
{
}
protectedvoidApplication_Error(object sender, EventArgs e)
{
}
protectedvoidSession_End(object sender, EventArgs e)
{
}
protectedvoidApplication_End(object sender, EventArgs e)
{
}
}
}
Now we will take a button on web form then coding on button click.
using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
namespace Application
{
publicpartialclass_Default : System.Web.UI.Page
{
protectedvoidPage_Load(object sender, EventArgs e)
{
www.enosislearning.com Page 75
ASP.NET
}
protectedvoid Button1_Click(object sender, EventArgs e)
{
Response.Write("<h1>Your are user Number-->" + Application["hits"].ToString());
}
}
}
Point to remeber
State management is the process by which you maintain state and page
information over multiple requests for the same or different pages.
www.enosislearning.com Page 76
ASP.NET
Chapter 10
CACHING
Overview
The majority [if not all] of the pages in a dynamic website are dynamic. That is, pages that are
created on user request. As we all know, dynamic web pages help to provide dynamic content,
customized for the user requesting the page [e.g.: the user's home page]. Dynamic pages also
help provide dynamic content fetched from a changing data store without the need for the
administrator to change the page content every time something changes in the data store [e.g.:
Listing of books in a publisher's website]. The disadvantage is the overhead in creating the pages
for every user request.
To overcome this, some websites have page creation engines which create all pages in one go
and save them as HTML pages which are then served to the users. But this will only help in
scenarios where the page content is the same for all requests [user-independent] as in the
second example above. The listing of books is the same irrespective of the user requesting the
page. Even if there is provision for listing books category wise by providing different category ID
values through the querystring, the page output for a particular category of books is the same
for all users.
ASP.NET provides support for "caching" which will help us solve this problem to a great extend.
It can cache [store in memory] the output generated by a page and will serve this cached
content for future requests. And this is useful only in the second scenario described earlier,
where the page content is the same for all requests [user-independent]. The caching feature is
customizable in various ways and we will see how we can do that as we go through this article.
Caching a page
In order to cache a page's output, we need to specify an @OutputCache directive at the top of
the page. The syntax is as shown below:
www.enosislearning.com Page 77
ASP.NET
As you can see, there are two attributes to this directive. They are:
Duration - The time in seconds of how long the output should be cached. After the specified
duration has elapsed, the cached output will be removed and page content generated for the
next request. That output will again be cached for 10 seconds and the process repeats.
VaryByParam - This attribute is compulsory and specifies the querystring parameters to vary the
cache.
In the above snippet, we have specified the VaryByParam attribute as None which means the
page content to be served is the same regardless of the parameters passed through the
querystring [see Example 1 in the sample download].
If there are two requests to the same page with varying querystring parameters, e.g.:
.../PageCachingByParam.aspx?id=12 and .../PageCachingByParam.aspx?id=15] and separate
page content is generated for each of them, the directive should be:
<%@ OutputCache Duration=5 VaryByParam="id" %>
The page content for the two requests will each be cached for the time specified by the
Duration attribute [see Example 2 in the sample download].
To specify multiple parameters, use semicolon to separate the parameter names. If we specify
the VaryByParam attribute as *, the cached content is varied for all parameters passed through
the querystring.
Some pages generate different content for different browsers. In such cases, there is provision
to vary the cached output for different browsers. The @OutputCache directive has to be
modified to:
<%@ OutputCache Duration=5 VaryByParam="id" VaryByCustom="browser" %>
This will vary the cached output not only for the browser but also its major version. I.e., IE5, IE 6,
Netscape 4, Netscape 6 will all get different cached versions of the output.
Sometimes we might want to cache just portions of a page. For example, we might have a
header for our page which will have the same content for all users. There might be some
text/image in the header which might change every day. In that case, we will want to cache this
header for duration of a day.
The solution is to put the header contents into a user control and then specify that the user
control content should be cached. This technique is called fragment caching.
www.enosislearning.com Page 78
ASP.NET
To specify that a user control should be cached, we use the @OutputCache directive just like we
used it for the page.
<%@ OutputCache Duration=10 VaryByParam="None" %>
With the above directive, the user control content will be cached for the time specified by the
Duration attribute [10 secs]. Regardless of the querystring parameters and browser type and/or
version, the same cached output is served. [See Example 3 in the download for a
demonstration].
Data Caching
ASP.NET also supports caching of data as objects. We can store objects in memory and use them
across various pages in our application. This feature is implemented using the Cache class. This
cache has a lifetime equivalent to that of the application. Objects can be stored as name value
pairs in the cache. A string value can be inserted into the cache as follows:
Cache["name"]="Smitha";
if (Cache["name"] != null)
Label1.Text= Cache["name"].ToString();
To insert objects into the cache, the Add method or different versions of the Insert method of
the Cache class can be used. These methods allow us to use the more powerful features
provided by the Cache class. One of the overloads of the Insert method is used as follows:
Cache.Insert("Name" strName
new CacheDependency(Server.MapPath("name.txt")
DateTime.Now.AddMinutes(2) TimeSpan.Zero);
The first two parameters are the key and the object to be inserted. The third parameter is of
type CacheDependency and helps us set a dependency of this value to the file named name.txt.
www.enosislearning.com Page 79
ASP.NET
So whenever this file changes, the value in the cache is removed. We can specify null to indicate
no dependency. The fourth parameter specifies the time at which the value should be removed
from cache. [See example 5 for an illustration.] The last parameter is the sliding expiration
parameter which shows the time interval after which the item is to be removed from the cache
after its last accessed time.
The cache automatically removes the least used items from memory, when system memory
becomes low. This process is called scavenging. We can specify priority values for items we add
to the cache so that some items are given more priority than others:
Cache.Insert("Name" strName
new CacheDependency(Server.MapPath("name.txt")
DateTime.Now.AddMinutes(2) TimeSpan.Zero
CacheItemPriority.High null);
The CacheItemPriority enumeration has members to set various priority values. The
CacheItemPriority.High assigns a priority level to an item so that the item is least likely to be
deleted from the cache.
Points of interest
If there are old ASP pages in your website which use the Response.Expires
property to cache page output, they can be retained as such. ASP.NET
supports this property as well.
The Insert method of the Cache class will overwrite any existing item with the
same key name.
The CacheItemPriority.NotRemovable priority value can be used with
Cache.Insert method to set the priority level of an item so that the item will not
be removed from the cache during scavenging.
ASP.NET provides a couple of caching methods: Output Cache (including Page level cache and
User Control level cache) and the Cache API. In this article, we will discuss Output Cache. Output
www.enosislearning.com Page 80
ASP.NET
Cache has the advantage of being simple to implement, and is sufficient in most cases. It simply
keeps a copy of the response that was sent to the client in memory and subsequent requests are
then responded with the cached output until the cache expires, which incredibly improves the
ASP.NET web application performance.
For ASP.NET Output Cache, ASP.NET uses @ OutputCache to declare many attributes to control
the output caching policies of the ASP.NET page or a user control contained in a page.
www.enosislearning.com Page 81
ASP.NET
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>OutPutCacheWithDuration</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblResult" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="btnPostBack" runat="server" Text="Post Back" />
<p>
The page will be cached 10s, and then you can
click Button to update datetime.
</p>
</div>
</form>
</body>
</html>
www.enosislearning.com Page 82
ASP.NET
<head runat="server">
<title>OutPutCacheWithVaryByControl</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblResult" runat="server"></asp:Label>
<br />
<br />
<asp:DropDownList ID="ddlOption" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ddlOption_SelectedIndexChanged">
<asp:ListItem Selected="True">Option One</asp:ListItem>
<asp:ListItem>Option Two</asp:ListItem>
<asp:ListItem>Option Three</asp:ListItem>
</asp:DropDownList>
<p>
The page will be rendered from cache basing
on the selected item of DropDownList.
The different item has corresponding cache.
</p>
</div>
</form>
</body>
</html>
www.enosislearning.com Page 83
ASP.NET
For example:
~/OutputCacheWithParam.aspx?id=1
~/OutputCacheWithParam.aspx?id=2 >
www.enosislearning.com Page 84
ASP.NET
The .NET data caching API is comprised of the two classes in the System.Web.Caching
namespace. The first class, Cache, is the class we'll be using to add and remove items from the
data cache. The second class, CacheDependency, is used when assigning a cache dependency to
an item in the data cache (we'll be discussing this in due time).
To add an item to the cache you can simply do:
. Note:- The C# version uses brackets instead of parenthesis when referencing the items of the
cache in the above manner. In the remainder of the examples in this article I will be using
VB.NET syntax, but will point out any major differences between the VB.NET and C# syntax
www.enosislearning.com Page 85
ASP.NET
The above code adds the item value to the data cache with the key key. The key is used to
reference the item at some later point. That is, in another ASP.NET Web page we can extract the
value inserted above by using:
value = Cache("key")
- or -
value = Cache.Get("key")
To explicitly remove an item from the data cache you can use the Remove method, specifying
the key of the cache item you want removed:
Cache.Remove("key")
www.enosislearning.com Page 86
ASP.NET
Chapter 11
Overview
Like ASP, ASP.NET encapsulates its entities within a web application. A web application is an
abstract term for all the resources available within the confines of an IIS virtual directory. For
example, a web application may consist of one or more ASP.NET pages, assemblies, web
services configuration files, graphics, and more. In this section we explore two fundamental
components of a web application, namely global application files (Global.asax) and configuration
files (Web.config).
Global.asax
Global.asax is a file used to declare application-level events and objects. Global.asax is the
ASP.NET extension of the ASP Global.asa file. Code to handle application events (such as the
start and end of an application) reside in Global.asax. Such event code cannot reside in the
ASP.NET page or web service code itself, since during the start or end of the application, its code
has not yet been loaded (or unloaded). Global.asax is also used to declare data that is available
across different application requests or across different browser sessions. This process is known
as application and session state management.
The Global.asax file must reside in the IIS virtual root. Remember that a virtual root can be
thought of as the container of a web application. Events and state specified in the global file are
then applied to all resources housed within the web application. If, for example, Global.asax
defines a state application variable, all .aspx files within the virtual root will be able to access the
variable.
Like an ASP.NET page, the Global.asax file is compiled upon the arrival of the first request for
any resource in the application. The similarity continues when changes are made to the
Global.asax file; ASP.NET automatically notices the changes, recompiles the file, and directs all
new requests to the newest compilation. A Global.asax file is automatically created when you
create a new web application project in the VS.NET IDE.
www.enosislearning.com Page 87
ASP.NET
There are 2 ‘set’ of methods that fire corresponding to the events. The first set which gets
invoked on each request and the second set which does not get invoked on each request. Let us
explore these methods.
www.enosislearning.com Page 88
ASP.NET
• fired just
before the session state is retrieved
Application_AcquireRequestState()
for the current request.
www.enosislearning.com Page 89
ASP.NET
Show me an example!!
Let us see an example of how to use the Global.asax to catch unhandled errors that occur at the
application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add
New Item > Global.asax). In the Application_Error() method, add the following code:
www.enosislearning.com Page 90
ASP.NET
Here we make use of the Application_Error() method to capture the error using the
Server.GetLastError().
Application Directives
Application directives are placed at the top of the Global.asax file and provide information used
to compile the global file. Three application directives are defined, namely Application,
Assembly, and Import. Each directive is applied with the following syntax:
<%@ appDirective appAttribute=Value ...%>
Web.config
In ASP, configuration settings for an application (such as session state) are stored in the IIS
metabase. There are two major disadvantages with this scheme. First, settings are not stored in
a human-readable manner but in a proprietary, binary format. Second, the settings are not
easily ported from one host machine to another.(It is difficult to transfer information from an
IIS�s metabase or Windows Registry to another machine, even if it has the same version of
Windows.)
Web.config solves both of the aforementioned issues by storing configuration information as
XML. Unlike Registry or metabase entries, XML documents are human-readable and can be
modified with any text editor. Second, XML files are far more portable, involving a simple file
transfer to switch machines.
Unlike Global.asax, Web.config can reside in any directory, which may or may not be a virtual
root. The Web.config settings are then applied to all resources accessed within that directory, as
well as its subdirectories. One consequence is that an IIS instance may have many web.config
files. Attributes are applied in a hierarchical fashion. In other words, the web.config file at the
lowest level directory is used.
www.enosislearning.com Page 91
ASP.NET
Since Web.config is based on XML, it is extensible and flexible for a wide variety of applications.
It is important, however, to note that the Web.config file is optional. A default Web.config file,
used by all ASP.NET application resources, can be found on the local machine
[Web.config file]
<appSettings>
<add key="ConnectionString" value="server=localhost;database=TestDB;uid=sa;password=secret;" />
</appSettings>
using System.Configuration;
public class TestGetConnection
{
public TestGetConnection()
{
try
{
// Get connection string from Web.Config
string strConnection = ConfigurationSettings.AppSettings("ConnectionString");
}
}
}
Introduction to web.config
You will more often use the Web.config file not only for securing your application but also for
wide range of other purposes which it is intended for. ASP.NET Web.config file provides you a
flexible way to handle all your requirements at the application level. Despite the simplicity
provided by the .NET Framework to work with web.config, working with configuration files
would definitely be a task until you understand it clearly.
The contents of the articles are summarized below:
Web.config sections/settings
Reading Web.config
Writing or manipulating Web.config
Encrypting the Web.config and
Creating your own Custom Configuration Sections
www.enosislearning.com Page 92
ASP.NET
Points to be Remembered
ASP.NET Web.config allows you to define or revise the configuration settings at the
time of developing the application or at the time of deployment or even after
deployment. The following are brief points that can be understood about the
Web.config file:
Web.config files are stored in XML format which makes us easier to work
with.
You can have any number of Web.config files for an application. Each
Web.config applies settings to its own directory and all the child directories
below it.
All the Web.config files inherit the root Web.config file available at the
following location
systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Web.config
location
IIS is configured in such a way that it prevents the Web.config file access from
the browser.
The changes in Web.config don’t require the reboot of the web server.
Web.config Settings
Before we start working with configuration settings of ASP.NET, we see the hierarchy of the
Web.config file.
<configuration>
<configSections>
<sectionGroup>
</sectionGroup>
</configSections>
<system.web>
</system.web>
<connectionStrings>
</connectionStrings>
<appSettings>
</appSettings>
…………………………………………………………………………………………………………
…………………………………………………………………………………………………………
…………………………………………………………………………………………………………
…………………………………………………………………………………………………………
…………………………………………………………………………………………………………
www.enosislearning.com Page 93
ASP.NET
</configuration>
So from the above tree structure, we can understand that the configuration tag is the root
element of the Web.config file under which it has all the remaining sub elements. Each element
can have any number of attributes and child elements which specify the values or settings for
the given particular section. To start with, we’ll see the working of some of the most general
configuration settings in the Web.config file.
system.web
In the configuration hierarchy, the most common thing we will work with is the system.web
section. Now we look at some of the child sections of the system.web section of Web.config file.
Compilation Settings
If you are using Visual Studio 2010, probably the only available section of Web.config file by
default is Compilation section. If you want to specify the target framework or if you need to add
an assembly from the Global Assembly Cache (GAC) or if you want to enable the debugging
mode of the application, you can take Compilation settings as granted for these tasks. The
following code is used to achieve the discussed settings:
<system.web
<compilation
debug="true" strict="true" explicit="true" batch="true"
optimizeCompilations="true" batchTimeout="900"
maxBatchSize="1000" maxBatchGeneratedFileSize="1000"
numRecompilesBeforeAppRestart="15" defaultLanguage="c#"
targetFramework="4.0" assemblyPostProcessorType="">
<assemblies>
<add assembly="System, Version=1.0.5000.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089"/>
</assemblies>
</compilation>
</system.web>
Under the assemblies element, you are supposed to mention the type, version, culture and
public key token of the assembly. In order to get the public key token of an assembly, you need
to follow the below mentioned steps:
Go to Visual Studio tools in the start menu and open the Visual Studio command prompt.
In the Visual Studio command prompt, change the directory to the location where the assembly
or .dll file exists.
www.enosislearning.com Page 94
ASP.NET
Example
C:\WINNT\Microsoft.NET\Framework\v3.5> sn -T itextsharp.dll
Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8
Copyright (c) Microsoft Corporation. All rights reserved.
Explicit and sample attributes are applicable only to VB.NET and C# compiler however ignores
these settings.
Page Settings
Ok, by this time, we have got familiar with the Web.config file and we have seen the settings of
Compilation Sections, now we will see the settings of a page. As an ASP.NET application consists
of several number of pages, we can set the general settings of a page like sessionstate,
viewstate, buffer, etc., as shown below:
By using the MasterPageFile and theme attributes, we can specify the master page and theme
for the pages in web application.
o 400 Bad Request
o 401 Unauthorized
o 404 Not Found
o 408 Request Timeout
Location Settings
If you are working with a major project, probably you might have numerous numbers of folders
and sub-folders, at this kind of particular situation, you can have two options to work with. First
thing is to have a Web.config file for each and every folder(s) and Sub-folder(s) and the second
one is to have a single Web.config for your entire application. If you use the first approach, then
www.enosislearning.com Page 95
ASP.NET
you might be in a smoother way, but what if you have a single Web.config and you need to
configure the sub-folder or other folder of your application, the right solution is to use the
"Location" tag of "system.web" section of Web.config file. However you can use this tag in
either of the discussed methods.
The following code shows you to work with Location settings:
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
These settings are directly available in the web.config file if you have created the ASP.NET
application by using the Visual Studio 2010. I'm not going to elaborate them as there are lot of
articles in CodeProject describing the functionality and use of these settings and for further
information you can refer to them.
Authentication Settings
<authentication mode="Forms">
<forms cookieless="UseCookies" defaultUrl="HomePage.aspx"
loginUrl="UnAuthorized.aspx" protection="All"
timeout="30">
</forms>
</authentication>
Authorization Settings
<authorization
<allow roles ="Admin"/>
<deny users ="*"/>
</authorization>
www.enosislearning.com Page 96
ASP.NET
<membership defaultProvider="Demo_MemberShipProvider">
<providers>
<add name="Demo_MemberShipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="cnn"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="5"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="">
</providers>
</membership>
<profile defaultProvider="Demo_ProfileProvider">
<providers>
<add name="Demo_ProfileProvider" connectionStringName="cnn"
applicationName="/" type="System.Web.Profile.SqlProfileProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
<properties>
<add name="Name" type="String"/>
<add name="DateofBirth" type="DateTime"/>
<add name="Place" type="string"/>
</properties>
</profile>
AppSettings
In the above section, we have seen the settings available in system.web tag, now we will see the
available settings in appSettings section.
www.enosislearning.com Page 97
ASP.NET
appSettings element helps us to store the application settings information like connection
strings, file paths, URLs, port numbers, custom key value pairs, etc.
The following code snippet shows the example of appSettings Section:
<appSettings>
<add key="AppKey" value="APLJI12345AFAFAF89999BDFG"/>
</appSettings>
connectionStrings
The most common section of web.config file the connectionStrings sections allows you to store
multiple connection strings that are used in the application. The connectionStrings tag consists
of child element with attributes name and connectionstring which is used to identify the
connectionstring and the other is used to connect to the database server respectively.
The general connectionstring settings are shown below:
<connectionStrings>
<add name ="cnn" connectionString ="Initial Catalog = master;
Data Source =localhost; Integrated Security = true"/>
</connectionStrings>
ConfigSections
ConfigSections helps you to create your own custom configuration section that can be used with
the web.config file. We look at this in the later section of the article, for the time being, we can
have look at the configsection settings. ConfigSections should be declared just below the
configuration (parent element) otherwise it is going through you an error.
<configSections>
<sectionGroup name="pageAppearanceGroup">
<section
name="pageAppearance"
type="PageAppearanceSection"
allowLocation="true"
allowDefinition="Everywhere"
/>
</sectionGroup>
</configSections>
We can use the C# classes to read and write the values to the Web.config file.
www.enosislearning.com Page 98
ASP.NET
The following code is used to read the appSettings values from Web.config file. You can use
either of the methods shown below:
//Method 1:
string key = ConfigurationManager.AppSettings["AppKey"];
Response.Write(key);
//Method 2:
Configuration config =
WebConfigurationManager.OpenWebConfiguration("~/");
KeyValueConfigurationElement Appsetting =
config.AppSettings.Settings["AppKey"];
Response.Write(Appsetting.Key + " <br/>" + "Value:" +
Appsetting.Value);
The following code is used to read the connectionstring values from Web.config file. You can use
either of the methods shown below:
//Method 1:
string cnn =
ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
//Methods 2:
Configuration config =
WebConfigurationManager.OpenWebConfiguration("~/");
ConnectionStringSettings cnnstring;
if (config.ConnectionStrings.ConnectionStrings.Count > 0)
{
cnnstring = config.ConnectionStrings.ConnectionStrings["conn"];
if (cnnstring != null)
Response.Write("ConnectionString:" +
cnnstring.ConnectionString);
Else
Response.Write(" No connection string");
}
The following code is used to read the configuration section values from Web.config file. The
comments in the code will help you to understand the code:
www.enosislearning.com Page 99
ASP.NET
CompilationSection compilation =
(CompilationSection)config.GetSection("system.web/compilation");
//Access the properties of the web.config
Response.Write("Debug:"+compilation.Debug+"<br/>""+
"Language:"+compilation.DefaultLanguage);
The following code is used to read the configuration section values from Web.config file:
As we have already discussed that IIS is configured in such a way that it does not serve the
Web.Config to browser, but even in some such situation to provide more security, you can
encrypt some of the sections of web.config file. The following code shows you the way to
encrypt the sections of web.config file:
appSettings.SectionInformation.ProtectSection("DataProtectionConfigurationPr
ovider");
}
config.Save();
The ConfigurationSection class helps us to extend the Web.config file in order to fulfill our
requirements. In order to have a custom configuration section, we need to follow the below
steps:
Before we actually start working with it, we will have a look at the section settings. We need to
have a ProductSection element with child elements girdSettings and color. For this purpose, we
will create two classes with the child elements which inherits ConfigurationElement as shown
below:
get
{
return (String)this["background"];
}
set
{
this["background"] = value;
}
}
Then we will create a class called ProductSection, for the root element which includes the above
child elements.
Then finally, we will configure these elements in Web.config file as shown below:
<configSections>
<section name ="ProductSection" type ="<ProductSection"/>
</configSections>
<ProductSection>
<gridSettings title ="Latest Products" count ="20"></gridSettings>
<color background="FFFFCC" foreground="FFFFFF"></color>
</ProductSection>
ProductSection config =
(ProductSection)ConfigurationManager.GetSection("ProductSection");
string color =config.Color.Background;
string title =config.gridSettings.Title;
int count = config.gridSettings.Count;
Chapter 12
AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better,
faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model
and JavaScript for dynamic content display.
Conventional web application transmit information to and from the sever using synchronous
requests. This means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the
results and update the current screen. In the purest sense, the user would never know that
anything was even transmitted to the server.
XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.
AJAX is a web browser technology independent of web server software.
A user can continue to use the application while the client program requests information from
the server in the background
Intuitive and natural user interaction. No clicking required only Mouse movement is a sufficient
event trigger.
Data-driven as opposed to page-driven
What is AJAX?
AJAX is just an acronym referring to Asynchronous JavaScript and XML. Now, if we take a look
those words, most of us know what JavaScript and XML are, but the term Asynchronous can be
confusing, so let’s focus on that.
Asynchronous refers to events that are happening on the background independently of the main
application flow. These events do not disturb the flow of the application, allowing the
continuation of its normal process. A fairly good example of this happening is in your Facebook
home page, when all of a sudden, without refreshing your browser window, you notice that
there are new status feed updates from your friends. (Although I did notice, and think many
have as well, how they do implement this. If you haven’t then, try leaving your facebook
homepage on the browser without moving your mouse for about 1 minute. After that minute,
just move your mouse from one point to another, and all of a sudden, you will see the feeds get
updated. ) I’m assuming they are using some jQuery mousemove or something similar for this to
happen.
So what happens there is, facebook sends your profile information ( or your user id ) to their
servers. Their servers then look for your friends list, grab their newly added status, return the
result to the browser and then add them to your wall so that you can see. All of that, without
pressing that refresh button.
So you see, AJAX allows you to update a web page asynchronously on the background by
exchanging simple, and small amounts of data. Some more examples of pages using AJAX is:
Youtube, Gmail, Google Maps, StackOverflow and many more on the web.
So you are still asking yourself, What is AJAX? Well, I’m going to ask for forgiveness, as I have no
art skills, but the following image should help you just a little bit.
Advantages
AJAX, you see, is based on internet standards. It uses a combination of the following to
accomplish it’s goal:
XMLHttpRequest Object(Modern Broswers and IE7+)
ActiveXObject (IE6 and below)
JavaScript/DOM (Used to interact browser and server)
XML (Returned results)
JSON (Returned results)
HTML (Returned results)
These standards are browser based, making them platform independent. It doesn’t matter
where you program this in, as long as you have a browser, then this ‘should’ work. All you would
need is a server with the application files, and the browser should do the rest.
Another advantage using AJAX would be a better user interactivity. This could be named the
most obvious benefit of using AJAX, and why web developers and webmasters are using AJAX
more and more every day. AJAX simplifies the flow of an application, thus making it have quicker
interaction between user and website since pages are not reloaded for content to be displayed.
This activity can be simplified, since the loading times can be reduced from websites.
The advantage above opens up for this next advantage, which you can call it, smoother
navigation on a website. While using AJAX, users will not have the need to use the refresh nor
the back button, thus, allowing quicker response from the server.
Disadvantages
Even though the back and refresh button are not needed while navigating a website with AJAX,
these two buttons can become useless. This is due to the fact that, AJAX ‘navigating’ does not
change you URL, so if you were in the middle of a process, and have no direct URL to where you
were, then this might be bad. In some cases, the use of Hijaxing is used, which is the use of
hashing url (#) at the end.
Another disadvantage would be that it is dependent on JavaScript. While it is ok to depend on it,
since most modern (if not all) already use it, but in some cases, there are users who prefer
disabling JavaScript. This makes AJAX worthless. Gladly, there is a workaround this problem, as
web developers must have in mind, every time they create an AJAX Website, they need to
always think of this and make an optional non-AJAX version of the AJAXified website they just
created.
The last disadvantage I want to point out would be the SEO factor. Since there are no SEO
Friendly URL’s, then search engine tend to bypass your application, and it would appear as if
that part of your site does not exist.
If you are an ASP.NET developer then you probably are aware of the AJAX Extension tab in Visual
Studio (2010 or higher generally) Toolbox and the tab has a few very useful tools to implement
AJAX in a web application. In the first example we will implement AJAX using UpdatePanel and
ScriptManager . Both tools are available in the same tab of the Toolbox.
UpdatePanel
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
</div>
</form>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
If you observe the content of my aspx page then you will discover that I have kept one drop
down list, one button and one GridView within the UpdatePanel. And our hero (read
ScriptManager) is just in the previous line of update panel. Now it's time to observe C# code for
the same aspx page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace YahooProject
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DDLAjax.Items.Add("first");
this.DDLAjax.Items.Add("second");
}
}
if (this.DDLAjax.SelectedItem.Text == "first")
{
cmd = new SqlCommand("select * from first",con);
}
if (this.DDLAjax.SelectedItem.Text == "second")
{
cmd = new SqlCommand("select * from second", con);
}
this.GridView1.DataSource = cmd.ExecuteReader();
this.GridView1.DataBind();
}
}
}
The user will choose the table name by selecting it from the drop down list and after clicking the
button the data from the relevant table will be fetched and bound with the Grid View.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me"
OnClientClick="DisplayMessageCall();return false;" /><br />
In the head section of the HTML element you can see one function that I have implemented to
an AJAX call in JavaScript.
$.ajax({
type: "POST",
url: pageUrl + "/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
You can see a few parameters are needed for AJAX to call using the jQuery ajax() method. My
URL parameter is in the second and it's the defined location of the actual function from where
the data will come. Here "HelloWorld" is the function name. And this function is located within
the AjaxServeice.asmx service application page.
OK, let's concentrate on the service function from where the data will come in the ajax() method
and in the following it is.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace YahooProject
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService] // Don't forget to uncomment
it.
public class AjaxServeice : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
Update panels are the oldest trick in the book for ASP.NET. It is the simplest way to have ajax
functionality in your web application. We will not see them in depth, just mention a few basic
points about them. Below is a simple example:
In code behind, you have access to the entire form. That is possible because when an update
panel refreshes, the whole form is been posted to the web server. But only the markup of the
update panel can change. So, if we try to change something that it is not inside our update panel
the change will not happen.
It is that simple to have ajax functionality in your web application. We can also assign some event
handlers so when an update panel refreshes we can execute some JavaScript code.
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
With that level of abstraction, it is pretty clear than it is not a very optimal approach. If an update
panel encloses a big part of the web form, it will be much slower. Even having a small update
panel, the whole form is posted to the server, including the ViewState.
Generally it is not a good practice to have nested update panels in a big depth (up to 2 is
generally ok). Finally, different update panels cannot refresh simultaneously. You can read about it
(and a workaround for it) here.
Page Methods
With update panels we can update html sections of our web page. There is no direct way to get a
value (e.g. a string or an integer) via ajax. For that, we can use page methods.
Page methods are static methods declared in code behind and are exposed via JavaScript int the
client. Page methods are much more lightweight since they don’t post nothing from the form,
except what necessary parameters each method has.
In the following example you see a sample page method. You have to enable page methods in
the ScriptManager. When calling the method in JavaScript you can set two function as attributes
that will behave as success and error handlers of the ajax call.
ASP.NET part
JavaScript part
function success(data) {
alert(data);
}
function error() {
...
}
function call_page_method() {
PageMethods.HelloWorld(false, success, error);
}
Page methods are lightweight. One disadvantage is that we can only use them in .aspx pages. We
cannot declare a page method in a user control. Also, the JavaScript declaration of the method is
embedded directly into the HTML. So, having many page methods will lead to bigger HTML files.
Also, there is no way to declare them in a single place so that our entire web application can
make use of them.
Web Methods
Page methods can be very useful and practical. In the scenarios where we would like to have such
methods declared globally we can use Web methods. We can declare our methods in a .asmx file.
When we create the new .asmx file we need to uncomment one line of code, as the comments on
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
' To allow this Web Service to be called from script, using ASP.NET AJAX,
uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_
1)> _
<ToolboxItem(False)> _
Public Class myMethods
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Shared Function HelloWorld(ByVal LowerCase As Boolean) As String
If (LowerCase) Then Return ("Hello World").ToLower
Return "Hello World"
End Function
End Class
In order to use the declared web methods, we need to register the .asmx service to our script
manager. This can be in the asp.net markup or in the code behind.
function call_web_method() {
DemoWebApplication.myMethods.HelloWorld(true, success, error);
}