Saturday 19 October 2013

Single User login at a time any where with cache in asp.net

On Login Page-
Globle Define--  public System.Data.DataTable dtSessionGlobal = new DataTable();

  if (Cache["UserSessions"] != null)
        {
            dtSessionGlobal = (DataTable)Cache["UserSessions"];
        }
        else
        {
            dtSessionGlobal.Columns.Add("UserName");
            dtSessionGlobal.Columns.Add("SessionID");
            Cache["UserSessions"] = dtSessionGlobal;
        }

        EventArgs ee = new EventArgs();
        if (Session["username"] == null)
        {        
            btnsessionout_Click(sender, ee);
            //Response.Redirect("~/SignIn Users", false);
        }


On Logout Button-

 protected void btnsessionout_Click(object sender, EventArgs e)
    {
        string UserName =Session["UName"]==null ? "" : Session["UName"].ToString();
        Application[UserName] = null;
        if (dtSessionGlobal.Rows.Count > 0)
        {

            System.Data.DataRow[] dr = dtSessionGlobal.Select(" UserName='" + Session["UName"] + "'");// AND SessionID='" + Session.SessionID + "'
            if (dr.Length > 0)
            {
                foreach (DataRow drRow in dr)
                {
                    dtSessionGlobal.Rows.Remove(drRow);
                }
            }
        }
     
        Cache["UserSessions"] = dtSessionGlobal;

    }




At All Pages-

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dtSessionGlobal = new DataTable();
        if (Cache["UserSessions"] != null)
        {
            dtSessionGlobal = (DataTable)Cache["UserSessions"];
        }
     
        if (!IsPostBack)
        {
            if (dtSessionGlobal.Rows.Count > 0)
            {
                System.Data.DataRow[] dr = dtSessionGlobal.Select(" UserName='" + Session["UName"] + "' AND SessionID<>'" + Session.SessionID + "'");
                if (dr.Length > 0)
                {
                    Response.Redirect("~/SignIn Users");
                }
                else if (dtSessionGlobal.Select(" UserName='" + Session["UName"] + "'").Length == 0)
                {
                    Response.Redirect("~/SignIn Users");
                }
            }
            else
            {
                Session.Abandon();
                Response.Redirect("~/SignIn Users");
            }
}

No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...