閱讀262 返回首頁    go 技術社區[雲棲]


ASP.NET使用數據庫實現網站統計器

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml.Linq;
using System.Data.SqlClient;

//使用數據庫存在總訪問量,這樣一個網站統計器

//////////////////////////////////////////////////////////////////////////
//Global.asas.cs文件中,定義全局變量
//////////////////////////////////////////////////////////////////////////

namespace PPPP
{
    public class Global : System.Web.HttpApplication
    {
        private string strConnString = "server=localhost;database=REGISTER;uid=sa;pwd=tianshi520;";

        protected void Application_Start(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(strConnString);
            conn.Open();
            SqlCommand cmd = new SqlCommand("select * from visit", conn);
            int total = (int)(cmd.ExecuteScalar());
            conn.Close();

            Application["total"] = total;
            Application["online"] = 0;
            
        }


        protected void Session_Start(object sender, EventArgs e)
        {
            Session.Timeout = 1;
            Application.Lock();
            Application["total"] = Convert.ToInt32(Application["total"]) + 1;
            Application["online"] = Convert.ToInt32(Application["online"]) + 1;
            Application.UnLock();
        }


        protected void Session_End(object sender, EventArgs e)
        {
            // 在會話結束時運行的代碼。
            // 注意: 隻有在 Web.config 文件中的 sessionstate 模式設置為 
            // InProc 時,才會引發 Session_End 事件。如果會話模式設置為 StateServer 
            // 或 SQLServer,則不會引發該事件。
            Application.Lock();
            Application["online"] = Convert.ToInt32(Application["online"]) - 1;
            Application.UnLock();
        }

        protected void Application_End(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(strConnString);
            conn.Open();
            SqlCommand cmd = new SqlCommand("insert into visit values(" + Application["total"] + ")", conn);
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
}


//////////////////////////////////////////////////////////////////////////
//default.aspx中加入以下兩句代碼:
//當前在線人數:<asp:Label ID="online" runat="Server" /> <br />
//曆史訪問量:<asp:Label ID="total" runat="Server" />
//////////////////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////
//default.aspx.cs
//加入以下代碼:
/*
 * 
        protected void Page_Load(object sender, EventArgs e)
        {
            online.Text = Application["online"].ToString();
            total.Text = Application["total"].ToString();
        }
 * /
//////////////////////////////////////////////////////////////////////////

最後更新:2017-04-04 07:03:07

  上一篇:go Android Bitmap轉字節數組後大小問題
  下一篇:go 提高顯示布局文件的性能 4 - 提升ListView的性能