首页  ·  知识 ·  云计算
访问量和在线人数
网友       编辑:dezai   图片来源:网络
1.建一个表,标的第一列字段Number,int类型 2.在web.config编辑连接数据库的字符串:b

1.建一个表,标的第一列字段Number,int类型
2.在web.config编辑连接数据库的字符串:

<connectionStrings>
<add name="northwindConnectionString" connectionString="DataSource=.;
InitialCatalog=northwind;User ID=sa;Password=sa" providerName="System.Data.SqlClient" />
</connectionStrings>
3.添加新项--->全局应用程序集:Global.asax,文件内容如下:
<%@ Application Language="C#" Debug=true%>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("select * from users", con);
int count = Convert.ToInt32(cmd.ExecuteScalar());

con.Close();
Application["total"] = count;
Application["online"] = 0;
}

void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["northwindConnectionString"].ConnectionString;
con.Open();
SqlCommand cmd = new SqlCommand("update users set Number=" + Application["total"].ToString(), con);
cmd.ExecuteNonQuery();
con.Close();

}

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

}

void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
Session.Timeout = 5; //设置Session的有效时间,可根据需要修改
Application.Lock();
Application["total"] = (int)Application["total"] + 1;
Application["online"] = (int)Application["online"] + 1;
Application.UnLock();


}

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


}

</script>
4.调用
调用方式1----在源代码里编辑:
<asp:Label ID="Label1" runat="server">当前在线&nbsp;<font color=red><%=Application["online"]%></font>&nbsp;人</asp:Label>
<asp:Label ID="Label2" runat="server">总访问量:&nbsp;<font color=red><%=Application["total"]%></font>&nbsp;</asp:Label>


调用方式2----在设计编辑:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
int i = (int)Application.Get("total");
Label2.Text = "在线人数:" + i.ToString();
}
//也可以这样:
// Label2.Text = "总访问人数" + Application["total"].ToString();
}

本文作者:网友 来源:网络
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读
也许感兴趣的
我们推荐的
主题最新
看看其它的