Monday, 9 June 2014

Restrict multiple login of a single user in asp.net using cache


//On Master Page

protected void Page_Init(object sender, EventArgs e)
    {
        Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
    }


protected void Page_Load(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetAllowResponseInBrowserHistory(false);
        Request.Browser.Adapters.Clear();
       
}

Globly- Login Page

 public System.Data.DataTable dtSessionGlobal = new DataTable();

//On Page Load

 protected void Page_Load(object sender, EventArgs e)
    {      

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

//On All Page Load Event

 protected void Page_Load(object sender, EventArgs e)
    {
        
        DataTable dtSessionGlobal = new DataTable();
        if (Cache["UserSessions"] != null)
        {
            dtSessionGlobal = (DataTable)Cache["UserSessions"];
        }
        if (Session["username"] == null)
        {
            Response.Redirect("~/SignIn Users", false);
        }
        
        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");
                }
            }
}

No comments:

Post a Comment

How to highlight selected text in notepad++

  –> To highlight a block of code in Notepad++, please do the following steps step-1  :- Select the required text. step-2  :- Right click...