Lesson 2: Namespaces in a Web Application
In this lesson, you ll learn how to navigate the ASP.NET namespaces to find the objects you use to create a Web application. You will also see how to use the Application, Page, Request, and Response objects in code. These four objects form the core of Web application programming.
After this lesson, you will be able to
Navigate the .NET Framework to find objects for Web applications
Explain how objects relate to each other in the ASP.NET architecture
Get at the ASP.NET objects and control them in code
Navigate the object hierarchy to get subordinate ASP.NET objects such as the Browser and Cookies objects.
Estimated lesson time: 30 minutes
Overview of Web Namespaces
The class definitions for objects used in Web applications reside in the System.Web namespace. Table 3-4 shows the namespace hierarchy and describes the kinds of class definitions you will find in each namespace. Use this table as a guide to finding objects that perform specific tasks.
Namespace | Contains classes for |
System.Web | The Application, Browser, Cache, Cookies, Exception, Request, Response, Server, and Trace objects. Use these classes in most Web programming tasks. The Application object defined in Global.asax is based on the Application class. |
System.Web.SessionState | The Session object. Use these classes to save and retrieve items saved in the Session state. |
System.Web.Services | The WebService object. Use these classes to create and use Web services. |
System.Web.UI | The Page and Control objects. Use these classes within a Web form to create and control an application s user interface. Web forms are based on the Page class. |
System.Web.UI.WebControls | All server control objects. Use these classes within Web forms. |
System.Web.UI.HTMLControls | All HTML control objects. Use these classes within Web forms. |
System.Web.Caching | The Cache object. Use these classes to control server-side caching to improve application performance. |
System.Web.Mail | The MailMessage, MailAttachment, and SmtpMail objects. Use these classes to send mail messages from your application. |
System.Web.Security | Authentication objects and modules. Use these classes to authenticate users and provide security within your application. |
When programming a Web application, you deal directly with two types of objects derived from classes in the Web namespaces:
Derived from the HttpApplication class. In your application, this definition resides in the Global.asax file.
Derived from the Page class. In your application, this definition resides in Web Form modules.
The following code shows the declarations that Visual Studio generates for the Global and WebForm1 classes. These classes are instantiated automatically by the ASP.NET run time.
Visual Basic .NET
Public Class Global Inherits System.Web.HttpApplication End Class Public Class WebForm1 Inherits System.Web.UI.Page End Class
Visual C#
public class Global : System.Web.HttpApplication { } public class WebForm1 : System.Web.UI.Page { }
These Global and WebForm1 objects are the entry points you use to get at other Web objects in an application. Those objects, along with Request and Response, are the objects you will most commonly work with in code. The following sections explain how to use the Application, Page, Request, and Response objects to navigate among other objects.
Using the Application Object
The Application object is a top-level object in your Web application s object hierarchy. Use the Application object to configure your application, to save state information, and to respond to application-wide events. The Application object has properties and methods that provide access to other objects in your application, as shown in Figure 3-2.
Figure 3-2. The Application object
When ASP.NET starts your application, it automatically instantiates the Global object defined in Global.asax. Use the events in the Global object to configure your application and to initialize application-level state variables.
The HttpApplication base class provides the properties and methods to access the subordinate objects for the Global object. These properties and methods are described in Table 3-5. Use these properties and methods to get at other objects from the Application object.
Property/method | Use to |
Application | Save data items in the Application state. |
Context | Get Handler, Trace, Cache, Error, and other objects for the current context. |
Modules | Access HTTP modules. |
Request | Read a request and get Browser, ClientCertificates, Cookies, and Files objects from the current request. |
Response | Write text or data to a response and get Cache, Cookies, and Output objects from the current response. |
Server | Process requests and responses. The Server object provides helper methods for URL encoding and decoding. |
Session | Save data items in the Session state. |
User | Get authentication information about the user making the current request. By default, Web applications allow anonymous access. |
The following code uses the Request and Browser objects available from within the Application object to determine whether a browser making a request is version 4.0 or later:
Visual Basic .NET
Sub Application_BeginRequest(ByVal sender As Object, _ ByVal e As EventArgs) ' Fires at the beginning of each request If Request.Browser.MajorVersion < 4 Then ' Disable advanced features. End If End Sub
Visual C#
protected void Application_BeginRequest(Object sender, EventArgs e) { // Fires at the beginning of each request. if (Request.Browser.MajorVersion < 4) { // Disable advanced features. } }
Using the Page Object
The Page object controls your application s user interface. The Page object has properties and methods that provide access to other objects in the user interface, as shown in Figure 3-3.
Figure 3-3. The Page object
When a user requests a page from your application, ASP.NET automatically instantiates the Web form and displays the page. You add event procedures to the form to control the user interface and to interact with the user.
The Page base class provides the core methods and properties that you use most frequently when programming Web forms. These properties and methods are shown in Table 3-6.
Property/method | Use to |
Application | Save data items in the Application state. |
Cache | Control how responses are cached on the server. |
Controls | Get at controls on the page. |
Request | Read a request and get Browser, ClientCertificates, Cookies, and Files objects from the current request. |
Response | Write text or data to a response and get Cache, Cookies, and Output objects from the current response. |
Server | Process requests and responses. The Server object provides helper methods for URL encoding and decoding. |
Session | Save data items in the Session state. |
Trace | Turn tracing on or off and write to the trace log. |
The following code adds a new control to the Web form at run time:
Visual Basic
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Create a new control. Dim txtNew As New TextBox() ' Set some text to display in the control. txtNew.Text = "Some new text" ' Add the control between the <form> </ form> elements ' as the second control on the page. FindControl("Form1").Controls.AddAt(2, txtNew) End Sub
Visual C#
private void Page_Load(object sender, System.EventArgs e) { // Create a new control. TextBox txtNew = new TextBox(); // Set some text to display in the control. txtNew.Text = "Some new text"; // Add the control between the <form> </ form> elements // as the second control on the page. FindControl["Form1"].Controls.AddAt(2, txtNew); }
Using the Request Object
The Request object contains the information sent by the client browser when a page is requested from the application. The Request object has properties and methods that provide access to other objects that make up the request, as shown in Figure 3-4.
Figure 3-4. The Request object
The Request object provides the methods and properties to access the subordinate objects described in Table 3-7.
Property/method | Use to |
Browser | Determine the capabilities of the browser making the request. Browser properties provide the browser version number, determine whether it is the AOL browser, determine whether the browser supports cookies, and supply other information. |
ClientCertificates | Authenticate the client. |
Cookies | Get information from the client in the form of cookies. |
Files | Get files that are uploaded by the client. |
InputStream | Read and write to the raw data sent in the request. |
The following code uses the Request object to check whether the browser supports cookies and whether a particular cookie exists before saving the value of a cookie in the Session state:
Visual Basic .NET
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Run first time page is displayed. If Not IsPostBack Then ' Check if Browser supports cookies. If Request.Browser.Cookies Then ' Check if the UName cookie exists. If Not IsNothing(Request.Cookies("UName")) Then ' Save the value of the cookie. Session("User") = Request.Cookies("UName").Value End If End If End If End Sub
Visual C#
private void Page_Load(object sender, System.EventArgs e) { // Run first time page is displayed. if(!IsPostBack) // Check if Browser supports cookies. if(Request.Browser.Cookies) // Check if the UName cookie exists. if(Request.Cookies["UName"] != null) // Get the value of the cookie. Session["User"] = Request.Cookies["UName"].Value; }
Using the Response Object
Use the Response object to form the response sent from the server to the client browser. The Response object has properties and methods that provide access to other objects that make up the request, as shown in Figure 3-5.
Figure 3-5. The Response object
The Response object provides methods and properties to access the subordinate objects, as described in Table 3-8.
Property/method | Use to |
Cache | Determine how the server caches responses before they are sent to the client |
Cookies | Set the content of cookies to send to the client |
Output | Get or set the raw data returned to the client as the response |
The following code creates a cookie and sends it to the client as part of the response:
Visual Basic .NET
Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Run the first time this page is displayed. If Not IsPostBack Then ' If the browser supports cookies If Request.Browser.Cookies Then ' Create a cookie. Dim cookUname As New HttpCookie("UName") cookUname.Value = "Wombat" ' Add the cookie. Response.Cookies.Add(cookUname) End If End If End Sub
Visual C#
private void Page_Load(object sender, System.EventArgs e) { if(!IsPostBack) // If the browser supports cookies if (Request.Browser.Cookies) { // Create a cookie. HttpCookie cookUname = new HttpCookie("UName"); cookUname.Value = "Wombat"; // Add the cookie. Response.Cookies.Add(cookUname); } }