Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在不使用会员资格的情况下显示当前联机用户的列表_C#_Asp.net - Fatal编程技术网

C# 如何在不使用会员资格的情况下显示当前联机用户的列表

C# 如何在不使用会员资格的情况下显示当前联机用户的列表,c#,asp.net,C#,Asp.net,我需要显示当前登录到网站的用户列表。目前,它显示登录的用户数,但我想显示谁也登录了 在线。aspx: <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <div class="panel"> <div class="panel-headin

我需要显示当前登录到网站的用户列表。目前,它显示登录的用户数,但我想显示谁也登录了

在线。aspx:

<div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="panel-heading">
                        <h3 class="panel-title">Online Users</h3>
                    </div>
                    <div class="panel-body">
                        <asp:GridView
                            ID="gvOnlineUsers"
                            runat="server"
                            AutoGenerateColumns="False"
                            GridLines="None"
                            CssClass="table table-bordered table-hover">
                            <Columns>
                                <asp:BoundField DataField="country_name" HeaderText="Country" SortExpression="country_name"></asp:BoundField>
                                <asp:BoundField DataField="userCount" HeaderText="Users" ReadOnly="True" SortExpression="userCount"></asp:BoundField>
                            </Columns>
                        </asp:GridView>
                    </div>
                </div>
            </div>
        </div>
    </div>
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        txtUsername.Focus();
        GetAuthenticationInfo();

        if (!IsPostBack)
        {
            if (Request.Browser.Cookies)
            {
                /*Check if the cookies with name UM_LOGIN exists on user's machine.*/
                if (Request.Cookies["UM_LOGIN"] != null)
                {
                    string strQuery = "EXEC sp_um_getCredentials '" + Request.Cookies["UM_LOGIN"]["username"].ToString() + "','" + Request.Cookies["UM_LOGIN"]["password"].ToString() + "'";
                    DataSet ds = DataControl.GetDataSet(strQuery);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "LOCKED")
                        {
                            Toastr.ShowToast("Your account is locked due to invalid login attempts and will be unlocked after " + ds.Tables[0].Rows[0]["unlockTimeRemaining"].ToString() + " or else you may contact your administrator to unlock the account.", "Account Locked", Toastr.Type.Error);
                        }
                        else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "INVALID")
                        {
                            int intAttemptsLeft = 0;
                            intAttemptsLeft = maxLoginAttempts - int.Parse(ds.Tables[0].Rows[0]["failed_attempts"].ToString());
                            Toastr.ShowToast("Password is invalid. You are left with " + intAttemptsLeft + " more attempts.", "Error", Toastr.Type.Error);
                        }
                        else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "VALID")
                        {
                            loginStatus = 1;
                            Session["loginStatus"] = loginStatus;
                            Session["userId"] = ds.Tables[0].Rows[0]["user_id_pk"].ToString();
                            Session["firstName"] = ds.Tables[0].Rows[0]["first_name"].ToString();
                            Session["middleName"] = ds.Tables[0].Rows[0]["middle_name"].ToString();
                            Session["lastName"] = ds.Tables[0].Rows[0]["last_name"].ToString();
                            Session["userName"] = txtUsername.Text.Trim();
                            Session["password"] = txtPassword.Text.Trim();
                            Session["userRole"] = ds.Tables[0].Rows[0]["user_role"].ToString();

                            if (bool.Parse(ds.Tables[0].Rows[0]["user_status"].ToString()).Equals(true))
                            {
                                /*Store the log date and time*/
                                string strQueryLog = "EXEC sp_um_addLog " + Int32.Parse(Session["userId"].ToString());
                                DataControl.ExecuteNonQuery(strQueryLog);
                                Response.Redirect(ResolveUrl("default.aspx"), false);
                            }
                            else
                                Toastr.ShowToast("Your account is suspended", "", Toastr.Type.Error);
                        }
                    }
                    else
                    {
                        Toastr.ShowToast("Invalid Username or Password", "", Toastr.Type.Error);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

public void GetAuthenticationInfo()
{
    try
    {
        string strQuery = "SELECT remember_me, forgot_password, throttle_auth, maximum_attempts, company_name FROM tbl_settings";
        ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            if (bool.Parse(ds.Tables[0].Rows[0]["remember_me"].ToString()) == true)
            {
                divRememberMe.Visible = true;
                rememberMe = true;
            }
            else
            {
                divRememberMe.Visible = false;
                rememberMe = false;
            }
            if (bool.Parse(ds.Tables[0].Rows[0]["forgot_password"].ToString()) == true)
            {
                divForgotPassword.Visible = true;
                forgotPassword = true;
            }
            else
            {
                divForgotPassword.Visible = false;
                forgotPassword = false;
            }
            maxLoginAttempts = Int32.Parse(ds.Tables[0].Rows[0]["maximum_attempts"].ToString());
            Session["maxLoginAttempts"] = maxLoginAttempts;

            strCompanyName = ds.Tables[0].Rows[0]["company_name"].ToString();
            Session["companyName"] = strCompanyName;
            lblCompanyName.Text = strCompanyName;
        }
        else
        {
            //
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

protected void btnLogin_Click(object sender, EventArgs e)
{
    try
    {
        if (cbRememberMe.Checked && rememberMe == true)
        {
            if (Request.Browser.Cookies)
            {
                Response.Cookies["UM_LOGIN"].Expires = DateTime.Now.AddDays(360);
                Response.Cookies["UM_LOGIN"]["username"] = txtUsername.Text.Trim();
                Response.Cookies["UM_LOGIN"]["password"] = txtPassword.Text.Trim();
            }
            else
            {
                Response.Cookies["UM_LOGIN"]["username"] = txtUsername.Text.Trim();
                Response.Cookies["UM_LOGIN"]["password"] = txtPassword.Text.Trim();
            }
        }
        else
        {
            /*Clean the cookie UM_LOGIN.*/
            Response.Cookies["UM_LOGIN"].Expires = DateTime.Now.AddDays(-1);
        }
        string strQuery = "EXEC sp_um_getCredentials '" + txtUsername.Text.Trim() + "','" + txtPassword.Text.Trim() + "'";
        DataSet ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            /*Check whether the user account is locked or unlocked due to invalid login attempts OR valid OR invalid.*/
            if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "LOCKED")
            {
                Toastr.ShowToast("Your accounts is locked due to invalid login attempts and will be unlocked after " + ds.Tables[0].Rows[0]["unlockTimeRemaining"].ToString() + " or else you may contact your administrator to unlock the account.", "Account Locked", Toastr.Type.Error);
            }
            else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "INVALID")
            {
                int intAttemptsLeft = 0;
                intAttemptsLeft = maxLoginAttempts - int.Parse(ds.Tables[0].Rows[0]["failed_attempts"].ToString());
                Toastr.ShowToast("Password is invalid. You are left with " + intAttemptsLeft + " more attempts.", "Error", Toastr.Type.Error);
            }
            else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "VALID")
            {
                loginStatus = 1;
                Session["loginStatus"] = loginStatus;
                Session["userId"] = ds.Tables[0].Rows[0]["user_id_pk"].ToString();
                Session["firstName"] = ds.Tables[0].Rows[0]["first_name"].ToString();
                Session["middleName"] = ds.Tables[0].Rows[0]["middle_name"].ToString();
                Session["lastName"] = ds.Tables[0].Rows[0]["last_name"].ToString();
                Session["userName"] = txtUsername.Text.Trim();
                Session["password"] = txtPassword.Text.Trim();
                Session["userRole"] = ds.Tables[0].Rows[0]["user_role"].ToString();

                /*Check whether the user is active or not.*/
                if (bool.Parse(ds.Tables[0].Rows[0]["user_status"].ToString()) == true)
                {
                    string strQueryLog = "EXEC sp_um_addLog " + Int32.Parse(Session["userId"].ToString());
                    DataControl.ExecuteNonQuery(strQueryLog);
                    Response.Redirect(ResolveUrl("default.aspx"), false);
                }
                else
                {
                    Toastr.ShowToast("Your account is inactive, contact your administrator to activate the account.", "Account Suspended", Toastr.Type.Error);
                }
            }
        }
        else
        {
            Toastr.ShowToast("Invalid username or password.", "", Toastr.Type.Error);
        }
    }

    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}
void Application_Start(object sender, EventArgs e) 
{
    Application["OnlineUsers"] = 0;
}

void Session_Start(object sender, EventArgs e) 
{
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    Application.UnLock();
    Session.Timeout = 8;
}

void Session_End(object sender, EventArgs e) 
{
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
    Application.UnLock();
}    
然后在myGlobal.asax:

<div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="panel">
                    <div class="panel-heading">
                        <h3 class="panel-title">Online Users</h3>
                    </div>
                    <div class="panel-body">
                        <asp:GridView
                            ID="gvOnlineUsers"
                            runat="server"
                            AutoGenerateColumns="False"
                            GridLines="None"
                            CssClass="table table-bordered table-hover">
                            <Columns>
                                <asp:BoundField DataField="country_name" HeaderText="Country" SortExpression="country_name"></asp:BoundField>
                                <asp:BoundField DataField="userCount" HeaderText="Users" ReadOnly="True" SortExpression="userCount"></asp:BoundField>
                            </Columns>
                        </asp:GridView>
                    </div>
                </div>
            </div>
        </div>
    </div>
protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        txtUsername.Focus();
        GetAuthenticationInfo();

        if (!IsPostBack)
        {
            if (Request.Browser.Cookies)
            {
                /*Check if the cookies with name UM_LOGIN exists on user's machine.*/
                if (Request.Cookies["UM_LOGIN"] != null)
                {
                    string strQuery = "EXEC sp_um_getCredentials '" + Request.Cookies["UM_LOGIN"]["username"].ToString() + "','" + Request.Cookies["UM_LOGIN"]["password"].ToString() + "'";
                    DataSet ds = DataControl.GetDataSet(strQuery);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "LOCKED")
                        {
                            Toastr.ShowToast("Your account is locked due to invalid login attempts and will be unlocked after " + ds.Tables[0].Rows[0]["unlockTimeRemaining"].ToString() + " or else you may contact your administrator to unlock the account.", "Account Locked", Toastr.Type.Error);
                        }
                        else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "INVALID")
                        {
                            int intAttemptsLeft = 0;
                            intAttemptsLeft = maxLoginAttempts - int.Parse(ds.Tables[0].Rows[0]["failed_attempts"].ToString());
                            Toastr.ShowToast("Password is invalid. You are left with " + intAttemptsLeft + " more attempts.", "Error", Toastr.Type.Error);
                        }
                        else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "VALID")
                        {
                            loginStatus = 1;
                            Session["loginStatus"] = loginStatus;
                            Session["userId"] = ds.Tables[0].Rows[0]["user_id_pk"].ToString();
                            Session["firstName"] = ds.Tables[0].Rows[0]["first_name"].ToString();
                            Session["middleName"] = ds.Tables[0].Rows[0]["middle_name"].ToString();
                            Session["lastName"] = ds.Tables[0].Rows[0]["last_name"].ToString();
                            Session["userName"] = txtUsername.Text.Trim();
                            Session["password"] = txtPassword.Text.Trim();
                            Session["userRole"] = ds.Tables[0].Rows[0]["user_role"].ToString();

                            if (bool.Parse(ds.Tables[0].Rows[0]["user_status"].ToString()).Equals(true))
                            {
                                /*Store the log date and time*/
                                string strQueryLog = "EXEC sp_um_addLog " + Int32.Parse(Session["userId"].ToString());
                                DataControl.ExecuteNonQuery(strQueryLog);
                                Response.Redirect(ResolveUrl("default.aspx"), false);
                            }
                            else
                                Toastr.ShowToast("Your account is suspended", "", Toastr.Type.Error);
                        }
                    }
                    else
                    {
                        Toastr.ShowToast("Invalid Username or Password", "", Toastr.Type.Error);
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

public void GetAuthenticationInfo()
{
    try
    {
        string strQuery = "SELECT remember_me, forgot_password, throttle_auth, maximum_attempts, company_name FROM tbl_settings";
        ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            if (bool.Parse(ds.Tables[0].Rows[0]["remember_me"].ToString()) == true)
            {
                divRememberMe.Visible = true;
                rememberMe = true;
            }
            else
            {
                divRememberMe.Visible = false;
                rememberMe = false;
            }
            if (bool.Parse(ds.Tables[0].Rows[0]["forgot_password"].ToString()) == true)
            {
                divForgotPassword.Visible = true;
                forgotPassword = true;
            }
            else
            {
                divForgotPassword.Visible = false;
                forgotPassword = false;
            }
            maxLoginAttempts = Int32.Parse(ds.Tables[0].Rows[0]["maximum_attempts"].ToString());
            Session["maxLoginAttempts"] = maxLoginAttempts;

            strCompanyName = ds.Tables[0].Rows[0]["company_name"].ToString();
            Session["companyName"] = strCompanyName;
            lblCompanyName.Text = strCompanyName;
        }
        else
        {
            //
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}

protected void btnLogin_Click(object sender, EventArgs e)
{
    try
    {
        if (cbRememberMe.Checked && rememberMe == true)
        {
            if (Request.Browser.Cookies)
            {
                Response.Cookies["UM_LOGIN"].Expires = DateTime.Now.AddDays(360);
                Response.Cookies["UM_LOGIN"]["username"] = txtUsername.Text.Trim();
                Response.Cookies["UM_LOGIN"]["password"] = txtPassword.Text.Trim();
            }
            else
            {
                Response.Cookies["UM_LOGIN"]["username"] = txtUsername.Text.Trim();
                Response.Cookies["UM_LOGIN"]["password"] = txtPassword.Text.Trim();
            }
        }
        else
        {
            /*Clean the cookie UM_LOGIN.*/
            Response.Cookies["UM_LOGIN"].Expires = DateTime.Now.AddDays(-1);
        }
        string strQuery = "EXEC sp_um_getCredentials '" + txtUsername.Text.Trim() + "','" + txtPassword.Text.Trim() + "'";
        DataSet ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            /*Check whether the user account is locked or unlocked due to invalid login attempts OR valid OR invalid.*/
            if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "LOCKED")
            {
                Toastr.ShowToast("Your accounts is locked due to invalid login attempts and will be unlocked after " + ds.Tables[0].Rows[0]["unlockTimeRemaining"].ToString() + " or else you may contact your administrator to unlock the account.", "Account Locked", Toastr.Type.Error);
            }
            else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "INVALID")
            {
                int intAttemptsLeft = 0;
                intAttemptsLeft = maxLoginAttempts - int.Parse(ds.Tables[0].Rows[0]["failed_attempts"].ToString());
                Toastr.ShowToast("Password is invalid. You are left with " + intAttemptsLeft + " more attempts.", "Error", Toastr.Type.Error);
            }
            else if (ds.Tables[0].Rows[0]["lockStatus"].ToString() == "VALID")
            {
                loginStatus = 1;
                Session["loginStatus"] = loginStatus;
                Session["userId"] = ds.Tables[0].Rows[0]["user_id_pk"].ToString();
                Session["firstName"] = ds.Tables[0].Rows[0]["first_name"].ToString();
                Session["middleName"] = ds.Tables[0].Rows[0]["middle_name"].ToString();
                Session["lastName"] = ds.Tables[0].Rows[0]["last_name"].ToString();
                Session["userName"] = txtUsername.Text.Trim();
                Session["password"] = txtPassword.Text.Trim();
                Session["userRole"] = ds.Tables[0].Rows[0]["user_role"].ToString();

                /*Check whether the user is active or not.*/
                if (bool.Parse(ds.Tables[0].Rows[0]["user_status"].ToString()) == true)
                {
                    string strQueryLog = "EXEC sp_um_addLog " + Int32.Parse(Session["userId"].ToString());
                    DataControl.ExecuteNonQuery(strQueryLog);
                    Response.Redirect(ResolveUrl("default.aspx"), false);
                }
                else
                {
                    Toastr.ShowToast("Your account is inactive, contact your administrator to activate the account.", "Account Suspended", Toastr.Type.Error);
                }
            }
        }
        else
        {
            Toastr.ShowToast("Invalid username or password.", "", Toastr.Type.Error);
        }
    }

    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally { }
}
void Application_Start(object sender, EventArgs e) 
{
    Application["OnlineUsers"] = 0;
}

void Session_Start(object sender, EventArgs e) 
{
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    Application.UnLock();
    Session.Timeout = 8;
}

void Session_End(object sender, EventArgs e) 
{
    Application.Lock();
    Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;
    Application.UnLock();
}    
因此,基本上我想在
Gridview中显示当前登录的用户

更新

代码隐藏

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        if (Session["userRole"] != null || Session["userRole"].ToString() != "")
        {
            if (Session["userRole"].ToString().Equals("Admin"))
            {
                getOnlineUsers();
            }
            else
            {
                Response.Redirect(ResolveUrl("~/eh/401.aspx"), false);
            }
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
}
public void getOnlineUsers()
{
    try
    {
        string strQuery = "SELECT * FROM tbl_um_user WHERE user_id_pk = '" + Session["userId"].ToString() + "'";
        ds = DataControl.GetDataSet(strQuery);
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvOnlineUsers.DataSource = ds;
            gvOnlineUsers.DataBind();

            gvOnlineUsers.UseAccessibleHeader = true;
            gvOnlineUsers.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        else
        {
            ds.Dispose();
            gvOnlineUsers.DataSource = ds;
            gvOnlineUsers.DataBind();
        }
    }
    catch (Exception ex)
    {
        Toastr.ShowToast(ex.Message, "Error", Toastr.Type.Error);
    }
    finally
    {
        //ds.Dispose();
    }
}

你到底有什么问题好的,您从一个示例中获取这段代码,可能您不了解它的功能。。。实际上,如果您使用web表单或会话结束失败,这是不准确的。。如果您没有在进程内会话,可能会。要解决您的问题,您需要访问数据库并在那里编写信息。为了获得更好的结果,您甚至需要一个javascript部件每隔几秒钟检查一次页面是否仍然存在。我正在尝试显示当前登录到该网站的用户名。我已经用隐藏的代码编辑了我的问题,但没有显示当前登录的用户。也没有错误消息。您需要编写一些代码并将其保存到数据库中。我是否可以只获取登录用户的当前会话并将其显示在gridview中?此代码使用静态变量来保存它们,此静态变量是每个应用程序的,因此如果您将其托管在web garden上,您将永远看不到实际用户(并且每次重新启动池时都会丢失这些变量)。这是一个非常旧的示例,我认为它根本不正确。
Application[]
出于与旧版asp兼容的原因,请避免使用它。