Professional Documents
Culture Documents
0
Alok sharma MCA Pune university
An Introduction to .NET
.NET languages: Primarily C# and VB.NET Common Language Runtime (CLR) .NET class library ASP.NET Visual Studio .NET
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
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
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
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.
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
10
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
12
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
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
16
17
Form Processing
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
a1.aspx
Server Controls
Two types
Server-based equivalents of standard HTML elements ASP.NET equivalent controls for the HTML controls
Web controls
24
Provide an object interface for standard HTML elements Three key features
Web Controls
Provide richer UI (e.g. calendar, data grid) Provide consistent object model Adjust for browsers automatically
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
27
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
30
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
32
<div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLFqeuwAwK/76bvDAKhwImNC0Gv6Kcq4KxNxSSW8vaRexezd95A" /> </div></form> </body> </html>
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
34
Resulting Output
35
<div> <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAwLFqeuwAwK/76bvDAKhwImNC0Gv6Kcq4KxNxSSW8vaRexezd95A" /> </div></form> </body> </html>
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
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
<%@ 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>
39
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
<%@ 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>
42
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
44
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
45
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
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
<%@ 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
<%@ 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 }
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
Approaches to Coding
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.
60
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>
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
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.
67
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.
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
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
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
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
76
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
77
Validation Controls
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.
80
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
82
Validation Controls
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
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=f2TqBkrftdNOxTb2bmboBlygriVRf-F331lV9yZtbLE1&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("ctl02", "", true, "", "", 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>
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
89
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
93
94
Analysis
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
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+
\w{4,10}
\d{3}-\d{2}\d{4}
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
<%@ 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
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
103
ValidationSummary Example
Modified Example
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>
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) { }
108
Authentication Example
Refer to LoginExampleSite
Edit Web.config
Add the following <authentication mode="Forms"> <forms loginUrl ="login.aspx"/> </authentication>
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
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
114
Passport authentication
Windows authentication
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
118
Adding Controls
119
120
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
122
Resulting Output
123
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
124
125
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.
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
128
Source View
129
130
131
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
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
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
134
135
The maximum allowed value. The minimum allowed value. The data type used (e.g. String, Integer, Double, Date, or Currency)
136
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
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
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
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
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.
142
144
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
Press F5 or click on the Start Button Project is compiled and browser will open
146
Result
147
148
The Output
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
OR
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
153
Session[Email] = email; String email = Session[Email].ToString (); Session.Remove (Email); String email = HttpContext.Current.Session[Email].ToString ();
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
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
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
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
We can control how the session state is maintained and sent to the user In Web.Config:
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
User_id=user1;email=user1@test.com ASP.NET_SessionId=jsswpu5330cyzx22uf
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
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
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
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
SQL server .NET provider for accessing SQL server databases OLE DB .NET providers for non-SQL server databases
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
168
ObjectDataSource
XmlDataSource SiteMapDataSource
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
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
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
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
Programming Options
Database Programming in ADO.NET
Set-based data access Captures entire query in memory, allows backward/forward traversal, edit data (Disconnected) e.g. DataSet and OleDbAdapter
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
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
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
UPDATE Operations
For INSERT, UPDATE, and DELETE, we cannot use DataReader Instead, we need to call the ExecuteNonQuery method directly on the command object
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
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
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
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
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
<%@ 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
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
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
DataSet Equivalent to an in-memory database DataAdapter Bridge between DataSet and physical data sources
200
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
201
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
202
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
204
DataAdapter Methods
Fill () Queries a database and initializes a DataSet (actually a DataTable) with the results Update () Propagates changes back to the database
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
<%@ 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
<%@ 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
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
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
210
Explanation 3
We can see the commands built by the command builder by using the following code:
211
Thank you!