You are on page 1of 81

ASP.

NET

.NET Fundamentals Ver 2.0 1 of 156


Pre-requisites

• Knowledge of Web Servers

• Good knowledge of ASP and Scripting

• Good knowledge of HTML

• .NET Fundamentals

.NET Fundamentals Ver 2.0 2 of 156


Objectives

• Why do we need a new version of ASP ?


• Benefits of ASP.NET
• ASP.NET - Where Does it Fit within .NET?
• Using Compiled Code
– Web Forms
– HTML Controls
– Web Controls
– HTML Control Vs. Web Controls
– Authoring your own controls
• Separating code and content
• Improved Caching
• Tracing
• Configuration
• Session state Management

.NET Fundamentals Ver 2.0 3 of 156


Objectives

.NET Fundamentals Ver 2.0 4 of 156


Why Do We Need a New Version of ASP?

• ASP can only be scripted using the basic non-typed languages such as VBScript and
Jscript

• ASP pages contain a spaghetti-like mixture of code, HTML, text, object declarations
there by a mix of code an content

• In previous versions of ASP, you have to write code to do almost anything

• No caching or tracing facility was given .

• ASP pages were interpreted.

.NET Fundamentals Ver 2.0 5 of 156


ASP.NET

• ASP.NET provides a true language-neutral execution framework


for Web applications to use.

• ASP.NET allows true separation of code and content.

• ASP.NET introduces a real component model, with server-based


controls

.NET Fundamentals Ver 2.0 6 of 156


ASP.NET development
• ASP has been totally revamped from the ground up into a whole
new programming environment.

• Visual Studio 7.0 will be providing full support to make building


ASP.NET applications easy .

• The rich, component-based, event-driven programming model is


specifically designed to be 'tools friendly.

• Support will be available for all Visual Studio languages –


including VB, C++, and C#.

.NET Fundamentals Ver 2.0 7 of 156


Benefits of ASP.NET
• ASP.NET makes code cleaner

• ASP.NET improves deployment, scalability, security, and


reliability

• ASP.NET provides better support for different browsers.

• Web Forms in ASP.NET addresses browser compatibility


issues.

.NET Fundamentals Ver 2.0 8 of 156


Dynamic Compilation
Code-
Parse ASPX Generate
behind
Engine class
file

Request ASPX Gen’d


Instantiate
ASPX
File Page
Request File Class
File

Response Page
Class
Response Instantiate, process
and render

.NET Fundamentals Ver 2.0 9 of 156


.NET Fundamentals Ver 2.0 10 of 156
ASP.NET Web Forms

.NET Fundamentals Ver 2.0 11 of 156


Web Forms

• Creation of programmable Web pages as part of an overall Web


application .

• Allows complete separation of HTML markup from application logic.

• Web forms can be created using Server Controls or HTML controls

.NET Fundamentals Ver 2.0 12 of 156


Web forms

• ASP.NET Web Forms pages are text files with an .aspx file
name extension.

• .aspx file is compiled only the first time it is accessed; the


compiled type instance is then reused across multiple requests

.NET Fundamentals Ver 2.0 13 of 156


HTML controls

• These controls exist within the System.Web.UI.HtmlControls


namespace, and derive (directly or indirectly) from the
HtmlControl base class

• HTML controls are very similar to the classic HTML controls we


were using before

.NET Fundamentals Ver 2.0 14 of 156


.NET Fundamentals Ver 2.0 15 of 156
Server Controls

• These controls exist within the System.Web.UI.WebControls


namespace .

• Web controls include form controls such as the TextBox and


Button controls as well as other higher-level abstractions such
as the Calendar and DataGrid controls .

• A rich and consistent object model.

• Automatic browser detection

.NET Fundamentals Ver 2.0 16 of 156


Object Model

• Server controls act like the client side controls but execution
happens on the server.

• The execution must be passed from the client back to the server
via HTTP request.

• The execution gets passed between the server-client within the


same aspx page called as a server round trip.

.NET Fundamentals Ver 2.0 17 of 156


Page ViewState

• Server round trip calls for a page to maintain ViewState

• Pages retain its ViewState between requests to the server.

• The ViewState contains the state of all the controls on the server.

• Stored as a name-value pair using the System.Web.UI.StateBag

• View state can be enabled at page level or individual control


level.

.NET Fundamentals Ver 2.0 18 of 156


Page Processing

Configuration Event Handling

Clean Up Rendering

.NET Fundamentals Ver 2.0 19 of 156


Configuration

• If we are not on a postback then page and control view state is


restored

• Page_Load event is fired

.NET Fundamentals Ver 2.0 20 of 156


Event Handling and Rendering

• The processing of the other events that have occurred and have
not been processed are processed.

• They are always processed first before the event that triggered
the post back is processed.

• The fired event is processed at the last.


Rendering
• All the static HTML in the page is rendered to the client

.NET Fundamentals Ver 2.0 21 of 156


Clean Up

• Final stage of page processing

• Page_UnLoad event is triggered.

• Tasks performed are close connections, etc .

.NET Fundamentals Ver 2.0 22 of 156


Server Controls

• Web controls appear in the HTML markup as namespaced


tags
– <asp:TextBox id="textBox1" runat="server"
Text="[Entry Keywords]"></asp:TextBox>

– "asp" is the tag prefix and maps to the


System.Web.UI.WebControls namespace.

.NET Fundamentals Ver 2.0 23 of 156


Server Controls

• TextBox
• ListBox
• DropdownList Box
• Navigation
• Image
• Repeater
• Radiobutton
• Button
• Panel

.NET Fundamentals Ver 2.0 24 of 156


.NET Fundamentals Ver 2.0 25 of 156
.NET Fundamentals Ver 2.0 26 of 156
.NET Fundamentals Ver 2.0 27 of 156
.NET Fundamentals Ver 2.0 28 of 156
Server Controls

• Data Selection
– The Calendar control is used to allow navigating
between dates and make date selections,
including date ranges:
– <asp:Calendar runat=server
DayNameFormat="FirstLetter" ...><property
name=SelectedDayStyle><asp:TableItemStyle
Font-Bold="True"
BackColor="#CCCCFF"/></property>
...</asp:Calendar>

.NET Fundamentals Ver 2.0 29 of 156


Miscellaneous

The AdRotator control is used to display advertisements or


banners. The information about the advertisements, including
their image URL, is specified in an XML file:
<asp:AdRotator runat="server"
AdvertisementFile="AdsList.xml"></asp:AdRotator>

.NET Fundamentals Ver 2.0 30 of 156


Creating your own controlb

• User control is of type System.Web.UI.UserControl


• Inherits directly from System.Web.UI.Control
• The .ascx extension is used to indicate such controls
• User controls are included in a Web Forms page using a
Register directive
• The TagPrefix determines a unique namespace for the user
control
• The TagName is the unique name for the user control
• The Src attribute is the virtual path to the user control--for
example "MyPagelet.ascx"

.NET Fundamentals Ver 2.0 31 of 156


Code Sample
<%@ Register TagPrefix="Acme" TagName="Message"
Src="pagelet1.ascx" %>

<html>
<body style="font: 10pt verdana">

<h3>A Simple User Control</h3>

<Acme:Message runat="server"/>

</body>
</html>

.NET Fundamentals Ver 2.0 32 of 156


Validation controls

RequiredFieldValidator

RangeValidator

CompareValidator

RegularExpressionValidator

CustomValidator

Validation controls

.NET Fundamentals Ver 2.0 33 of 156


Sample for validation controls

<asp:text id=”txtname” runat=“server”>


<asp: requiredfieldvalidator id=“txtnamevalidator” runat= server
controltovalidate=“txtname”
errormessage = “ you must enter your name” display = “dynamic” >
</ asp: requiredfieldvalidator>

.NET Fundamentals Ver 2.0 34 of 156


Range Validator

<asp:textbox id=”txtage” value=”enter your age” runat=”server” />


…………
<asp:rangeValidator id=“txtagevalidator” runat=“server”
controltovalidate = “txtage”
type=“integer”
minimumvalue=“18”
maximumvalue=“50”
errormessage = “ Applicants must be between 18 and 50”
display=“dynamic”>
</asp:rangeValidator>

.NET Fundamentals Ver 2.0 35 of 156


Sample for Compare Validator

<asp:textbox id=”txtage” value=”enter your age” runat=”server” />


…….
<asp:comparevalidator id=”txtagecomparevalidator”
“runat=server” controltovalidate=”txtage”
valuetocompare =”0”
type=”integer”
Operator = “GreaterThanEqual”
Errormessage = “ Please enter a whole number zero or greater.”>
</asp : comparevalidator>

.NET Fundamentals Ver 2.0 36 of 156


RegularExpressionValidator

• The RegularExpressionValidator server control checks that


the entry matches a pattern defined by a regular expression.
• This type of validation allows you to check for predictable
sequences of characters,

• RegularExpressionValidator uses two key properties to


perform its validation. ControlToValidate contains the value to
validate. ValidationExpression contains the regular expression
to match.

.NET Fundamentals Ver 2.0 37 of 156


ValidationSummary

• The validation controls test the user's input and set a property to
indicate whether the entry passed the validation test.
• The IsValid property on the page is set.

• The ValidationSummary control is displayed when the IsValid


property of the page is false

• It polls each of the validation controls on the page and


aggregates the text messages exposed by each.

.NET Fundamentals Ver 2.0 38 of 156


The Page Class

• The components that make the aspx file are


– The .aspx file being requested
– The .NET class file containing the code for the
page
– Any user control used by the page.

• The class is inherited from System.Web.UI.Page.

• The compilation takes place only when one of the


components changes.

.NET Fundamentals Ver 2.0 39 of 156


HttpRequest Object

• The HttpRequest object is mapped to the request property of the


Page Object.

• Available in the same way as it was in ASP.

• Enhancements made with regard to the properties available.


– Browser
– Server Variables
• Methods
– SaveAs (will help save contents of the request
object)

.NET Fundamentals Ver 2.0 40 of 156


HttpResponse Object

• HttpResponse Object is mapped to the Response property of


the page object

• Available in the same way as it was in ASP.

• The buffer property is changed to BufferOutput property

• Methods like
– Save
– ClearHeaders

.NET Fundamentals Ver 2.0 41 of 156


Page Directives

• @Page

• @Imports

• @Register

• @OutputCache

.NET Fundamentals Ver 2.0 42 of 156


Summary

• Controls
– Server Controls

– HTML controls

– Custom Controls

– Validation Controls

.NET Fundamentals Ver 2.0 43 of 156


Caching Services in ASP.NET

.NET Fundamentals Ver 2.0 44 of 156


Caching Overview

• Caching is a technique widely used in computing to increase


performance by keeping frequently accessed or expensive data in
memory

• ASP.NET has three kinds of caching that can be used by Web


applications:
 Output caching, which caches the dynamic response generated by a
request.
 Fragment caching, which caches portions of a response generated by
a request.
 Data caching, which caches arbitrary objects programmatically.

.NET Fundamentals Ver 2.0 45 of 156


Page Output Caching

• Output caching is a powerful technique that increases


request/response throughput by caching the content generated
from dynamic pages

• This can be done using either the low-level OutputCache API


or the high-level @ OutputCache directive.

• Subsequent GET or HEAD requests are served from the output


cache entry until the cached request expires.

.NET Fundamentals Ver 2.0 46 of 156


Sample Program

<%@OutputCache Duration="60" VaryByParam="none" %>


<html>
<script language="VB" runat="server">
Sub Page_Load(Src As Object, E As EventArgs)
TimeMsg.Text =DateTime.Now.ToString("G")
End Sub
</script>
<body>
<h3><font face="Verdana">Using the Output Cache
</font></h3><p><i>Last generated on:</i>
<asp:label id="TimeMsg" runat="server"/>
</body> </html>

.NET Fundamentals Ver 2.0 47 of 156


Page Fragment Caching
• ASP.NET provides a simple way for you to output cache regions
of page content

• You delineate regions of your page with a user control, and


mark them for caching using the @ OutputCache

• This directive specifies the duration (in seconds) that the output
content of the user control should be cached on the server, as
well as any optional conditions by which it should be varied.

.NET Fundamentals Ver 2.0 48 of 156


Page Fragment Caching
<%@ OutputCache Duration="120"
VaryByParam = "CategoryID;SelectedID"%>

• The above directive instructs ASP.NET to output cache the user


control for 120 seconds, and to vary the caching using the
"CategoryID" and "SelectedID" querystring or form post parameters.

.NET Fundamentals Ver 2.0 49 of 156


Page Data Caching
• The ASP.NET cache is private to each application and stores
objects in memory.

• The lifetime of the cache is equivalent to the lifetime of the


application; that is, when the application is restarted, the cache
is recreated.

• The cache provides a simple dictionary interface that allows


programmers to easily place objects in and retrieve them from
the cache.
– Cache("mykey") = myValue

.NET Fundamentals Ver 2.0 50 of 156


Page Data Caching

myValue = Cache("mykey")
If myValue <> Null Then
DisplayData(myValue)
End If

myValue = Cache("mykey");
if(myValue != null )
{
DisplayData(myValue);
}

.NET Fundamentals Ver 2.0 51 of 156


Page Data Caching

• Dependencies—A key added to the Cache can set up


dependency relationships that can force that key to be removed
from the Cache. The supported dependencies include key, file,
and time.
• Automatic Expiration—Underused items added to the Cache
that have no dependencies will automatically expire if they are
underused.
• Support for Callback—Code paths can be added that will be
called when an item is removed from the Cache, giving us an
opportunity to update the Cache or not remove the item.

.NET Fundamentals Ver 2.0 52 of 156


Page Data Caching

File-based Dependency
• File-based dependency invalidates a particular Cache item
when file(s) on disk change. For example, if instead of loading
our ProductData from a database, we loaded it from an XML file:

Dim dom As XmlDocument()


dom.Load(Server.MapPath("product.xml")
Cache("ProductData") = dom

.NET Fundamentals Ver 2.0 53 of 156


Page Data Caching

Key based Dependency


• Key-based dependency invalidates a particular Cache item when
another Cache item changes.
Dim dependency (1) As String
dependencyKey(0) = "ProductData”

Dim productDataDependency As new


CacheDependency (nothing, dependencyKey)

Cache.Insert("SalesData", LoadDataSet("Sales"),
productDataDependency)

.NET Fundamentals Ver 2.0 54 of 156


Page Data Caching

• In the above example code, we use the Insert() method to


create a new Cache entry named SalesData

• Passing in an instance of a CacheDependency class named


productDataDependency which names the Cache key
ProductData.

• Now, whenever ProductData changes, SalesData will be


removed from the Cache.

.NET Fundamentals Ver 2.0 55 of 156


Time Based Dependency

• Time-based dependency simply expires the item at a defined


point in time.

• We have two options for time-based dependency:

– Absolute—Sets an absolute time; for example,


current time + 10 minutes for the Cache entry to
expire.

– Sliding—Resets the time for the item in the Cache


to expire on each request.

.NET Fundamentals Ver 2.0 56 of 156


Summary

• Caching can be

– Output caching
– Fragment caching
– Data caching

.NET Fundamentals Ver 2.0 57 of 156


Configuration

.NET Fundamentals Ver 2.0 58 of 156


Current Scenario

• Configuration if ASP Pages


– IIS
– page level

• In web farms the changes done to one machine needs to be


duplicated in others.

.NET Fundamentals Ver 2.0 59 of 156


Benefits of ASP.NET Configuration

• Human readable configuration settings

• Updates are immediate

• Local server access is not required

• Easily replicated

.NET Fundamentals Ver 2.0 60 of 156


Configuration in ASP.NET

• Server Configuration
– machine.config

• Application configuration
– web.config

.NET Fundamentals Ver 2.0 61 of 156


Web.config

• Configuration information for ASP.NET resources is


contained in a collection of configuration files, each named
Web.config.

• Each configuration file contains a nested hierarchy of XML


tags and subtags with attributes that specify the
configuration settings.

• Because the tags must be well-formed XML, the tags,


subtags, and attributes are case-sensitive

.NET Fundamentals Ver 2.0 62 of 156


Web.config

• Tag names and attribute names are camel-cased

• All configuration information resides between the


<configuration> and </configuration> root XML tags

.NET Fundamentals Ver 2.0 63 of 156


DEMO

.NET Fundamentals Ver 2.0 64 of 156


Tracing and performance in ASP.NET

.NET Fundamentals Ver 2.0 65 of 156


Tracing

• When you are developing an application, it is often helpful to be


able to insert debugging print statements into your code to
output variables or structures
• ASP.NET provides two levels of tracing services that make it
easy to do
– Page Level Tracing
– Application Level Tracing

.NET Fundamentals Ver 2.0 66 of 156


Page Output Tracing
• Page-level tracing enables you to write debugging statements
directly to a page's output

• To enable tracing for a page, include the following directive at


the top of the page code:
– <%@ Page Trace="true"%>
• When tracing is disabled (that is, when Trace="false" on the
Page directive, or is not present), these statements do not run
and no Trace output appears in the client browser.
• This makes it possible to keep debugging statements in
production code and enable them conditionally at a later time.

.NET Fundamentals Ver 2.0 67 of 156


Output if trace is enabled

.NET Fundamentals Ver 2.0 68 of 156


.NET Fundamentals Ver 2.0 69 of 156
.NET Fundamentals Ver 2.0 70 of 156
.NET Fundamentals Ver 2.0 71 of 156
Application Level Tracing
• ASP.NET provides a way to enable trace output for an entire
application
• Enabling Trace at the application level has the effect of enabling
Page-level Trace for every page within that application
• To enable tracing for an application, place the following in the
application's config.web file at the application root directory:
<configuration>
<system.web>
<trace enabled="true"/>
</system.web>
</configuration>

.NET Fundamentals Ver 2.0 72 of 156


Application Level Tracing

• The config.web file would have a trace section consisting of the


following paratmeters.
<configuration>
<trace
enabled="false"
requestlimit="10"
pageoutput="false"
tracemode="SortByTime"
/>
</configuration>

.NET Fundamentals Ver 2.0 73 of 156


TraceContext Object

• Tracing is handled by the TraceContextObject


• Methods /Properties
– IsEnabled
– TraceMode
– Write
– Warn

.NET Fundamentals Ver 2.0 74 of 156


ASP.NET advantages

Process independent.
ASP.NET session state is able to run in a separate process from the
ASP.NET host process.

If session state is in a separate process, the ASP.NET process can


come and go while the session state process remains available.

.NET Fundamentals Ver 2.0 75 of 156


ASP.NET advantages

Support for server farm configurations.


By moving to an out-of-process model, ASP.NET
also solves the server farm problem.

The new out-of-process model allows all servers in


the farm to share a session state process.

You can implement this by changing the ASP.NET


configuration to point to a common server.

.NET Fundamentals Ver 2.0 76 of 156


.NET Fundamentals Ver 2.0 77 of 156
ASP.NET advantages
Cookie independent.
• ASP.NET, on the other hand, reduces the complexities of cookieless
session state to a simple configuration setting.
– Config.web file for setting configuration
<configuration>
<sessionstate
mode="inproc"
cookieless="false"
timeout="20"
sqlconnectionstring="datasource=127.0.0.1;user
id=sa;password="server="127.0.0.1" port="42424"
/> </configuration>

.NET Fundamentals Ver 2.0 78 of 156


Performance Tunning

• Disable Session State when not in use


• Choose your Session State provider carefully
• Avoid excessive round trips to the server
• Use Page.IsPostback to avoid extra work on a round trip
• Use server controls sparingly and appropriately
• Do not rely on exceptions in your code
• Port call-intensive COM components to managed code
• Cache data and output wherever possible
• Do not forget to disable Debug mode

.NET Fundamentals Ver 2.0 79 of 156


Performance Tunning
• Manage ViewState
– size of the view state can entail performance hit.

• Manage Session State


– Use session when they are actually required .

• Use Output Caching


– Caching can give a ten fold performance

• Use Sql Classes for Data Access

.NET Fundamentals Ver 2.0 80 of 156


Thank You

.NET Fundamentals Ver 2.0 81 of 156

You might also like