建立 Global.asax
自 VS 2005 後,系統就不會自動幫你建立 Global.asax 的檔案。因此,得自行建立。
1. 於開啟 Project 後,點選工具列上的 [Website] -> [Add New Item]
2. 選取 [Global Application Class]
3. 選取你所使用的 Language後,點選 [Add] 即新增完成。
修改 Global.asax 的內容範例如下
<%@ Application Language="VB" %>
<%@ Import namespace="System.Data.SqlClient" %>
<%@ Import namespace="System.Data" %>
<%@ Import namespace="System.io" %>
<script runat="server">
'目前應用程序啟動後發生
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
'連結資料庫,將瀏覽人數載入至 application("total")
'上線人數 application("online) 歸零
Dim SqlDS1 As SqlDataSource = New SqlDataSource
SqlDS1.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("Panel_alignmentConnectionString").ConnectionString
SqlDS1.SelectCommand = "select * from countPeople"
SqlDS1.DataSourceMode = SqlDataSourceMode.DataReader
Dim arg As New DataSourceSelectArguments
Dim dv As IDataReader = CType(SqlDS1.Select(arg), IDataReader)
If dv.Read() Then
Application("total") = dv.Item(0).ToString()
Application("online") = 0
Else
End If
dv.Close()
dv.Dispose()
SqlDS1.Dispose()
End Sub
'應用程序結束後會發生
' 只有在 IIS Restart 時才會觸發此動作。
Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application shutdown
End Sub
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
End Sub
'客戶端一連到server,事件發生
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
'Code that runs when a new session is started
'Application鎖定後,只有此session能夠對話
Application.Lock()
Application("total") = CType(Application("total"), Integer) + 1
Application("online") = CType(Application("online"), Integer) + 1
'對話完畢後,Application解鎖
Application.UnLock()
End Sub
'Session 結束後執行
'Session_End 事件中,因为 Session_End 才是页面级的事件,关闭页面时会触发该事件!
Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when a session ends.
' Note: The Session_End event is raised only when the sessionstate mode
' is set to InProc in the Web.config file. If session mode is set to StateServer
' or SQLServer, the event is not raised.
Application.Lock()
Application("online") = CType(Application("online"), Integer) - 1
Application.UnLock()
'連結資料庫,並更新瀏覽人數
Dim SqlDS1 As SqlDataSource = New SqlDataSource
SqlDS1.ConnectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("Panel_alignmentConnectionString").ConnectionString
SqlDS1.UpdateCommand = "UPDATE [countPeople] set count = " + Application("total").ToString
SqlDS1.Update()
SqlDS1.Dispose()
End Sub
</script>