Post on 26-Dec-2015
transcript
MSIS 5133 Advanced MIS - E-Commerce
Spring 2003
Lecture 4: DotNet Technologies - Part 5
Developing Applications – Part 1
Dr. Rathindra SarathyDr. Rathindra Sarathy
Application Level Considerations
Applications and sessionsApplications and sessions State MaintenanceState Maintenance Configuring ApplicationsConfiguring Applications Tracing and DebuggingTracing and Debugging Error-handlingError-handling CachingCaching AuthenticationAuthentication
Web Application Benefits A A Web applicationWeb application is a group of files and folders (including is a group of files and folders (including
virtual folders) located under the Web applications root virtual folders) located under the Web applications root directorydirectory Create application-level and session-level variables that Create application-level and session-level variables that
are available to all pages within the Web applicationare available to all pages within the Web application A Web application runs in its own memory space, so that A Web application runs in its own memory space, so that
an error in one Web application does not bring down the an error in one Web application does not bring down the rest of the Web applications on your serverrest of the Web applications on your server
Maintains information about your session, such as your Maintains information about your session, such as your IP address, what pages you clicked and when, when you IP address, what pages you clicked and when, when you visited the site, what browser you are using, and your visited the site, what browser you are using, and your preferencespreferences
Maintains information across the entire Web application Maintains information across the entire Web application with the application objectwith the application object
ASP.Net Application ASP.NET Framework applications consist of everything under one ASP.NET Framework applications consist of everything under one
virtual directory of the Web server. You create an ASP.NET virtual directory of the Web server. You create an ASP.NET Framework application by adding files to a virtual directory on the Framework application by adding files to a virtual directory on the Web server. Web server.
ASP.NET maintains a pool of ASP.NET maintains a pool of HttpApplicationHttpApplication instances over the instances over the course of a Web application's lifetime. ASP.NET automatically course of a Web application's lifetime. ASP.NET automatically assigns one of these instances to process each incoming HTTP assigns one of these instances to process each incoming HTTP request that is received by the application. request that is received by the application.
An ASP.NET Framework application is created the first time a An ASP.NET Framework application is created the first time a request is made to the server; before that, no ASP.NET code request is made to the server; before that, no ASP.NET code executes. When the first request is made, a pool of executes. When the first request is made, a pool of HttpApplicationHttpApplication instances is created and the instances is created and the Application_StartApplication_Start event is raised. The event is raised. The HttpApplicationHttpApplication instances process this and subsequent requests, instances process this and subsequent requests, until the last instance exits and the until the last instance exits and the Application_EndApplication_End event is event is raised. raised.
Use application state variables to store data that is modified Use application state variables to store data that is modified infrequently but used ofteninfrequently but used often
Using Application Settings in web.configConfiguration files are perfectly suited for storing custom application Configuration files are perfectly suited for storing custom application
settings, such as database connection strings, file paths, or remote settings, such as database connection strings, file paths, or remote XML Web service URLs. The default configuration sections (defined in XML Web service URLs. The default configuration sections (defined in the machine.config file) include an <appSettings> section that may be the machine.config file) include an <appSettings> section that may be used to store these settings as name/value pairs. used to store these settings as name/value pairs.
<configuration><configuration> <appSettings><appSettings> <add key="pubs" value="server=(local)\NetSDK;database=pubs;Trusted_Connection=yes" /><add key="pubs" value="server=(local)\NetSDK;database=pubs;Trusted_Connection=yes" /> <add key="northwind" value="server=(local)\NetSDK;database=northwind;Trusted_Connection=yes" <add key="northwind" value="server=(local)\NetSDK;database=northwind;Trusted_Connection=yes"
/>/> </appSettings></appSettings></configuration></configuration>
The ConfigurationSettings object exposes a special AppSettings property The ConfigurationSettings object exposes a special AppSettings property that can be used to retrieve these settings: that can be used to retrieve these settings:
Using the web.config in application code
<%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Data.SqlClient" %><%@ Import Namespace="System.Data.SqlClient" %><%@ Import Namespace="System.Configuration" %><%@ Import Namespace="System.Configuration" %><html><html><script language="VB" runat="server"><script language="VB" runat="server"> Sub Page_Load(Src As Object, E As EventArgs)Sub Page_Load(Src As Object, E As EventArgs) Dim dsn As String = ConfigurationSettings.AppSettings("pubs")Dim dsn As String = ConfigurationSettings.AppSettings("pubs") Dim MyConnection As SqlConnectionDim MyConnection As SqlConnection Dim MyCommand As SqlDataAdapterDim MyCommand As SqlDataAdapter MyConnection = New SqlConnection(DSN)MyConnection = New SqlConnection(DSN) MyCommand = New SqlDataAdapter("select * from Authors", MyConnection)MyCommand = New SqlDataAdapter("select * from Authors", MyConnection) Dim DS As New DataSetDim DS As New DataSet MyCommand.Fill(DS, "Authors")MyCommand.Fill(DS, "Authors") MyDataGrid.DataSource= New DataView(DS.Tables(0))MyDataGrid.DataSource= New DataView(DS.Tables(0)) MyDataGrid.DataBind()MyDataGrid.DataBind() End SubEnd Sub</script></script>
Maintaining State Can be configured within controls themselves using hidden fields - This Can be configured within controls themselves using hidden fields - This
means that the controls automatically retain their state between page means that the controls automatically retain their state between page postbacks without any programming interventionpostbacks without any programming intervention
Additionally, ASP.NET provides three types of state to Web applications: Additionally, ASP.NET provides three types of state to Web applications: application, session, and user. application, session, and user.
All the state management services are implemented as HTTP modules All the state management services are implemented as HTTP modules Application state, as in ASP, is specific to an application instance and is Application state, as in ASP, is specific to an application instance and is
not persisted. not persisted. Session state is specific to a user session with the application. Session state is specific to a user session with the application. User state resembles session state, but generally does not time out and User state resembles session state, but generally does not time out and
is persisted. Thus user state is useful for storing user preferences and is persisted. Thus user state is useful for storing user preferences and other personalization information. other personalization information.
The Programmable Web Web Services Provides Building Blocks for the Microsoft .NET Framework -- MSDN Magazine, September 2000
Maintaining State in an ASP.NET Application Three methods that use a unique identifier to Three methods that use a unique identifier to
recognize the client across Web pages: recognize the client across Web pages:
ASP.NET uses Application and SessionASP.NET uses Application and Session objects - objects - store data and require session supportstore data and require session support
Client-side cookiesClient-side cookies - small files stored on the - small files stored on the client’s systemclient’s system
Cookieless applicationsCookieless applications – applications do not – applications do not require the user to support client-side or require the user to support client-side or server-side cookies as the identification data is server-side cookies as the identification data is passed with the URL. Stores the data with the passed with the URL. Stores the data with the requestrequest
Sample Global.asax file
<script language="VB" runat="server"> Sub Application_Start(Sender As Object, E As EventArgs) ' Do application startup code here End Sub Sub Application_End(Sender As Object, E As EventArgs) ' Clean up application resources here End Sub Sub Session_Start(Sender As Object, E As EventArgs) Response.Write("Session is Starting...<br>") End Sub Sub Session_End(Sender As Object, E As EventArgs) ' Clean up session resources here End Sub Sub Application_BeginRequest(Sender As Object, E As EventArgs) Response.Write("<h3><font face='Verdana'>Using the Global.asax File</font></h3>") Response.Write("Request is Starting...<br>") End Sub Sub Application_EndRequest(Sender As Object, E As EventArgs) Response.Write("Request is Ending...<br>") End Sub Sub Application_Error(Sender As Object, E As EventArgs) Context.ClearError() Response.Redirect("errorpage.htm") End Sub</script>
Global.asax contains information on what happens when applications, Global.asax contains information on what happens when applications, sessions (& requests) start and end.sessions (& requests) start and end.
Global.asax itself compiled into .NET assembly. Can use code insideGlobal.asax itself compiled into .NET assembly. Can use code inside
Creating Reusable Data in Global.asax
<%@ Import Namespace="System.Data" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System.IO" %><%@ Import Namespace="System.IO" %><script language="VB" runat="server"><script language="VB" runat="server"> Sub Application_Start(Sender As Object, E As EventArgs)Sub Application_Start(Sender As Object, E As EventArgs) Dim DS As New DataSetDim DS As New DataSet Dim FS As FileStreamDim FS As FileStream FS = New FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read)FS = New FileStream(Server.MapPath("schemadata.xml"),FileMode.Open,FileAccess.Read) Dim Reader As StreamReaderDim Reader As StreamReader Reader = New StreamReader(FS)Reader = New StreamReader(FS) DS.ReadXml(Reader)DS.ReadXml(Reader) FS.Close()FS.Close() Dim View As DataViewDim View As DataView View = New DataView(ds.Tables(0))View = New DataView(ds.Tables(0)) Application("Source") = ViewApplication("Source") = View End SubEnd Sub</script></script>
Sub Page_Load(Src As Object, E As EventArgs) Dim Source As DataView = Application("Source") MySpan.Controls.Add(New LiteralControl(Source.Table.TableName)) MyDataGrid.DataSource = Source MyDataGrid.DataBind() End Sub
Session state In the machine.config and the web.config files, the sessionState node allows you In the machine.config and the web.config files, the sessionState node allows you
to configure the session managementto configure the session management Storing session data in the Web Server memory results in the best performanceStoring session data in the Web Server memory results in the best performance
The The modemode property property is used to identify which storage method to use to store session is used to identify which storage method to use to store session datadata
OffOff - turns off session management - turns off session management InProcInProc - - the data is stored in process with the Web Server the data is stored in process with the Web Server StateServerStateServer - stores the data with a Windows service called StateServer - stores the data with a Windows service called StateServer
To provide individual data for a user during a session, data can be stored with To provide individual data for a user during a session, data can be stored with session scopesession scope
Configuring session state: Session state features can be configured via the Configuring session state: Session state features can be configured via the <sessionState> section in a web.config file. To double the default timeout of 20 <sessionState> section in a web.config file. To double the default timeout of 20 minutes, you can add the following to the web.config file of an application: minutes, you can add the following to the web.config file of an application:
<sessionState timeout="40“ /><sessionState timeout="40“ /> If cookies are not available, a session can be tracked by adding a session If cookies are not available, a session can be tracked by adding a session
identifier to the URL. This can be enabled by setting the following: identifier to the URL. This can be enabled by setting the following: <sessionState cookieless="true“ /><sessionState cookieless="true“ />
Use session state variables to store data that is specific to one session or user. Use session state variables to store data that is specific to one session or user. The data is stored entirely on the server. Use it for short-lived, bulky, or The data is stored entirely on the server. Use it for short-lived, bulky, or sensitive data. sensitive data.
Use the Class: Use the Class: System.Web.SessionState.HttpSessionStateSystem.Web.SessionState.HttpSessionState
Storing and Using Session Data Session data can be stored in databases and used for data miningSession data can be stored in databases and used for data mining SessionID, a unique identifier that identifies each sessionSessionID, a unique identifier that identifies each session You need only one identifier such as login ID or IP address - then You need only one identifier such as login ID or IP address - then
all previous session data can be retrievedall previous session data can be retrieved UsersTableUsersTable - UserID and password fields - UserID and password fields SessionDataSessionData Table Table - information gathered from each session- information gathered from each session UserIDUserID fieldfield - links between the tables - links between the tables
Client-side and HTTP Cookies
Client-side cookies use the browser document object Client-side cookies use the browser document object manipulated by client-side code such as javascript manipulated by client-side code such as javascript
HTTP cookies are written by the server. They still use the HTTP cookies are written by the server. They still use the browser document object to eventually write/read cookie.browser document object to eventually write/read cookie.
HTTP Cookies HTTP cookiesHTTP cookies are cookies created by the Web server rather than the are cookies created by the Web server rather than the
browserbrowser The The SessionIDSessionID is the value of the HTTP cookie that identifies the is the value of the HTTP cookie that identifies the
client’s sessionclient’s session This SessionID is used to identify a Session object on the serverThis SessionID is used to identify a Session object on the server
Retrieve a cookie from the HTTP header using the server variable Retrieve a cookie from the HTTP header using the server variable HTTP_COOKIE from a Web page using the server variables that has HTTP_COOKIE from a Web page using the server variables that has Trace enabledTrace enabled
The The HttpCookieCollection objectHttpCookieCollection object represents the cookie variables represents the cookie variables One type of cookie collection contains cookies that have been One type of cookie collection contains cookies that have been
generated on the server and transmitted to the client in the generated on the server and transmitted to the client in the Set-Cookie Set-Cookie headerheader
The Response.Cookies method actually sends the cookie to the The Response.Cookies method actually sends the cookie to the browser, which in turn writes the cookie to the client’s file system browser, which in turn writes the cookie to the client’s file system
The named group of cookies is also referred to as a dictionary cookie, The named group of cookies is also referred to as a dictionary cookie, and the individual cookies within it are sometimes referred to as and the individual cookies within it are sometimes referred to as cookie keyscookie keys
Internet Explorer 5 - users can disable client side cookies, and still Internet Explorer 5 - users can disable client side cookies, and still allow HTTP cookies.allow HTTP cookies.
Internet Explorer 6 - the cookie settings have been moved from the Internet Explorer 6 - the cookie settings have been moved from the Security settings to a Security settings to a Privacy SettingsPrivacy Settings
HTTP Cookies Storing cookies on the client is one of the methods that ASP.NET's session Storing cookies on the client is one of the methods that ASP.NET's session
state uses to associate requests with sessions. Cookies can also be used state uses to associate requests with sessions. Cookies can also be used directly to persist data between requests, but the data is then stored on the directly to persist data between requests, but the data is then stored on the client and sent to the server with every request. Browsers place limits on client and sent to the server with every request. Browsers place limits on the size of a cookie; therefore, only a maximum of 4096 bytes is guaranteed the size of a cookie; therefore, only a maximum of 4096 bytes is guaranteed to be acceptable. to be acceptable.
To make a cookie persistent between sessions, the To make a cookie persistent between sessions, the ExpiresExpires property on the property on the HttpCookieHttpCookie class has to be set to a date in the future. class has to be set to a date in the future.
Protected Sub Submit_Click(sender As Object, e As EventArgs)Protected Sub Submit_Click(sender As Object, e As EventArgs) Dim cookie As New HttpCookie("preferences2")Dim cookie As New HttpCookie("preferences2") cookie.Values.Add("ForeColor",ForeColor.Value)cookie.Values.Add("ForeColor",ForeColor.Value) ...... cookie.Expires = DateTime.MaxValue ' Never Expirescookie.Expires = DateTime.MaxValue ' Never Expires Response.AppendCookie(cookie)Response.AppendCookie(cookie) Response.Redirect(State("Referer").ToString())Response.Redirect(State("Referer").ToString())
End SubEnd Sub Store small amounts of volatile data in a nonpersistent cookie. The data is Store small amounts of volatile data in a nonpersistent cookie. The data is
stored on the client, sent to the server on each request, and expires when stored on the client, sent to the server on each request, and expires when the client ends execution. the client ends execution.
Store small amounts of non-volatile data in a persistent cookie. The data is Store small amounts of non-volatile data in a persistent cookie. The data is stored on the client until it expires and is sent to the server on each request. stored on the client until it expires and is sent to the server on each request.
Retrieving HTTP Cookies with ASP.NET Retrieve a cookie’s value—whether from a simple Retrieve a cookie’s value—whether from a simple
cookie or from a group of cookies—using the Request cookie or from a group of cookies—using the Request objectobject
<% Request.Cookies(“CookieName”) %> <% Request.Cookies(“CookieName”) %> To retrieve the value of a single cookie from a group of To retrieve the value of a single cookie from a group of
cookies, you must identify the name of the cookie group cookies, you must identify the name of the cookie group as well as the name of the individual cookieas well as the name of the individual cookie
<% Request.Cookies("GroupID")(“CookieName_n”) <% Request.Cookies("GroupID")(“CookieName_n”) %> %>
You can add additional cookies to the HTTP cookiesYou can add additional cookies to the HTTP cookies
Dim MyCookie As New Dim MyCookie As New HttpCookie("CookieEmail")HttpCookie("CookieEmail")
MyCookie.Value = txtEmail.ValueMyCookie.Value = txtEmail.Value
Response.Cookies.Add(MyCookie)Response.Cookies.Add(MyCookie)
Maintaining State Without HTTP Cookies HTTP cookies were used to link the client’s HTTP cookies were used to link the client’s
session to the Session object using the SessionIDsession to the Session object using the SessionID The Session The Session timeout propertytimeout property specifies when specifies when
the session ends if no activity occursthe session ends if no activity occurs The default value for the session timeout is 20 The default value for the session timeout is 20
minutesminutes The process of creating a cookieless application The process of creating a cookieless application
is known as is known as cookie mungingcookie munging The The cookieless propertycookieless property in the in the sessionState sessionState
nodenode in the web.config file is used to in the web.config file is used to determine if the session key should require determine if the session key should require cookiescookies
The Web Server appends any requested URL The Web Server appends any requested URL with the Session IDwith the Session ID
The ViewState Property of Server Controls ASP.NET provides the server-side notion of a view state for ASP.NET provides the server-side notion of a view state for
each control. each control. A control can save its internal state between requests using A control can save its internal state between requests using
the ViewState property on an instance of the class StateBag. the ViewState property on an instance of the class StateBag. The StateBag class provides a dictionary-like interface to The StateBag class provides a dictionary-like interface to
store objects associated with a string key. store objects associated with a string key. Occasionally your pages will contain UI state values that Occasionally your pages will contain UI state values that
aren't stored by a control. You can track values in ViewState aren't stored by a control. You can track values in ViewState using a programming syntax is similar to that for Session using a programming syntax is similar to that for Session and Cache:and Cache:
' save in ViewState ' save in ViewState ViewState("SortOrder") = "DESC"ViewState("SortOrder") = "DESC"' read from ViewState ' read from ViewState Dim SortOrder As String = Dim SortOrder As String =
CStr(ViewState("SortOrder"))CStr(ViewState("SortOrder")) Store small amounts of request-specific data in the view Store small amounts of request-specific data in the view
state. The data is sent from the server to the client and state. The data is sent from the server to the client and back. back.
Web Server Configuration Files
XML-based XML-based Global machine-level configuration file - named machine.cfg located Global machine-level configuration file - named machine.cfg located
in C:\WINNT\Microsoft.NET\Framework\v1.0. 3705\CONFIG\in C:\WINNT\Microsoft.NET\Framework\v1.0. 3705\CONFIG\machine.configmachine.config
Application configuration files - named Application configuration files - named Web.configWeb.config About thirty configuration settings configured as a node, and may About thirty configuration settings configured as a node, and may
include nested child nodesinclude nested child nodes root node root node - of the file is - of the file is <configuration><configuration> ConfigSectionsConfigSections node - is used to identify the configuration sections node - is used to identify the configuration sections
and section groupsand section groups system.websystem.web section group - delineates Web configuration settings section group - delineates Web configuration settings
Sample TagsSample Tags <sessionState> - Responsible for configuring the session state HTTP <sessionState> - Responsible for configuring the session state HTTP
module.module. <globalization> - Responsible for configuring the globalization <globalization> - Responsible for configuring the globalization
settings of an application.settings of an application. <compilation> - Responsible for all compilation settings used by <compilation> - Responsible for all compilation settings used by
ASP.NET. ASP.NET. <trace> - Responsible for configuring the ASP.NET trace service. <trace> - Responsible for configuring the ASP.NET trace service. <browserCaps> - Responsible for controlling the settings of the <browserCaps> - Responsible for controlling the settings of the
browser capabilities component.browser capabilities component.
BrowserCaps (can also be in Machine.config)
<!-- For updates to this browser data visit cyScape, <!-- For updates to this browser data visit cyScape, Inc. at http://www.cyscape.com/browsercaps -->Inc. at http://www.cyscape.com/browsercaps -->
<browserCaps><browserCaps> <result <result
type="System.Web.HttpBrowserCapabilities" />type="System.Web.HttpBrowserCapabilities" /> <use var="HTTP_USER_AGENT" /><use var="HTTP_USER_AGENT" /> browser=Unknownbrowser=Unknown version=0.0version=0.0 majorversion=0majorversion=0 minorversion=0minorversion=0 frames=falseframes=false tables=falsetables=false cookies=falsecookies=false backgroundsounds=falsebackgroundsounds=false vbscript=falsevbscript=false javascript=falsejavascript=false javaapplets=falsejavaapplets=false activexcontrols=falseactivexcontrols=false … … xml=falsexml=false
<%@ Page Language="VB" %><%@ Page Language="VB" %><html><html><body style="font: 10pt verdana"><body style="font: 10pt verdana"> <h3>Retrieving Browser Capabilities</h3><h3>Retrieving Browser Capabilities</h3> Boolean ActiveXControls = <Boolean ActiveXControls = <
%=Request.Browser.ActiveXControls.ToString()%><br>%=Request.Browser.ActiveXControls.ToString()%><br>Boolean BackgroundSounds = <Boolean BackgroundSounds = <
%=Request.Browser.BackgroundSounds.ToString()%><br>%=Request.Browser.BackgroundSounds.ToString()%><br> Boolean Beta = <%=Request.Browser.Beta.ToString()%><br>Boolean Beta = <%=Request.Browser.Beta.ToString()%><br> String Browser = <%=Request.Browser.Browser%><br>String Browser = <%=Request.Browser.Browser%><br> Boolean CDF = <%=Request.Browser.CDF.ToString()%><br>Boolean CDF = <%=Request.Browser.CDF.ToString()%><br> Boolean Cookies = <%=Request.Browser.Cookies.ToString()%><br>Boolean Cookies = <%=Request.Browser.Cookies.ToString()%><br> Boolean Frames = <%=Request.Browser.Frames.ToString()%><br>Boolean Frames = <%=Request.Browser.Frames.ToString()%><br> Boolean JavaApplets = <%=Request.Browser.JavaApplets.ToString()Boolean JavaApplets = <%=Request.Browser.JavaApplets.ToString()
%><br>%><br> Boolean JavaScript = <%=Request.Browser.JavaScript.ToString()%><br>Boolean JavaScript = <%=Request.Browser.JavaScript.ToString()%><br> Int32 MajorVersion = <%=Request.Browser.MajorVersion.ToString()Int32 MajorVersion = <%=Request.Browser.MajorVersion.ToString()
%><br>%><br> Double MinorVersion = <%=Request.Browser.MinorVersion.ToString()Double MinorVersion = <%=Request.Browser.MinorVersion.ToString()
%><br>%><br> String Platform = <%=Request.Browser.Platform%><br>String Platform = <%=Request.Browser.Platform%><br> Boolean Tables = <%=Request.Browser.Tables.ToString()%><br>Boolean Tables = <%=Request.Browser.Tables.ToString()%><br> String Type = <%=Request.Browser.Type%><br>String Type = <%=Request.Browser.Type%><br> Boolean VBScript = <%=Request.Browser.VBScript.ToString()%><br>Boolean VBScript = <%=Request.Browser.VBScript.ToString()%><br> String Version = <%=Request.Browser.Version%><br>String Version = <%=Request.Browser.Version%><br></body></body></html></html>
Pages Configuration Node Allows you to configure settings that control how content is Allows you to configure settings that control how content is
delivered to the Web pagedelivered to the Web page BufferBuffer is an area in memory on the serveris an area in memory on the server enableSessionStateenableSessionState allows you to use the Session capabilities of allows you to use the Session capabilities of
ASP.NETASP.NET enableViewStateenableViewState is used to store data in the _VIEWSTATE hidden is used to store data in the _VIEWSTATE hidden
form field in the Web pageform field in the Web page enableViewStateMacenableViewStateMac is used to validate data using a one-way is used to validate data using a one-way
authentication code based on the MAC address of the serverauthentication code based on the MAC address of the server autoEventWireupautoEventWireup allows you to override the Page_OnLoad event allows you to override the Page_OnLoad event
The httpRuntime Configuration Node Properties:Properties:
executionTimeoutexecutionTimeout is the time that a resource is allowed to is the time that a resource is allowed to execute before the request times outexecute before the request times out
maxRequestLengthmaxRequestLength is the number of kilobytes that can be is the number of kilobytes that can be accepted from an HTTP requestaccepted from an HTTP request
UseFullyQualifiedRedirectURLUseFullyQualifiedRedirectURL property is used to fully property is used to fully qualify the URL when the client has been redirected to a qualify the URL when the client has been redirected to a new pagenew page
The AppSettings Configuration Node (also see earlier) To configure custom key/value pairs known as To configure custom key/value pairs known as
application variablesapplication variables
<appSettings><appSettings>
<add key="SN" value="Tara Store" /><add key="SN" value="Tara Store" />
<add key="CS" <add key="CS" value="Provider=Microsoft.Jet.OLEDB.4.0value="Provider=Microsoft.Jet.OLEDB.4.0; ;
Password='';Password='';
User ID=Admin;User ID=Admin;
Data Source= Data Source=
C:\Inetpub\wwwroot\Ch8\TS.mdb;" />C:\Inetpub\wwwroot\Ch8\TS.mdb;" />
</appSettings></appSettings>
Compiler Node Configuration
Settings related to the language compilers use to build the applicationSettings related to the language compilers use to build the application defaultLanguagedefaultLanguage property property changes the default compiler from changes the default compiler from
Visual Basic .NETVisual Basic .NET
<%@ Page Language="vb"> <%@ Page Language="vb"> debugdebug property property is used to configure the application to show the is used to configure the application to show the
source code files when you are debugging the applicationsource code files when you are debugging the application explicitexplicit property property requires you to declare your variables before requires you to declare your variables before
they are usedthey are used strictstrict property property requires you to declare the data type of a variable requires you to declare the data type of a variable
before it is usedbefore it is used
Trace Node Configuration Identify the data sent during a request or response.Identify the data sent during a request or response. Enable Tracing for a specific page
<%@ Page trace=true Language="vb" AutoEventWireup="false" Codebehind="Write_Trace_Info.aspx.vb" Inherits="Opt_Monitor.Write_Trace_Info"%>
enabledenabled property property - allows the application to turn tracing on. - allows the application to turn tracing on. Tracing information will be stored. Information can be accessed through http://site/trace.axd
localOnlylocalOnly property property - results are only displayed to the localhost at - results are only displayed to the localhost at http://localhost/http://localhost/. .
traceModetraceMode property property - allows you to sort trace results based on time using - allows you to sort trace results based on time using SortByTime or by category using SortByCategorySortByTime or by category using SortByCategory
pageOutputpageOutput property property - allows you to display the trace results at the bottom of - allows you to display the trace results at the bottom of Web page Web page
trace utility programtrace utility program - access the tracing data stored in memory using - access the tracing data stored in memory using TraceToolTraceTool
requestLimitrequestLimit property property - number of trace results stored - number of trace results stored
Configuration Setting:<trace enabled=“true" requestLimit="10"
pageOutput=“true" traceMode="SortByTime" />
Debugging using TRACE Page and Application tracingPage and Application tracing
Easy to include “debug” statements Easy to include “debug” statements Add trace directive at top of page - <%@ Page Add trace directive at top of page - <%@ Page
Trace=“True”%>Trace=“True”%> Trace.write Trace.write
to write data to the trace stack to write data to the trace stack trace.write("CategoryName", "Value") methodtrace.write("CategoryName", "Value") method CategoryNameCategoryName - a string that contains the text label to be - a string that contains the text label to be
displayed in the trace output displayed in the trace output valuevalue - a string that contains the data and appears in the - a string that contains the data and appears in the
Message columnMessage column Add trace calls throughout pageAdd trace calls throughout page Trace.Write(“MyApp”, “Button Clicked”)Trace.Write(“MyApp”, “Button Clicked”) Trace.Warn(“MyApp”, “Value: “ + value)Trace.Warn(“MyApp”, “Value: “ + value)
Collect request detailsCollect request details Server control treeServer control tree Server variables, headers, cookiesServer variables, headers, cookies Form/Querystring parametersForm/Querystring parameters
Access page from browserAccess page from browser Access tracing URL within appAccess tracing URL within app
http://localhost/approot/Trace.axd http://localhost/approot/Trace.axd oror at at localhost/Configuration/Tracing/TraceTool/trace.axdlocalhost/Configuration/Tracing/TraceTool/trace.axd
Using the Exception Classes to Identify Errors
.NET System class contains an Exception class that is base class for all .NET System class contains an Exception class that is base class for all exceptionsexceptions
An exception is an object that is thrown when a predefined error occursAn exception is an object that is thrown when a predefined error occurs The The SystemException classSystemException class is the base class for all predefined exceptions is the base class for all predefined exceptions The The ApplicationException classApplicationException class provides a base class to create user-defined provides a base class to create user-defined
exception objectsexception objects Common exceptions that are handled with the Common exceptions that are handled with the Try-Catch-Finally statementTry-Catch-Finally statement
include the SqlException, OleDbException, NullReferenceException, and include the SqlException, OleDbException, NullReferenceException, and IndexOutOfRangeException exceptionsIndexOutOfRangeException exceptions
SqlExceptionSqlException is thrown when an error occurs from the SQL Server DataAdapter is thrown when an error occurs from the SQL Server DataAdapter This exception is often thrown when the database server does not existThis exception is often thrown when the database server does not exist The The OleDbExceptionOleDbException is thrown when an error occurs from the OleDbDataAdapter is thrown when an error occurs from the OleDbDataAdapter The The NullReferenceExceptionNullReferenceException is thrown when null object is referenced is thrown when null object is referenced The The IndexOutOfRangeExceptionIndexOutOfRangeException is thrown when an Array object is improperly is thrown when an Array object is improperly
indexedindexed The The ExternalException ExternalException class allows other classes to indirectly inherit from the class allows other classes to indirectly inherit from the
SystemException classSystemException class When the Exception object is created from the SystemEXception class, several When the Exception object is created from the SystemEXception class, several
properties and methods are exposed that can help identify the source of the properties and methods are exposed that can help identify the source of the errorerror
Properties are exposed from objects derived from the SystemException classProperties are exposed from objects derived from the SystemException class The Message property (returns error message)The Message property (returns error message) - TargetSite property (method - TargetSite property (method
name that threw error)name that threw error) Helplink property (helpfile name)Helplink property (helpfile name) - StackTrace property (location in stack)- StackTrace property (location in stack) InnerException property (first exception in stack)InnerException property (first exception in stack) - ToString method - ToString method
Application-level Error Handling You can retrieve information about an exception that was You can retrieve information about an exception that was
thrown from the thrown from the HttpContext classHttpContext class The The ToString methodToString method provides the details of the exception object provides the details of the exception object To retrieve the last exception thrown by the application, you can To retrieve the last exception thrown by the application, you can
use the use the GetLastError methodGetLastError method from the from the HttpServerUtility classHttpServerUtility class You can clear all errors from the application using the You can clear all errors from the application using the ClearError ClearError
methodmethod from the HttpContext class from the HttpContext class You can redirect the client to a new URL when a general You can redirect the client to a new URL when a general
exception occurs by using the exception occurs by using the Error propertyError property of the HttpContext of the HttpContext classclass Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) ' Fires when an error occurs
Context.ClearError() Dim EM As String = Server.GetLastError.Message() Dim EHL As String = Server.GetLastError.HelpLink() Dim AST As String = Server.GetLastError.StackTrace() Dim ETS As String = Server.GetLastError.ToString() Context.ClearError() Response.Redirect("CustomError.aspx?" & _ "EM=" & Server.UrlEncode(EM) & _ "&EHL=" & Server.UrlEncode(EHL) & _ "&AST=" & Server.UrlEncode(AST) & _ "&ETS=" & Server.UrlEncode(ETS)) End Sub
In Global.asax.vb
Using the Try-Catch-Finally to Handle Specific Errors The The Try-Catch-Finally statementTry-Catch-Finally statement allows you to allows you to
attempt to run a block of code that detects when attempt to run a block of code that detects when an error has occurredan error has occurred
The goal of the Try-Catch-Finally statement is to The goal of the Try-Catch-Finally statement is to gracefully recover when an exception occursgracefully recover when an exception occurs
The The Try statementTry statement attempts to run a block of attempts to run a block of codecode
If there is an error, an exception object is createdIf there is an error, an exception object is created The The Catch statementCatch statement catches the error as an catches the error as an
exception objectexception object You can use the Catch statement multiple times You can use the Catch statement multiple times
to catch multiple types of errorsto catch multiple types of errors The The Finally statementFinally statement allows you to execute a allows you to execute a
block of codeblock of code
Caching Page Output CachingPage Output Caching: :
Pages That Don’t Change FrequentlyPages That Don’t Change Frequently Dramatic Performance Increase Dramatic Performance Increase
<%@ OutputCache Duration= "500" %><%@ OutputCache Duration= "500" %>
Fragment CachingFragment Caching Dynamic Portions of a Page - Data That Doesn’t Change FrequentlyDynamic Portions of a Page - Data That Doesn’t Change Frequently User ControlUser Control
<%@ OutputCache Duration=“60" %><%@ OutputCache Duration=“60" %> Programmatically Cache DataProgrammatically Cache Data
Cache.Insert( Cache.Insert( Key, Value, CacheDependency, _Key, Value, CacheDependency, _AbsoluteExpiration, SlidingExpiration, Priority, PriorityDecay, CallbackAbsoluteExpiration, SlidingExpiration, Priority, PriorityDecay, Callback))
KeyKey = String used to look up the cached item = String used to look up the cached item
ValueValue = Item or object to store in the cache = Item or object to store in the cache
CacheDependencyCacheDependency = Cache item can automatically expire when a file, = Cache item can automatically expire when a file, directory, ordirectory, or
other cache item changesother cache item changesAbsoluteExpirationAbsoluteExpiration = Cache item can expire at some fixed time (midnight, = Cache item can expire at some fixed time (midnight,
for example)for example)SlidingExpirationSlidingExpiration = Cache item can expire after a certain amount of = Cache item can expire after a certain amount of
inactivityinactivityPriorityPriority = When forcing items from the cache, which items should go first = When forcing items from the cache, which items should go firstPriorityDecayPriorityDecay = Within a given priority range, does this item expire fast or = Within a given priority range, does this item expire fast or
slowslow
Page Output Caching Page Output CachingPage Output Caching - technique of caching ASP.NET pages on Web server - technique of caching ASP.NET pages on Web server When a Web page is compiled, the page is stored on the server in the cache, When a Web page is compiled, the page is stored on the server in the cache,
When another request is made for the same page, the page from the cache is When another request is made for the same page, the page from the cache is returned to the clientreturned to the client
Storing Web pages in cache increases performance of Web applicationStoring Web pages in cache increases performance of Web application Configure Page Output Cache in Web page by using Configure Page Output Cache in Web page by using OutPutCache directiveOutPutCache directive Parameters that configure Page Output Cache include Duration & Parameters that configure Page Output Cache include Duration &
VaryByParamVaryByParam The The DurationDuration identifies how long the document is left in cache (in seconds) identifies how long the document is left in cache (in seconds) Use Use VaryByParam propertyVaryByParam property to cache parameters passed with page request to cache parameters passed with page request There are additional techniques that allow you to control how page is cachedThere are additional techniques that allow you to control how page is cached The The VaryByCustomVaryByCustom attribute allows you to create custom strings to determine attribute allows you to create custom strings to determine
if a page should be cachedif a page should be cached The The VaryByHeaderVaryByHeader attribute allows you to control the cached settings based attribute allows you to control the cached settings based
on the HTTP header that is sent with the requeston the HTTP header that is sent with the request You can also use fragment caching to cache one or more user controls on the You can also use fragment caching to cache one or more user controls on the
Web page with the Web page with the VaryByControl VaryByControl attributeattribute
Overview of ASP.NET Security Methods
AuthenticationAuthentication is the process of validating the identity of the is the process of validating the identity of the requestrequest
Authentication mode property can be set to Windows, Passport Forms, Authentication mode property can be set to Windows, Passport Forms, or None. If the mode is set to None you can setup your own custom or None. If the mode is set to None you can setup your own custom authenticationauthentication
Define the authentication method used with the Internet Service Define the authentication method used with the Internet Service ManagerManager
AnonymousAnonymous - default anonymous user - default anonymous user IUSR_MachineNameIUSR_MachineName BasicBasic authentication, the username and password are sent as clear authentication, the username and password are sent as clear
text over the Internet, unless you encrypt the login with SSL text over the Internet, unless you encrypt the login with SSL encryptionencryption
WithWith WindowsWindows authentication, the username and password are not authentication, the username and password are not sent over the Internetsent over the Internet
Passport Passport is a single sign-on passport identity system created by Microsoftis a single sign-on passport identity system created by Microsoft Passport service authenticates the user, sends a cookie backPassport service authenticates the user, sends a cookie back The benefit to the user is that they only have to login once to access The benefit to the user is that they only have to login once to access
multiple resources and servicesmultiple resources and services Passport at http://www.passport.com/Passport at http://www.passport.com/ The redirectURL property is the URL to redirect the user to when the The redirectURL property is the URL to redirect the user to when the
request is not authenticated such as login pagerequest is not authenticated such as login page
Forms-based Authentication
Forms AuthenticationForms Authentication is a cookie-based authentication method is a cookie-based authentication method When you log in using an ASP.NET form, the Web Server checks When you log in using an ASP.NET form, the Web Server checks
the IP address and domain in the host header of the requestthe IP address and domain in the host header of the request The user may be validated using the credential list within the The user may be validated using the credential list within the
configuration files, or the request may be validated against an configuration files, or the request may be validated against an
XML file, a database, an in-memory structure, an LDAP XML file, a database, an in-memory structure, an LDAP
directory, or even a Web servicedirectory, or even a Web service ASP.NET determines if an ASP.NET determines if an authentication cookieauthentication cookie is present in the is present in the
TCP/IP header packetTCP/IP header packet If there is no cookie, the client is redirected to the login pageIf there is no cookie, the client is redirected to the login page Once the user has been authenticated, a cookie is added to Once the user has been authenticated, a cookie is added to
the header packet to identify future requeststhe header packet to identify future requests There is no username or password stored in the HTTP There is no username or password stored in the HTTP
cookie. The HTTP cookie merely identifies the clientcookie. The HTTP cookie merely identifies the client The first time the user sends a username and password, the The first time the user sends a username and password, the
cookie has not been createdcookie has not been created Therefore, you must use SSL to encrypt the login Therefore, you must use SSL to encrypt the login
information until the HTTP cookie is generatedinformation until the HTTP cookie is generated
Authorization Node Configuration
AuthorizationAuthorization is the process of ensuring that you only have access is the process of ensuring that you only have access to resources that are granted by the system administratorsto resources that are granted by the system administrators Windows NTFS file systemWindows NTFS file system - allows you to set permissions on - allows you to set permissions on
individual files and folders using an individual files and folders using an access control list (ACL) access control list (ACL) The The Identity nodeIdentity node is used to identify which resources can be is used to identify which resources can be
accessed after the user is authenticatedaccessed after the user is authenticated The The Impersonate propertyImpersonate property is used to indicate if impersonation is is used to indicate if impersonation is
allowedallowed identity nodeidentity node - used to impersonate a Windows user account - used to impersonate a Windows user account impersonateimpersonate property is used to indicate if impersonation is property is used to indicate if impersonation is
allowed allowed allow nodeallow node - is used to configure users that are allowed to - is used to configure users that are allowed to
access the application access the application deny nodedeny node - is used to configure users that are not allowed - is used to configure users that are not allowed
to access the application to access the application usersusers property - is used to identify the user property - is used to identify the user rolesroles property - is used to identify a group of users property - is used to identify a group of users
wildcard * - used to identify all users wildcard * - used to identify all users wildcard ? - used to identify the anonymous user wildcard ? - used to identify the anonymous user
Forms Node Configuration When the authentication mode is set to Forms, the When the authentication mode is set to Forms, the child node child node
formsforms configure the HTTP cookie configure the HTTP cookie Name propertyName property - identify the cookie that contains the ID of the - identify the cookie that contains the ID of the
user, default name is .ASPXAUTH. user, default name is .ASPXAUTH. Path propertyPath property - is the server path that is valid for the cookie. The - is the server path that is valid for the cookie. The
default path property is “/” to access the cookie from any default path property is “/” to access the cookie from any directory. directory.
TimeoutTimeout - is the valid duration of the cookie. The default timeout - is the valid duration of the cookie. The default timeout value is 30 minutes. value is 30 minutes.
loginUrl loginUrl - is the page to redirect the user if they have not been - is the page to redirect the user if they have not been authenticated. The default is “login.aspx”. authenticated. The default is “login.aspx”.
ProtectionProtection - to protect the data in the HTTP cookie. Possible - to protect the data in the HTTP cookie. Possible values are All, None, Encryption, or Validation.values are All, None, Encryption, or Validation.
MachineKey Node Configuration The The machineKey nodemachineKey node is used to identify a value and method to is used to identify a value and method to
encrypt data on the serverencrypt data on the server The The validationKeyvalidationKey is used as part of the hash algorithm, so only is used as part of the hash algorithm, so only
ASP.NET applications that have the validationKey can use the dataASP.NET applications that have the validationKey can use the data The The decryptionKeydecryptionKey is used to guarantee that nontrusted sources is used to guarantee that nontrusted sources
can’t read the textcan’t read the text
Credentials Node Configuration The The credentials nodecredentials node is an optional child node of the Forms node to is an optional child node of the Forms node to
provide the credentials for users that may access the application provide the credentials for users that may access the application resourcesresources
passwordformat propertypasswordformat property - to specify the encryption method used to - to specify the encryption method used to encrypt the credentials. The possible values are Clear, SHA1, and encrypt the credentials. The possible values are Clear, SHA1, and MD5. SHA1 and MD5 store the password as a hash valueMD5. SHA1 and MD5 store the password as a hash value
user nodeuser node is a child node of the credentials node to identify users is a child node of the credentials node to identify users name propertyname property identifies the username identifies the username passwordpassword identifies the user’s password identifies the user’s password Once the user is validated, you can access that user’s identity Once the user is validated, you can access that user’s identity
informationinformation The following sample code displays the user’s name and the The following sample code displays the user’s name and the
authentication method used in the Web pageauthentication method used in the Web pageIf User.identity.IsAuthenticated thenIf User.identity.IsAuthenticated then
Message.Text = "Welcome Member: " & _Message.Text = "Welcome Member: " & _user.identity.name & _user.identity.name & _". You were authenticated using: " & _". You were authenticated using: " & _User.identity.AuthenticationType & "."User.identity.AuthenticationType & "."ElseElseMessage.Text = "Welcome Stranger!"Message.Text = "Welcome Stranger!"
End ifEnd if
Validating User Credentials
A Users Credentials File is an XML file to store user A Users Credentials File is an XML file to store user information such as e-mail and password information such as e-mail and password
The general process is to retrieve the user login information, The general process is to retrieve the user login information, retrieve the XML data, and locate the user within the XML fileretrieve the XML data, and locate the user within the XML file Then, if the user appears, validate the userThen, if the user appears, validate the user If the user is not validated, they are redirected by the Web If the user is not validated, they are redirected by the Web
configuration file to the login pageconfiguration file to the login page In the following exercises, you will import login.aspx, In the following exercises, you will import login.aspx,
home.aspx and XMLUsers.xml. Then, you will change the home.aspx and XMLUsers.xml. Then, you will change the configuration files to reflect the new user authentication configuration files to reflect the new user authentication modelmodel
Create a new WebForm named default.aspx Create a new WebForm named default.aspx In the Page_Load procedure enterIn the Page_Load procedure enter
Import the login.aspx, home.aspx, and XMLUsers.xml Import the login.aspx, home.aspx, and XMLUsers.xml In In XMLUsers.xmlXMLUsers.xml add your username and password to the add your username and password to the
list of users list of users
Use XML Based Validation