Control number of user accesses in Windows Forms

0

I am creating an application in Windows Forms and would like to control for users to log in to a single station that is running the application. In an earlier version, my solution was to keep a shared folder on a server and when the user logged into the application I would open a txt file for editing with the username. In this way, when the same was to open from another station, when the application tried to write this file it generated an error. I would like to change this format because not all stations currently have access to the same shared folder.

    
asked by anonymous 10.06.2017 / 13:19

1 answer

1

You can create a column in your database of type boolean to when it is logged in.

Adding the table:

ALTER TABLE tabela_usuarios ADD 'logado' boolean;

To put the boolean as true when opening the form, you can use the Form_Load() event like this:

private void Form1_Load(object sender, EventArgs e)
{
    if (checklogado())
    {
        string comando = "UPDATE tabela_usuarios SET logado=1 WHERE usuario=@Usuario";
        var cmd = new MySqlCommand(comando, connection); //connection é a string da conexão.
        cmd.Parameters.AddWithValue("@Usuario", usuario); //usuario seria o nome de usuário da pessoa logada.
        cmd.ExecuteScalar();
    }
    else
    {
        MessageBox.Show("Você já está logado em outra máquina!", "Erro");
        Environment.Exit(0);
    }
}

bool checklogado()
{
    string comando = "SELECT logado FROM tabela_usuarios WHERE usuario=@Usuario";
    var cmd = new MySqlCommand(comando, connection);
    cmd.Parameters.AddWithValue("@Usuario", usuario);
    bool returno = Convert.ToBoolean(cmd.ExecuteScalar());
    return retorno;
}

To put the boolean as false when closing the form, you can use the Form_FormClosing() event this way:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    string comando = "UPDATE tabela_usuarios SET logado=0 WHERE usuario=@Usuario";
    var cmd = new MySqlCommand(comando, connection); //connection é a string da conexão.
    cmd.Parameters.AddWithValue("@Usuario", usuario); //usuario seria o nome de usuário da pessoa logada.
    cmd.ExecuteScalar();
}
    
10.06.2017 / 22:38