Presentation is loading. Please wait.

Presentation is loading. Please wait.

SWE 444: Internet & Web Application Development

Similar presentations


Presentation on theme: "SWE 444: Internet & Web Application Development"— Presentation transcript:

1 SWE 444: Internet & Web Application Development
6. Server-Side Coding What is a Server? Server Architectures Why Server-Side Coding? Server-Side Technologies Overview of ASP Introduction to ASP.NET and Web Forms SWE 444: Internet & Web Application Development

2 SWE 444: Internet & Web Application Development
What is a Server? Server A computer (or the software that runs on it) that provides services to others Many types of server File server file: networked file space FTP server ftp: remote file space, often read-only Web server http: web pages and more Mail server mail: system News server news: newsgroups messages SWE 444: Internet & Web Application Development

3 Application Architectures
Multi-tier applications divide functionality into separate tiers (i.e., logical groupings of functionality) Tiers can be located on the same computer or on separate computers A three-tier architecture consists of The client/top tier Middle-tier Information/data/bottom-tier The client-tier is the application’s user interface The middle-tier implements business logic and presentation logic to control interactions between application clients and application data The bottom-tier maintains data for the application Typically stores data in relational DBMS Business logic is a non-technical term generally used to describe the functional algorithms which handle information exchange between a database and a user interface. There exists no definition of business logic in any programming language specification or API, nor in any academic research. However, usage of the term persists in trade publications where several individuals have tried to informally advance a meaning that could be standardised. Mostly the term is applied to web application development where programs are separated into a 3-tier architecture with business logic referring to the mid tier. It should be noted that business logic is a poorly-defined term which is used in several different ways by several different groups of people. Controller logic processes client requests from the top-tier (e.g., request to view a product catalog) and retrieves data from the DB Presentation logic then processes data from the information tier and present the content to the client The business logic in the middle-tier enforces business rules and ensures that the data are reliable before updating the DB or presenting data to the user Business rules dictate how clients can and cannot access application data and how applications process data SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

4 Dynamic, Interactive Web Server (3-tier Architecture)
Browser Request Internet Tier 2 Response Apps RDBMS Tier 1 Tier 3 SWE 444: Internet & Web Application Development

5 General Multi-tier Architecture
Application Server Browser HTTP Server Backend Server (Other Server) Client Server SWE 444: Internet & Web Application Development

6 Why Server-Side Coding?
Accessibility You can reach the Internet from any browser, any device, any time, anywhere Manageability Does not require distribution of application code Easy to change code Security Source code is not exposed Once user is authenticated, can only allow certain actions Scalability Web-based 3-tier architecture can scale out If bottlenecks in terms of performance occur, the server process can be moved to other servers at runtime The advantages of server-side scripting are many. Because all of the server side code is executed before the HTML is sent to the browser, your code is hidden. Server-side code is also the only choice if you want to access files and directories on the local machine. Server-side code is also browser independent. Because the HTML code returned by the server is simple HTML, you do not have to worry about the version of browser the client is using. The disadvantage to server-side scripting is that the server must use valuable resources to parse each page it sends out. This could slow down your web site. Client-side scripting can be very useful. The major advantage is that each web browser uses its own resources to execute the code found on the web page. This eases the burden on the server. The disadvantages are that you can not prevent the user from seeing your code and that you can not use client-side code to access local files, directories, or databases. SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

7 Server-Side Technologies
Compiled Languages: C C++ C# ASP .Net Java Servlets Java Server Pages (JSP) Looks like a scripting language, but is actually compiled into a Java Servlet Either portable byte code (such as a Java .class file) or a true executable (native to the microprocessor) is produced Scripting Languages: Server Side Includes (SSI) Perl PHP ASP (VBScript) Python Common to all scripting languages is some sort of real time interpreter that parses text and turns it into executable instructions for the server SSI (Server Side Includes) are directives that are placed in HTML pages, and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology. The decision of when to use SSI, and when to have your page entirely generated by some program, is usually a matter of how much of the page is static, and how much needs to be recalculated every time the page is served. SSI is a great way to add small pieces of information, such as the current time. But if a majority of your page is being generated at the time that it is served, you need to look for some other solution. In order for a web server in a default configuration to recognize an SSI-enabled HTML file and therefore carry out these instructions, the file must end with the .shtml or .shtm extension. (It is also possible to configure a web server to process files with extension .html.) SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

8 Which Technologies Should You Choose?
Some criteria affecting decisions Web server availability Knowledge of language Scalability and efficiency Personal preference SWE 444: Internet & Web Application Development

9 SWE 444: Internet & Web Application Development
What is ASP? ASP stands for Active Server Pages ASP is a program that runs inside IIS (Internet Information Services) ASP is a server-side programming technology developed by Microsoft What is an ASP File? An ASP file (with “.asp” extension) can contain text, HTML, XML, and scripts An ASP file can also contain server scripts, surrounded by the delimiters <% and %>. Server scripts are executed on the server, and can contain any expressions, statements, procedures, or operators valid for the scripting language you prefer to use. How Does ASP Differ from HTML? When a browser requests an HTML file, the server returns the file When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML ASP is a DLL which resides on the server. It will parse the ASP commands and allow you as the programmer to create server-side scripts thus allowing a web page to be altered (or created dynamically) before being sent to the user. SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

10 SWE 444: Internet & Web Application Development
ASP Intrinsic Objects Six built-in objects in the ASP environment used to provide services: Request Used to access information passed by an HTTP request (get information from users) Response Used to control information sent to the client (send information to users) Server Provides access to methods and properties on the server Application Used to hold information that can be used by many pages (e.g., DB connections) Session Used to maintain information about a user session Application variables store info for all users while Session variables store info about a single user ObjectContext Commonly uses ADO to interact with databases SWE 444: Internet & Web Application Development

11 SWE 444: Internet & Web Application Development
Example 1: Salam Shabab language="javascript"%> <html> <head><title>Salam.asp</title></head> <body> <% Response.Write(“Salam Shabab!") %> </body> </html> The first four lines are standard HTML. Line five is where the ASP code starts (note the "<%"). Here an object was inserted. The Response.Write object allows text (or HTML code) to be passed back from the server to the client. SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development 2

12 SWE 444: Internet & Web Application Development
Example 2: Salam Shabab language="javascript"%> <html> <head><title>Salam2.asp</title></head> <body> <form method="post"> <input type="submit" id=“bt” name=“bt” value="Push Me" /> <% if (Request.Form("bt”) != "") Response.Write("<p>Salam, the time is " + Now()+”</p>”); %> </form> </body> </html> SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development 2

13 Server-Side Form Processing
We have seen examples of client-side processing in earlier sessions Where all processing is local to the Web page, encapsulated within browser scripts or event handlers. Form controls can be used for submitting information from a Web page to a processing program located on the Web server. In this case, the controls to capture information are surrounded by a <form> tag containing action and method attributes. action gives the URL of the external page that handles the processing method indicates how the form information is transmitted (normally through the post method). The form includes a "submit" button to activate the form submission an optional "reset" button can be coded to automatically clear all form fields. As noted, though, form controls also are devices for submitting information from a Web page to a processing program located on the Web server. Although you may not be producing your own server scripts for form processing, you may have occasion to create forms for submission of information to Web pages created by others. For example, you may create a "guest book" form where visitors submit information about themselves or leave comments about your site. There are common, third-party sites to which this information can be submitted and which produce messages to you summarizing the submitted information. Information submitted for processing to an external site must be in the formats expected by the processing program. Otherwise, errors can result and expected processing is not performed. Therefore, it is often necessary to verify that the information submitted is complete and in the correct format for processing. These situations require that when the form's "submit" button is clicked the form information is not immediately transmitted to the processing page. Rather, a local script is run to validate the form and, only if all information is correct, is the form submitted. SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

14 Example 3: Handling User Input
<form method="get“ action="simpleform.asp"> First Name: <input type="text" name="fname"> <br /> Last Name: <input type="text" name="lname"> <br /><br /> <input type="submit" value="Submit"> </form> SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development 2

15 SWE 444: Internet & Web Application Development
… Handling User Input User input can be retrieved in two ways: With Request.QueryString or Request.Form. The Request.QueryString command is used to collect values in a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. If a user typed “Feras" and “Nabulsi" in the form example above, the URL sent to the server would look like this: The Request.Form command is used to collect values in a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. If a user typed “Feras" and “Nabulsi" in the form example above, the URL sent to the server would look like this: SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development 2

16 SWE 444: Internet & Web Application Development
… Handling User Input Assume simpleform.asp has the following simple script: <body> Welcome <% response.write(request.querystring("fname")); response.write(" " + request.querystring("lname")); %> </body> For both cases above, the browser will display: Welcome Feras Nabulsi SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development 2

17 SWE 444: Internet & Web Application Development
ASP Challenges Coding overhead (too much code) Everything requires writing code! Code readability (too complex; code and UI intermingled) Maintaining page state requires more code After submit button is clicked, if we click the back button, we expect to maintain scroll position, maintain which control had focus, and restore focus, or allow server code to focus a new control Reuse is difficult – lack of modularity Supporting many types of browsers is difficult – ASP.NET has better browser support Deployment issues (e.g. DLL locking) – ASP.NET easier to deploy Session state scalability and availability – ASP uses cookies to maintain state while ASP.NET uses cookieless means Have to write code to do anything. There is almost no purely declarative way to do anything. SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

18 Introduction to ASP.NET and Web Forms
ASP.NET Overview Programming Basics Server Controls Data Binding Conclusion SWE 444: Internet & Web Application Development

19 SWE 444: Internet & Web Application Development
ASP.NET Overview ASP.NET provides services to allow the creation, deployment, and execution of Web Applications and Web Services Like ASP, ASP.NET is a server-side technology Web Applications are built using Web Forms Web Forms are designed to make building Web-based applications easy SWE 444: Internet & Web Application Development

20 SWE 444: Internet & Web Application Development
Key Features Built on .NET framework Supports C++, C#, Visual Basic, and JScript (Microsoft's version of JavaScript) Simple programming model Complete object model Maintains page state XML configuration Separation of code and UI Security Simplified form validation SWE 444: Internet & Web Application Development

21 Development Environments
Visual Studio.NET Installed in college labs Available on CD from PC Admin support ASP .NET Web Matrix Lightweight, simple, community-oriented tool for building ASP.NET apps Full WYSIWYG support Small (~ 1.4 Mb) Community features IM integration, code sharing, chat features Available free-of-charge at SWE 444: Internet & Web Application Development

22 Common Language Specification Common Language Runtime
Architecture VB C++ C# JScript Visual Studio.NET Common Language Specification ASP.NET: Web Services and Web Forms Windows Forms ADO.NET: Data and XML Base Class Library Web Matrix Common Language Runtime The .NET framework has 2 parts: The Common Language Specification (CLS) and the .NET Framework class library CLS Defines a set of standards that allow .NET languages and the applications written using them to interoperate It includes: The Commpon Type System (CTS) The Common Language Runtime (CLR): The execution engine for .NET framework applications. It provides services including: loading and executing code, memory management, exception handling, conversion of MSIL to native platform code etc. .Net languages compile into a machine-independent language called Microsoft Intermediate Language (MSIL) Windows COM+ Services SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

23 Snippets and code sharing
WYSIWYG Controls Snippets and code sharing Community Support SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

24 SWE 444: Internet & Web Application Development
Programming Basics First ASP.NET Example Page Syntax Server Controls Code Blocks Data Bind Expressions Render Code SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

25 SWE 444: Internet & Web Application Development
Salam.aspx Page Language="c#" %> <script runat="server"> public void B_Click (object sender, System.EventArgs e) { Label1.Text = "Salam, the time is " + DateTime.Now; } </script> <html> <head> </head> <body> <form method="post" runat="server"> <asp:Button id="Button1" onclick="B_Click" runat="server" Text="Push Me" name="Button1"></asp:Button> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html> SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

26 SWE 444: Internet & Web Application Development
Page Syntax The most basic page is just static text Any HTML page can be renamed .aspx Pages may contain: Directives: Page Language="C#" %> Server controls: <asp:Button runat="server" > Code blocks: <script runat="server">…</script> Data bind expressions: <%# %> Server side comments: <%-- --%> Render code: <%= %> and <% %> Use is discouraged; use <script runat="server"> with code in event handlers instead SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

27 SWE 444: Internet & Web Application Development
The Page Directive Directives are commands used by the compiler when the page is compiled The Page directive is most frequently used directive Lets you specify page-specific attributes, e.g. AspCompat: Compatibility with ASP CodePage: Code page for this .aspx page Inherits: Base class of Page object Language: Programming language Trace: Enables tracing for this page Only one Page directive per .aspx file SWE 444: Internet & Web Application Development

28 SWE 444: Internet & Web Application Development
Server Control Syntax Controls are declared as HTML tags with runat="server" attribute Tag identifies which type of control to create Control is implemented as an ASP.NET class Controls are derived from System.Web.UI.Control The id attribute provides programmatic identifier It names the instance available during postback <input type=“text” id="text2" runat="server" /> <asp:calendar id="myCal" runat="server" /> SWE 444: Internet & Web Application Development

29 Server Control Properties
Tag attributes map to control properties <asp:button id= "c1" Text="Foo" runat= "server" > <asp:ListBox id="c2" Rows="5" runat="server" > Tags and attributes are case-insensitive Control properties can be set programmatically c1.Text = "Foo"; c2.Rows = 5; SWE 444: Internet & Web Application Development

30 SWE 444: Internet & Web Application Development
Maintaining State By default, controls maintain their state across multiple postback requests A postback occurs when a page generates an HTML form whose values are posted back to the same page Implemented using a hidden HTML field: __VIEWSTATE Works for controls with input data (e.g. TextBox, CheckBox), non-input controls (e.g. Label, DataGrid), and hybrids (e.g. DropDownList, ListBox) Can be disabled per control or entire page Set EnableViewState="false" Lets you minimize size of __VIEWSTATE SWE 444: Internet & Web Application Development

31 SWE 444: Internet & Web Application Development
Server Code Blocks Server code lives in a script block marked runat="server" Script blocks can contain Variables, methods, event handlers, properties They become members of a custom Page object <script language="C#" runat="server"> <script language="VB" runat="server"> <script language="JScript" runat="server"> SWE 444: Internet & Web Application Development

32 SWE 444: Internet & Web Application Development
Page Events Pages are structured using events Enables clean code organization Avoids the “Monster IF” statement Less complex than ASP pages Code can respond to page events e.g. Page_Load, Page_Unload Code can respond to control events Button1_Click Textbox1_Changed SWE 444: Internet & Web Application Development

33 SWE 444: Internet & Web Application Development
Page Event Lifecycle Initialize Page_Init Restore Control State Load Page Page_Load Control Events 1. Change Events Textbox1_Changed 2. Action Events Button1_Click Save Control State Render Unload Page Page_Unload SWE 444: Internet & Web Application Development

34 SWE 444: Internet & Web Application Development
Page Loading Page_Load fires at beginning of request after controls are initialized Input control values already populated protected void Page_Load(Object s, EventArgs e) { message.Text = textbox1.Text; } SWE 444: Internet & Web Application Development

35 SWE 444: Internet & Web Application Development
Page Loading Page_Load fires on every request Use Page.IsPostBack to execute conditional logic protected void Page_Load(Object s, EventArgs e) { if (! Page.IsPostBack) { // Executes only on initial page load Message.Text = "initial value"; } // Rest of procedure executes on every request SWE 444: Internet & Web Application Development

36 SWE 444: Internet & Web Application Development
Server Control Events Change Events By default, these execute only on next action event Use autopostback=“true” atribute to make them respond directly without waiting for an action event E.g. OnTextChanged, OnCheckedChanged Change events fire in random order Action Events Cause an immediate postback to server E.g. OnClick SWE 444: Internet & Web Application Development

37 Wiring Up Control Events
Control event handlers are identified on the tag Event handler code <asp:button onclick="btn1_click" runat="server"> <asp:textbox onchanged="text1_changed" runat="server"> protected void btn1_Click(Object s, EventArgs e) { Message.Text = "Button1 clicked"; } SWE 444: Internet & Web Application Development

38 SWE 444: Internet & Web Application Development
Event Arguments Events pass two arguments: The sender, declared as type object Usually the object representing the control that generated the event Allows you to use the same event handler for multiple controls Arguments, declared as type EventArgs Provides additional data specific to the event EventArgs itself contains no data; a class derived from EventArgs will be passed SWE 444: Internet & Web Application Development

39 SWE 444: Internet & Web Application Development
Page Unloading Page_Unload fires after the page is rendered Don’t try to add to output Useful for logging and clean up protected void Page_Unload(Object s, EventArgs e) { MyApp.LogPageComplete(); } SWE 444: Internet & Web Application Development

40 SWE 444: Internet & Web Application Development
Import Directive Adds code namespace reference to page Avoids having to fully qualify .NET types and class names Equivalent to the using directive of C# Import Namespace="System.Data" %> Import Namespace="System.Net" %> Import Namespace="System.IO" %> SWE 444: Internet & Web Application Development

41 SWE 444: Internet & Web Application Development
Page Class The Page object is always available when handling server-side events Provides a large set of useful properties and methods, including: Application, Cache, Controls, EnableViewState, EnableViewStateMac, ErrorPage, IsPostBack, IsValid, Request, Response, Server, Session, Trace, User, Validators DataBind(), LoadControl(), MapPath(), Validate() SWE 444: Internet & Web Application Development

42 Introduction to ASP.NET and Web Forms
9 Introduction to ASP.NET and Web Forms 5. Server Controls

43 SWE 444: Internet & Web Application Development
Server Controls ASP.NET ships with ~50 built-in controls Organized into two logical families HTML controls Controls / properties map 1:1 with HTML Web controls Richer functionality More consistent object model Use Server controls when You require a richer set of functionality to perform complicated page requirements Developing pages for multiple browser types SWE 444: Internet & Web Application Development

44 SWE 444: Internet & Web Application Development
HTML Controls Work well with existing HTML designers i.e., when converting existing ASP 3.0 Web pages to ASP.NET Web pages Easier to change to HTML server controls than to Web server controls Properties map 1:1 with HTML table.bgcolor ="red"; Can specify client-side event handlers Good when quickly converting existing pages Derived from System.Web.UI.HtmlControls.HtmlControl Supported controls have custom class, others derive from HtmlGenericControl HtmlAnchor controls the <a> element HtmlButton controls the <button> element HtmlForm controls the <for> element etc SWE 444: Internet & Web Application Development

45 SWE 444: Internet & Web Application Development
HTML Controls Supported controls <a> <img> <form> <table> <tr> <td> <th> <select> <textarea> <button> <input type=text> <input type=file> <input type=submit> <input type=button> <input type=reset> <input type=hidden> SWE 444: Internet & Web Application Development

46 SWE 444: Internet & Web Application Development
HTML Controls Can use controls two ways: Handle everything in action events (e.g. button click) Event code will read the values of other controls (e.g. text, check boxes, radio buttons, select lists) Handle change events as well as action events SWE 444: Internet & Web Application Development

47 SWE 444: Internet & Web Application Development
HTML Controls Demo 1: HTMLControls1.aspx Basic page lifecycle with HTML Controls Demo 2: HTMLControls2.aspx More HTML Controls SWE 444: Internet & Web Application Development

48 SWE 444: Internet & Web Application Development
Web Controls Web controls appear in HTML markup as namespaced tags Web controls have an asp: prefix <asp:button onclick="button1_click" runat="server"> <asp:textbox onchanged="text1_changed" runat="server"> Defined in the System.Web.UI.WebControls namespace This namespace is automatically mapped to the asp: prefix SWE 444: Internet & Web Application Development

49 SWE 444: Internet & Web Application Development
Web Controls Web Controls provide extensive properties used to control display and format, e.g. Font BackColor, ForeColor BorderColor, BorderStyle, BorderWidth Style, CssClass Height, Width Visible, Enabled SWE 444: Internet & Web Application Development

50 SWE 444: Internet & Web Application Development
Web Controls Four types of Web Controls Intrinsic controls List controls Rich controls Validation controls SWE 444: Internet & Web Application Development

51 SWE 444: Internet & Web Application Development
Intrinsic Controls Correspond to HTML controls Supported controls <asp:button> <asp:imagebutton> <asp:linkbutton> <asp:hyperlink> <asp:textbox> <asp:checkbox> <asp:radiobutton> <asp:image> <asp:label> <asp:panel> <asp:table> SWE 444: Internet & Web Application Development

52 SWE 444: Internet & Web Application Development
Intrinsic Controls TextBox, ListControl, CheckBox and their subclasses don’t automatically do a postback when their controls are changed Specify AutoPostBack=“true” to make change events cause a postback SWE 444: Internet & Web Application Development

53 SWE 444: Internet & Web Application Development
List Controls Controls that handle repetition Supported controls <asp:dropdownlist> <asp:listbox> <asp:radiobuttonlist> <asp:checkboxlist> <asp:repeater> <asp:datalist> <asp:datagrid> SWE 444: Internet & Web Application Development

54 SWE 444: Internet & Web Application Development
List Controls Repeater, DataList and DataGrid controls Powerful, customizable list controls Expose templates for customization Can contain other controls Provide event bubbling through their OnItemCommand event More about these controls and templates later SWE 444: Internet & Web Application Development

55 CheckBoxList & RadioButtonList
Provides a collection of check box or radio button controls Can be populated via data binding <asp:CheckBoxList id="Check1" runat="server"> <asp:ListItem>Item 1</asp:ListItem> <asp:ListItem>Item 2</asp:ListItem> <asp:ListItem>Item 3</asp:ListItem> <asp:ListItem>Item 4</asp:ListItem> <asp:ListItem>Item 5</asp:ListItem> </asp:CheckBoxList> SWE 444: Internet & Web Application Development

56 Intrinsic & Simple List Controls
Demo 1: WebControls1.aspx Assorted intrinsic and list controls Demo 2: WebControls2.aspx Same controls with AutoPostBack SWE 444: Internet & Web Application Development

57 SWE 444: Internet & Web Application Development
Rich Controls Custom controls with rich functionality Supported Controls <asp:calendar> <asp:adrotator> More will be added 3rd party controls are coming Demo: RichControls1.aspx The AdRotator control presents ad images that, when clicked, navigate to a new Web location. Each time the page is loaded into the browser, an ad is randomly selected from a predefined list. The following sample illustrates using the AdRotator control. The rotation schedule for ads is defined in an XML file. The following example demonstrates a rotation schedule in the file ads.xml. <Advertisements> <Ad> <ImageUrl>/quickstart/aspplus/images/banner1.gif</ImageUrl> <NavigateUrl> <AlternateText>Microsoft.com</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad> </Advertisements> SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

58 SWE 444: Internet & Web Application Development
Validation Controls Rich, declarative validation Validation declared separately from input control Extensible validation framework Supports validation on client and server Automatically detects uplevel clients Avoids roundtrips for uplevel clients Server-side validation is always done Prevents users from spoofing Web Forms On uplevel clients, validator controls display input errors without a server round trip. Per-field validation errors are displayed on the client as soon as the user tabs to a different field, and required field validation errors and an error summary are displayed when the user submits the form. If you do not set the ClientTarget property, the HttpBrowserCapabilities object associated with the Page.Request property reflects the capabilities of the client browser. If you do set this property, client browser detection is disabled and the page will use browser capabilities associated with the named alias. In particular, each alias has a user-agent definition. The configuration file (Web.config) on your Web server computer defines four default aliases you can use as shorthand for common user agent strings. These defaults are ie5, which allows you to customize pages for Microsoft Internet Explorer 5.5 browsers, ie4, which allows you to customize pages for Internet Explorer 4.0 browsers, uplevel, which allows you to customize pages for Internet Explorer 4.0 and later, and downlevel, which allows you to customize pages for browsers earlier than Internet Explorer 4.0. You can set the alias string programmatically using this property, or you can set it declaratively using Page directive's ClientTarget attribute. If you want to customize the response that a page sends to browsers beyond the four defaults, define a new alias in the <clientTarget> section of the application-level configuration file (Web.config) and then set this property to that alias. For more information, see ASP.NET Configuration Overview. Example The following code example defines an ie302 alias and includes sections needed to configure your application in its Web.config file. Using this alias, you can set the ClientTarget property to ie302 and customize pages specifically for Internet Explorer 3.02 browsers. <configuration> <system.web> <clientTarget> <add alias="ie302" useragent="Mozilla/2.0 (compatible; MSIE 3.02; Windows NT 3.5)" /> </clientTarget> </system.web> </configuration> SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

59 SWE 444: Internet & Web Application Development
Validation Controls <asp:RequiredFieldValidator> Ensures that a value is entered <asp:RangeValidator> Checks if value is within minimum and maximum values <asp:CompareValidator> Compares value against constant, another control or data type <asp:RegularExpressionValidator> Tests if value matches a predefined pattern <asp:CustomValidator> Lets you create custom client- or server-side validation function <asp:ValidationSummary> Displays list of validation errors in one place SWE 444: Internet & Web Application Development

60 SWE 444: Internet & Web Application Development
Validation Controls Validation controls are derived from System.Web.UI.WebControls.BaseValidator, which is derived from the Label control Validation controls contain text which is displayed only if validation fails Text property is displayed at control location ErrorMessage is displayed in summary SWE 444: Internet & Web Application Development

61 SWE 444: Internet & Web Application Development
Validation Controls Validation controls are associated with their target control using the ControlToValidate property Can create multiple validation controls with the same target control <asp:TextBox id="TextBox1" runat="server" /> <asp:RequiredFieldValidator id="Req1" ControlToValidate="TextBox1" Text="Required Field" runat="server" /> SWE 444: Internet & Web Application Development

62 SWE 444: Internet & Web Application Development
Validation Controls Page.IsValid indicates if all validation controls on the page succeed void Submit_click(object s, EventArgs e) { if (Page.IsValid) { Message.Text = "Page is valid!"; } SWE 444: Internet & Web Application Development

63 SWE 444: Internet & Web Application Development
Validation Controls Display property controls how the error message is shown Static: fixed layout, display won’t change if invalid; Space for the validation message is allocated in the page layout Dynamic: Space for the validation message is dynamically added to the page if validation fails None: Validation message is never displayed; can still use ValidationSummary and Page.IsValid Type property specifies expected data type: Currency, Date, Double, Integer, String SWE 444: Internet & Web Application Development

64 SWE 444: Internet & Web Application Development
Validation Controls Can force down-level option Only server-side validation Page Language="c#" ClientTarget="DownLevel" %> SWE 444: Internet & Web Application Development

65 SWE 444: Internet & Web Application Development
Validation Controls Demo: ValidationControls1.aspx Demonstrates each type of validation control SWE 444: Internet & Web Application Development

66 Introduction to ASP.NET and Web Forms
9 Introduction to ASP.NET and Web Forms 6. Data Binding

67 How to Populate Server Controls?
Specify the data in the control’s tags Not dynamic: can’t get data from a database Write code that uses the control’s object model This is okay if you need to populate a simple value or list, but quickly gets too complicated for populating sophisticated displays Data binding (a better solution than the previous two methods) Create an object that holds the data (DataSet, Array, string, int, etc.) Associate that object with the control SWE 444: Internet & Web Application Development

68 SWE 444: Internet & Web Application Development
What Is Data Binding? One of the most useful features of ASP.NET Allows programmers to easily display and manipulate data without dealing with the underlying data structure Provides a single simple yet powerful way to populate Web Form controls with data Enables clean separation of code from UI (control separate from object holding data) Supports binding to any data source Properties, expressions, method calls Collections (Array, Hashtable, etc.) DataSet, DataTable, DataView, DataReader XML SWE 444: Internet & Web Application Development

69 SWE 444: Internet & Web Application Development
… What Is Data Binding? Controls that support data binding expose a property named DataSource and a method called DataBind When a page is loaded, the user of the control initializes the DataSource property to some collection of data like an array, DataReader or DataSet When the DataBind method of the control is called, the expression is evaluated and bound DataBind for a single control (and subcontrols) Page.DataBind binds all controls on a page Works for scalars, e.g. Label control Works for lists, e.g. DropDown control, ListBox control, etc. Enables the use of templates SWE 444: Internet & Web Application Development

70 SWE 444: Internet & Web Application Development
Scalar Expressions Data binding expression: <%# expression %> Expression is evaluated when DataBind() is called <asp:Label id=label1 Text=<%# "The result is " + (1 + 2) + ", the time is " + DateTime.Now.ToLongTimeString() %> runat="server" /> public void Page_Load(object s, EventArgs e) { if (! Page.IsPostBack) Page.DataBind(); } SWE 444: Internet & Web Application Development

71 SWE 444: Internet & Web Application Development
Scalar Expressions Demo: DataBinding1.aspx Data binding to simple, scalar expressions SWE 444: Internet & Web Application Development

72 SWE 444: Internet & Web Application Development
Simple Lists Data binding a list creates a user interface element for each item in the list Each item contains text (displayed to user) and an optional value (not displayed) The simple list controls: <asp:ListBox> Single or multiple select <asp:DropDownList> <asp:RadioButtonList> <asp:CheckBoxList> The above controls can be populated with XML data or with the following objects: ArrayList Hashtable SortedList SWE 444: Internet & Web Application Development

73 SWE 444: Internet & Web Application Development
Simple Lists Steps to data bind a list control Declare the list control Optionally set DataValueField and DataTextField Set its DataSource Call DataBind() method Notes: Use ArrayList to populate controls with Text and Value fields to have the same name Use HashTable or SortedList object to add values that different for Text E.g.,: <asp:RadioButtonList id=“countryList” runat=“server”> <asp:ListItem value=“NG” text=“Nigeria” /> </asp:RadioButtonList> SWE 444: Internet & Web Application Development

74 SWE 444: Internet & Web Application Development
Simple Lists Demo: DataBinding2.aspx Data binding to simple lists SWE 444: Internet & Web Application Development

75 Binding to Database Sources
We have seen that it is possible to bind to many different types of collections in ASP.NET The most common type of binding is to bind to a result set retrieved from a database query ADO.NET provides two ways of retrieving result sets from a database: Using the streaming IDataReader interface (or DataReader class) Using the disconnected DataSet class Binding to database sources requires working with four main categories of objects: Connections Establishes a Web page connection to a specified data source. Commands Defines and executes a command, normally an SQL statement, to retrieve or update a set of records in the data source. DataReader Reads through a recordset retrieved by the Command object. DataAdapter Populates an in-memory data store with records from a data source, and manages updates to the source. SWE 444: Internet & Web Application Development

76 SWE 444: Internet & Web Application Development
List Binding Examples public void Page_Load(object s, EventArgs e) { if (! Page.IsPostBack) { // Databind a drop down to a DataReader DropDown1.DataSource = GetSampleDataDR(); DropDown1.DataValueField = "CategoryID"; DropDown1.DataTextField = "CategoryName"; DropDown1.DataBind(); // Databind a radio button list to a DataView RadiobuttonList1.DataSource = GetSampleDataDV(); RadiobuttonList1.DataValueField = "CategoryID"; RadiobuttonList1.DataTextField = "CategoryName"; RadiobuttonList1.DataBind(); } Compare the SqlCommand and the SqlDataAdapter SqlCommand used with an SqlDataReader when this is used, SqlDataAdapter Automatically handles opening connection SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

77 Binding to a DataReader
IDataReader GetSampleDataDR() { SqlConnection cxn = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True"); SqlCommand cmd = new SqlCommand("select CategoryID, CategoryName from Categories", cxn); cxn.Open(); SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); return dr; } SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

78 Binding to DataView of DataSet
DataView GetSampleDataDV() { DataSet ds; SqlConnection cxn = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;Integrated Security=True"); SqlDataAdapter adp = new SqlDataAdapter("select CategoryID, CategoryName from Categories", cxn); ds = new DataSet(); adp.Fill(ds, "Categories"); return ds.Tables["Categories"].DefaultView; } SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

79 SWE 444: Internet & Web Application Development
Binding to a Database Demo: DataBinding3.aspx Data binding to a database SWE 444: Internet & Web Application Development

80 DataReader Vs DataSet for Data Binding
Supports a connected, read-only access style Supports a disconnected access style Programmer must explicitly open and close the sqlConnection SqlDataAdapter automatically handles opening/closing connection Does not cache query results Makes a local copy of and manipulates query results, then reconcile with the actual DB later Preferred for Web applications where short operations (displaying data) are usually performed Suitable for long-running applications Focuses on data access and presentation Focuses on data management Use when you simply need to read data and immediately bind it to a control Use when binding one set of data to multiple controls using different DataViews SWE 444: Internet & Web Application Development

81 SWE 444: Internet & Web Application Development
DataGrid A control that displays data from a data source (e.g., a database) in the form of a table Full-featured list output Default look is a grid Default is to show all columns, though you can specify a subset of columns to display Columns can be formatted with templates Optional paging Updateable SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

82 SWE 444: Internet & Web Application Development
Binding to All Columns Binding all columns in the datasource Declare an <asp:DataGrid> Set its DataSource Call DataBind() void Page_Load(object s, EventArgs e) { myDataGrid.DataSource = GetSampleData(); myDataGrid.DataBind(); } <asp:datagrid id="myDataGrid" runat="server" /> SWE 444: Internet & Web Application Development

83 Binding to Specific Columns
By default, DataGrid will display all columns To control columns to display: Set AutoGenerateColumns="false" Specify Columns property Add column definition BoundColumn TemplateColumn etc SWE 444: Internet & Web Application Development

84 Binding to Specific Columns
Binding to specific columns in the datasource Declare an <asp:DataGrid> Declare its Columns collection Set its DataSource Call its DataBind() method <asp:datagrid id="myDataGrid" autogeneratecolumns="false" runat="server"> <Columns> <asp:BoundColumn HeaderText="Id" DataField="title_id" /> <asp:BoundColumn HeaderText="Title" DataField="title"/> </Columns> </asp:datagrid> SWE 444: Internet & Web Application Development

85 SWE 444: Internet & Web Application Development
DataGrid Paging When there is too much data to display in one screen, a DataGrid can provide automatic paging Set AllowPaging="true" Set PageSize=5 Handle OnPageIndexChanged event Set page index Fetch data Re-bind data SWE 444: Internet & Web Application Development

86 SWE 444: Internet & Web Application Development
DataGrid Demo Demo: DataBinding4.aspx Binding to a database with DataGrid Demo: DataBinding5.aspx Paging through data with DataGrid SWE 444: Internet & Web Application Development

87 SWE 444: Internet & Web Application Development
Templates Templates provide a powerful way to customize the display of a server control Customize structure – not just style Can use controls or other HTML within a template 3rd party controls can expose new templates With data binding, templates specify a set of markup (HTML or server controls) for each bound piece of data Not just specifying formatting and style for a column However, templates are not limited to data binding No fixed set of templates Controls may define their own and expose any number of them SWE 444: Internet & Web Application Development

88 SWE 444: Internet & Web Application Development
Templates Standard templates for list-bound controls HeaderTemplate: rendered once before all data bound rows ItemTemplate: rendered once for each row in the data source AlternatingItemTemplate: like ItemTemplate, but when present is used for every other row SeparatorTemplate: rendered between each row FooterTemplate: rendered once, after all data bound rows SWE 444: Internet & Web Application Development

89 SWE 444: Internet & Web Application Development
Templates HeaderTemplate Templates used in Repeater controls ItemTemplate SeparatorTemplate AlternatingItem- Template FooterTemplate SWE 444: Internet & Web Application Development

90 Data Binding in Templates
Templates need to access the bound data Container is an alias for the template’s containing control DataItem is an alias for the current row of the datasource DataBinder.Eval is a utility function provided to retrieve and format data within a template <%# DataBinder.Eval(Container.DataItem, "price", "$ {0}") %> SWE 444: Internet & Web Application Development

91 Repeater and DataList Controls
Repeater and DataList controls are templated controls They give greater flexibility over the rendering of list-like data The repeater control is just iterates over the bound data, rendering the ItemTemplate once for each item in the DataSource collection A general-purpose iterator Does not render anything beside the elements contained in the template DataList renders additional elements, like table rows and cells and spans containing style attributes Enables end-users to exactly control the structure and layout of each item within the list (using the ItemTemplate property) SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

92 SWE 444: Internet & Web Application Development
Repeater Control Provides simple output of a list of items No inherent visual form (DataGrid supports tabular visual form by default) Templates provide the visual form No paging (DataGrid supports paging) Can provide templates for separators Not updateable (DataGrid is updateable) SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

93 SWE 444: Internet & Web Application Development
Repeater Control <asp:Repeater id="repList" runat="server"> <template name="HeaderTemplate"> <table> <tr><td>Title</td><td>Type</td></tr> </template> <template name="ItemTemplate"> <tr> <td><%# DataBinder.Eval(Container.DataItem,"title_id") %></td> <td><%# DataBinder.Eval(Container.DataItem,"type") %></td> </tr> </template> <template name="FooterTemplate"> </table> </template> </asp:Repeater> SWE 444: Internet & Web Application Development

94 SWE 444: Internet & Web Application Development
DataList Control Provides list output with editing Default look is a table Customized via templates Directional rendering (horizontal or vertical) Using RepeaterColumns and RepeaterDirection (similar to background-repeat in CSS) Updateable No paging SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

95 SWE 444: Internet & Web Application Development
DataList Control void Page_Load(object s, EventArgs e) { myDataGrid.DataSource = GetSampleData(); myDataGrid.DataBind(); } <asp:datalist id="myDataList" runat="server"> <template name="itemtemplate"> <b>Title id:</b> <%# DataBinder.Eval(Container.DataItem, "title_id") %> <br> <b>Title:</b> <%# DataBinder.Eval(Container.DataItem, "title") %> </template> </asp:datalist> SWE 444: Internet & Web Application Development

96 SWE 444: Internet & Web Application Development
Templates Demo Demo: DataBinding6.aspx, DataBinding7.aspx Using templates and data binding to a database with DataGrid, Repeater and DataList controls SWE 444: Internet & Web Application Development

97 Running Our DB-Based Data Binding Examples
Many of those examples use the sample databases shipped with SQL Server 2000 The PUBS and NORTHWIND databases, specifically Using SQL Server 2000 There should be no problems, hopefully Otherwise you may need to Locate the example databases in the install directory and add them to your application See next slide Change the connection string SWE 444: Internet & Web Application Development

98 Adding a DB to a Website Project
Open your Website project in Visual Studio 2005 (for example) Select the Solutions Explorer, if necessary, to expose the Website’s files (in the right panel of the VS 2005 window) Right-click on the App_Data folder of your Website (in the Solution Explorer) and select “Add Existing Item …”. Browse the file system to locate database and add it You may find it somewhere like C:\Program Files\Microsoft SQL Server\MSSQL\Data If you downloaded the example databases separately and run the .msi file, they are likely to be placed in C:\SQL Server 2000 Sample Databases SWE 444: Internet & Web Application Development

99 Changing the Connection String
A common problem in connecting to DBs from your application is due to using the wrong connection string A typical error due to wrong connection string looks like: Note that when you select the DB in your Website, the Properties window below the Solution Explorer’s window displays a Connection String property of the DB From my experience, connecting to the DB using this connection string always fails! I fix the problem as follows: Open an .aspx file in my Website Make sure the .aspx file contains a control requiring a datasource, like DataGrid. Otherwise add such a control to the file (you may delete it after following the next step) View the .aspx page in Design view Select the DataList control, right-click on it and select “Show Smart Tag” Select “New Data Source” in the “Select Data Source” dropdown from the resulting pop-up Select “Database” from the resulting “Data Source Configuration Wizard” and click OK Select the database added to your application from the dropdown of the resulting popup window Expand the “connection string” tab on this window to reveal the correct connection string you need to connect to the database. SWE 444: Internet & Web Application Development

100 Running Our DB-Based Data Binding Examples
Using SQL Server 2005 I have had more problems with this than with SQL Server 2000 You may need to download the example databases Install them and add them to the appropriate examples You will need to change the connection string As explained in the preceding slides SWE 444: Internet & Web Application Development

101 SWE 444: Internet & Web Application Development
Resources ASP.NET QuickStart Tutorial W3 Schools ASP .NET Tutorial Several Online Presentations SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

102 Application Object, Events and Code
A web application refers to the collection of web pages and objects defined on the server as a virtual directory There is one instance of the Application object for each application running on the web server The application object Stores information accessible to all clients Stores information about the sessions active within a particular application Variables in Application object are defined in a special ASP.NET file – global.asax Placed in the application’s root directory Each application can have only one global.asax SWE 444: Internet & Web Application Development

103 SWE 444: Internet & Web Application Development
The Global.asax File Parsed and compiled, at runtime, into a dynamically generated .NET Framework class derived from the HttpApplication base class. Configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it. A suitable place to place application-sensitive data The Global.asax file is optional. When the application receives the first user request, the Application_Start event is fired. If the global.asax file is edited and the changes are saved, then all current pending requests are completed, the Application_End event is fired, and the application is restarted. This sequence effectively reboots the application, flushing all state information. The rebooting of the application is transparent to any users, however, since it occurs only after satisfying any pending requests and before any new requests are accepted. When the next request is received, the application starts over again raising another Application_Start event. SWE 444: Internet & Web Application Development

104 SWE 444: Internet & Web Application Development
Application Events SWE 444: Internet & Web Application Development

105 Application Code – global.asax
<script language="c#" runat="server" > void Application_OnStart(Object obj, EventArgs e){ Application[“timeKeeper"]= ""; Application[“visitCounter"]= 0; } </script> Here is a demo on how to use this file. SWE 444: Internet & Web Application Development

106 Application Configuration Settings
In classic ASP all Web site related information was stored in the metadata of IIS. Disadvantage: remote Web developers couldn't easily make Web-site configuration changes. Such configuration changes need to be done through the IIS admin tool Your Web host will likely charge you a fee to do this for you. With ASP.NET, these settings are directly under developer control Placed into an XML-formatted text file (Web.config) that resides in the Web site's root directory. Goal of ASP.NET configuration (web.config): Provide extensible configuration for admins & developers to hierarchically apply settings for an application SWE 444: Internet & Web Application Development

107 Hierarchy of .config Files
Multiple .config files can, and typically do, exist on a single system. System-wide configuration settings for the .NET Framework are defined in the Machine.config file. Placed in %SystemRoot%\Microsoft.NET\Framework\%VersionNumber%\CONFIG\ folder. Configuration files can be stored in application folders Configuration system automatically detects changes Hierarchical configuration architecture Applies to the actual directory and all subdirectories Root Dir Sub Dir1 Dir2 web.config SWE 444: Internet & Web Application Development

108 Creating a web.config File
At the root level of web.config is the <configuration> tag. Inside this tag you can add a number of other tags The most common and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to specify application-wide settings you use the <appSettings> tag. Inside of this tag you can specify zero to many settings by using the <add ... /> tag. For example, if we wanted to add a database connection string parameter we could have a Web.config file like: <?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="connectionString" value="Data Source=localhost;Initial Catalog=pubs;Integrated Security=True" /> </appSettings> <system.web> ... </system.web> </configuration> Retrieve as: string str = ConfigurationSettings.AppSettings[“connectionString”]; SWE 444: Internet & Web Application Development

109 SWE 444: Internet & Web Application Development
Forms Authentication Like IIS, ASP.NET has its own authentication methods When IIS receives a request for an ASP.NET resource, like .aspx file It performs its own authentication (if the web app is configured in IIS to do so) And then passes on the request and a security token to the ASP.NET runtime ASP.NET supports the following authentication modes None – ASP.NET relies on IIS for authentication Windows – treats the user identity supplied in the security token by IIS as the authenticated user Forms – allows authentication via login forms of the Web Application Passport – uses the Microsoft Passport system running on a separate Passport server for authentication Authentication mode is specified within the authentication element of the application’s Web.config file: <system.web> <authentication mode=“Windows” /> </system.web> SWE 444: Internet & Web Application Development

110 Forms Authentication: Example 1
Consider the following configuration file: <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="Login.aspx" > </forms> </authentication> <authorization> <deny users="?"/> </authorization> </system.web> </configuration> Suppose you place the above in the folder containing your Web application files, then An attempt by a user to access any file in the Web application now will be redirected to Login.aspx automatically <deny users=“?” /> specifies that all unauthenticated users are denied access to ASP.NET resources in the site Users information can be hard-coded in an event handler, inside a web.config file or, more appropriately, inside a database SWE 444: Internet & Web Application Development

111 Forms Authentication: Example 1
The authentication logic can be hard-coded as follows: protected void btnLogin_Click(object sender, EventArgs e) { string user= txtUser.Text; string password = txtPassword.Text; if (IsValidUser(user, password)) FormsAuthentication.RedirectFromLoginPage(user, true); else labError.Text = "User not found, try again"; } private bool IsValidUser(string user, string password) if (user == "sahl" && password == "abushabab") return true; return false; SWE 444: Internet & Web Application Development

112 Forms Authentication: Example 2
Storing user credentials in a web.config file: <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="Login.aspx" > <credentials passwordFormat="Clear"> <user name="sahl" password="abushabab"/> <user name="ahmad" password="abuatfal"/> <user name="ali" password="abulkhair"/> </credentials> </forms> </authentication> <authorization> <deny users="?"/> </authorization> </system.web> </configuration> SWE 444: Internet & Web Application Development

113 Forms Authentication: Example 2
Since the credentials are now stored in web.config, we can use the built-in Authenticate method of FormsAuthentication: protected void btnLogin_Click(object sender, EventArgs e) { string user= txtUser.Text; string password = txtPassword.Text; if (FormsAuthentication.Authenticate(user,password)) FormsAuthentication.RedirectFromLoginPage(user, true); else labError.Text = "User not found, try again"; } SWE 444: Internet & Web Application Development

114 Example 3: Customizing Authentication
Suppose we want to allow everyone access to the main folder of the application and allow access to a MembersOnly folder only to authenticated users We place the following in the main folder <configuration> <system.web> <authentication mode="Forms"> <forms loginUrl="Login.aspx" > <!– can add credentials here ! --> </forms> </authentication> <authorization> <allow users=“*"/> </authorization> </system.web> </configuration> And place the following in the MembersOnly folder (there should not be authentication element here!): <configuration > <deny users="?"/> SWE 444: Internet & Web Application Development

115 Example 4: Authentication using WAT
The most versatile solution is to store user credentials in a database This can be done by creating authentication information using the WAT (Website Administration Tool) in Visual Studio 2005 Start the WAT: Web Site > ASP.NET Configuration Click the Security Table Click the Create User link Fill in the form and click the Create User button Add two more users From the above steps, the WAT would have created an SQL server database with the information you entered added to a number of tables Inspect Example 4 for details Or better still see Chapter 13 of Randy Connolly’s “Core Internet Application Development with ASP.NET 2.0”, 2007 SWE 444: Internet & Web Application Development

116 SWE 444: Internet & Web Application Development
Stored Procedures A precompiled collection of SQL statements stored under a name and processed as a unit. They’re stored in and deployed with the database They are usually written in a proprietary database language like PL/SQL for Oracle database or PL/PgSQL for PostgreSQL. Stored procedures are extremely similar to the constructs seen in other programming languages.  They accept data in the form of input parameters that are specified at execution time.  These input parameters (if implemented) are utilized in the execution of a series of statements that produce some result.  This result is returned to the calling environment through the use of a recordset, output parameters and a return code. Types User-defined Stored Procedures System Stored Procedures SWE 444: Internet & Web Application Development

117 Benefits of Stored Procedures
Precompiled execution.  SQL Server compiles each stored procedure once and then reutilizes the execution plan.  This results in tremendous performance boosts when stored procedures are called repeatedly.  Reduced client/server traffic.  Stored procedures can reduce long SQL queries to a single line thereby reducing network traffic. Efficient reuse of code and programming abstraction.  Stored procedures can be used by multiple users and client programs.  Judicious use of stored procedures can reduce development time. Enhanced security controls.  You can grant users permission to execute a stored procedure independently of underlying table permissions. Improved security By including database privileges with stored procedures that use static SQL, the database administrator (DBA) can improve security. The DBA or developer who builds the stored procedure must have the database privileges that the stored procedure requires. Users of the client applications that call the stored procedure do not need such privileges. This can reduce the number of users who require privileges. SWE 444: Internet & Web Application Development SWE 444: Internet & Web Application Development

118 Stored Procedures: Example
Consider the following studentGrades table:  ID Name Standing Grades(%) 40232 Ahmad P 50 40165 Khalid G 40147 Qais 40244 Ibrahim 99 40284 Ali 84 40434 Amr 32 SWE 444: Internet & Web Application Development

119 SWE 444: Internet & Web Application Development
Example (cont’d) In Query:  In Stored Procedure :  SELECT Name, Grades FROM studentGrades WHERE Standing = ‘G’ CREATE PROCEDURE sp_GetGrades @standing varchar(1) AS SELECT Name, Grades FROM studentGrades WHERE Standing SWE 444: Internet & Web Application Development

120 SWE 444: Internet & Web Application Development
Example (cont’d) If we want to get the grades for good standing students: EXECUTE sp_GetGrades ‘G' If we want to get the grades for probation students: EXECUTE sp_GetGrades ‘P‘   Show a demo. SWE 444: Internet & Web Application Development


Download ppt "SWE 444: Internet & Web Application Development"

Similar presentations


Ads by Google