Introduction to ASP.
NET
Prepared By : Rajeswari Badi (190985)
Key Learning Objectives
Introduction to Web Technology ASP.NET Architecture ASP.NET Web Forms and Controls ASP.NET Programming using VS.NET ASP.NET Security ASP.NET Deployment ASP.NET Application Configuration Introduction to ASP.NET Web Services ASP to ASP.NET Migration and Performance
10 Reasons You Love ASP.NET!
Much simpler page development model Clean separation of code and content Ability to use compiled languages Deploy and upgrade running apps with XCOPY Support for wide range of mobile devices Great tools support Web farm scalable session state Modular, well-factored architecture Automatically detects and recovers from errors Its really, really fast!
Introduction to Web Technology
Request Response Model Web Server Web Client Presentation Layer Scripting Client / Server side State Less State management Levels Page/Session/Application Web Page Actions Get/Post
ASP.NET Architecture
(Or Will After This Talk!) Pages Services
HTTP Runtime
Runtime Compilation
Parse ASPX Engine Generate Codebehind class
Request Request
ASPX File
Instantiate
Gend Page Class
Compile
Response Response
Page DLL Instantiate, Process and Render
Page Life Cycle
Control Properties Updated Page Load View State Restored Control Event Handlers
Request Request
Page Initialized
Response Response Page Unload Output Rendered View State Saved
ASP.NET Page Execution Cycle
Client Server IIS ASP.NET Runtime Parse .aspx file Generate page class Instantiate controls Code behind
Request .aspx file
Response
ASP.NET Web Forms
What WebForm Offers
Device Specific Behaviour Browser-Independence Less Code
Server Side Controls
Less Code Drag and Drop
Validation Controls
Declarative Programming
User Controls
Reusability
Web Forms
Dramatically easier, more productive
Requires a lot less code for a given job Enables much cleaner code organization
Server UI Controls provide encapsulation
VB-like, event-driven programming model Functionality and rendering Cross browser, cross device
Separation of code from content
Developers, designers can work independently
Executed via CLR as native code
VB, C#, JScript or any other .NET language
Separation of Code, Content
ASP page combines declarative tags (HTML, ASP directives, server controls and static text) with code ASP.NET separates the code and tags for better manageability single file code <tags> <tags> code separate files
Form1.asp
Form1.aspx
Form1.vb
ASP.NET Server Controls
(1 of 2)
Server controls encapsulate behavior
Declarative, tag with runat="server"
Generate HTML that is sent to the client
Can support multiple client types DHTML, HTML 3.2, WML, etc.
Process input sent from client
Bind to data in Forms collection Fire events for notifications
ASP.NET Server Controls
(2 of 2)
Allow look and feel to be customized
Template properties allow fine grained control
Are stateless on the server
ViewState travels with the page or URL
Server Controls
Server-programmable objects
Properties, method and events
Encapsulate behavior, rendering Can render differently to support multiple browsers or other Web clients
Mobile device support should be in beta 2
Users can create server controls
And derive from existing controls!
Uses a special tag (runat=server)
<asp:TextBox id="txtName" runat="server Text=Hello World!"/>
Class Hierarchy
System.Object System.Web.UI.Control
System.Web.UI. WebControls ListControl ListBox CheckBoxList ...
WebControl Table Button TextBox ...
How Do Server Controls Work?
When the ASP.NET page is executed:
Creates action and method attributes of form Adds unique id and name attributes to controls Adds value attribute to controls Adds a Hidden control to the form to save view state information(see as __VIEWSTATE field) The resulting HTML is sent down to the client
Code Behind Pages
ASP.NET includes support for all CLR languages
VB, C#, JScript and many others
Still supports <% %> tags for backwards compatibility
Code is compiled though, not interpreted
For maximum programming power use Server Controls
Write code for them using all the features of your favorite language and IDE Very VB-like get access to properties, methods and events
Power of Code Behind
Gives your ASP.NET applications access to the full power of the CLR
Compiled code All language features
strong typing early binding complete language set
Structured error handling API access Etc, etc, etc
Validation in ASP
Write custom code every time Client-side code becomes interwoven with content Server-side code works but you have to manually propagate state between trips to the client Usually lots of tedious code snippets that take a lot of time to get right
Validation Controls in ASP.NET
Added to Web Form like any other server control Controls validation for a variety of requirements
Required field Range checking Pattern matching
You can attach more than one validation control to an input Only works with a subset of controls
Controls You Can Validate
Control HtmlInputText HtmlTextArea HtmlSelect HtmlInputFile TextBox ListBox DropDownList RadioButtonList Validation Property Value Value Value Value Text SelectedItem.Value SelectedItem.Value SelectedItem.Value
Types of Validation
Required Field Compare Range
Input MUST be entered Input must match a pre-defined value or other control value Input must be within a lower- and upper-range Input must conform to a regular expression pattern Uses a custom function you create Summarizes the results of all the validation controls
Regular Expression Custom
Summary
Where Does Validation Occur?
Always on the server If your browser supports DHTML, it will also validate on the client by default
You can disable client-side validation
Set the Pages ClientTarget property to "Downlevel"
It will still validate on the server Prevents bypassing client security
Happens when you submit the page
Displaying Validation Errors
All validation controls are checked
If all pass muster the Pages IsValid property is set to True
When input fails validation, the associated validation controls Text property is displayed A summary validation control displays the ErrorMessage properties for all the Validation controls on the page
If the Text property is empty, it displays the ErrorMessage property
This is only displayed when the pages IsValid property is False
ASP Data Binding
No real notion of binding to an HTML control Use ADO Connections, Commands and Recordsets to retrieve data Manually iterate through Recordset results to build an HTML Table or fill the contents of a Select Building the HTML is relatively easy; making it look good takes longer HTML and ASP code intermingle Recordsets are usually the only data source
Data Binding in ASP.NET
Choices, Choices, Choices
Bind to Properties
Customer: <%# custID %>
Bind to Collections
<asp:ListBox datasource='<%# myArray %>'>
Bind to Expressions
Contact: <%# ( foo.FName + " " + foo.LName ) %>
Bind to Method Results
Outstanding Balance: <%# GetBal(custID) %>
Bind to DataSets
Grid.DataSource = myDataSet.Tables(0)
The DataBind Method
DataBind is a method on the Page object and all Server controls
Calling it once on a page will bind all child controls
Binding syntax <%# someField %> is NOT evaluated unless/until DataBind Binding expressions just work as long as the result is the expected data type
You may need to coerce to the appropriate type, such as myVal.ToString
Complex Binding
Most applications are going to talk to a big backend database like SQL Server This is more difficult than simple binding
Going to use ADO.NET Have to deal with Inserts, Updates and Deletes Have to manage multiple interfaces for each type of operation
Complex Binding in ASP
Usually is a complicated interface
Different pages for different actions Different code to render results, accept changes, etc. Lots of state management that needs to occur Can quickly become a time-consuming process
Complex Binding in ASP.NET
More complicated than simple binding, but still much easier than ASP Bindable server controls like DataGrid are big time savers Supports themes out of the box to give a professional presentation and appearance ViewState of page gives big perf benefits for maintaining state Supports properties and events to let you use the same interface for Updates and Deletes
One Grid Does It All
DataGrid offers the ability to edit, delete and update all in the same page You can add special EditCommand buttons
Edit Update Cancel Delete
There are event handlers associated with each button put your code there to update the database Using a TemplateColumn in a grid gives you complete control over the GUI
You can put any HTML control in a cell
ASP.NET Caching
Caching in ASP.NET
Lots of things you can cache
Cache sets of data Cache fragments of a page Cache an entire page
Lots of control over how its cached
Cache based on time (keep it for x seconds) Cache based on content (keep a copy for each unique value in this dataset) Cache based on dependencies (keep a copy until a file or other cache item changes
Getting Cached Items
Try retrieving item from cache
Item retrieval is based on a key MyValue = Cache(someKey) If the return value is Nothing, create it
When you create a cache item you set the desired lifetime and rules Cache persists until expiration or application is recycled Use Cache.Insert to create item
Creating Cached Items
Cache based on file dependency
Expires when authors.xml changes Cache.Insert("MyData", Source, New CacheDependency(Server.MapPath("authors.xml")))
Absolute expiration
Expires in one hour Cache.Insert("MyData", Source, null, DateTime.Now.AddHours(1), TimeSpan.Zero)
Relative expiration
Expires 20 minutes after it was last used Cache.Insert("MyData", Source, null, DateTime.MaxValue, TimeSpan.FromMinutes(20))
Caching Support
Full page output caching
Vary by params, language, user-agent Enables portions of pages to be cached Developers can cache arbitrary objects Multiple expiration policies, file change invalidation
Fragment Caching Extensible Cache API
Caching Directive
Add a <%@ OutputCache %> directive to the page Set the Duration property for how long it should be served from cache Set the VaryByParam to whatever GET/POST parameters should cause a new item to be cached
Example: <%@ OutputCache Duration="15" VaryByParam="none" %>
Page Fragment Caching
Allows you to mark certain regions of your page for caching Each Web Control is a separate file Each Web Control can have its own Duration that is separate from its Parent Just include the <%@ OutputCache %> directive in the control Cache can be purged by duration or changing content in one of the Web Controls child controls
Requires using Web Controls (.ascx files)
Uses VaryByControl parameter in OutputCache When the value of that control changes, a new entry is added to the cache for the duration
Thank You