.Net 新手之global.asax - application 的用法 (1) 今天 .Net 新手看到了gloabl.asax 的用法,試了幾次後,上來寫寫筆記,感覺上 global.asax 這一個檔案集合了 Web Application 中的所有共用事件,我依網路上提供的範例做了練習,並稍微改寫一下下:
首先請先建立在專案的目錄中,一個名為 global.asax 的檔案,檔案內容如下:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(Object sender, EventArgs e) {
}
void Application_OnBeginRequest(Object sender, EventArgs E)
{
Response.Write("歡迎光臨<br>");
}
protected void Application_OnEndRequest()
{
Response.Write("<hr>This page was served at " +DateTime.Now.ToString());
}
protected void Application_Error(Object sender, EventArgs e)
{
Response.Write("<span >");
Response.Write("資料庫忙碌中<hr></font>");
Response.Write("<font face=\"Arial\" size=\"2\">");
Server.ClearError();
}
</script>
在 Application_Error 裡頭,也可以將 Error message 寫入 log file 或是以 email 呈現在網頁上,以下是我在網路上所看到的範例:
void Application_Error(object sender, EventArgs e)
{
string Message = "";
Exception ex = Server.GetLastError();
Message = "發生錯誤的網頁:{0}錯誤訊息:{1}堆疊內容:{2}";
Message = String.Format(Message, Request.Path + Environment.NewLine, ex.GetBaseException().Message + Environment.NewLine, Environment.NewLine + ex.StackTrace);
//寫入事件撿視器,方法一
System.Diagnostics.EventLog.WriteEntry("WebAppError", Message, System.Diagnostics.EventLogEntryType.Error);
//寫入文字檔,方法二
System.IO.File.AppendAllText(Server.MapPath(string.Format("Log\\{0}.txt", DateTime.Now.Ticks.ToString())), Message);
//寄出Email,方法三
//此方法請參考System.Net.Mail.MailMessage
//清除Error
Server.ClearError();
Response.Write("系統錯誤,請聯絡系統管理員!!");
}
而我們也可以利用 web.config file,依據錯誤的類型而導到不同的網頁,xml tag 是 <customErrors>,如下:
<customErrors defaultRedirect="GeneralError.htm" mode="on">
<error statuscode="404" redirect="FileNotFound.htm"/>
</customErrors>
可以利用Application_BeginRequest,在使用瀏灠網頁時,記錄user id, current time(System.DateTime.Now) 以及 Path(Request.AppRelativeCurrentExecutionFilePath) 等等資訊,可以做為使用者的喜好分析或是檔案下載分析……
Part II
30 08 2008
How to create Scheduled Jobs in .net web applications.
Calling a function at predefined iteration of time has been one of the key requirements of web applications.
Example:
You want to automatically archive the data.
You want to automatically purge the data.
You want to automatically send the News Letters.
You want to take backup of the files or database etc.
Generally this type of functionality can be easily archived by creating and configuring scheduled jobs in SQL Server.
What if you are using the express edition of SQL Server?
You cannot take advantage of this feature because all the editions of SQL Server do not provide this functionality.
In this article I will explain how we can achieve this functionality using purely .Net framework class.
First of all let’s thanks System.Threading class. The main cream lies inside this class shipped in .Net Framework. Many of us usually do not use it but believe me its one of the most beautiful classes of the framework.
Anyways
Following are the steps which you need to perform:
Step 1) Create a class called Jobs.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
namespace
myScheduler
{
public
sealed
class
Jobs
{
public
Jobs(){}
public
static
void
DailyJob(object
state)
{
//Your dream goes here.
}
public
static
void
HourlyJob(object
state)
{
//Your dream goes here.
}
}
}
Jobs class includes the below two functions that will be called by our scheduler which we will create in the second step.
I have created two functions for this purpose.
DailyJob: Will be called daily by the scheduler.
HourlyJob: Will be called hourly by the scheduler.
Step 2) Create a class called Scheduler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using
System;
using
System.Threading;
namespace
myScheduler
{
public
sealed
class
Scheduler
{
public
Scheduler() { }
public
void
Scheduler_Start()
{
TimerCallback callbackDaily = new
TimerCallback(Jobs.DailyJob);
Timer dailyTimer = new
Timer(callbackDaily, null, TimeSpan.Zero, TimeSpan.FromHours(24.0));
TimerCallback callbackHourly = new
TimerCallback(Jobs.HourlyJob);
Timer hourlyTimer = new
Timer(callbackHourly, null, TimeSpan.Zero, TimeSpan.FromHours(1.0));
}
}
}
Scheduler class contains the actual mechanism for running jobs created in Jobs class in Step one.
Timer: Mechanism for executing method at specified time intervals. This method has 5 overloads which we can use as per our needs. Some of its parameters are
TimerCallback: Represents the method that you want to actually callback on at a particular interval of time.
State: Any type of object you want to pass to your callback method.
Due Time: Amount of delay after which callback will be invoked. TimeSpan.Zero means immediately.
Period: Time period between invocations of callback function.
Step 3) Add Global.asax file to your web project. In Application_Start event instantiate Scheduler object and make a call to Scheduler_Start() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<%@ Application Language="C#" %>
<%@ Import Namespace="myScheduler" %>
<script
RunAt="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Scheduler objmyScheduler = new Scheduler();
objmyScheduler.Scheduler_Start();
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// 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.
}
</script>
You are done.
How it works?
Whenever the applications is first started the Application_Start() in Global.asax is called and this calls Scheduler_Start() method which configures all the Jobs that we have created.
I have demonstrated a daily and hourly job in the above examples. In order to debug and test this code you need to wait for an Hour or a Day. Don’t panic I have done this intentionally. So in order to brush up your above learning’s prepare a job in Jobs.cs file that would be called every minute. Configure the callback and timer for your new job in Scheduler.cs file and enjoy the gist of scheduling.
Note: After running the project once do not forget to restart the IIS because Application_Start() wont be called every time you run your project. You know why?