540 likes | 650 Views
Introduction to ASP.NET. Static and Dynamic Web Applications. HTML is used to create static content Browser software interprets HTML tags and formats the output Dynamic Web applications enable the user to interact with the Web application
E N D
Static and Dynamic Web Applications • HTML is used to create static content • Browser software interprets HTML tags and formats the output • Dynamic Web applications enable the user to interact with the Web application • Examples of dynamic Web applications include shopping carts, membership databases, online catalogues, and personalized web sites
Server-side Programming • Server-side programs allowed you to create dynamic Web applications such as process a form or manage a database • The Web server sends static HTML to the client’s browser • Because the processing of the script occurs on the server, you can hide code from the client • Microsoft’s implementation of Web server programming technology is referred to as Active Server Pages (ASP) • Server-side scripts can be used to create dynamic Web applications that are browser independent
ASP.NET • The latest version of ASP is known as ASP.NET • Visual Studio .NET is a developer application used to create ASP.NET Web applications • There are two main types of Web resources created with ASP.NET applications • WebForms are ASP.NET pages within an ASP.NET application • Web Services are ASP.NET Web pages that contain publicly exposed code so that other applications can interact with them • Web Services are identified with the file extension .asmx
WebForms • The ASP.NET WebForm is separated into two logical areas: • The HTML template • A collection of code behind the WebForm • The HTML template • Contains the design layout, content, and the controls • Creates the user interface, or presentation layer • Instructs the browser how to format the Web page • Is created using a combination of HTML controls, HTML Server controls, Mobile Controls, and ASP.NET controls
Server Controls • HTML Server controls are similar to the HTML controls, except they are processed by the server • Add runat = "server" to the HTML control to transform it into an HTML Server control • HTML control: <input type="text"> • HTML Server control: <input type="text" runat="server"/> <input type=”radio” runat=”server” value=”Yes”/> Yes • Server-side programs can interact with the control before it is rendered as a plain HTML control and sent to the browser
XHTML • XHTML requires that all HTML elements be compliant with XML standards • XML is another example of a markup language that can be used to build applications • One of the rules of XML is that all controls must have a closing tag, or end with />. So, all controls that do not have a closing tag are closed in the initial tag with /> • The XML, HTML, and XHTML standards are maintained by the World Wide Web Consortium (www.w3c.org)
ASP.NET Controls • ASP.NET form controls will create the HTML code • ASP.NET Server controls are organized as: • ASP.NET Form Controls • Data Validation Controls • User Controls • Mobile Controls • ASP.NET controls are usually identified with the prefix asp: followed by the name of the control • ASP.NET button: <asp:Button id="ShowBtn" runat="server" Text="Show the message." />
HTML Server Versus ASP.NET Server Controls • ASP.NET form controls can interact with client-side events such as when the user clicks on a button • When the event occurs, ASP.NET can trigger a script to run on the server • ASP.NET form controls also have different properties than their HTML server control counterparts • HTML Server label control • Message1.InnerHTML = "Product 1" • ASP server label control • Message2.Text = "Product 2"
Browser Source Code • It is very important that you look at the browser’s source code of each ASP.NET page that you create in order to understand what the Web server is sending to the browser • ASP.NET code is never sent to the browser • Only HTML tags, along with client-side scripts, are sent to the browser • Many errors are related to the syntax of the HTML that is sent to the browser, such as a missing closing tag, or a missing quotation mark • By viewing the source code in the browser, you can more quickly locate the HTML syntax errors
User Controls • User controls are external files that can be included within another WebForm • User controls allow you to reuse code across multiple files • For example, you can create a user control that displays the top ten music selections for the week • You can use this control on the home page; they are often used for creating self-contained code, headers, menus, and footers • User controls replace the functionality of ASP server-side include pages • They are identified with the file extension .asmx
Other ASP.NET Server Controls • Data validation controls • A series of controls that validate form data without extensive JavaScript programming • Mobile controls • A series of controls that provide form functionality within wireless and mobile devices • Literal controls • Page content that is not assigned to a specific HTML control such as a combination of HTML tags and text to the browser
Server Controls within Visual Studio .NET • In Visual Studio .NET most of the ASP.NET Server controls are located on the Web Forms tab in the toolbox Figure 1-2 Server controls with Visual Studio.NET
The Code Behind the Page • Server programs are written in a separate file known as the code behind the page • By separating the programming logic and presentation layer, the application becomes easier to maintain • Only Server controls can interact with the code behind the page • Written in any ASP.NET compatible language such as Visual Basic .NET, C#, Perl, or Java • Filename is the same as the WebForm filename • Add a file extension that identifies the language • Visual Basic .NET use .vb (mypage.aspx.vb) • C# use .cs (mypage.aspx.cs)
Code Behind the Page • The location of the code behind the page is determined via a property that is set on the first line in the page using the @Page directive <%@ Page Language="vb" Codebehind="WebForm1.vb" Inherits="TaraStore.WebForm1"%> • The @Page directive allows you to set the default properties for the entire page such as the default language • The CodeBehind property identifies the path and filename of the code behind the page • The Inherits property indicates that the code behind the page inherits the page class • This page class contains the compiled code for the entire page
Compiling the Page Class • The compiled code behind the page is the class definition for the page • A class is a named logical grouping of code • The class definition contains the functions, methods, and properties that belong to that class • In Visual Studio .NET the process of compiling a class is called building • When you build the application, you compile the code into an executable file • Visual Studio .NET compiles the code behind the page into an executable file and places the file in the bin directory
Compiling the Page Class Figure 1-3 Compiling the ASP.NET page and the code behind the page into the Page class
Postback • To keep this information across browser requests is known as maintaining state • The process of posting data back to a form is known as postback • All server controls support postback by default • A hidden form field named _ViewState is a very long encoded string that contains information required to maintain the form data across multiple page requests • This encoded string is decoded by the Web Server and will change each time the form is reposted back to the server • The values that are stored with the page remain with the page
Postback Data Using the _ViewState Hidden Field Figure 1-4 Postback data using the _ViewState hidden field
Enable _ViewState Property • The Web page does not have to support the postback feature • You can turn the postback property on or off by setting the EnableViewState property to true or false within the @Page directive • You can also turn the EnableViewState property on or off by setting the property for any individual server control, or for the entire application by setting the property in the application configuration files • In the following sample code, the postback property is turned off for the entire page for all server controls. This code is placed on the first line in the ASP.NET page • <%@ Page EnableViewState="false" %>
Page Class Events • The Page Class consists of a variety of methods, functions, and properties that can be accessed within the code behind the page • The first time a page is requested by a client, a series of page events occurs • The first page event is the Page_Init event which initializes the page control hierarchy • The Page_Load event loads any server controls into memory and occurs every time the page is executed
Page Class Event Cycle Figure 1-5 Page class event cycle
Procedures • In the following sample code, a message is displayed when the Page_Load event occurs • In Visual Basic .NET, the event handler is known as a procedure • When you create a procedure, you must identify the beginning of the procedure with the keyword Sub, and the ending with the keywords End Sub • Sub Page_Load(s As Object, e As EventArgs) • Message.InnerHtml = "Welcome!" • End Sub
Control Events • Control events can be action events, such as the click event for a server button control, or change events, such as when the value of a server text control changes • If a user clicks a server button control, then you can execute code in the OnServerClick event handler • The HTML server button control named MyBtn and a span tag named Message • <button id="MyBtn" runat="server" OnServerClick="MyBtn_Click"> • Click me!</button> • <h1><span id="Message" runat=server /></h1>
Control Events • When the user clicks the button, an OnServerClick event handler is called • The event handler calls a procedure named MyBtn_Click • In the code behind the page, the OnServerClick event handler can send a message back to the browser • Sub MyBtn_Click(s As Object, E as EventArgs) • Message.InnerHtml = "You clicked me!" • End Sub
Trace Property • To view the order in which the server controls are rendered to the Web page, turn on the trace property • The trace feature provides you with the ability to view the page controls, the order in which they are loaded, and the time it takes to load the control • The ID is a property that is assigned to the server control in the Web page • If no ID is provided for the server control, a generic ID value is assigned • To turn on the trace feature, on the first line of code set the trace property for the page to true as shown in the sample code below <% @Page Trace = "true" %>
Page_UnLoad • When the page unloads, the Page_UnLoad event occurs and the page is removed from the server’s memory • You can use the Page_Unload event handler to close database connections, close files, and release any programming variables or objects • In the sample code below, a message is displayed on the Web page when the page is unloaded • Sub Page_UnLoad(s As Object, e As EventArgs) • Message.InnerHtml = "Goodbye!" • End Sub
Built-in ASP.NET Objects • ASP.NET pages have access to objects that are built-in the Web Server, along with their properties and methods • HTTPRequest — object is mapped directly to the Request property of the Page object • HTTPResponse —Used to send information from the Web server to the client’s browser and is used to redirect the user to another Web page. The HTTPResponse object is mapped directly to the Response property of the Page object • Session —Used to share information between a single client and the Web server. The session object is used to store data during the course of a session. The session ends, and the session variable no longer exists when the user closes the browser or when the default session timeout is reached • Application —Allows developers to treat a sequence of Web pages as a single application, which means that information, such as the name of the application or the total number of visitors on the Web site, can be shared among all the users of an ASP application
The ASP.NET Page.Request Property • When a browser sends a request for a Web page, the Web server receives the request and some additional information in the TCP/IP header • The TCP/IP header is a portion of the data packet that includes information that determines how to send the file and where to send the file • The TCP/IP header includes the date and time, the type of request (get or post), the page requested, and the HTTP version
The ASP.NET Page.Request Property • Additional information includes the default language, the referring page, the IP address of the client, the cookies associated with that domain, and the user agent • The user agent can be used to identify the client software • Because the Request property belongs to the Page class, you can refer to the Request property using Page.Request.PropertyName or Request.PropertyName
The ASP.NET Page.Request Property • In the sample code below, three server variables are written to the browser • Server variables are variables that are passed in the TCP/IP header • Response.write(Request.PhysicalPath) • Response.write(Request.UserHostAddress) • Response.Write(Request.UrlReferrer.Host)
Browser Object • The user agent provides a string which can be used to detect the browser version • However, the string must be parsed to locate the browser application name and version • With the browser property, you can directly access the browser application name and version without the user agent • The Browser property displays the client browser version, then writes out the short name of the browser application, the version number, and the platform • Response.Write(Request.Browser.Browser) • Response.Write(Request.Browser.Version) • Response.Write(Request.Browser.Platform)
Processing a Form Using the QueryString Collection • The Request property provides you access to the form field names and values • If the form method is GET, then the form is sent appended to the URL requested as a single string called the QueryString • If the form method is POST, it is sent as part of the HTTP request body • The Request property contains a Form collection and QueryString collection that allow you to collect form information from both methods • http://www.tarastore.com/index.asp?name=katie&topic=asp
Processing a FormUsing the Form Collection • The sample code below creates a text box named password and a button named MyBtn • <span id="Message" runat="server"> • Please enter your password</span> • <input id="PWD" type="password" • size="8" runat="server"><br/> • <input id="MyBtn" type="submit" value="Login" OnServerClick="MyBtn_Click" runat="server"> • The page uses the Request property to retrieve information from the form field and displays the value • Response.write(Request.Form("PWD"))
Direct Access to Form Values • A simpler method to retrieve the value from a form field is to directly access the value properties of the form field • The property name (ID) that you use to access the value is different with each type of server control • You can create en event handler that will process the form • Sub MyBtn_Click(s As Object, e As EventArgs) • If (PWD.Value = "Course") Then • Message.InnerHtml = "Welcome!" • Else • Message.InnerHtml = "Try again!" • End If • End Sub
Using Page.Request to Retrieve Form Values and Server Variables Figure 1-8 Using Page.Request to retrieve form values and server variables
The ASP.NET Page.Response Property • The Response object is used to send information to the browser • Some of this information identifies the server and server properties • For example, the IP address of the server, and the name and version number of the Web server software are sent to the client • The Cookies collection is used to send cookies to the browser • A status code is sent to indicate whether the browser request was successful or encountered an error
Response.Write and Response.WriteFile • The Response object has several methods, such as Write and WriteFile • Write is a a method that allows you to send a string to the browser • You can send text, HTML and client-script to the browser using the write method • WriteFile allows you to send the entire contents of a text file to the Web page • Response.Write("TaraStore<br/>") • Dim strMessage as String = "TaraStore<br/>") • Response.WriteFile(strMessage) • Response.WriteFile("c:\foo.txt")
Server-side Redirection • The Response object sends data either via the HTTPResponse object or via the Page.Response property • The Response object holds the contents of the page in an area of memory called the buffer until you send the page • The methods and properties of the Response object allow you to control the caching of content from the ASP page • When the page is processed, a copy of the page created is stored on the server. This copy of the page is known as a cached page • The Response object allows you to redirect the browser to another page. Because this redirection occurs on the server, the visitors never know that they have been redirected to a new page Response.Redirect("http://www.msn.com/")
Locating Your ASP.NET Application • You can only view ASP.NET Web pages on a Web Server that supports ASP.NET • The default directory for the root Web site is at C:\InetPub\wwwroot • The root Web site is mapped as localhost as http://localhost/ • Web applications in Visual Studio .NET are in a folder in the root directory, named after your application • To deploy a Web application, you copy all of the Web application files to a live Web server on the Internet
Web Services • If your business partner is Course Technology and you want to query that company’s product catalog from your Web site, you could: • Post a link • Scrape a Web site (use a program to view a Web site and capture the source code) • Provide a Web Service to their catalog application • Web Services are used to create business-to-business applications • Web Services allow you to expose part or all of your programs over the Internet. The Web Service source file has the extension .asmx • A public registry known as UDDI contains registered public Web Services. Third party Web Services are available at http://www.xmethods.com
The Tara Store Web Service Figure 1-9 The Tara Store Web Service
The .NET Framework • ASP.NET is used to develop dynamic Web applications within the .NET Framework • The .NET Framework consists of: • A Common Language Runtime (CLR) • A hierarchical set of Base Class Libraries (BCL) • The .NET Framework is the architectural model for creating programs that interface with the operating system and the base class libraries
The .NET Framework Figure 1-10 The .NET Framework
The Base Class Libraries • The base class libraries are commonly used code providing general functions that can be accessed from any application • Libraries contain fundamental code structures and methods that allow you to communicate with the operating system software and other applications • By storing commonly used code in libraries, the code can be reused across applications • The actual library of code is located in one or more dynamic link library files • For example, the code for accessing a database object is stored in the Database class library, located in the file called System.Data.dll
Namespace • The base class libraries are organized into logical groupings of code called namespaces • A namespace is a hierarchical way to identify resources in .NET • The System object is at the top of the namespace hierarchy, and all objects inherit from it • ASP.NET: System.Web namespace • WebForms: System.Web.UI namespace • HTML Server Controls: System.Web.UI.Control.HTMLControl • ASP.NET Server Controls: System.Web.UI.Control.WebControl
Importing Namespaces • Visual Studio .NET adds references to your projects’ commonly used namespaces by default • You can import the namespaces into your page using the @Import directive • The following is the syntax for importing a .NET namespace <%@ Import NamespaceName %> • Below is a sample of how you would import the ASP.NET Page class <%@ Imports System.Web.UI.Page %>
Common Language Runtime • Visual Studio .NET and the Common Language Runtime are language independent • Language independence is achieved via the use of the Common Language Runtime (CLR) • The CLR supports new features such as a Common Type System (CTS), Garbage Collection (GC), and an Intermediate Language (IL) • The Common Type System (CTS) requires that all applications built within .NET, including ASP.NET applications, support the same basic data types • Examples of data types are strings and integers • These common data types are derived from the System namespace
Common Language Runtime • The compiled code is transformed into an intermediate language called the Microsoft Intermediate Language (MSIL or IL) • An integer in Visual Basic .NET or an int in C# are converted to the same .NET data type, which is Int32 • The IL that is created is the same for all languages • The assembly is the compiled .NET program • The assembly contains the IL along with additional information called metadata • Metadata contains information about the assembly • Use the IL Disassembler (ildasm.exe) to view the IL within an assembly