Download presentation
Presentation is loading. Please wait.
1
ASP.NET Page Objects Each ASP.NET page inherits for the PAGE object The PAGE supplies 5 built in objects: –APPLICATION: stores app wide state info. –SESSION: info. on a per user basis visiting the site –REQUEST: all info passed to the server from the browser. Contains form and query data. –RESPONSE: writes HTML and other info back to the client browser. –SERVER: provides server functionality for use in ASP eg using a database connection. –Global.asax and web.config are used for application control
2
PAGE Class Represents an.aspx file requested from a server that hosts an ASP.NET Web application. – Application Gets the Application object for the current Web request.Application –Request Gets the HttpRequest object for the requested page.RequestHttpRequest – Response Gets the HttpResponse object associated with the Page. This object allows you to send HTTP response data to a client and contains information about that response.ResponseHttpResponse – Server Gets the Server object, which is an instance of the HttpServerUtility class.Server HttpServerUtility – Session Gets the current Session object provided by ASP.NET.Session – many other members to the page class; See ms- help://MS.VSCC/MS.MSDNVS/cpref/html/frlrfsystemwebuip agememberstopic.htm. -for more documentation.
3
Page.Request Property Gets the HttpRequest object for the requested page.HttpRequest In the system.web.ui namespace so can abbreviate to Request (same for others) Some properties: – AcceptTypes Gets a string array of client-supported MIME accept types.AcceptTypes – ApplicationPath Gets the ASP.NET application's virtual application root path on the server.ApplicationPath – Browser Gets information about the requesting client's browser capabilities.Browser – ClientCertificate Gets the current request's client security certificate.ClientCertificate – ContentEncoding Gets the character set of the entity-body.ContentEncoding – ContentLength Specifies the length, in bytes, of content sent by the client.ContentLength
4
Page.Request Property-1 –ContentType Gets the MIME content type of the incoming request.ContentType – Cookies Gets a collection of cookies sent by the client.Cookies – CurrentExecutionFilePath Gets the virtual path of the current request.CurrentExecutionFilePath – FilePath Gets the virtual path of the current request.FilePath – Files Gets the collection of client-uploaded files (Multipart MIME format).Files – Filter Gets or sets the filter to use when reading the current input stream.Filter – Form Gets a collection of form variables.Form – Headers Gets a collection of HTTP headers.Headers – HttpMethod Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.HttpMethod – InputStream Gets the contents of the incoming HTTP entity body.InputStream
5
Page.Request Property-2 –IsAuthenticated Gets a value indicating whether the user has been authenticated.IsAuthenticated – IsSecureConnection Gets a value indicting whether the HTTP connection uses secure sockets (that is, HTTPS).IsSecureConnection – Params Gets a combined collection of QueryString, Form, ServerVariables, and Cookies items.ParamsQueryStringForm ServerVariablesCookies – Path Gets the virtual path of the current request.Path – PathInfo Gets additional path information for a resource with a URL extension.PathInfo – PhysicalApplicationPath Gets the physical file system path of the currently executing server application's root directory.PhysicalApplicationPath – PhysicalPath Gets the physical file system path corresponding to the requested URL.PhysicalPath – QueryString Gets the collection of HTTP query string variables.QueryString – RawUrl Gets the raw URL of the current request.RawUrl
6
Page.Request Property-3 –RequestType Gets or sets the HTTP data transfer method (GET or POST) used by the client.RequestType – ServerVariables Gets a collection of Web server variables.ServerVariables – TotalBytes Gets the number of bytes in the current input stream.TotalBytes – Url Gets Information about the URL of the current request.Url – UrlReferrer Gets information about the URL of the client's previous request that linked to the current URL.UrlReferrer – UserAgent Gets the raw user agent string of the client browser.UserAgent – UserHostAddress Gets the IP host address of the remote client.UserHostAddress – UserHostName Gets the DNS name of the remote client.UserHostName – UserLanguages Gets a sorted string array of client language preferences.UserLanguages –All these can be found in the VS documentation
7
Request eg. browsercheck Sub Page_Load(Source As Object, E as EventArgs) If Not IsPostBack Then If Request.Browser.Browser = "IE" Then If Request.Browser.MajorVersion < 6 Then MyLabel.Text = "Time to upgrade Internet Explorer!" Else MyLabel.Text = "Your copy of Internet Explorer is up to date." End If Else MyLabel.Text = "You're not using Internet Explorer" End If End If End Sub
8
Response public props & meths-1 – Buffer Gets or sets a value indicating whether to buffer output and send it after the entire response is finished processing. Default is TRUE; increases performanceBuffer –ContentType Gets or sets the HTTP MIME type of the output stream. (Multipurpose Internet Mail Extension)eg text/html, image/gifContentType – Cookies Gets the response cookie collection. Write a cookie.Cookies – Expires Gets or sets the number of minutes before a page cached on a browser expires. If the user returns to the same page before it expires, the cached version is displayed. Expires is provided for compatiblility with previous versions of ASP.Expires – Clear() Clears all content output from the buffer stream.Clear –End() Sends all currently buffered output to the client, stops execution of the page, and raises the Application_EndRequest event.End
9
Response public props & meths-2 –Flush() Sends all currently buffered output to the client.Flush –Redirect() Overloaded. Redirects a client to a new URL. No HTML is allowed to have already be sent to the browserRedirect –Write() Overloaded. Writes information to an HTTP output content stream.Write – WriteFile() Overloaded. Writes the specified file directly to an HTTP content output stream.WriteFile
10
Redirect example Sub Page_Load(Source As Object, E as EventArgs) If Not IsPostBack Then MyButton.Text = "OK" MyDropDownList.Items.Add("http://www.microsoft.com") MyDropDownList.Items.Add("http://www.wrox.com") MyDropDownList.Items.Add("http://msdn.microsoft.com") End If End Sub Public Sub Click (ByVal sender As Object, ByVal e As System.EventArgs) Response.Redirect(MyDropDownList.SelectedItem.Text) End Sub
11
Redirect example cont.
12
Response.write &.writefile Used to output text to the browser windows. The text is not part of a label or textbox.text etc. –Response.write(“Hello my name is Fred”) Writefile takes its input form a server file Response.WriteFile() <% Dim filename As String filename = Request.PhysicalApplicationPath + "file.txt" Response.WriteFile(filename) %>
13
Server properties and methods –MachineName Gets the server's computer name.MachineName –ScriptTimeout Gets and sets the request time-out in seconds. Default = 90.ScriptTimeout – HtmlDecode() Decodes a string that has been encoded to eliminate invalid HTML characters.HtmlDecode – HtmlEncode() Encodes a string/special characters like to < and > to be displayed in a browser.HtmlEncode – MapPath() Returns the physical file path that corresponds to the specified virtual path on the Web server.MapPath –UrlDecode() Decodes a string encoded for HTTP transmission and sent to the server in a URL.UrlDecode – UrlEncode() Encodes a string for reliable HTTP transmission from the Web server to a client via the URL. Eg spaces are converted to + and special characters like & to %26UrlEncode
14
Server Example-birthday1 <% Dim Name As string Dim Age As string Age = "twenty three??" Name = " & " Age = Server.UrlEncode(Age) Name = Server.UrlEncode(Name) %> &name=<% Response.Write(Name)%>">click here
15
Server Example-birthday2 <% Dim Name As string Dim Age as string Name = Request.QueryString("Name") Age = Request.QueryString("Age") Name = Server.HtmlEncode(Name) Age = Server.HtmlEncode(Age) %> Happy Birthday May the next years be as good!
16
State management Overcome the stateless nature of HTTP Two areas: Session and Application –Session refers to one user connecting to a web site (regardless of how many pages are accessed) eg shopping cart –Application is one off – it applies to the whole web site (global info eg how many users here now) –Each web site has its own session and application management –ASP.NET has global.asax and web.config for application & session events eg application_onstart()
17
Application management – Count Gets the number of objects in the HttpApplicationState collectionCount – Lock() Locks access to an HttpApplicationState variable to facilitate access synchronization.Lock – UnLock() Unlocks access to an HttpApplicationState variable to facilitate access synchronization.UnLock –Many other properties and methods see VS documentation –Used for application global information Application.Lock() Application("MyCode") = 21 Application("MyCount") = Convert.ToInt32(Application("MyCount")) + 1 Application.UnLock() …. Response.write(Application(“Mycount”))
18
Initial configuration for Application state Global.asax file is used to initialise application state Sub Application_onStart() Application(“CompanyPhone”) = “9123 3456” End Sub Global.asax must be in the application root directory –The Global.asax file itself is configured so that any direct URL request for it is automatically rejected; external users cannot download or view the code written within it. –The Global.asax file is optional. If you do not define the file, the ASP.NET page framework assumes that you have not defined any application or session event handlers.
19
Global.asax –When you save changes to an active Global.asax file, the ASP.NET page framework detects that the file has been changed. It completes all current requests for the application, sends the Application_OnEnd event to any listeners, and restarts the application domain. In effect, this reboots the application, closing all browser sessions and flushing all state information. When the next incoming request from a browser arrives, the ASP.NET page framework re-parses and recompiles the Global.asax file and raises the Application_OnStart event. Sub Application_OnAuthenticateRequest(Source As Object, Details as EventArgs) 'Authentication code goes here. End Sub
20
Global.asax cont. Sub Application_OnStart() ' Application startup code goes here. End Sub Sub Session_OnStart() ' Session startup code goes here. End Sub Sub Session_OnEnd() ' Session cleanup code goes here. End Sub Sub Application_OnEnd() ' Application cleanup code goes here. End Sub
21
Session State – IsNewSession Gets a value indicating whether the session was created with the current request.IsNewSession – Item Gets or sets individual session values.Item –SessionID Gets the unique session ID used to identify the session.SessionID –Timeout Gets and sets the time-out period (in minutes) allowed between requests before the session- state provider terminates the session.Timeout – Abandon() Cancels the current session.Abandon –Clear() Clears all values from session state.Clear
22
Session state eg.-1 Sub EmptyClick(sender As System.Object, e As System.EventArgs) Session("BasketCount") = 0 End Sub ‘ note that session.clear() would clear ALL session variables Sub AddClick(sender As System.Object, e As System.EventArgs) Session("BasketCount") += 1 End Sub
23
Session state eg.-2 Basket items :
24
Notes re session state Session and application variables use server memory –Keep to a minimum to preserver server performance –Use to hold FREQUENTLY used data –Use web.config file to store rarely used items. This is a disk file so access is slower. XML formatted.
25
Cookies Same restrictions as with PHP as they are client based. Cookies store text information only (session can store objects) Cookies are part of the HttpRequest and HttpResponse messages Set with Dim MyCookie As New HttpCookie("Background") MyCookie.Value = MyDropDownList.SelectedItem.Text Response.Cookies.Add(MyCookie) Read with ">
26
Some HttpCookie properties – Expires Gets or sets the expiration date and time for the cookie.Expires – Item Shortcut for HttpCookie.Values[ key ]. This property is provided for compatibility with previous versions of ASP. In C#, this property is the indexer for the HttpCookie class.Item – Name Gets or sets the name of a cookie.Name – Path Gets or sets the virtual path to transmit with the current cookie.Path – Secure Gets or sets a value indicating whether to transmit the cookie securely (that is, over HTTPS only).Secure – Value Gets or sets an individual cookie value.Value – Values Gets a collection of key-and-value value pairs that are contained within a single cookie object.Values
27
Cookie setting example-1 Sub Page_Load(Source As Object, E as EventArgs) If Not IsPostBack Then MyButton.Text = "Save Cookie" MyDropDownList.Items.Add("Blue") MyDropDownList.Items.Add("Red") MyDropDownList.Items.Add("Gray") End If End Sub Public Sub Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim MyCookie As New HttpCookie("Background") Dim dt as DateTime= datetime.now() Dim ts as new timespan(30,0,0,0)
28
Cookie setting example-2 MyCookie.Value = MyDropDownList.SelectedItem.Text MyCookie.Expires = dt.add(ts) Response.Cookies.Add(MyCookie) End Sub
29
Cookie Reading example Sub Page_Load(Source As Object, E as EventArgs) Response.Cache.SetExpires(DateTime.Now) End Sub <body bgcolor="<%= Request.Cookies("Background").Value %>">
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.