使用ASP.NET Cache 的 CacheDependency 來偵測資料庫是否變更

使用ASP.NET Cache 的 CacheDependency 來偵測資料庫是否變更

小弟前陣子在討論區看到此篇文章...經過測試後有小小心得..分享給大家呀...

首先準備下列檔案:

CacheDependencyDataAdd.aspx,CacheDependencyDataAdd.aspx.cs→做資料更新網頁

CacheDependencyDemo.aspx,CacheDependencyDemo.aspx.cs→做資料瀏覽網頁

CheckChange.txt→檢查資料是否有更改的文字檔(內容空的)

--------------------------------------------------------------------------------------------------------------------------------

CacheDependencyDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CacheDependencyDemo.aspx.cs" Inherits="CacheDependencyDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>CacheDependencyDemo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>

CacheDependencyDemo.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using System.Data.SqlClient;

public partial class CacheDependencyDemo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Cache["data"] == null)
        {
            DataTable dt = GetData();
            //增加一個檢查資料是否有更改的文字檔
            CacheDependency file = new CacheDependency(Server.MapPath("CheckChange.txt"));
            Cache.Insert("data", dt, file, DateTime.MaxValue, TimeSpan.FromMinutes(10));
            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
            Response.Write("no Cache");
        }

        else
        {
            DataTable dt = (DataTable)Cache["data"];
            this.GridView1.DataSource = dt;
            this.GridView1.DataBind();
            Response.Write("use Cache");
        }

    }


    //取得資料
    protected DataTable GetData()
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

        {
            string queryString = "SELECT * FROM [user]";
            SqlCommand cmd = new SqlCommand(queryString, conn);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            return dt;
        }

    }

}

CacheDependencyDataAdd.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CacheDependencyDataAdd.aspx.cs" Inherits="CacheDependencyDataAdd" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>CacheDependencyDataAdd</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
            DataSourceID="SqlDataSource1" OnRowUpdated="GridView1_RowUpdated">
            <Columns>
                <asp:CommandField ShowEditButton="True" />
                <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
                    SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField DataField="tel" HeaderText="tel" SortExpression="tel" />
                <asp:BoundField DataField="gender" HeaderText="gender" SortExpression="gender" />
            </Columns>
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            SelectCommand="SELECT * FROM [user]" UpdateCommand="UPDATE [user] SET name = @name, tel = @tel, gender = @gender WHERE (id = @id)">
            <UpdateParameters>
                <asp:Parameter Name="name" />
                <asp:Parameter Name="tel" />
                <asp:Parameter Name="gender" />
            </UpdateParameters>
        </asp:SqlDataSource>
    
    </div>
    </form>
</body>
</html>

CacheDependencyDataAdd.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class CacheDependencyDataAdd : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        //資料有更新時,將檢查資料是否有更改的文字檔,做更新動作,如果沒做此動作資料不會馬上更新
        using (System.IO.StreamWriter StreamWriter1 = new StreamWriter(Server.MapPath("CheckChange.txt")))

        {
            //寫入一串文字,讓文字檔有異動過
            StreamWriter1.WriteLine(DateTime.Now.ToString());
        }

    }

}

執行如果:

CacheDependencyDemo

CacheDependencyDataAdd

參考網址:

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080402082116KNJ&fumcde=FUM20041006161839LRJ

http://aspnet.4guysfromrolla.com/articles/121802-1.aspx