Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft ASP .NET Professional Projects - Premier Press

.pdf
Скачиваний:
147
Добавлен:
24.05.2014
Размер:
4.63 Mб
Скачать

Framework class the first time any resource within its application namespace is requested. This file cannot be requested directly by users, hence its contents are protected. The Global.asa and Global.asax files can coexist in the same virtual directory. This is to provide backward compatibility to ASP developers—ASP applications continue to use the Global.asa, whereas ASP.NET applications use Global.asax. However, the two files cannot share application and session state variables.

When you change the Global.asax file, the ASP.NET framework detects the change, completes all pending requests, and fires the Application_OnEvent event and reboots the application, which in turn clears all state information. This process is invisible to the user, who does not experience any downtime.

The Global.asax file has two events that are fired each time a request (or a postback) is made. These are the Application_BeginRequest and the

Application_EndRequest events. Code that must be executed at the beginning of each page can be placed in the Application_BeginRequest event. Figure 10.5 shows an example application that uses the Global.asax file. You can find the code in the "samples" folder for this chapter under the subfolder called "events." Please note that you must place the Global.asax file in the root directory of the virtual directory.

Global.asax

<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 Start Fired...<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> Global.asax Demo</h3>")

Response.Write("Begin Request Fired...<br>")

End Sub

Sub Application_EndRequest(Sender As Object, E As EventArgs)

Response.Write("End Request Fired...<br>")

End Sub </script>

Here is a Web page that calls it.

GlobalTest.aspx

<html>

<script language="VB" runat="server">

Sub Page_Load(Sender As Object, E As EventArgs)

Response.Write("Page.Load Fired...<br>")

End Sub

Sub Session_End(Sender As Object, E As EventArgs)

Session.Abandon()

Response.Redirect("GlobalTest.aspx")

End Sub

</script>

<body>

<form runat="server">

<input type="submit" Value="Refresh " runat="server"/>

<input type="submit" OnServerClick="Session_End" Value="End Session" runat="server"/>

<hr>

</form>

</body>

</html>

When the page is requested, the following sequence of events occurs:

1.Application_BeginRequest fires.

2.Session_Start fires.

3.Page Load fires.

4.Application_EndRequest fires. Figure 10.5 shows this.

Figure 10.5: Initial request.

When the page is refreshed, the following sequence of events occurs:

1.Application_BeginRequest fires.

2.Page Load fires.

3.Application_EndRequest fires. Figure 10.6 shows this.

Figure 10.6: Page refresh.

When the session is abandoned, the following sequence of events occurs:

1.Application_BeginRequest fires.

2.Session_Start fires.

3.Page Load fires.

4.Application_EndRequest fires.

When the session is abandoned, a new session is created and the Session_Start event is fired again. Figure 10.7 shows this.

Figure 10.7: Session abandoned.

Locking and UnLocking methods provide a safeguard against data corruption when multiple users are trying to update the same variable. The syntax for this is straightforward as shown in the following example:

<%

Application.Lock()

Application("hits") = CType(Application("hits") + 1, Int32)

Application.UnLock()

%>

When a page finishes execution or times out or an unhandled error occurs, the Application object is automatically unlocked.

Storing data in Application objects should be used wisely because significant resources, which might be put to better use elsewhere, might be absorbed. The Application object is not maintained across Web farms or Web gardens, which might be a limitation if you use these techniques.

Application or Session-Scoped Objects

You can define .NET Framework classes or classic COM components with either an appinstance, session, or application scope using the object tag. The appinstance scope implies that the object is specific to one instance of HttpApplication and is not shared.

<object id="id" runat="server" class=".NET Framework class Name" scope="appinstance"/>

<object id="id" runat="server" progid="Classic COM ProgID" scope="session"/>

<object id="id" runat="server" classid="Classic COM ClassID" scope="application"/>

Global.asax and Application State

You can store variables with application-level scope in the Global.asax file. The following example shows you how to store a DataView in an application variable, which can then be used throughout an application. The code for this example is available in the "..samples\Application" subfolder on the book's Web site at www.premierpressbooks.com/downloads.asp.

First code the Application_Start event of the Global.asax file as follows:

Global.asax

<%@ Import Namespace="System.IO" %>

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.OleDb" %>

<script language="VB" runat="server">

Sub Application_Start(Sender As Object, E As EventArgs)

' Do application startup code here

Dim dv As DataView

Dim i As integer

Dim myConnection As OleDbConnection

Dim myCommand As OleDbDataAdapter

Dim ds As New DataSet

Dim ConnStr As String

Dim SQL As String

ConnStr = "Provider=SQLOLEDB; Data Source=(local); Initial Catalog=ASP NET;User

ID=sa;"

myConnection = New OleDbConnection(ConnStr)

SQL = "select * from groups "

myCommand = New OleDbDataAdapter(SQL, myConnection)

myCommand.Fill(ds, "groups")

dv = new DataView(ds.Tables("groups"))

Application("Source") = dv

End Sub

</script>

I have extracted rows from the Groups table and populated a DataView with the resultset. I have then stored this DataView in an application variable called source. Note that I had to import System.Data and the System.ADO namespaces as I have to interact with the database.

I can now use the source application variable to populate a DataGrid in a web form as follows:

ApplicationState.aspx

<%@ Import Namespace="System.Data" %>

<%@ Import Namespace="System.Data.OleDb" %>

<html>

<script language="VB" runat="server">

Sub Page_Load(Src As Object, E As EventArgs)

Dim Source As DataView = Application("Source")

vSpan.InnerHtml = Source.Table.TableName

vGrid.DataSource = Source

vGrid.DataBind()

End Sub

</script>

<body>

<h3><font face="Verdana">DataSource in Application_OnStart</font></h3>

<h4><font face="Verdana"> Table: <span runat="server" id="vSpan"/></font></h4>

<ASP:DataGrid id="vGrid" runat="server"

Width="900"

BackColor="#ccccff"

BorderColor="black"

ShowFooter="false"

CellPadding=3

CellSpacing="0"

Font-Name="Verdana"

Font-Size="8pt"

HeaderStyle-BackColor="#aaaadd"

MaintainState="false"

/>

</body>

</html>

Figure 10.8 shows what the output looks like.

Figure 10.8: Application state.

Session State

While the Application object has not changed much from the previous versions of ASP, the Session object has seen a major updating. A session variable is a key-value pair that can be set and read for the duration of a user's session. For example, you can store a value in a session variable as follows:

Session("Name") = "Hersh Bhasin"

This session variable can then be accessed on a Web page as follows:

Dim ls_name As string

ls_name = Session("Name")

Each session is assigned a unique key, which is stored as an HTTP cookie and sent to the server on each request. The server reads the key and reestablishes the server state. The problem with this implementation is that clients might reject cookies for privacy or security reasons, which in turn disables state management. Another problem is that the state management is linked with the Web server (IIS) and when the Web server is recycled or fails, state information is lost. The third disadvantage is that each ASP server maintains its own state and unless the user returns to the same server, state will be lost. This would be the case where ISPs use proxy load balancing solutions.

ASP.NET solves these problems. The ASP.NET session state is process independent. This means that even if the Web server goes down or is restarted, state will still be maintained. The session content can alternatively be serialized to a SQL Server database and the state information can be reloaded after a machine failure. Using session variables has always been a problem on Web farms where multiple servers handle user requests. This is not a problem anymore. By moving to an out-of-process model, ASP.NET enables servers in the farm to share a session state process.

Session state settings are handled by settings in the web.config file. This file will be discussed in greater detail later in this chapter. The default file (called machine.config) is located in the ...\Framework\[Version]\ folder of the windows folder (for example the WinNt\Framework\[Version]\ folder). Each application can have its own web.config file and the settings specified there override the default machine.config file.

Six settings can be applied to configure session state (<sessionState>). These are

§mode: This can be InProc, SQLServer, and StateServer. The InProc stands for in-process and is the traditional ASP state management setting. There are two types of out-of-process modes: memory-based (StateServer) and SQL Server–based (SQLServer). I will be dealing with these in detail later.

§cookieless: This can be either True or False. The default is false. True implies that this mode is enabled.

§timeout: Length of time that a session is considered valid.

§sqlConnectionString: Used with the SQL Server mode. Specifies the

connection string to the ASP.NET state management database.

§StateConnectionString: Used when the mode is StateServer. This identifies the TCP/IP address and port of the Windows NT Service that provides the state management facilities.

I have created a test web form that I will be using in my discussion. This form has two simple functions, one for setting a session state variable and the other for retrieving the value of this variable. Here is what the code looks like:

Session.aspx

<html>

<Script runat="server">

Sub AddSession(sender As Object, e As EventArgs)

Session("MySession") = text1.Value

message.text = "Session Variable stored as : " +Session("MySession").ToString()

End Sub

Sub CheckVariable(sender As Object, e As EventArgs)

If Session("MySession") = "" Then

message.text = "Session Data has been erased"

Else

message.text = "Stored Session Variable is : " + Session("MySession").ToString()

End If

End Sub

</Script>

<body style="font: 10pt verdana; background-color:ivory">

<h1> Session State </h1>

<form runat=server>

<input id=text1 type=text runat=server><br><br>

<asp:Button id="Add" text="Add Session Variable" onclick="addSession" runat="server"

/>

<asp:Button id="Check" text="Check Session Variable" onclick="checkVariable" runat="server" />

<hr>

<asp:label id="message" runat="server" />

</form>

</body>

</html>

In-Process Mode

The in-process mode is the way ASP has always handled state management. State is managed within the process and is lost when the process is recycled. You might question the need for this mode when you have the out-of-process modes available, which are undoubtedly more efficient. The reason is performance. Out-of-process modes add additional overhead required to marshal data back and forth between processes or SQL Server. The following are the steps you will take to set up state management in this mode:

1.In web.config, set the mode attribute of sessionState to InProc (this is the default). When this setting is chosen, the only other web.config settings used are timeout and cookieless.

2.<configuration>

3.<system.web>

4.<sessionState

5.mode="InProc"

6.cookieless="false"

7.timeout="20"

8./>

9.</system.web>

</configuration>

10.Run Session.aspx. Store a session state value. Stop and restart the IIS using the command-line utility iisreset, which ships with IIS5 as follows:

C:\iisreset [computername] /RESTART (or simply issue the command iisreset from the command prompt)

11. Click the Check Session Variable button. You will have lost the session variable.

The code for this example is included in the ...\samples\sessionstate\inprocess subfolder for this chapter on the book's Web site at www.premierpressbooks.com/downloads.asp.

Out-of-Process Mode

Out-of-process mode maintains state in a separate process. This mode gives the reliability of a separate process with the performance advantage of reading and writing from memory. This state should be used when performance is important but when you can't guarantee which server a user uses to request an application. Here are the steps to set up this mode:

1.In web.config, set the mode attribute of sessionState to "StateServer." This tells ASP.NET to look for the ASP.NET state service at the server and port settings specified in the web.config file, which in this case is the local server.

2.<configuration>

3.<system.web>

4.<sessionState

5.mode="StateServer"

6.stateConnectionString ="tcpip=127.0.0.1:42424"

7.sqlConnectionString="data source=127.0.0.1;user id=sa;password="

8.cookieless="false"

9.timeout="20"

10./>

11.</system.web>

</configuration>

12.The ASP.NET SDK includes Windows NT service called aspnet_state, which is used by ASP.NET for out-of-process state management. Start this service by running this at the command prompt:

net start aspnet_state

Figure 10.9 shows what you will see.