Application對象


一、Application對象

1.定義:Application對象用於共享應用程序級信息,即多個用戶共享一個Application對象。

2.常用集合

Application對象的常用集合
集合 說明
Contents 用於訪問應用程序狀態集合中的對象名
StaticObject 確定某對象指定屬性的值或遍歷集合,並檢索所有靜態對象的屬性

3.常用屬性

Application對象的常用屬性
屬性 說明
AllKeys 返回全部Application對象變量名到一個字符串數組中
Count 獲取Application對象變量的數量
Item 允許使用索引或Application變量名稱傳回內容值

4.常用方法

Application對象的常用方法
方法 說明
Add 新增一個Application對象變量
Clear 清除全部Application對象變量
Lock 鎖定全部Application對象變量
Remove 使用變量名稱移除一個Application對象變量
RemoveAll 移除全部Application對象變量
Set 使用變量名更新一個Application對象變量的內容
UnLock 解除鎖定的Application對象變量

5.實例

(1)訪問計數器

前台代碼

    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>&nbsp;</div>
    </form>

后台代碼

    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "您是該網站的第" + Application["count"].ToString() + "個訪問者";
    }

Application對象的設置代碼

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // 在應用程序啟動時運行的代碼
        Application["count"] = 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["count"] = (int)Application["count"] + 1;
        Application.UnLock();
    }

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

結果

(2)聊天室

登陸頁面代碼

    <form id="form1" runat="server">
    <div>
        <table align="center" border="1" cellpadding="0" cellspacing="0" style="width: 199px;
            height: 100px">
            <tr>
                <td colspan="2" style="font-weight: bold; font-size: 16pt; color: #ffffff; background-color: #54a4ff;
                    text-align: center">
                    登錄</td>
            </tr>
            <tr>
                <td style="font-size: 9pt; background-color: #f7f6f3; text-align: right">
                    用戶名:</td>
                <td style="background-color: #f7f6f3; text-align: center">
                    <asp:TextBox ID="TextBox1" runat="server" Width="113px"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="background-color: #f7f6f3">
                </td>
                <td style="background-color: #f7f6f3; text-align: center">
                    <asp:Button ID="btnLogin" runat="server" Font-Size="9pt" OnClick="btnLogin_Click"
                        Text="登錄" />
                    &nbsp;
                    <asp:Button ID="btnExit" runat="server" Font-Size="9pt" OnClick="btnExit_Click" Text="退出" /></td>
            </tr>
        </table>
    
    </div>
    </form>
    protected void Page_Load(object sender, EventArgs e)
    {
        int P_int_judge = 0;
        P_int_judge = Convert.ToInt32(Request["value"]);
        if (!IsPostBack)
        {
            if (P_int_judge == 1)
                Response.Write("<script>alert('該用戶已經登錄!')</script>");
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Application.Lock();
        int P_int_num;     //在線人數
        string P_str_name; //登錄用戶
        string P_str_names;  //已在線的用戶名
        string[] P_str_user; //用戶在線數組
        P_int_num = int.Parse(Application["userNum"].ToString());
        if (TextBox1.Text == "")
        {
            Response.Write("<script>alert('用戶名不能為空')</script>");
            TextBox1.Focus();
        }
        else
        {
            P_str_name = TextBox1.Text.Trim();
            P_str_names = Application["user"].ToString();
            P_str_user = P_str_names.Split(',');
            for (int i = 0; i <= P_int_num - 1; i++)
            {
                if (P_str_name == P_str_user[i].Trim())
                {
                    int P_int_judge = 1;
                    Response.Redirect("Login.aspx?value=" + P_int_judge);                
                }
            }
            if (P_int_num == 0)
                Application["user"] = P_str_name.ToString();
            else
                Application["user"] = Application["user"] + "," + P_str_name.ToString();
            P_int_num += 1;
            Application["userNum"] = P_int_num;
            Session["userName"] = TextBox1.Text.Trim();
            Application.UnLock();
            Response.Redirect("Default.aspx");
        }
    }
    protected void btnExit_Click(object sender, EventArgs e)
    {
        Response.Write("<script>window.close();</script>");
    }

主頁面代碼

    <form id="form1" runat="server">
    <div style="text-align: center">
        <table style="width: 603px; height: 442px" border="1" cellpadding="0" cellspacing="0">
            <tr>
                <td colspan="2" style="height: 51px; font-size: 16pt; color: #ffffff; background-color: #54a4ff;">
                    聊天室</td>
            </tr>
            <tr>
                <td style="width: 404px; height: 18px">
                </td>
                <td align="left" style="width: 200px; height: 18px; font-size: 9pt; border-right-style: none; border-left-style: none;">
                    用戶列表:</td>
            </tr>
            <tr>
                <td style="width: 404px; height: 354px;">
                <iframe id="Iframe1" src="Content.aspx" runat="server" scrolling="no" noresize="noResize" frameborder="0" style="width: 400px; height: 350px"></iframe>
                </td>
                <td style="width: 200px; height: 354px;">
                <iframe id="Iframe2" src="List.aspx" runat="server" frameborder="no" noresize="noResize" scrolling="no" style="width: 200px; height: 350px"></iframe>
                </td>
            </tr>
            <tr>
                <td style="width: 400px" align="left">
                    <asp:TextBox ID="txtMessage" runat="server" Width="316px"></asp:TextBox><asp:Button ID="btnSend" runat="server" Text="發送" OnClick="btnSend_Click" /><asp:Button ID="btnExit" runat="server" Text="退出" OnClick="btnExit_Click" /></td>
                <td style="width: 200px">
                </td>
            </tr>
        </table>
    
    </div>
    </form>
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        int P_int_current = Convert.ToInt32(Application["current"]);
        Application.Lock();
        if (P_int_current == 0 || P_int_current > 20)
        {
            P_int_current = 0;
            Application["chats"] = Session["userName"].ToString() + "說:" + txtMessage.Text.Trim() + "(" + DateTime.Now.ToString() + ")";
        }
        else
        {
            Application["chats"] = Application["chats"].ToString() + "," + Session["userName"].ToString() + "說:" + txtMessage.Text.Trim() + "(" + DateTime.Now.ToString() + ")";
        }
        P_int_current += 1;
        Application["current"] = P_int_current;
        Application.UnLock();
    }
    protected void btnExit_Click(object sender, EventArgs e)
    { 
        
        Application.Lock();
        string P_str_userName = Application["user"].ToString();
        Application["user"] = P_str_userName.Replace(Session["userName"].ToString(), "");
        Application.UnLock();
        Response.Write("<script>window.opener=null;window.close();</script>");
    }

用戶聊天信息頁面代碼

    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtContent" runat="server" Height="345px" TextMode="MultiLine" Width="380px"></asp:TextBox></div>
    </form>
    protected void Page_Load(object sender, EventArgs e)
    {
        int P_int_current = Convert.ToInt32(Application["current"]);
        Application.Lock();
        string P_str_chats = Application["chats"].ToString();
        string[] P_str_chat = P_str_chats.Split(',');
        for (int i = P_str_chat.Length - 1; i >= 0; i--)
        {
            if (P_int_current == 0)
            {
                txtContent.Text = P_str_chat[i].ToString();
            }
            else
            {
                txtContent.Text = txtContent.Text + "\n" + P_str_chat[i].ToString();
            }
        }
        Application.UnLock();
    }

在線用戶頁面代碼

    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="lbList" runat="server" Height="345px" Width="180px"></asp:ListBox></div>
    </form>
    protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList ItemList = new ArrayList();
        Application.Lock();
        string P_str_names;       //已在線的用戶名
        string[] P_str_user;        //用戶在線數組
        int P_int_num =Convert.ToInt32(Application["userNum"]);
        P_str_names = Application["user"].ToString();
        P_str_user = P_str_names.Split(',');
        for (int i = (P_int_num - 1); i >= 0; i--)
        {
            if(P_str_user[i].ToString ()!="")
                ItemList.Add(P_str_user[i].ToString());
        }
        lbList.DataSource = ItemList;
        lbList.DataBind();
        Application.UnLock();
    }

Application對象設置的代碼

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // 在應用程序啟動時運行的代碼
        //建立用戶列表
        string user = "";//用戶列表
        Application["user"] = user;
        Application["userNum"] = 0;
        string chats = "";//聊天記錄  
        Application["chats"] = chats;
        //當前的聊天記錄數
        Application["current"] = 0;

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  在應用程序關閉時運行的代碼
        Application["user"] = "";
        Application["chats"] = "";

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // 在出現未處理的錯誤時運行的代碼

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // 在新會話啟動時運行的代碼

    }

    void Session_End(object sender, EventArgs e) 
    {
        // 在會話結束時運行的代碼。 
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式設置為
        // InProc 時,才會引發 Session_End 事件。如果會話模式設置為 StateServer 
        // 或 SQLServer,則不會引發該事件。

    }
       
</script>

結果

登錄頁面

聊天頁面

聊天信息頁面

在線用戶頁面

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM