Presentation is loading. Please wait.

Presentation is loading. Please wait.

Server-side Programming using ASP.NET Web Forms Yingcai Xiao.

Similar presentations


Presentation on theme: "Server-side Programming using ASP.NET Web Forms Yingcai Xiao."— Presentation transcript:

1 Server-side Programming using ASP.NET Web Forms Yingcai Xiao

2 Part I Programming the Internet

3 The Internet as a Computer Every computer on the Internet is a “CPU” Transmitting data/information in a standardized way is the key Analogy of Internet Protocols: IP => “ Binary ” (low-level Internet transmission protocol) HTTP => “ Assembly ” (high-level Internet transmission protocol) HTML => High Level Language (for writing web-pages) An international language everyone understand

4 Internet Protocol  IP: Internet Protocol data transmission protocol (standard) for the Internet. The Internet is a computer network based on the Internet Protocol. Each computer on the Internet is identified by its Internet Address: 130.101.10.134 or wp.cs.uakron.edu Data transmitted between computers on the Internet as packet. Each packet has an IP header followed by data. The first 2 entries in an IP header are the receiver’s address and the sender’s address. IP is similar to postal mailing (Packet Switching), not phoning (Circuit Switching). IPv4 (32bit addressing, 4B), IPv6 (48bit addressing, 256T) The headers are in the standard IP format, platform-independent. Data (any type) is transmitted over the Internet bit-by-bit. No restrictions on what can be transmitted. Binary data are platform-dependent. Binary data transmitted from one computer to another computer may not be readable by the receiver if it has a different binary data format than the sender.

5 Hypertext Transfer Protocol  Can we make it platform-independent?  The World Wide Web is an application built on the Internet using the Hypertext Transfer Protocol in which only text data is permitted to be transmitted.  HTTP (Hypertext Transfer Protocol) Tim Berners-Lee ("father of the Web") and RFC 2068 (www.w3.org/Protocols/rfc2068/rfc2068). Entirely text based: ASCII (8-bits) or Unicode (16-bits). Platform independent Defines how Web browsers and Web servers communicate. 7 instructions defined in HTTP 1.1.: GET, POST, … Transmitted over TCP/IP (Transport Control Protocol/Internet Protocol). Web applications are implemented over the Internet using HTML and other Web languages.

6  HTML (Hypertext Markup Language) Defines syntax and semantics of the Web language. Entirely text based (platform independent) Hypertexts are tagged in, not to be displayed. They are metadata describing regular text. (http://www.w3schools.com/tags/) Browsers are GUI-based HTML interpreters.  HTML 4.01 became XHTML 1.0 in 2000 simple.html: Hello, world HTML

7  Client-Side: Thin client 1.Only a browser is needed. 2.The browser renders a html page on the client computer. 3.HTML (static), DHTML (dynamic), HTML5 (dynamic and multi-medium). 4.Programming with embedded scripts: JavaScript,. Dynamic and computational. 5.Ajax (asynchronous JavaScript & XML): asynchronous. 6.Plugins: VRML (3D Web) 7.Java Applet: transmit the application to the client and run it there. Too much to transmit for large distribution lists. Computing over the Internet

8  Client-Side: Thick client 1.Client program installed prior, no need to download at runtime. 2.Runs like any other program on the client, but can talk to the server when needed. 3..NET Remoting, Windows Communication Foundation (WCF), 4.Java's Remote Method Invocation (RMI) 5.Common Object Request Broker Architecture (CORBA) Computing over the Internet

9  Server-Side: Web pages are generated by server side programs at runtime. Dynamic contents and heavy-duty computing. Server Scripts 1.Perl, PHP, …. 2.Does not scale well. (each client needs a process to service) Server VMs 1..NET ASP (Active Server Page), JSP (Java Server Page), 2.All clients are served by a single process. The process will create a thread to serve each client. Computing over the Internet

10  Server-Side: CMS (Content Management Systems): web contents are managed at server side on demand. Dejango CMS, Joomla.  Server-Client Communication: Important for Internet based computing. HTTP channel (slower, works for both thin and thick clients). TCP/IP channel (faster, works only for thick clients). Computing over the Internet

11 What happens when browsing a web page on a server? http://www.wintellect.com/simple.html Start a client (a browser). Type in the URL (Unified Resource Locator). Internet ’ s Domain Name System (DNS) converts www.wintellect.com into an IP address (66.45.26.25). The browser opens a socket (IP) connection to the server using default port 80 (mailbox #). http://www.wintellect.com:80/simple.html

12 What happens when browsing a web page on a server? The browser transmits an HTTP request to the server. GET /simple.html HTTP/1.1 Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-agent: Mozilla/4.0.(compatible; MSIE.6.0; Windows NT 5.1) Host: www.wintellect.com Connection: Keep-Alive [blank line]

13 What happens when browsing a web page on a server? The server transmits an HTTP response back. HTTP/1.1 200 OK Server: Microsoft-IIS/5.0 Date: Wed, 24 Oct 2001 14:12:37 GMT Content-Type: text/html Accept-Ranges: bytes Last-Modified: Wed, 24 Oct 2001 14:00:53 GMT ETag: "d02acf81975cc11:a78" Content-Length: 46 [blank line] Hello, world

14 What happens when browsing a web page on a server? Upon receiving the response, the browser parses the HTML and displays the resulting Web page. This is just a static page. To compute, we need get the data from the client user. A client form is needed. HTML form serves the purpose.

15 http://winserv1.cs.uakron.edu/xiaotest/Calc.html + HTML Forms

16 What ’ s happening? No action to send anything to the server when the user types values in the text fields. But when the submit button ( ) is clicked, the browser submits the form along with any input in the form ’ s controls. POST /calc.html HTTP/1.1 … Content-Length: 11 [blank line] op1=2&op2=2

17 Part II Server Side Programming

18 Web Server  Deploying a Web Page on an IIS server. IIS: Internet Information Services Server: winserv1.cs.uakron.edu Deploying Directory: C:\Inetpub\wwwroot Access URL: http://winserv1.cs.uakron.edu/ (case insensitive)  Server-Side Processing Common Gateway Interface (CGI) CGI applications write HTTP responses to standard output (stdout) on the server, which are then forwarded to the client browser. Defines a low-level programmatic interface between Web servers and applications that run on Web servers. CGI applications can be written in any programming language. CGI applications read the input accompanying postbacks through server environment variables and standard input (stdin). Slow, restarts a process on every request.

19 ISAPI  ISAPI: Internet Server Application Programming Interface ISAPI extensions are Windows DLLs hosted by IIS. They ’ re referenced by URL just like HTML files (for example, http://www.wintellect.com/calc.dll). IIS forwards HTTP requests to an ISAPI DLL by calling a special function exported from the DLL. The DLL generates HTTP responses. Faster than CGI (run in the same process as IIS). Once loaded, they remain in memory. They ’ re difficult to write.

20 Active Server Pages (ASP)  Active Server Pages (ASP)  Introduced in 1996.  Dynamically generates HTML on Web servers.  Allows HTML and scripts / languages to be mixed.  The embedded script code are between the tags.  When an Active Server Page is requested, ASP server parses the page and executes any scripts contained inside it.  Scripts access the input by using the Request object.  Scripts write HTML to the HTTP response using the Response object, which is sent to the client by the Web server along with the static HTML.  ASP integrates with ActiveX Data Objects (ADO).  Interpreted, slow.  Lacks encapsulation.

21 "/> + " /> <% If Request ("op1") <> "" And Request ("op2") <> "" Then a = CInt (Request ("op1")) b = CInt (Request ("op2")) Response.Write (CStr (a + b)) End If %> Calc.asp

22 Part III ASP.NET

23 APS.NET  ASP: Microfoft ’ s equivalent of JSP Code on the server that dynamically generates HTML for the clients at runtime.  JSP: Java Server Page Java code on the server that generates HTML for the clients. HTML contents can be dynamically generated at runtime  ASP.NET: ASP based on the.NET framework, one of the most popular web programming techniques. Code on the server that dynamically generates HTML for the clients at runtime.

24 ASP.NET WEB S E R V E R IIS WEB C L I E N T Application 3 Application 2 Application 1 ASP.NET HTTP

25 Web Forms  Web Forms are GUI-based EDP (Event Driven Programming) web pages built around controls and event handlers. .NET web forms are processed on the server side.  Web forms use HTML, HTTP and IP to transmit and display GUI into a client web-browser.

26  ASP.NET Web Forms GUI for Web applications Object-oriented (encapsulation, inheritance, polymorphism) Event driven (EDP) Server-side processing (dynamic generation of HTML) Compiled code, faster HTML embedding tag: (processed on the server side) File extension:.aspx To deploy on winserv1: copy Examples/c5/calc.aspx to C:\Inetpub\wwwroot\xiaotest To access: http://winserv1.cs.uakron.edu/xiaotest/calc.aspx ASP.NET Web Forms

27 + void OnAdd (Object sender, EventArgs e) { int a = Convert.ToInt32 (op1.Text); int b = Convert.ToInt32 (op2.Text); Sum.Text = (a + b).ToString (); } Calc.aspx

28 When Calc.aspx is accessed by a client  An ASP.NET server page contains two parts: static HTML code and dynamic embedded APS.NET code.  ASP.NET-enabled web server processes the ASP.NET code in the server page. (Tomcat does not support ASP.NET but Mono does) It instantiates TextBox, Button, and Label objects (the classes are defined in System.Web.UI.WebControls). Each object dynamically renders itself into HTML.  The dynamically generated HTML is merged into the static HTML.  The resulting HTML is returned to the client as an HTTP response.

29 Calc.aspx as seen by the client <form name="_ctl0" method="post" action="calc.aspx" id="_ctl0"> + note: there are also “ hidden ” and “ div ” (section) tags.

30 When the “ = “ button is clicked, the input from “ op1 ” and “ op2 ” are posted to the server and directed to calc.aspx (since action="calc.aspx"). On the server side, ASP.NET notifies the Button object in calc.aspx and the Button responds by firing a Click event. ASP.NET receives the event and subsequently invokes its handler: OnAdd ( ). “ Sum.Text = (a + b).ToString (); ” renders the result into the “ Sum ” label in as HTML. The dynamically generated HTML is merged with the static HTML (parts not in server side tags). The resulting HTML is sent to the client browser. Use the client browser ’ s View->Page Source menu to see the final HTML code received by the client. (Mac: Tools->Web Developer->Page Source) When Calc.aspx is accessed by a client

31 ASP.NET Controls  Two types: Web Controls and HTML Controls  Web Controls Class names are prefixed with asp:. Classes are from System.Web.UI.WebControls. The name of the object is defined by the ID attribute. ASP Web controls are rendered into HTML. ASP Web controls are highly programmable. They support methods, properties, events. This web control initializes the textbox to display 2. Any public property of a control can be used this way.

32 ASP.NET Controls Control properties can be accessed from server-side scripts (code between the and tags). Read a control property by scripts: int a = Convert.ToInt32 (op1.Text); Write a control property by scripts: Sum.Text = (a + b).ToString (); Event-driven programming. Controls fire events when users click on them. Wiring an event to an event handler is accomplished by prefixing the event name with “ On ”.

33 Exception handling can be added in the handlers. void OnAdd (Object sender, EventArgs e) { try { int a = Convert.ToInt32 (op1.Text); int b = Convert.ToInt32 (op2.Text); Sum.Text = (a + b).ToString (); } catch (FormatException) { Sum.Text = “ Format Error"; } ASP.NET Controls

34 Three principles of the Web Forms programming model: A Web form ’ s user interface is “ declared ” using a combination of HTML and server controls. Server controls fire events that can be handled by server-side scripts. Server-side scripts in ASP.NET are compiled to CIL and executed by the CLR on the server. RunAt= “ server ” must be used in every tag that ASP.NET is to process The Web Forms Programming Model

35 Web Controls AdRotator Displays rotating banners in Web forms Button Generates submit buttons Calendar Displays calendars with selectable dates CheckBox Displays a check box in a Web form CheckBoxList Displays a group of check boxes CompareValidator Validates user input by comparing it to another value CustomValidator Validates user input using the algorithm of your choice

36 Web Controls DataGrid Displays data in tabular format DataList Displays items in single-column or multicolumn lists using HTML templates DropDownList Generates HTML drop-down lists HyperLink Generates hyperlinks Image Displays images in Web forms ImageButton Displays graphical push buttons Label Generates programmable text fields LinkButton Generates hyperlinks that post back to the server

37 Web Controls ListBox Generates HTML list boxes Literal Generates literal text in a Web form Panel Groups other controls RadioButton Displays a radio button in a Web form RadioButtonList Displays a group of check boxes RangeValidator Verifies that user input falls within a specified range RegularExpressionValidator Validates user input using regular expressions Repeater Displays items using HTML templates

38 Web Controls RequiredFieldValidator Verifies that an input field isn ’ t empty Table Generates HTML tables TextBox Generates text input fields ValidationSummary Displays a summary of validation errors Xml Displays XML documents and optionally formats them using XSLT

39  ASP.NET HTML controls mimic the original HTML tags. (They are processed on the server side. They are not HTML tags which are processed by the client browser.) e.g. HTML controls are used like HTML tags. An HTML control is an instance of System.Web.UI.HtmlControls.HtmlInputText. ASP.NET sees the RunAt= “ server ” attribute and creates an HtmlInputText object. The HtmlInputText object, in turn, emits an tag that ’ s ultimately returned to the browser. HTML controls (server side) have properties and can generate events which make them more powerful than HTML tags (client side).  Without RunAt="server “, HTML controls become HTML tags. HTML Controls

40 TagCorresponding HTML Control HtmlAnchor HtmlButton HtmlForm HtmlImage HtmlInputButton HtmlInputButton HtmlInputButton

41 HTML Controls HtmlInputCheckBox HtmlInputFile HtmlInputHidden HtmlInputImage HtmlInputRadioButton HtmlInputPassword HtmlInputText HtmlSelect

42 HTML Controls HtmlTable HtmlTableCell HtmlTableCell HtmlTableRow HtmlTextArea Any other tag with runat= “ server ” HtmlGenericControl

43 + void OnAdd (Object sender, EventArgs e) { int a = Convert.ToInt32 (op1.Value); int b = Convert.ToInt32 (op2.Value); Sum.InnerText = (a + b).ToString (); } The HTML controls version of Calc.aspx

44 Part IV ASP.NET Internals

45 When ASP.NET processes the first HTTP request for an ASPX file: 1.It creates class representing the dynamic code of the file. 2.It compiles it, loads it, creates an object for it. 3.The object initializes itself and processes page-level events. 4.The object generates HTML output to be sent to the client. 5.The object remains in the server memory to process further requests to the page. 6.When the ASPX file is modify, ASP.NET automatically repeats steps 1-4. How does an ASP.NET enabled server process an ASPX file?

46 When ASP.NET processes the first HTTP request for an ASPX file: 1.It creates a Page class deriving from class System.Web.UI.Page. 2.It copies the code in the ASPX file to the Page-derived class. 3.A method (e.g. OnAdd) in a block becomes a member method of the derived class. 4.ASP.NET compiles the derived class and places the resulting DLL in a system folder and caches it there. C:\WINNT\Microsoft.NET\Framework\vn.n.nnnn\Temporary ASP.NET Files. 5.ASP.NET instantiates an object of the derived Page class and “ executes ” it by calling a series of methods on it. 6.The Page object instantiates any controls declared inside it and solicits their output. How does a ASP.NET enabled server process an ASPX file? (Details)

47 7.As the Page object executes, it fires a series of events (page-level events) that can be processed by server-side scripts:  “ Init ”, which is fired when the page is first instantiated, and  “ Load ”, which is fired after the page ’ s controls are initialized but before the page renders any output. 8.Implicit wiring of Page events to handlers by defining handlers ’ names as Page_EventName.... void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { // if it is not from the client for (int i=0; i<5; i++) {// list 5 days DateTime date = DateTime.Today + new TimeSpan (i, 0, 0, 0); MyList.Items.Add (date.ToString ("MMMM dd, yyyy")); } } } Page-Level Events

48 ASP.NET Compilation Directives @ @ Page Defines general attributes and compilation settings for ASPX files (e.g. Language) @ Control Defines general attributes and compilation settings for ASCX files @ Import Imports a namespace @ Assembly Enables linkage to assemblies, not linked to by default @ Register Registers user controls and custom controls for use in a Web form @ OutputCache Exerts declarative control over page caching and fragment caching @ Reference Adds a reference to an external ASPX or ASCX file @ Implements Identifies an interface implemented by a Web page Must be positioned at the top of an ASPX file.

49 1.ASPX files are in text files, anyone can read it. 2.When a company sells its ASPX server programs, it does not want people to see their source code. 3.How? Code-behind is designed to protect the source code. 4.For the static code in HTML, we can ’ t do anything about it. 5.Dynamic code in C# or other.NET languages can be separated out and compiled into DLLs. 6.Only the static HTML code and the DLLs are delivered to the customs. Separating Static Code from Dynamic Code

50 1.Create a CS file (e.g. Examples/C5/Lander/Lander.cs) containing code that would normally appear between and tags. Make each of these source code elements members of a class (e.g. LanderPage) derived from System.Web.UI.Page. 2.In your Page-derived class, declare protected fields whose names mirror the IDs of the controls declared in the ASPX file (e.g. Lander.aspx). At run time, ASP.NET maps these fields to the controls of the same name. 3.Compile the CS file into a DLL. In a Visual Studio Command Prompt window, run the following: csc /target:library Lander.cs Code-behind with C#

51 4.Place the HTML portion of the Web form—everything between the and tags—in an ASPX file (e.g. Lander.aspx). 5.Include in the ASPX file an @ Page directive containing an Inherits attribute that identifies the Page-derived class in the DLL. When a request arrives for that page at run-time, ASP.NET derives a child class from this class to create the form. e.g. 6.To use the source code without recompiling: 7. Code embedded has to be in C#, VB.NET, or JScript. Code- behind can be in any other language supported by.NET. Code-behind in Web forms coded in C#

52 8.To deploy the program: move the ASPX file to Inetpub/wwwroot/xiaotest/Lander and the DLL to Inetpub/wwwroot/xiaotest/Lander/bin. 9.The program can be accessed the same way as other ASP.NET programs: http://winserv1.cs.uakron.edu/xiaotest/Lander/Lander.aspx 9.In order for http://winserv1.cs.uakron.edu/xiaotest/Lander/Lander.aspx to work, the Lander directory has to be converted to a Web Application, which instructs ASP.NET to find Lander.dll under the application’s bin directory. Code-behind in Web forms coded in C#

53 Create a Web Application in IIS * You need to be an administrator to use IIS  winserv1 -> Sites -> Default Web Site  Right-click->Add Application  Alias: xiaotestLander  Application pool: defualtAppPool  Physical path: C:\inetpub\wwwroot\xiaotest\Lander http://winserv1.cs.uakron.edu/xiaotest/Lander/Lander.aspx Existing directories can be converted to Web Applications winserv1 -> Sites -> Default Web Site->xiaotest Right-click on Lander Convert to Application Application pool: defualtAppPool http://winserv1.cs.uakron.edu/xiaotest/Lander/Lander.aspx

54 Development of Web forms using Visual Studio.NET Create a Web Application project Use forms designer to design forms by drag-and-drop controls from a palette onto the forms. Edit the HTML. Write event handlers by double-clicking controls and filling in empty method bodies. Compile and run applications by executing simple menu commands. Web Forms and Visual Studio.NET

55 Summary Web Programming, Client Side, Server Side, HTTP, HTML, HTML Forms, CGI, ISAPI, ASP, ASP.NET, ASP.NET Forms, ASP.NET Controls, IIS, Web Forms Programming Model, Page-Level Events, Code Behind.  Principles: What are they? How do they work? (internals, static structures, dynamic data/event flow.)  Practice: Explain the logic, output, and internal working of a given code segment. Find errors in a given code segment. Write a simple program to perform a given task.


Download ppt "Server-side Programming using ASP.NET Web Forms Yingcai Xiao."

Similar presentations


Ads by Google