Fork me on GitHub

asp.net状态管理小示例

   开学了,一直拖到今天才决定来学校, 这个期间变懒了许多,没有做什么,只是有点闷骚型的真实感悟。己所不欲勿施于人,人性本自私,但要宽容与大度,钱永远不够,亲情弥足珍贵。

   本来不打算写博客了,但是开学校时间有比较多,还是打算继续写点东西,写东西的时候心也会安静很多,这里做一个asp.net的综合小例子拿出来给新学习的同学看看,全部 集中在一个程序里了可能有点凌乱。当然里面涉及到几处关于sqlserver,sessionstate等相关的服务和config文件的配置,但是由于简单,估计大家也会所以也就不写出来了。

     页面显示效果如下:

  例子很简单而且也很基础就直接贴代码了,如果有需要补充说明的以后补充的写点注释:

  前台页面代码如下:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="statusManager.aspx.cs" Inherits="statusManager"%>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml">
 4 <head runat="server">
 5     <title>状态管理测试</title>
 6     <style type="text/css">
 7         .style1
 8         {
 9             position: absolute;
10             top: 100px;
11             left: 232px;
12             height: 250px;
13             bottom: 166px;
14             width: 769px;
15         }
16     </style>
17 </head>
18 <body>
19     <form id="form1" runat="server">
20     <div style="text-align: center; background-color: Burlywood;" class="style1">
21         <br />
22         <asp:Button ID="btn_SaveCookie" runat="server" Text="保存Cookie" OnClick="btn_SaveCookie_Click" />
23         &nbsp;
24         <asp:Button ID="btn_ReadCookie" runat="server" Text="读取Cookie" OnClick="btn_ReadCookie_Click" />
25         &nbsp;
26         <asp:Button ID="btn_ModifyCookie" runat="server" Text="修改Cookie" OnClick="btn_ModifyCookie_Click" />
27         &nbsp;
28         <asp:Button ID="btn_DeleteCookie" runat="server" Text="删除Cookie" OnClick="btn_DeleteCookie_Click" />
29         <br />
30         <br />
31         <asp:Button ID="btn_WriteSession" runat="server" Text="写入Session" OnClick="btn_WriteSession_Click" />
32         &nbsp;
33         <asp:Button ID="btn_ReadSession" runat="server" Text="读取Session" OnClick="btn_ReadSession_Click" />
34         <br />
35         <br />
36         <asp:Button ID="btn_GetDataFromsqlServerCache" runat="server" Text="验证数据库缓存读取数据" 
37             OnClick="btn_GetDataFromsqlServerCache_Click" Width="156px" />
38         &nbsp;
39         <asp:Button ID="Button1" runat="server" Text="从缓存中读取数据" OnClick="btn_GetDataFromCache_Click" />
40         &nbsp;<asp:Button ID="btn_GetDataFromDb" runat="server" Text="从数据库中读取数据" OnClick="btn_GetDataFromDb_Click" />
41         <br />
42         <br />
43         <asp:Button ID="btn_InsertNoExpirationCache" runat="server" Text="插入永不过期的缓存" OnClick="btn_InsertNoExpirationCache_Click" />
44         &nbsp;<asp:Button ID="btn_InsertAbsoluteExpirationCache" runat="server" Text="插入绝对时间过期的缓存"
45             OnClick="btn_InsertAbsoluteExpirationCache_Click" />
46         &nbsp;<asp:Button ID="btn_InsertSlidingExpirationCache" runat="server" Text="插入变化时间过期的缓存"
47             OnClick="btn_InsertSlidingExpirationCache_Click" />
48         <br />
49         <br />
50         <asp:Button ID="btn_ModifyFile" runat="server" Text="修改文件" OnClick="btn_ModifyFile_Click" />&nbsp;<asp:Button ID="btn_AddFileDependencyCache" runat="server" Text="插入文件依赖" OnClick="btn_AddFileDependencyCache_Click" />
51         &nbsp;<asp:Button ID="btn_SetPageCache" runat="server" Text="遍历删除所有的缓存" 
52             onclick="btn_SetPageCache_Click" />
53         &nbsp;<asp:Button ID="btn_DependencySqlserver" runat="server" Text="插入数据库缓存依赖" 
54             onclick="btn_DependencySqlserver_Click" Width="158px" />
55     &nbsp;<asp:Button ID="btn_RemoveCache" runat="server" Text="移除单个缓存" 
56             onclick="btn_RemoveCache_Click" />
57         <br />
58         <br />
59         <asp:Button ID="btn_PassiveUpdate" runat="server" Text="缓存被动更新" 
60             onclick="btn_PassiveUpdate_Click" Width="100px" />
61     &nbsp;
62         <asp:Button ID="btn_InsertActiveUpdataCache" runat="server" Text="缓存自动更新" 
63             onclick="btn_InsertActiveUpdataCache_Click" Width="101px" />
64         &nbsp;
65          <asp:Button ID="btn_AddViewState" runat="server" Text="设置ViewState" 
66             onclick="btn_AddViewState_Click" Width="106px" />
67          &nbsp;&nbsp;
68          <asp:Button ID="btn_decompileViewState" runat="server" Text="反编译ViewState" 
69             onclick="btn_decompileViewState_Click" Width="121px" />
70     &nbsp;
71         <asp:Button ID="btn_ControlState" runat="server" Text="ControlState读取字符" 
72             onclick="btn_ControlState_Click" Width="148px" />
73         <br />
74         <br />
75 &nbsp;</div>
76     </form>
77 </body>
78 </html>

后台代码如下:

  1 using System;
  2 using System.Web;
  3 using System.Data;
  4 using System.Data.SqlClient;
  5 using System.Configuration;
  6 using System.Diagnostics;
  7 using System.IO;
  8 using System.Web.Caching;
  9 using System.Collections;
 10 using System.Xml.Serialization;
 11 
 12 public partial class statusManager : System.Web.UI.Page
 13 {
 14     protected void Page_Load(object sender, EventArgs e)
 15     {
 16         if (!IsPostBack)
 17         {
 18             Application.Lock();
 19             Application["PageClick"] = (int)Application["PageClick"] + 1;
 20             Application.UnLock();
 21             Response.Write(string.Format("页面单击数:{0}<br/>", Application["PageClick"]));
 22             Response.Write(string.Format("用户访问数:{0}<br/>", Application["UserVisit"]));
 23         }
 24     }
 25     protected void btn_SaveCookie_Click(object sender, EventArgs e)
 26     {
 27         //HttpCookie SingValueCookie = new HttpCookie("test1", "单值Cookie");
 28         HttpCookie SingValueCookie = new HttpCookie("test1");
 29         SingValueCookie.Value = "单值Cookie";
 30         SingValueCookie.Expires = DateTime.Now.AddDays(1);
 31         Response.Cookies.Add(SingValueCookie);
 32         HttpCookie MultValueCookie = new HttpCookie("test2");
 33         // MultValueCookie.Values["key1"]= "value1";
 34         //MultValueCookie.Values["key2"]="value2";
 35         MultValueCookie.Values.Add("key1", "value1");
 36         MultValueCookie.Values.Add("key2", "value2");
 37         MultValueCookie.Expires = DateTime.Now.AddDays(1);
 38         Response.Cookies.Add(MultValueCookie);
 39     }
 40     protected void btn_ReadCookie_Click(object sender, EventArgs e)
 41     {
 42         HttpCookie SingleValueCookie = Request.Cookies["test1"];
 43         if (SingleValueCookie != null)
 44         {
 45             Response.Write(string.Format("Key:{0} Value:{1} Expires:{2}<br/>", "test1", SingleValueCookie.Value, SingleValueCookie.Expires));
 46         }
 47         HttpCookie MultValueCookie = Request.Cookies["test2"];
 48         if (MultValueCookie != null)
 49         {
 50             Response.Write(string.Format("Key:{0} Value:{1} Expires:{2}<br/>", "test2", MultValueCookie.Value, MultValueCookie.Expires));
 51             foreach (string subkey in MultValueCookie.Values.AllKeys)
 52             {
 53                 Response.Write(string.Format("Key:{0} Value:{1} Expires:{2}<br/>", "test2", MultValueCookie.Values[subkey], MultValueCookie.Expires));
 54             }
 55         }
 56     }
 57     protected void btn_DeleteCookie_Click(object sender, EventArgs e)
 58     {
 59         //HttpCookie SingleValueCookie = Request.Cookies["test1"];
 60         //SingleValueCookie.Expires = DateTime.Now.AddDays(-1);
 61         //Response.Cookies.Add(SingleValueCookie);
 62         foreach (string key in Request.Cookies.AllKeys)
 63         {
 64             HttpCookie cookie = Request.Cookies[key];
 65             cookie.Expires = DateTime.Now.AddDays(-1);
 66             Response.Cookies.Add(cookie);
 67         }
 68     }
 69     protected void btn_ModifyCookie_Click(object sender, EventArgs e)
 70     {
 71         HttpCookie SingleValueCookie = Request.Cookies["test1"];
 72         SingleValueCookie.Value = "修改后的单值Cookie";
 73         Response.Cookies.Add(SingleValueCookie);
 74     }
 75     /*存储SessionID(24位)的模式
 76      * 1.Cookie (默认的)
 77      * 2.URL:cookie功能开启与否不再影响Session的使用,缺点是不能在使用绝对链接
 78      * 存储Session内容的模式
 79      * 1.InPrc(默认)Session默认存储在IIS进程中(Web服务器内存)
 80      * 2.StateServer Session存储在独立的windows服务进程中,可以不是Web服务器
 81      * 3.sqlServer Session存储在sqlServer数据库的表中(sqlserver服务器)
 82      */
 83     protected void btn_WriteSession_Click(object sender, EventArgs e)
 84     {
 85 
 86         //MyUser user = new MyUser();
 87         //user.sUserName = "小朱";
 88         //user.Age = 25;
 89         Session["SimpleString"] = "这是一个简单的Session测试";
 90         MyUser user = new MyUser { sUserName = "小朱", Age = 25 };
 91         Session["CustomClass"] = user;
 92         // Session.Abandon();
 93         //IEnumerator SessionEnum = Session.Keys.GetEnumerator();
 94         //while (SessionEnum.MoveNext())
 95         //{
 96         //  //  Response.Write(Session[SessionEnum.Current.ToString()].ToString()+"<br/>");
 97         //}
 98 
 99         //    DataSet ds = new DataSet();
100         //    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ForumConnString"].ToString()))
101         //    {
102         //        SqlDataAdapter da = new SqlDataAdapter("select * from tbUser;select * from tbTopic; select * from tbBoard",conn);
103         //        da.Fill(ds);
104         //    }
105         //    ArrayList al = new ArrayList();
106         //    for (int i = 0; i < 10000000; i++)
107         //    {
108         //        al.Add(ds);
109         //    }
110         //    Session["largeData"] = al;
111     }
112     protected void btn_ReadSession_Click(object sender, EventArgs e)
113     {
114         if (Session["SimpleString"] != null)
115         {
116             string str = Session["SimpleString"].ToString();
117             Response.Write(str + "<br/>");
118         }
119         else
120         {
121             Response.Write("读取当前字符串失败<br/>");
122         }
123         if (Session["CustomClass"] == null)
124         {
125             Response.Write("读取当前字符串失败<br/>");
126         }
127         else
128         {
129             MyUser user = Session["CustomClass"] as MyUser;
130             Response.Write(user.ToString() + "<br/>");
131         };
132     }
133 
134     /*Cache提供的过期策略 
135      * 永不过期
136      * 绝对时间过期,缓存在某一时间过期
137      * 变化时间过期,缓存在某一时间内未访问则超时过期,这个和Session有点类似,比如我们可设定缓存5分钟没有人访问则过期
138      * 依赖过期 缓存依赖与数据库或者文件中的内容。一旦数据库或者文件的内容发生变动,则缓存自动过期
139      * 被动更新 缓存过期以后自动更新
140      * 主动更新 缓存过期以后在回调方法中更新。
141      */
142     protected void btn_GetDataFromCache_Click(object sender, EventArgs e)
143     {
144         InsertRecord();
145         Stopwatch sw = new Stopwatch();
146         sw.Start();
147         if (Cache["Data"] == null)
148         {
149             Response.Write("缓存无效<br/>");
150         }
151         else
152         {
153             DataSet ds = Cache["Data"] as DataSet;
154             Response.Write(string.Format("查询结果:  {0}<br/>", ds.Tables[0].Rows[0][0]));
155             Response.Write(string.Format("耗费时间:  {0}<br/>", sw.ElapsedTicks));
156         }
157     }
158     private void InsertRecord()
159     {
160         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnString"].ToString()))
161         {
162             conn.Open();
163             using (SqlCommand cmd = conn.CreateCommand())
164             {
165                 cmd.CommandText = "insert into CacheTest(Test)values('Test')";
166                 cmd.ExecuteNonQuery();
167             }
168         }
169     }
170     protected void btn_GetDataFromDb_Click(object sender, EventArgs e)
171     {
172         InsertRecord();
173         Stopwatch sw = new Stopwatch();
174         sw.Start();
175 
176         DataSet ds = GetData();
177         Response.Write(string.Format("查询结果:  {0}<br/>", ds.Tables[0].Rows[0][0]));
178         Response.Write(string.Format("耗费时间:  {0}<br/>", sw.ElapsedTicks));
179     }
180     private DataSet GetData()
181     {
182         DataSet ds = new DataSet();
183         using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnString"].ToString()))
184         {
185             conn.Open();
186             using (SqlCommand cmd = conn.CreateCommand())
187             {
188                 cmd.CommandText = "select count(*) from CacheTest";
189                 SqlDataAdapter da = new SqlDataAdapter(cmd);
190                 da.Fill(ds);
191             }
192             return ds;
193         }
194     }
195     protected void btn_InsertNoExpirationCache_Click(object sender, EventArgs e)
196     {
197         DataSet ds = GetData();
198         // Cache["Data"] = ds;
199         Cache.Insert("Data", ds);
200     }
201     protected void btn_InsertAbsoluteExpirationCache_Click(object sender, EventArgs e)
202     {
203         DataSet ds = GetData();
204         Cache.Insert("Data", ds, null, DateTime.Now.AddSeconds(10), TimeSpan.Zero);
205     }
206     protected void btn_InsertSlidingExpirationCache_Click(object sender, EventArgs e)
207     {
208         DataSet ds = GetData();
209         Cache.Insert("Data", ds, null, DateTime.MaxValue, TimeSpan.FromSeconds(10));
210     }
211     protected void btn_ModifyFile_Click(object sender, EventArgs e)
212     {
213         using (FileStream fs = new FileStream(Server.MapPath("test.txt"), FileMode.Append, FileAccess.Write))
214         {
215             using (StreamWriter sw = new StreamWriter(fs))
216             {
217                 sw.WriteLine(DateTime.Now.ToString());
218             }
219         }
220     }
221     protected void btn_AddFileDependencyCache_Click(object sender, EventArgs e)
222     {
223         CacheDependency cd = new CacheDependency(Server.MapPath("test.txt"));
224         DataSet ds = GetData();
225         Cache.Insert("Data", ds, cd);
226     }
227     protected void btn_DependencySqlserver_Click(object sender, EventArgs e)
228     {
229         SqlCacheDependency scd = new SqlCacheDependency("TestDB", "CacheTest");
230         DataSet ds = GetData();
231         Cache.Insert("Data", ds, scd);
232     }
233     protected void btn_SetPageCache_Click(object sender, EventArgs e)
234     {
235         IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
236         while (CacheEnum.MoveNext())
237         {
238             Cache.Remove(CacheEnum.Key.ToString());
239         }
240     }
241     protected void btn_RemoveCache_Click(object sender, EventArgs e)
242     {
243         Cache.Remove("Data");
244 
245     }
246     protected void btn_GetDataFromsqlServerCache_Click(object sender, EventArgs e)
247     {
248         Stopwatch sw = new Stopwatch();
249         sw.Start();
250         if (Cache["Data"] == null)
251         {
252             Response.Write("缓存无效<br/>");
253         }
254         else
255         {
256             DataSet ds = Cache["Data"] as DataSet;
257             Response.Write(string.Format("查询结果:  {0}<br/>", ds.Tables[0].Rows[0][0]));
258             Response.Write(string.Format("耗费时间:  {0}<br/>", sw.ElapsedTicks));
259         }
260     }
261     protected void btn_PassiveUpdate_Click(object sender, EventArgs e)
262     {
263         InsertRecord();
264         DataSet ds = new DataSet();
265         Stopwatch sw = new Stopwatch();
266         sw.Start();
267         if (Cache["Data"] == null)
268         {
269             ds = GetData();
270             Cache.Insert("Data", ds, null, DateTime.Now.AddSeconds(10), TimeSpan.Zero);
271         }
272         else
273         {
274             ds = Cache["Data"] as DataSet;
275         }
276         Response.Write(string.Format("查询结果:  {0}<br/>", ds.Tables[0].Rows[0][0]));
277         Response.Write(string.Format("耗费时间:  {0}<br/>", sw.ElapsedTicks));
278     }
279     protected void btn_InsertActiveUpdataCache_Click(object sender, EventArgs e)
280     {
281         DataSet ds = GetData();
282         Cache.Insert("Data", ds, null, DateTime.Now.AddSeconds(10), TimeSpan.Zero, CacheItemPriority.Default, CacheItemRemovedCallback);
283     }
284     public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
285     {
286         DataSet ds = GetData();
287         Cache.Insert(key, value, null, DateTime.Now.AddSeconds(10), TimeSpan.Zero, CacheItemPriority.Default, CacheItemRemovedCallback);
288     }
289     protected void btn_AddViewState_Click(object sender, EventArgs e)
290     {
291         ViewState["test1"] = "这是一个简单的ViewState测试";
292         MyUser user = new MyUser { sUserName = "小朱", Age = 25 };
293         ViewState["test2"] = user;
294     }
295     protected void btn_decompileViewState_Click(object sender, EventArgs e)
296     {
297         Response.Write(new System.Text.UTF8Encoding(true).GetString(Convert.FromBase64String(Request["__VIEWSTATE"])));
298     }
299     protected void btn_ReadViewState_Click(object sender, EventArgs e)
300     {
301         MyUser user = ViewState["test2"] as MyUser;
302         Response.Write(string.Format("{0}-{1} <br/>", user.sUserName, user.Age));
303     }
304     protected void btn_ControlState_Click(object sender, EventArgs e)
305     {
306         PageStatePersister.ControlState = "这是一个ControlState测试";
307         Response.Write(PageStatePersister.ControlState.ToString());
308     }
309 }
310 
311 [Serializable]
312 class MyUser
313 {
314     public string sUserName { get; set; }
315     public int Age { set; get; }
316     public override string ToString()
317     {
318         return string.Format("姓名:{0},年龄 {1}", sUserName, Age);
319     }
320 }

此外差点丢掉一个全局配置文件,主要是用来演示Application的使用,代码如下:
<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        //在应用程序启动时运行的代码
        Application["PageClick"] = 0;
        Application["UserVisit"] = 0;
    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //在应用程序关闭时运行的代码

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        //在出现未处理的错误时运行的代码

    }

    void Session_Start(object sender, EventArgs e) 
    {
        //在新会话启动时运行的代码
        Application.Lock();
        Application["UserVisit"] = (int)Application["UserVisit"] + 1;
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e) 
    {
        //在会话结束时运行的代码。 
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
        // InProc 时,才会引发 Session_End 事件。如果会话模式 
        //设置为 StateServer 或 SQLServer,则不会引发该事件。

    }
       
</script>

 

posted @ 2012-08-29 22:32  Halower  阅读(1229)  评论(1编辑  收藏  举报