Login in C # with database [closed]

1

I'm trying to make a login panel, but it does not recognize the data recorded in the database.

Code:

SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\Trabalho Programação - VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True;Connect Timeout=30");

if (txtPass.Text == "" & txtUser.Text == "") //Campos vazios
{
    MessageBox.Show("Por favor preencha os dados de login!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}
else if(txtPass.Text == "") //txtPass vazia
{
    MessageBox.Show("Campo Password vazio!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}
else if(txtUser.Text == "") //txtuser vazia
{
    MessageBox.Show("Campo Utilziador vazio!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}
else
{
    MessageBox.Show("Por favor verifique os dados de login!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    txtPass.Text = "";
    txtUser.Text = "";
}


try
{
    con.Open();
    string user = txtUser.Text;
    string pass = txtPass.Text;
    SqlCommand cmd = new SqlCommand("SELECT * FROM Login WHERE User='" + txtUser.Text + "' AND Pass ='" + txtPass.Text + "'", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        this.Hide();
        //Abre Form Geral caso os dados do Login estejam certos
        Form1 btHome = new Form1();
        btHome.Show();
    }
}
catch(Exception error)
{
    MessageBox.Show(error.Message, "ERRO!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
    if  (con != null)
    {
        con.Close();
    }
}
    
asked by anonymous 17.05.2017 / 22:22

2 answers

0

Resolved login

SqlConnection sqlCon = null; //Conexão começa em Null

    private string strCmd = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True"; //Conection String da BD

    private string strSQL = string.Empty;

    public bool logado = false;




    public void Sign_in() //Class com as condições do Login
    {
        sqlCon = new SqlConnection(strCmd);

        //Declaração variavéis ( user = txtUser.txt & pass = txtPass.text)
        string senha, uti; 

        try
        {
            //Variáveis = TextBoxs
            uti = txtUser.Text;
            senha = txtPass.Text;

            strSQL = "SELECT COUNT(ID) FROM [Login] WHERE [User] = @utilizador AND [Pass] = @password";

            SqlCommand cmd = new SqlCommand(strSQL, sqlCon);

            cmd.Parameters.Add("@utilizador", SqlDbType.VarChar).Value = uti;
            cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = senha;

            sqlCon.Open(); //Abre a conexão com a BD

            int count = (int)cmd.ExecuteScalar(); 

            if(count > 0) //Login com sucesso
            {
                MessageBox.Show("Login realizado com sucesso!", "Parabéns!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                logado = true;
                this.Dispose();

            }
            else if (txtPass.Text =="" & txtUser.Text=="") //txtUser & txtPass vazia
            {
                MessageBox.Show("Por favor preencha os campos Utilizador & Password!", "Campos vazios!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUser.Focus();
                logado = false;
            }
            else if (txtUser.Text == "") //txtUser &vazia
            {
                MessageBox.Show("Por favor preencha o campo Utilizador!", "Campo Utilizador vazio!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUser.Focus();
                logado = false;
            }
            else if (txtPass.Text == "") //txtPass vazia
            {
                MessageBox.Show("Por favor preencha o campo Password!", "Campo Password vazio!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPass.Focus();
                logado = false;
            }
            else
            {
                MessageBox.Show("Dados de login errados. Por favor verifique os seus daods!", "Atenção!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                logado = false;

            }

        }
        catch(SqlException erro)
        {
            MessageBox.Show(erro + "");
        }
    
19.05.2017 / 15:30
3

Some comments:

If the password field is empty, why compel the user to retype the user? just set the cursor focus to the password field ... txtPass.Focus(); Equally for the opposite situation.

To check if a string is empty, I use String.IsNullOrEmpty(txtPass.Text);

Just below where you open the connection, you declare two variables:

string user = txtUser.Text;
string pass = txtPass.Text;

but do not use them at all.

And at the time of executing the SQL command, use parameters, and do not concatenate string in this way. The way SQL injection is is very easy.

I made a very simple code of how would a login screen in your case:

The main Application Form (which opens in the Main method with Application.Run ) should be its main form, not the login form. So I put the login dialog and if the result is OK, I continue with the application and open FormPrincipal , in your case Form1 or FormGeral.

Program:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        FormLogin formLogin = new FormLogin();
        if (formLogin.ShowDialog() == DialogResult.OK)
        {
            Application.Run(new FormPrincipal(formLogin.UsuarioLogado));
        }
    }
}

FormLogin: This would be the code for FormLogin :

public partial class FormLogin : Form
{
    public Usuarios UsuarioLogado { get; set; }

    public FormLogin()
    {
        InitializeComponent();
        //O botão cancela, retorna 'Cancel'
        buttonCancela.DialogResult = System.Windows.Forms.DialogResult.Cancel;
    }

    //Botão Login ou OK
    private void buttonLogin_Click(object sender, EventArgs e)
    {
        try
        {
            if (!String.IsNullOrEmpty(txtUser.Text))
            {
                if (!String.IsNullOrEmpty(txtPass.Text))
                {

                    //A rotina que valida o login do usuário, está dentro da 
                    //classe Usuarios, e se for válido, retorna um objeto do 
                    //tipo Usuarios, caso contrário, retorna null
                    UsuarioLogado = Usuarios.ValidarLogin(txtUser.Text, txtPass.Text);

                    if (UsuarioLogado != null)
                    {
                        //Se retornou o usuário, ou seja: é válido, retorna OK
                        this.DialogResult = System.Windows.Forms.DialogResult.OK;

                    }
                    else
                    {
                        txtUser.Text = txtPass.Text = "";
                        labelStatus.Text = "Usuario / Senha inválido";
                    }
                }
                else
                {
                    labelStatus.Text = "Informe a senha do usuário";
                    txtPass.Focus();
                }
            }
            else
            {
                labelStatus.Text = "Informe o nome de usuário";
                txtUser.Focus();
            }
        }
        catch (Exception ex)
        {
            labelStatus.Text = ex.Message;
        }

    }
}

Users: This would be a class of users, here are user properties, and Insert / Update / Delete methods, in addition to the validate login method that is used in FormLogin

public class Usuarios
{
    public string Usuario { get; set; }
    public string Senha { get; set; }
    public string Nome { get; set; }

    //Quaisquer outras propriedades

    public static Usuarios ValidarLogin(string _user, string _senha)
    {
        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\Trabalho Programação - VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True;Connect Timeout=30");

        con.Open();

        SqlCommand cmd = new SqlCommand("SELECT * FROM Login WHERE User= @usuario AND Pass = @senha;", con);

        cmd.Parameters.Add(new SqlParameter("@usuario", _user));
        cmd.Parameters.Add(new SqlParameter("@senha", _senha));

        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.Read())
        {
            Usuarios obj = new Usuarios();
            obj.Nome = reader["coluna_nome"].ToString();
            obj.Usuario = reader["User"].ToString();

            return obj;
        }
        else
            return null;
    }

}

FormPrincipal: In FormPrincipal, in your constructor, I put a parameter of type Users that will be the user logged into the application, from there you can have which user is using the system.

public partial class FormPrincipal : Form
{
    public FormPrincipal(Usuarios _usuarioLogado)
    {
        InitializeComponent();
        labelUsuario.Text = _usuarioLogado.Nome;
    }
}

I tried not to extend much, if any other members have suggestions are comfortable. Any questions available.

I've made changes to your code, regardless of my observations, and object-oriented concepts:

SqlConnection sqlCon = null; //Conexão começa em Null

private string strCmd = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='C:\Users\TutoDS\Desktop\VideoClub\VideoClub\VideoClub\bdVideoClub.mdf';Integrated Security=True"; //Conection String da BD

private string strSQL = string.Empty;

public bool logado = false;


public void Sign_in()
{

    if (!String.IsNullOrEmpty(txtUser.Text))
    {
        if (!String.IsNullOrEmpty(txtPass.Text))
        {
            string usuarioLogado =null;


            try
            {
                sqlCon = new SqlConnection(strCmd);
                strSQL = "SELECT Nome FROM [Login] WHERE [User] = @utilizador AND [Pass] = @password";                      
                sqlCon.Open();

                SqlCommand cmd = new SqlCommand(strSQL, con);

                cmd.Parameters.Add(new SqlParameter("@utilizador", txtUser.Text));
                cmd.Parameters.Add(new SqlParameter("@password", txtPass.Text));

                SqlDataReader reader = cmd.ExecuteReader();

                if (reader.Read())
                {
                    //usuário é válido e o nome está na variável usuarioLogado
                    logado = true;
                    usuarioLogado = reader["Nome"].ToString();
                }
                else
                {
                    //usuário não é válido
                    txtUser.Text = txtPass.Text = "";
                    labelStatus.Text = "Usuario / Senha inválido";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        else
        {
            labelStatus.Text = "Informe a senha do usuário";
            txtPass.Focus();
        }
    }
    else
    {
        labelStatus.Text = "Informe o nome de usuário";
        txtUser.Focus();
    }
}
    
17.05.2017 / 22:35