简体   繁体   中英

Only allow a single login per user at a time

I am planning to code an application in C# that will only allow a single logged in user connection at a time. I will have a bit column in my SQL Database called LoggedOn and when logging in I will make it check if the database says loggedon = true such as.

if (Loggedon == true) {
    //Login things
} else {
    //it appears you are already logged on.
}

My problem is what if my program unexpectedly shuts down?

For example: Force shutdown or task manager end process, how can I run a query before someone does that to prevent no changes to my database.

I am not sure if I explained this well enough but heres my code

   protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        string myConnection = "******;";
        MySqlConnection conn = new MySqlConnection(myConnection);
        conn.Open();
        MySqlCommand comm = conn.CreateCommand();
        comm.CommandText = "INSERT INTO users LoggedOn = 'False' where username = '" + Form1.TextBoxText + "'";
        comm.ExecuteNonQuery();
        conn.Close();
        base.Dispose(disposing);
    }

Will this code cover all unexpected closes?is there any alternative easy fast ways of doing this?

Would an eventhandler fix my issue? such as this: http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

Along with the singleton and Loggedon persistance the following will help solve the application crashing scenarios:

If you want persist Loggedon in the database to ensure the user is not logged on to the system from anywhere else in the world you can have a heartbeat timer to keep the value of Loggedon updated. So ever few minutes the client will update the db to indicate user is still logged on. This will handle the situations in which the application is crashed.

There are other ways like: You could logoff all other sessions of the user if a user logs in again. Or you can have a watchdog timer instead of a heartbeat - very similar but watchdog essentially ensures long running sessions are infact active

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM