Sie sind auf Seite 1von 212

ASP.NET 2.

0
Alok sharma MCA Pune university

An Introduction to .NET

The .NET Programming Framework




   

.NET languages: Primarily C# and VB.NET Common Language Runtime (CLR) .NET class library ASP.NET Visual Studio .NET

ASP.NET | Atul Kahate

What is .NET?
  

Development platform Old wine in new bottle? Support for over 25 programming languages Concept of Microsoft Intermediate Language (MSIL) Common Language Runtime (CLR)
ASP.NET | Atul Kahate 4

.NET Architecture

ASP.NET | Atul Kahate

How .NET Languages Work?




Source code gets compiled into an intermediary binary code, which is independent of the hardware and operating systems The intermediate binary code is MSIL (Microsoft Intermediate Language) MSIL is executed in the Common Language Runtime (CLR)
 

CLR is similar to the JVM in Java MSIL is translated into machine language by a JIT compiler
ASP.NET | Atul Kahate 6

Common Language Specification (CLS)




CLS is the specification to which all .NET languages must adhere The compiler compiles the source code into MSIL Hence, a class written in C# can extend a class written in VB.NET! Performance of all languages is also similar
ASP.NET | Atul Kahate 7

More on CLR 1


Common set of data types across languages Says nothing about the syntax Individual languages are free to choose what suits them Garbage collection

ASP.NET | Atul Kahate

More on CLR 2


Deep language integration: No difference between languages now, since CLR only gets to see IL. No more DLL hell: IL programs store extra information about their classes and components they require (called as metadata). CLR examines this to prevent usage of a wrong version of a component.

ASP.NET | Atul Kahate

More on CLR 3


Side-by-side execution: CLR has the ability to load more than one version of a component at a time. Fewer errors: Automatic memory management, garbage collection

ASP.NET | Atul Kahate

10

Base Framework Classes

ASP.NET | Atul Kahate

11

Managed Code


Code that gets executed by the CLR is called as managed Unmanaged code bypasses the CLR, and is considered non-standard


Discouraged practice

ASP.NET | Atul Kahate

12

ASP.NET (Earlier ASP+)

ASP.NET


 

Allows development of dynamic Web pages Specification for dynamic Web pages Common development languages are C# and VB.NET Far more sophisticated than ASP

ASP.NET | Atul Kahate

14

ASP.NET Advantages


No more scripting: ASP relied on scripting languages, such as JavaScript and VBScript; ASP.NET uses C# or VB.NET Deployment and configuration was a headache earlier; not any more Application structuring: Earlier, HTML and scripting code was intermixed State limitations: Was a problem earlier in Web farm; not any more
ASP.NET | Atul Kahate 15

Starting ASP.NET


An ASP.NET Web application is called as a Web site under ASP.NET 2.0 Start with File -> New Web Site command The following screen appears after choosing a Web Site name

ASP.NET | Atul Kahate

16

Starting Screen for a New Web Site

ASP.NET | Atul Kahate

17

Form Processing

Creating Simple Forms 1 (Project name: WebSite1)




default.aspx

<%@ Page Language="C#" %> <html> <body> <form id="form1" action = "a1.aspx"> <input type = "text" value = "Hi" name = "aa" /> <br /> <input type = "submit" value = "Click here" /> </form> </body> </html>
ASP.NET | Atul Kahate 19

Creating Simple Forms 2




a1.aspx

<%@ Page Language="C#" %> <html> <body> Hi there! </body> </html>


ASP.NET | Atul Kahate 20

Retrieving Form Values (a2.aspx)


<%@ Page Language="C#" %> <html> <body> Hi in a2.aspx <% String a; a = Request.QueryString["aa"]; Response.Write(a); %> </body> </html>
ASP.NET | Atul Kahate 21

Conditional Processing (a3.aspx)


<%@ Page Language="C#" %> <html> <body> <% String a; a = Request.QueryString["aa"]; if (a == "atul") Response.Write("<h1>Welcome " + a + "</h1>"); else Response.Write("<h2>You are not Welcome " + a + "</h2>"); %> </body> </html>
ASP.NET | Atul Kahate 22

Server Controls

Two types


HTML server controls




Server-based equivalents of standard HTML elements ASP.NET equivalent controls for the HTML controls

Web controls


ASP.NET | Atul Kahate

24

HTML Server Controls




Provide an object interface for standard HTML elements Three key features
  

Generate their own interface Retain their state Fire events

Need for adding runat = server attribute


ASP.NET | Atul Kahate 25

Web Controls


 

Provide richer UI (e.g. calendar, data grid) Provide consistent object model Adjust for browsers automatically

ASP.NET | Atul Kahate

26

AutoPostBack


Automatic postback submits a page back to the server when it detects a specific user action, without waiting for the entire user action to get over

ASP.NET | Atul Kahate

27

Using Server Controls (default.aspx changed now)


<%@ Page Language="C#"%> <html> <body> <form id="form1" action = "a4.aspx" runat = "server"> <asp:TextBox ID = "aa" runat = "server" /> <br /> <asp:Button Text = "Click here" runat = "server" /> </form> </body> </html>
ASP.NET | Atul Kahate 28

Details on Server Controls




Usage of special tags such as <asp:Textbox> instead of standard HTML tags such as <input type = text> ASP.NET asks the server to generate HTML tags corresponding to the ASP tags
ASP.NET | Atul Kahate 29

Result of doing View Source


<html> <body> <form name="form1" method="post" action="Default.aspx" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMzE5MDUyNjFkZBJrCfY2wEmriQ3bal/1iDikFr4/" /> </div> <input name="aa" type="text" value="test" id="aa" /> <br /> <input type="submit" name="ctl00" value="Click here" /> <div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLFqeuwAwK/76bvDAKhwImNC0Gv6Kcq4KxNxSSW8vaRexezd95A" /> </div></form> </body> </html>

ASP.NET | Atul Kahate

30

The _VIEWSTATE field


 

It is hidden Because we had added runat = server attribute, ASP.NET adds this hidden field to remember the state of the form on its own In other words, it keeps information about the users data entry between requests Also, note that the form is posted back to itself (see form actioni)
ASP.NET | Atul Kahate 31

Capturing Events (default.aspx modified)


<%@ Page Language="C#"%> <html> <body> <form id="form1" method = "post" action = "Default.aspx" runat = "server"> <script language = "C#" runat = "server"> void abc(Object a, EventArgs e) { Response.Write("hello"); } </script> <asp:TextBox ID = "aa" runat = "server" /> <br /> <asp:Button Text = "Click here" onClick = "abc" runat = "server"/> </form> </body> </html>

ASP.NET | Atul Kahate

32

View Source of the previous Example


<html> <body> <form name="form1" method="post" action="Default.aspx" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMzE5MDUyNjFkZBJrCfY2wEmriQ3bal/1iDikFr4/" /> </div> <input name="aa" type="text" id="aa" /> <br /> <input type="submit" name="ctl00" value="Click here" />

<div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLFqeuwAwK/76bvDAKhwImNC0Gv6Kcq4KxNxSSW8vaRexezd95A" /> </div></form> </body> </html>

ASP.NET | Atul Kahate

33

Analysis


OnClick attribute and the function abc have disappeared! We would realize that the attribute type has got added to our button Now let us type the word test in the text box and submit

ASP.NET | Atul Kahate

34

Resulting Output

ASP.NET | Atul Kahate

35

View Source now


hello <html> <body> <form name="form1" method="post" action="Default.aspx" id="form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTEzMzE5MDUyNjFkZBJrCfY2wEmriQ3bal/1iDikFr4/" /> </div> <input name="aa" type="text" value="test" id="aa" /> <br /> <input type="submit" name="ctl00" value="Click here" />

<div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLFqeuwAwK/76bvDAKhwImNC0Gv6Kcq4KxNxSSW8vaRexezd95A" /> </div></form> </body> </html>

ASP.NET | Atul Kahate

36

Analysis


When we enter some text in the text box and submit the form, our function abc gets called It also remembers the state of the textbox

ASP.NET | Atul Kahate

37

Cross-page Posting


When the Runat = Server attribute is added to a page, the page posts back to itself as default (Next slide) To change this behavior and making the page post results to another page, we need to use the property PostbackUrl (Slide after next)
ASP.NET | Atul Kahate 38

Try this default2.aspx




<%@ Page Language="C#"%> <html> <body> <form id="form1" action = "a4.aspx" runat = "server"> <asp:TextBox ID = "aa" runat = "server" /> <br /> <asp:Button ID="Button1" Text = "Click here" runat = "server" /> </form> </body> </html>

    

   

ASP.NET | Atul Kahate

39

Now try this - a1.aspx


<%@ Page Language="C#"%> <html> <body> <form id="form1" runat = "server"> <asp:TextBox ID = "aa" runat = "server" /> <br /> <asp:Button ID="Button1" Text = "Click here" runat = "server" PostBackUrl = "~/a2.aspx" /> </form> </body> </html>
ASP.NET | Atul Kahate 40

Cross-Page Posting Issues




Although we may be able to do crosspage posting, it is not easy to read values of controls from the previous page Standard techniques of Request.QueryString do not work How to do it, then? Example follows.
ASP.NET | Atul Kahate 41

Cross-Page Parameter Posting




<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> Hi in a2.aspx <% String a; TextBox t1; t1 = (TextBox) PreviousPage.FindControl ("aa"); a = t1.Text.ToString (); Response.Write(a); Response.Write("Hello World"); %> </body> </html>

               

ASP.NET | Atul Kahate

42

Creating a Drop-Down List and a Label


<%@ Page Language="C#"%> <html> <body> <form id="form1" method = "post" action = "Default.aspx" runat = "server"> <script language = "C#" runat = "server"> void abc(Object a, EventArgs e) { cc.Text = aa.Text + " " + bb.SelectedItem; } </script> <asp:TextBox ID = "aa" runat = "server" /> <br /> <asp:DropDownList ID = "bb" runat = "server"> <asp:ListItem>Wood</asp:ListItem> <asp:ListItem>Copper</asp:ListItem> <asp:ListItem>Iron</asp:ListItem> </asp:DropDownList> <asp:Button Text = "Click here" onClick = "abc" runat = "server"/> <asp:Label ID = "cc" runat = "server" /> </form> </body> </html>

ASP.NET | Atul Kahate

43

Label


Label does not get displayed on the screen unless it has some value When the user submits the form, the label is initialized by the function abc

ASP.NET | Atul Kahate

44

Drop Down List




Allows us to create a list of possible choices The individual items are displayed by using the Listitem property The selected item is identified by using the SelectedItem property

ASP.NET | Atul Kahate

45

Displaying Current Time


<%@ Page Language="C#"%> <html> <body> <script language = "C#" runat = "server"> void Page_Load (Object a, EventArgs e) { aa.Text = "Time is: " + DateTime.Now; } </script> <asp:Label ID = "aa" Font-Size = "24" Font-Bold = "true" runat ="server" /> </body> </html>

ASP.NET | Atul Kahate

46

Output
Output Time is: 18-03-2007 06:13:08  View Source


<html> <body> <span id="aa" style="font-size:24pt;font-weight:bold;">Time is: 18-03-2007 06:13:08</span> </body> </html>
ASP.NET | Atul Kahate 47

Analysis


Page_Load is a method that gets called on the server, whenever we override it It is called prior to generating the page

ASP.NET | Atul Kahate

48

Adding a URL
<%@ Page Language="C#"%> <html> <body> <script language = "C#" runat = "server"> void Page_Load (Object a, EventArgs e) { aa.Text = " Atul"; bb.NavigateUrl = a5.aspx?cc=" + aa.Text; } </script> <asp:HyperLink ID = "bb" Font-Size = "24" runat = "server"> Hi <asp:Label ID = "aa" runat ="server" /> </asp:HyperLink> </body> </html> ASP.NET | Atul Kahate 49

Analysis
   

To add a hyper link, we need the HyperLink tag Its ID is bb There is also a label with ID aa The label value is changed in the Page_Load method, and the NavigateUrl property of the hyper link is also changed When the URL is clicked, a5.aspx is called with cc initialized to Atul Request.Params function is similar to Request.QueryString
ASP.NET | Atul Kahate 50

Dynamically Generating a Control from an Array


<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected void ASP.NET | Atul Kahate 51 DropDownList1_SelectedIndexChanged(objec t sender, EventArgs e)

Disabling Certain ListItems from a Collection




<%@ Page Language = "C#" %> <html> <body> <form id = "form1" runat = "server"> <asp:dropdownlist id="DropDownList1" runat="server" autopostback = "True" onselectedIndexchanged = ASP.NET | Atul Kahate "DropDownList1_SelectedIndexChanged">

 

52

Adding Items to a Collection




<%@ Page Language = "C#" %> <script runat="server"> protected void Button1_Click(object sender, EventArgs e) { ListBox1.Items.Add(TextBox1.Text.ToString() ); ASP.NET | Atul Kahate 53 }

 

Using Radio Buttons


<%@ Page Language = "C#" %> <script runat="server">

protected void RadioButton_CheckedChanged(object sender, EventArgs e) { if (RadioButton1.Checked == true) ASP.NET | Atul Kahate 54 {

RadioButtonList
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, 55 EventArgs e) ASP.NET | Atul Kahate

Calendar Control
<%@ Page Language = "C#" %> <script runat="server">

protected void Calendar1_SelectionChanged(object sender, EventArgs e) { ASP.NET | Atul Kahate 56 Response.Write("You selected " +

Checkboxes
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected void ASP.NET | Atul Kahate 57 CheckBox1_CheckedChanged(object sender, EventArgs e)

CheckBoxList
<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected void Button1_Click(object sender, 58 EventArgs e) ASP.NET | Atul Kahate

ASP.NET Web Page Code Model

Approaches to Coding
 

Single-file page model Code-behind page model Differences




In the code-behind model, there is no script block with the runat="server" attribute. (The page can contain script blocks without the runat="server" attribute if you want to write client-side script in the page.) The @ Page directive in the code-behind model contains attributes that reference an external file (SamplePage.aspx.vb or SamplePage.aspx.cs) and a class. These attributes link the .aspx page to its code.

ASP.NET | Atul Kahate

60

Single-file Page Model




In the single-file page model, the page's markup and its programming code are in the same physical .aspx file. The programming code is in a script block that contains the attribute runat="server" to mark it as code that ASP.NET should execute. Example follows.
ASP.NET | Atul Kahate 61

Example
<%@ Page Language="C#" %> <script runat="server"> void Button1_Click(Object sender, EventArgs e) { Label1.Text = "Clicked at " + DateTime.Now.ToString(); } </script> <html> <head> ASP.NET | Atul Kahate 62 <title>Single-File Page Model</title>

Code-behind Page Model




The code-behind page model allows you to keep the markup in one filethe .aspx fileand the programming code in another file. The name of the code file varies according to what programming language you are using. Example follows.
ASP.NET | Atul Kahate 63

Example
<%@ Page Language="C#" CodeFile="SamplePage.aspx.cs" Inherits="SamplePage" AutoEventWireup="true" %> <html> <head runat="server" > <title>Code-Behind Page Model</title> </head> <body> <form id="form1" runat="server"> ASP.NET | Atul Kahate <div>

64

C# Code
using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class SamplePage : System.Web.UI.Page { protected void Button1_Click(object sender, EventArgs e) { ASP.NET | Atul Kahate 65 Label1.Text = "Clicked at " +

More Details
 

The code-behind file contains the complete class declarations in the default namespace. However, the class is declared with the partial keyword, which indicates that the class is not contained entirely in one file. Instead, when the page runs, the compiler reads the .aspx page and the file it references in the @ Page directive, assembles them into a single class, and then compiles them as a unit into a single class.
ASP.NET | Atul Kahate 66

Single-File Page Model




In pages where there is not very much code, the convenience of keeping the code and markup in the same file can outweigh other advantages of the code-behind model. For example, it can be easier to study a single-file page because you can see the code and the markup in one place. Pages written using the single-file model are slightly easier to deploy or to send to another programmer because there is only one file. Because there is no dependency between files, a single-file page is easier to rename. Managing files in a source code control system is slightly easier, because the page is self-contained in a single file.

ASP.NET | Atul Kahate

67

Code-behind Page Model




Code-behind pages offer a clean separation of the markup (user interface) and code. It is practical to have a designer working on the markup while a programmer writes code. Code is not exposed to page designers or others who are working only with the page markup. Code can be reused for multiple pages.

ASP.NET | Atul Kahate

68

Client-Side Callback

Basic Concepts
  

Similar to AJAX Available only with ASP.NET 2.0 Allows retrieving of page values and populating them without refreshing the page End users will not notice flicker or refresh
ASP.NET | Atul Kahate 70

How it Works? 1


Traditional processing


An event (such as button click) causes the browser to send a postback request to the Web server The IPostbackEventHandler class gets called, which runs the request through a series of page events, such as loading state, data processing, processing postback events, and rendering new page Causes refresh or flicker
ASP.NET | Atul Kahate 71

How it Works? 2


Client-side Callbacks


An event such as a button click causes the event to be posted to a script handler (i.e. a JavaScript function) that sends off an asynchronous request to the Web server for processing The ICallBackEventHandler class runs through the steps, but does not render the page once again Refresh or flicker does not occur

ASP.NET | Atul Kahate

72

CallbackExample.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CallbackExample.aspx.cs" Inherits="CallbackExample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> ASP.NET | Atul Kahate
73

CallbackExample.aspx.cs
        

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
ASP.NET | Atul Kahate 74

public partial class CallbackExample :

Understanding the Example 1




In the HTML page, a standard HTML button is used, because an <asp:button> does not work in these situations The onclick event calls a JavaScript function


The GetNumber function calls the name of the client-side script handler that is defined in the pages code-behind A string type resulting from the GetNumber () is retrieved by using the GetRandomNumberFromServer () function, which copies the value in the text box on the screen
ASP.NET | Atul Kahate 75

Understanding the Example 2




Code behind
 

Implements ICallbackEventHandler interface Requires that we implement methods RaiseCallbackEvent and GetCallbackResult These two methods work with the client script request


RaiseCallbackEvent invokes a callback event with the specified arguments GetCallbackResult returns the results of a callback event that targets a control

ASP.NET | Atul Kahate

76

Understanding the Example 3




Page_Load Event


Page_Load event include creation and placement of client callback script manager (the function that manages requests and responses) on the client Page.ClientScript.GetCallbackEventReference(this, "arg", "GetRandomNumberFromServer", "context"); obtains a reference to the client-side function, which, when invoked, initiates a client callback to a server-side function Then the statement Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", cbScript, true); registers the script with the Page object note that the function name UseCallback is the same as in our JavaScript

ASP.NET | Atul Kahate

77

Validation Controls

Client Side Script in ASP.NET

Basics
 

ASP.NET is a server-based technology, and therefore does not directly interact with the browser. For example, there are no ASP.NET methods to get keyboard input from the browser, respond to mouse events, or perform other tasks that involve user interaction with the browser. ASP.NET can get the results of such actions after the page has been posted, but cannot directly respond to browser actions.

ASP.NET | Atul Kahate

80

ASP.NET Server Controls and Client Script Events




<asp:textbox id="TextBox1" runat="server" text="Sample Text" />




You can add client script to controls on an ASP.NET Web page declaratively, as you would to HTML elements. Alternatively, you can add client script events to an ASP.NET Web server control programmatically, which is useful if the event or the code relies on information that is available only at run time.
ASP.NET | Atul Kahate 81

Adding Event Handlers


<%@ Page Language="C#" %> <html> <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> var previousColor; function MakeRed() { previousColor = window.event.srcElement.style.color; window.event.srcElement.style.color = "#FF0000"; } function RestoreColor() { window.event.srcElement.style.color = previousColor; } </script> </head> <body> <form id="form1" runat="server"> <asp:button id="Button1" runat="server" text="Button1" onmouseover="MakeRed();" onmouseout="RestoreColor();" /> </form> </body> </html>

ASP.NET | Atul Kahate

82

Validation Controls

How Validation Works


 

 

ASP.NET checks the browser when generating a page If the browser can support JavaScript, ASP.NET sends client-side JavaScript to the browser for validations Otherwise, validations happen on the server Even if client-side validation happens, serverside validation still happens; ensuring double security
ASP.NET | Atul Kahate 84

Validation Controls


RequiredFieldValidator


Checks that a value has been entered into a control Matches the value of a control with some value Validation based on a range of values Comparison with a regular expression Validation using a user-defined function
ASP.NET | Atul Kahate 85

CompareValidator


RangeValidator


RegularExpressionValidator


CustomValidator


Adding a Validation Control


<%@ Page Language="C#"%> <html> <body> <form action = "default.aspx" runat = "server"> <asp:RequiredFieldValidator ControlToValidate = "aaa" ErrorMessage = "Please enter something" runat = "Server" /> <asp:TextBox ID = "aaa" runat = "server" /> <asp:Button Text = "Click" runat = "server" /> </form> </body> </html>
ASP.NET | Atul Kahate 86

Analysis


A textbox and a button would get displayed We have added a RequiredFieldValidator validation control on our form, and have associated it with the textbox If the textbox is empty, this validation control displays an error message
ASP.NET | Atul Kahate 87

View Source
<html> <body> <form name="ctl00" method="post" action="Default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="ctl00"> <div> <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNjAxNjA3Mjc1ZGQakbvYOOynI9SIT6V0YBb1bFalqA==" /> </div> <script type="text/javascript"> <!-var theForm = document.forms['ctl00']; if (!theForm) { theForm = document.ctl00; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } // --> </script>

<script src="/WebSite1/WebResource.axd?d=A3fny7oVE8uDWTOe_7T6Qg2&amp;t=632969234944906146" type="text/javascript"></script>

<script src="/WebSite1/WebResource.axd?d=f2TqBkrftdNOxTb2bmboBlygriVRf-F331lV9yZtbLE1&amp;t=632969234944906146" type="text/javascript"></script> <script type="text/javascript"> <!-function WebForm_OnSubmit() { if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false; return true; } // --> </script> <span id="ctl01" style="color:Red;visibility:hidden;">Please enter something</span> <input name="aaa" type="text" id="aaa" /> <input type="submit" name="ctl02" value="Click" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl02&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))" /> <script type="text/javascript"> <!-var Page_Validators = new Array(document.getElementById("ctl01")); // --> </script> <script type="text/javascript"> <!-var ctl01 = document.all ? document.all["ctl01"] : document.getElementById("ctl01"); ctl01.controltovalidate = "aaa"; ctl01.errormessage = "Please enter something"; ctl01.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid"; ctl01.initialvalue = ""; // --> </script>

ASP.NET | Atul Kahate

88

Analysis


 

For implementing the validation checks, ASP.NET converts our validation control code into JavaScript and sends it to the browser along with it Hence, these are client-side validations Request does not go to the server

ASP.NET | Atul Kahate

89

Validating Drop Down List Selections


<%@ Page Language="C#"%> <html> <body> <form action = "default.aspx" runat = "server"> <asp:DropDownList ID = "aa" runat = "server"> <asp:ListItem>Select Choice</asp:ListItem> <asp:ListItem>Wood</asp:ListItem> <asp:ListItem>Copper</asp:ListItem> <asp:ListItem>Steel</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator ControlToValidate = "aa" InitialValue = "Select Choice" ErrorMessage = "Please select something" runat = "Server" /> <asp:Button Text = "Click" runat = "server" /> </form> </body> </html> ASP.NET | Atul Kahate 90

Validating if a complete page is valid


<%@ Page Language="C#"%> <html> <head> <script language = "C#" runat = "server"> void abc(Object S, EventArgs e) { if (Page.IsValid == true) { aa.Text = "Page is valid!"; } else { aa.Text = "There are some errors!"; } } </script> </head> <body> <form runat = "server"> <asp:Label ID = "aa" Text = "Fill it up" runat = "server"/> <asp:RadioButtonList ID = "bb" runat = "server"> <asp:ListItem>Wood</asp:ListItem> <asp:ListItem>Copper</asp:ListItem> <asp:ListItem>Steel</asp:ListItem> </asp:RadioButtonList> <asp:RequiredFieldValidator ID = "r1" ControlToValidate = "bb" InitialValue = "" runat = "Server"> * </asp:RequiredFieldValidator> <asp:TextBox ID = "cc" runat = "server" /> <asp:RequiredFieldValidator ID = "r2" ControlToValidate = "cc" width = "100%" runat = "Server">hey </asp:RequiredFieldValidator> <asp:Button ID = "B1" Text = "Validate" onClick = "abc" runat = "server" /> </form> </body> </html>

ASP.NET | Atul Kahate

91

Comparison Validator
<%@ Page Language="C#" AutoEventWireup="True" %> <html> <head> <script runat="server"> void Button_Click(Object sender, EventArgs e) {
ASP.NET | Atul Kahate 92

Range Validator
 

Allows us to check the range of a field We can specify the minimum and maximum values, the control to validate, and the error message We can also specify what data type should be applied during validation

ASP.NET | Atul Kahate

93

Range Validator Example


<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void Button_Click(Object sender, EventArgs e) { if (Page.IsValid) { MessageLabel.Text = "Page submitted successfully."; } else { MessageLabel.Text = "There is an error on the page."; } } </script> <html > <head id="Head1" runat="server"> <title>Validator Example</title> </head> <body> <form id="form1" runat="server"> <h3>Validator Example</h3> Enter a number from 1 to 10. <asp:textbox id="NumberTextBox" runat="server"/> <asp:rangevalidator id="NumberCompareValidator" controltovalidate="NumberTextBox" enableclientscript="False" type="Integer" display="Dynamic" errormessage="Please enter a value from 1 to 10." maximumvalue="10" minimumvalue="1" text="*" runat="server"/> <asp:requiredfieldvalidator id="TextBoxRequiredValidator" controltovalidate="NumberTextBox" enableclientscript="False" display="Dynamic" errormessage="Please enter a value." text="*" runat="server"/> <br /><br /> <asp:button id="SubmitButton" text="Submit" onclick="Button_Click" runat="server"/>

ASP.NET | Atul Kahate

94

Analysis


Two controls used on the form are


 

A radio button A text box

When no text is entered in the text box, the word hey is displayed in front of the text box When no option is chosen in the radio button, a red * appears in front of the radio button Every ASP.Net page has a free variable called as Page.IsValid, that tells us whether all controls on the page contain valid data
ASP.NET | Atul Kahate 95

Regular Expressions
 

Used for pattern matching See next slide

ASP.NET | Atul Kahate

96

Regular Expressions
Character * + () | [] [^] \d \s \S Description 0 or more occurrences of the previous character. For example, 7*8 matches 7778 or just 8. 1 or more occurrences of the previous character. For example, 7+8 matches 7778 but not 8. Groups a sub-expression that will be treated as a single element. For example, (78)+ matches 78 and 787878. Either of two matches. For example, 8 | 6 matches 8 or 6. Matches one character in a range of valid characters. For example, [A-C] matches A, B, or C. Matches a character that is not in a given range. For example, [^A-B] matches any character except A and B. Any digit. Any white space character (e.g. space, tab). Any non white space character.
ASP.NET | Atul Kahate 97

Examples
Content Regular Expression \S+@\S+\.\S+ Description Email address Password Check for an ampersand, dot and only non white space characters. Any sequence of word characters (letter, space, or underscore). Password between 4 and 10 characters.

\w+

Specificlength password Social security number

\w{4,10}

\d{3}-\d{2}\d{4}

Sequence of 3, 2, and 4 digits, each group separated by a dash.

ASP.NET | Atul Kahate

98

More Examples
Expression \d{3} \w(5,20} \d{2}-\d{4} \w{1,8}.\w{1,3} (AB)|(SB)-d{1,5} \d{5}(-\d{4})? \w*\d\w* [xyz]\d{3} Example 289 College 10-3944 Test.jpg SB-3276 93711-2765 Arm01 x023 Details A three digit number Word between 5 and 20 characters A two-digit number, followed by hyphen, followed by a four-digit number Up to 8 characters, followed by a dot, followed by up to 3 characters Letters AB or SB, followed by a hyphen, followed by a one-to-five digit number A five-digit number, optionally followed by a hyphen and a four-digit number A text entry that must have at least one number Letter x, or y, or z, followed by a three-digit number
ASP.NET | Atul Kahate 99

Regular Expression Example




<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RegularExpressionValidator.aspx.c s" Inherits="RegularExpressionValidator" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html ASP.NET | Atul Kahate 100 xmlns="http://www.w3.org/1999/xhtml" >

Custom Validator 1


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomValidatorExample.aspx.cs" Inherits="CustomValidatorExample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html ASP.NET | Atul Kahate 101 xmlns="http://www.w3.org/1999/xhtml" >

Custom Validator 2
         

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; ASP.NET | Atul Kahate 102

ValidationSummary Server Control




Consolidates error reporting for all controls on a page Usually used for forms containing large amounts of data Shows list of errors in a bulleted list

ASP.NET | Atul Kahate

103

ValidationSummary Example


<%@ Page Language = "C#" %> <script runat="server">

   

</script> <html> <body>


ASP.NET | Atul Kahate 104

Modified Example


<%@ Page Language = "C#" %> <script runat="server">

   

</script> <html> <body>


ASP.NET | Atul Kahate 105

ValidationSummary and Dialog Box


<%@ Page Language = "C#" %> <script runat="server > </script> <html> <body> <form id = "form1" runat = "server"> &nbsp; First Name &nbsp;<asp:TextBox ID="TextBox1" ASP.NET | Atul Kahate runat="server"></asp:TextBox>

106

User Authentication
Authentication Flow See next slide

Client
Web.config

Server

GET //default.aspx

<authentication mode="Forms"> <forms loginUrl ="login.aspx"/> </authentication> <authorization> <deny users="?"/> </authorization>

Log In User ID: _________ Password: ________ Login

Redirect to login.aspx

<script runat="server"> protected bool AuthenticateUser(string strUserName, string strPassword) { if (strUserName == "atul" && strPassword == "atul") return true; else return false; } public void onLogin(object src, EventArgs e) { }

POST //login.aspx User=atul Password=atul

default.aspx Congratulations! You have been authenticated!

ASP.NET | Atul Kahate

108

Authentication Example
Refer to LoginExampleSite

Edit Web.config
Add the following <authentication mode="Forms"> <forms loginUrl ="login.aspx"/> </authentication>


<authorization> <deny users="?"/> </authorization>


ASP.NET | Atul Kahate 110

Code login.aspx


<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected bool AuthenticateUser(string ASP.NET | strPassword) strUserName, string Atul Kahate

111

How it works?


FormsAuthenticationClass is used
 

Provides many useful methods Here, we are redirecting user to another page after successful authentication

ASP.NET | Atul Kahate

112

Change default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html ASP.NET | Atul Kahate 113 xmlns="http://www.w3.org/1999/xhtml" >

How to test?
  

Run default.aspx It should redirect us to the login page If user ID and password are correct, it should show success, else failure

ASP.NET | Atul Kahate

114

Other Authentication Mechanisms




Passport authentication


Uses Microsoft Passport technology Managed by IIS

Windows authentication


Most preferred is ASP.NET Authentication


ASP.NET | Atul Kahate 115

Using ASP.NET Login Controls





1. 2. 3.

In-built login page, no need for manual text boxes, etc Steps
Add a new page titled login2.aspx In that page, drag the Login ASP.NET control Change Web.config to say the following <forms loginUrl ="login2.aspx"/> Now try accessing default.aspx It should redirect us to the new login page
ASP.NET | Atul Kahate 116

4. 5.

Developing Applications

Designing a Form
  

We want to add six Web server controls to the form They are derived from ASP.NET classes They are: one drop-down list, two text boxes, one label, and two buttons Flow layout concept is used
 

Use the Design view Text and controls added to a form are positioned from left to right and top to bottom

ASP.NET | Atul Kahate

118

Adding Controls

ASP.NET | Atul Kahate

119

Corresponding Code Generated by ASP.NET


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <span style="font-size: 20px">Future Value Calculator</span><br /> <br /> Monthly investment&nbsp; <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList><br /> <br /> Annual interest rate &nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></div> </form> </body> </html>

ASP.NET | Atul Kahate

120

Adding a Table to a Form


 

Use Layout -> Insert Table command Set the number of rows and columns and other options and click OK To resize a row, column or table, drag the appropriate borders Use the Formatting toolbar or the Format menu to format text in the table
ASP.NET | Atul Kahate 121

Adding a Table to a Form

ASP.NET | Atul Kahate

122

Resulting Output

ASP.NET | Atul Kahate

123

Adding Server Controls




To add a server control to a form, just drag a control to the form OR take cursor to the appropriate location of the form and then double click on the control to be inserted in the form

ASP.NET | Atul Kahate

124

Result of Adding Web Server Controls

ASP.NET | Atul Kahate

125

Common Web Server Control Properties


Property AutoPostBack Description Determines whether the page is posted back to the server when the value of the control changes. Available with controls such as check box, drop-down list, radio button, or text box. Default value is false. Determines whether the validation done by the validation controls occurs when you click on the button, link, or image button. Determines whether the control maintains its view state between HTTP requests. Default is true. Determines whether the control is function. Default is true. Height of the control. Name used to refer to the control. Indicates that the control will be processed at the server. Determines the order in which controls on the form receive the focus when Tab key is pressed. Text displayed in the control. Text displayed when the user hovers the mouse over the control. Determines whether the control is visible or hidden. The width of the control. ASP.NET | Atul Kahate 126 CausesValidation EnableViewState Enabled Height ID Runat TabIndex Text ToolTip Visible Width

Common Drop-down list and List box Controls


Property Description

Items

Collection of ListItem objects that represent the items in the control. We can add, insert, and remove items using run time code. ListItem object for the currently selected item. Index of the currently selected item, -1 if none is selected. Value of the currently selected item.

SelectedItem SelectedIndex SelectedValue

ASP.NET | Atul Kahate

127

Modify Code
  

Change the title of the page Note that the page has an extension of .aspx Note the code for various server controls, e.g. <asp:Button> and </asp:Button>


This is converted into plain HTML before the page is sent to the browser, since the browser cannot interpret code of such controls

ASP.NET | Atul Kahate

128

Source View

ASP.NET | Atul Kahate

129

Add More Controls to the Form

ASP.NET | Atul Kahate

130

Source Code Now


<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Future Value Calculation</title> </head> <body> <form id="form1" runat="server"> <div> <span style="font-size: 20px"></span> <table> <tr> <td style="width: 100px"> Monthly investment</td> <td style="width: 100px"> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList></td> </tr> <tr> <td style="width: 100px"> Annual interest rate</td> <td style="width: 100px"> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> </tr> <tr> <td style="width: 100px"> Number of years</td> <td style="width: 100px"> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td> </tr> <tr> <td style="width: 100px"> Future value</td> <td style="width: 100px"> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></td> </tr> <tr> <td style="width: 100px"> </td> <td style="width: 100px"> </td> </tr> <tr> <td style="width: 100px"> <asp:Button ID="Button1" runat="server" Text="Calculate" Width="98px" /></td> <td style="width: 100px"> <asp:Button ID="Button2" runat="server" Text="Clear" Width="100px" /></td> </tr> </table> </div> </form> </body> </html>

ASP.NET | Atul Kahate

131

Adding Validation Controls to a Form


 

We can use validation controls to test user input and produce error messages Validation is performed when the focus leaves the control being validated and also when the user clicks on a button control whose CausesValidation property is set to True Each validation control is associated with a specific server control, but we can associate one or more validation controls with a single server control
ASP.NET | Atul Kahate 132

How Validation Controls Work


 

Validation controls run client-side script If validation fails, the page is not posted back to the server If the client does not support scripts, validation happens on the server If the client does not support scripts, we can test whether the validation has been successful on the server by testing the IsValid property of the page
ASP.NET | Atul Kahate 133

Validation Controls Example




We can drag a validation control to the screen In our example, we will use four validators: two range validators, and two required field validators We will add them below our table

ASP.NET | Atul Kahate

134

Adding Validation Controls

ASP.NET | Atul Kahate

135

Additional Properties of a Range Validator


Property Description

Maximum Minimum Type

The maximum allowed value. The minimum allowed value. The data type used (e.g. String, Integer, Double, Date, or Currency)

ASP.NET | Atul Kahate

136

Our Modified Validator Code


<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Interest rate is required"></asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="TextBox1" Display="Dynamic" ErrorMessage="Interest rate must range from 1 to 20"></asp:RangeValidator><br /> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Number of years is required"></asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator2" runat="server" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="Years must range from 1 to 45"></asp:RangeValidator>
ASP.NET | Atul Kahate 137

Adding Code to a Form


  

Double click on a form in the Design view This starts an event handler for the page Similarly, double click on a control to write event handler for that control Events can be of two types
 

Page events Control events

All events execute on the server after the page is posted back to the server
ASP.NET | Atul Kahate 138

Page Events


When a page is posted back to the server, its Init and Load events are always raised, then the individual control events are raised When all the control events are finished, the PreRender event is raised and any event handler for that event is run
ASP.NET | Atul Kahate 139

Common Page Events


Event Method name Occurs when

Init

Page_Init

A page is requested from the server. This event is raised before the view state of the page controls has been restored. The page is requested from the server, after all controls have been initialised and view state has been restored. This is the event we typically use to perform initialisation operations such as retrieving data and initialising form controls. All the control events for the page have been processed but before the HTML that will be sent back to the browser is generated.

Load

Page_Load

PreRender

Page_PreRender

ASP.NET | Atul Kahate

140

Control Events
 

Individual control events Occur when the user takes an action on the control, e.g.


When a button is clicked, the Click event of the button is fired When a user changes the value in a text box, the TextChanged event gets fired

ASP.NET | Atul Kahate

141

AutoPostBack Property


If we want the event handler to be executed immediately when the event occurs, we need to set the AutoPostBack property of the control to True. In this case, the Init and Load events for the page are fired, followed by this control event. If the AutoPostBack property is set to false, the event is still raised, but the event handler is not executed until another event causes the page to be posted to the server. After the page is posted, the page Init and Load events are fired, followed by the control events in the order in which they were raised.

ASP.NET | Atul Kahate

142

Code Snippet for Clear Button


protected void Button2_Click(object sender, EventArgs e) { DropDownList1.SelectedIndex = 0; TextBox1.Text = ""; TextBox2.Text = ""; Label1.Text = ""; }
ASP.NET | Atul Kahate 143

Code for the Entire Form


using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) for (int i = 50; i <= 500; i += 50) DropDownList1.Items.Add(i.ToString()); } protected void Button1_Click(object sender, EventArgs e) { if (IsValid) { int monthlyInvestment = Convert.ToInt32(DropDownList1.SelectedValue); decimal yearlyInterestRate = Convert.ToDecimal(TextBox1.Text); int years = Convert.ToInt32(TextBox2.Text); int months = years * 12; decimal monthlyInterest = yearlyInterestRate / 12 / 100; decimal futureValue = this.CalculateFutureValue(monthlyInvestment, monthlyInterest, months); Label1.Text = futureValue.ToString("c"); } } protected decimal CalculateFutureValue(int monthlyInvestment, decimal monthlyInterestRate, int months) { decimal futureValue = 0; for (int i = 0; i < months; i++) { futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate); } return futureValue; } protected void Button2_Click(object sender, EventArgs e) { DropDownList1.SelectedIndex = 0; TextBox1.Text = ""; TextBox2.Text = ""; Label1.Text = ""; } }

ASP.NET | Atul Kahate

144

Understanding the Code


 

There are three event handlers: Page load and two button clicks Another method titled CalculateFutureValue is called by one of the event handlers Two page properties are used


IsPostBack True means the page is posted back by the user, false means page is being sent to the user for the first time. Here, if it is for the first time, the list box will contain values 50, 100, IsValid Indicates that all validations were ok.
ASP.NET | Atul Kahate 145

Run the Application


 

Press F5 or click on the Start Button Project is compiled and browser will open

ASP.NET | Atul Kahate

146

Result

ASP.NET | Atul Kahate

147

After Entering Values

ASP.NET | Atul Kahate

148

The Output

ASP.NET | Atul Kahate

149

Managing State

View State


We know that for Web controls, state is automatically maintained by using hidden fields In addition to this, we can programmatically add our own data to view state For this, we need to use the view state object, that is created from the StateBag class This object contains a collection of key-value pairs
ASP.NET | Atul Kahate 151

Working with the ViewState Object




ViewState.Add (TimeStamp, DateTime.Now);




OR

ViewState[TimeStamp] = DateTime.Now; DateTime timeStamp = (DateTime) ViewState (TimeStamp); ViewState.Remove (TimeStamp);


ASP.NET | Atul Kahate 152

Session State


ASP.NET uses the session state to track the state of each user of the application For this, it creates a session state object for every user, which contains a unique session ID for each users session This session ID keeps getting exchanged between the server and the browser for every request/response from either side

ASP.NET | Atul Kahate

153

Managing Session State




Add/Update Session State Item




Session[Email] = email; String email = Session[Email].ToString (); Session.Remove (Email); String email = HttpContext.Current.Session[Email].ToString ();

Retrieve Session State Item




Remove Session State Item




Access Session State from a different class




ASP.NET | Atul Kahate

154

SessionStateExample.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SessionStateExample.aspx.cs" Inherits="SessionStateExample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html ASP.NET | Atul Kahate 155 xmlns="http://www.w3.org/1999/xhtml" >

SessionStateExample.aspx.cs
         

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; ASP.NET | Atul Kahate 156

How does this work?




If a session state item is accessed from two or more event handlers, we should code the application to retrieve it from the Load event handler and to save it back to the session state in the PreRender event handler Load event is raised before any other control events


Hence, we can capture it to read the session state into classlevel variables, making it available to everyone

PreRender event is raised after all control events for the page have been raised


Hence, we should update session state back to whatever value we want, here
ASP.NET | Atul Kahate 157

Where is Session Information Stored?




Storing Session State Four Options




By default, ASP.NET keeps it in server memory (called as In-process mode). In State server mode, state is kept in server memory under the control of a separate service called ASP.NET state service. This is useful in Web farms. In SQL Server mode, it is kept inside SQL Server database. Slower, most reliable. In Custom mode, we need to write code.
ASP.NET | Atul Kahate 158

How is Session ID Tracked?




Sending Session ID to the User - Two Options




By default, cookies are used to send session IDs back to the user. If cookies are disabled, session ID is appended to the URL (called as URL encoding).


Disabling cookies in IE Privacy -> Advanced under Tools -> Internet Options May or may not work, since cookies may still be enabled internally Now, run the application in Firefox after disabling cookies Counter does not increment! Then enable them and refresh. Counter increments.
ASP.NET | Atul Kahate 159

Setting Session State Properties


 

We can control how the session state is maintained and sent to the user In Web.Config:


<sessionState mode="InProc" cookieless="UseUri" timeout="30"/>

Tells us that session state should be maintained using the In Process mode and that it should be sent along with the URL to the user Other values for mode are Off, StateServer, SQLServer, or Custom Other values for cookieless are AutoDetect and UseCookies
ASP.NET | Atul Kahate 160

Using Cookies and URL Encoding




A cookie is a name/value pair stored on the clients computer; e.g.




User_id=user1;email=user1@test.com ASP.NET_SessionId=jsswpu5330cyzx22uf

A cookie can contain session id; e.g.




To create a cookie, we instantiate an object from the HttpCookie class, and include it in the HTTP response that the server sends back to the browser
ASP.NET | Atul Kahate 161

How Browser Stores Cookies




Session cookies


 

Browser can store cookies in its memory if it is a session cookie Session cookies are lost when the session is closed Example: Session ID Written to the browsers computer as a text file on the disk

Persistent cookies


Regardless of the type, once a cookie is sent to a browser, the browser sends it back to the server every time with the HTTP request Unfortunately, if cookies are disabled, there is no way to know about it on the server
ASP.NET | Atul Kahate 162

Cookie Programming


Creating session cookies




HttpCookie nameCookie = new HttpCookie (UserName, user_1); HttpCookie nameCookie = new HttpCookie (UserName); nameCookie.Value = user_1; HttpCookie nameCookie = new HttpCookie (UserName, user_1); nameCookie.Expires = DateTime.Now.AddYears (1);
ASP.NET | Atul Kahate 163

Creating persistent cookies




CookieExample.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookieExample.aspx.cs" Inherits="CookieExample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html ASP.NET | Atul Kahate 164 xmlns="http://www.w3.org/1999/xhtml" >

CookieExample.aspx.cs
         

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; ASP.NET | Atul Kahate 165

Database Programming

Basic Concepts


Two data providers are supported




SQL server .NET provider for accessing SQL server databases OLE DB .NET providers for non-SQL server databases

ASP.NET | Atul Kahate

167

Data Binding


Ability to bind entire collections of data to controls at run time without writing large code Controls understand that they are bound to data and render appropriate HTML for each item in the collection Data source controls were introduced in ASP.NET 2.0 to make this even more easier

ASP.NET | Atul Kahate

168

Data Source Controls


Control name SqlDataSource Description Provides access to any data source that has an ADO.NET data provider (e.g. ODBC, OLE DB, SQL Server, Oracle) Provides access to business objects or other classes that return data Provides access to XML documents Provides access to site map data for Web site stored by the site map provider

ObjectDataSource

XmlDataSource SiteMapDataSource

ASP.NET | Atul Kahate

169

SqlDataSource


 

Drag the SqlDataSource control from the toolbox to the form Then use the Configure Data Source option Perform steps to choose an MS-Access database self-explanatory Then add a server control (e.g. a drop-down list) and bind it to the SqlDataSource control Example follows
ASP.NET | Atul Kahate 170

Using SqlDataSource


<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> </script>
ASP.NET | Atul Kahate 171

GridView


Display data without writing even a single line of code Drag this control on the screen, and link it to a data source Sorting: Set the AllowSorting property to true Paging: Set the AllowPaging property to true (PageSize decides size of page)
ASP.NET | Atul Kahate 172

Updating Data


Modify the SqlDataSource by adding an UpdateCommand attribute

ASP.NET | Atul Kahate

173

FormView
 

New control in ASP.NET 2.0 Displays a single data item from a bound data source control and allows adding, editing, and deleting data We can provide a custom template for the display of the data

ASP.NET | Atul Kahate

174

FormView Example


<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected void ASP.NET | Atul Kahate FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)

175

TreeView


Can be used to display hierarchical data (e.g. XML data)

ASP.NET | Atul Kahate

176

TreeView Example


<%@ Page Language="C#" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <script runat="server"> protected void ASP.NET | Atul Kahate FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)

177

Command Object Programming

Programming Options
Database Programming in ADO.NET

Stream-based data access Fast, efficient, Read-only, Forward-only

Set-based data access Captures entire query in memory, allows backward/forward traversal, edit data (Disconnected) e.g. DataSet and OleDbAdapter

(Connected) e.g. OleDbDataReader

ASP.NET | Atul Kahate

179

Steps to be followed
1.

2. 3. 4. 5. 6.

Declare an OleDbConnection, OleDbCommand, and OleDbDataReader Declare connection Specify the SQL command to be used Link the command with the connection Open connection via command Read data
ASP.NET | Atul Kahate 180

Various Useful Methods in the Command Object


 

ExecuteNonQuery Executes command and returns number of rows affected. ExecuteReader Executes command and returns an SQLDataReader object instance. It is a read-only and forward-only cursor. ExecuteRow Executes command and returns an object of the SQLRecord class. Contains a single returned row. ExecuteXMLReader Returns an object of XMLReader class, allowing processing of result set in the form of an XML document.
ASP.NET | Atul Kahate 181

Using Data Reader

Note on DataReader


DataReader is READ-ONLY and FORWARD-ONLY It expects a live connection with the database It cannot be instantiated directly; instead we need to call the ExecuteReader method of the Command object
ASP.NET | Atul Kahate 183

Selecting Data
 

<%@ Page Language="C#" Debug = "true"%> <%@ Import Namespace = "System.Data" %> <%@ Import Namespace = "System.Data.SqlClient" %> <%@ Import Namespace = "System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate 184

<!DOCTYPE html PUBLIC "-//W3C//DTD

UPDATE Operations using Command Object Directly

UPDATE Operations


For INSERT, UPDATE, and DELETE, we cannot use DataReader Instead, we need to call the ExecuteNonQuery method directly on the command object

ASP.NET | Atul Kahate

186

Inserting Data
 

<%@ Page Language="C#" Debug = "true"%> <%@ Import Namespace = "System.Data" %> <%@ Import Namespace = "System.Data.SqlClient" %> <%@ Import Namespace = "System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate 187

<!DOCTYPE html PUBLIC "-//W3C//DTD

Updating Data
 

<%@ Page Language="C#" Debug = "true"%> <%@ Import Namespace = "System.Data" %> <%@ Import Namespace = "System.Data.SqlClient" %> <%@ Import Namespace = "System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate 188

<!DOCTYPE html PUBLIC "-//W3C//DTD

Deleting Data
 

<%@ Page Language="C#" Debug = "true"%> <%@ Import Namespace = "System.Data" %> <%@ Import Namespace = "System.Data.SqlClient" %> <%@ Import Namespace = "System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate 189

<!DOCTYPE html PUBLIC "-//W3C//DTD

Parameterized Operations

Why Parameterized Operations?




Allows specifying the actual values at run time Similar to functions/subroutines in programming languages Can be executed repeatedly with different values every time

ASP.NET | Atul Kahate

191

Parameterized SELECT
 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 192

Parameterized UPDATE
 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 193

Parameterized INSERT Accepting Data From the User


 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 194

Using DataSet and DataTable

DataSet and DataTable


 

Most commonly used ASP.NET database construct Allows data management when the data is disconnected from the data source An object created from the DataSet class works as a container for other objects that are created from the DataTable class DataTable represents a logical table in memory


Contains rows, columns, primary keys, relationships with other tables etc

From ASP.NET 2.0, we can directly work with DataTable, and not with DataSet unless we are working with multiple DataTable objects

ASP.NET | Atul Kahate

196

Selecting Data
 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 197

Inserting Data
 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 198

Data Set and Data Adapter

Set-Based Data Access




Revolves around two classes




DataSet Equivalent to an in-memory database DataAdapter Bridge between DataSet and physical data sources

ASP.NET | Atul Kahate

200

The DataSet Class 1


 

In-memory database Actual data is stored in DataTable objects, which are similar to tables in a database The DataSet.Tables property exposes a list of DataTables in a DataSet


Records in a DataTable are represented by the DataRow objects, and columns by DataColumn objects Constraints collection on a DataSet allows specifying constraints on the individual columns DataRelation object specifies relations between two tables

ASP.NET | Atul Kahate

201

The DataSet Class 2




Ideal for capturing results of database queries and storing them in memory for examination and perhaps modifications Random access, propagating changes back to the database possible

ASP.NET | Atul Kahate

202

The DataAdapter Classes




A DataSet does not interact with a database directly they take the help of DataAdapter DataAdapters job is to perform database operations and create DataTables containing the query results It also writes changes done to DataTables back to the database See next slide
ASP.NET | Atul Kahate 203

DataAdapter Concept

DataSet

DataAdapter

Database

Updates

Queries

ASP.NET | Atul Kahate

204

DataAdapter Methods


Fill () Queries a database and initializes a DataSet (actually a DataTable) with the results Update () Propagates changes back to the database

ASP.NET | Atul Kahate

205

DataAdapter - SELECT
 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 206

DataAdapter Parameterized SELECT


 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 207

DataAdapter Parameterized INSERT


 

<%@ Page Language="C#" %> <%@ Import Namespace ="System.Data" %> <%@ Import Namespace ="System.Data.SqlClient" %> <%@ Import Namespace ="System.Configuration" %> <%@ Import Namespace = "System.Data.OleDb" %>
ASP.NET | Atul Kahate <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 208

Explanation 1


How does the Update method update the database?




It executes INSERT commands for rows added to a DataTable, UPDATE commands for rows that were modified, and DELETE commands for rows that were deleted These statements are manufactured by the OleDbCommandBuilder object at run time using dynamic SQL Why is this needed?
ASP.NET | Atul Kahate 209

Explanation 2


The traditional data adapter has four properties




SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand MyAdapter = new OleDbDataAdapter ("SELECT * FROM departments", ); This causes the SelectCommand with an SqlCommand object wrapping the query string to be created, but leaves the insert, update, and delete commands set to null Hence, if we now call Update on the data adapter, it fails (as there is no OleDbCommandBuilder available to build update queries) Once we provide an OleDbCommandBuilder, it builds the insert, update, and delete commands by looking at the SelectCommand created as mentioned above; at run time

When we create a data adatper as follows:




ASP.NET | Atul Kahate

210

Explanation 3


We can see the commands built by the command builder by using the following code:


String GeneratedInsert = MyBuilder.GetInsertCommand().CommandText;

This is what we have displayed in our label2

ASP.NET | Atul Kahate

211

Thank you!

Any Questions? Many..