Ibraheem Ghaffar
Ibraheem Ghaffar

Reputation: 60

How to call a method from another class inside a Window?

So I have a Class called "User" in which I have the following method and code:

public void Login()
{
   LoginWindow l = new LoginWindow();
   if (l.tbxEmail.Text != "" && l.tbxPassword.Text != "")
   {
      string query = "SELECT * FROM UsersTBL";
      l.con.Open();
      l.com = l.con.CreateCommand();
      l.com.CommandText = query;
      SqlDataReader dr = l.com.ExecuteReader();
      if (dr.Read())
      {
         if (dr["Email"].Equals(l.tbxEmail.Text.ToString()) && dr["UserPassword"].Equals(l.tbxPassword.Text.ToString()))
         {
            AppWindow a = new AppWindow();
            a.Show();
         }
         else
            l.lblMissingParameter.Content = "Incorrect Password or Email entered";
      }
   }
}

And in my LoginWindow I have:

public partial class LoginWindow:Window
{
     User u = new User();
     private void BtnSignup_Click(object sender, RoutedEventArgs e)
     {
         u.Login();
     }
}

When I try to call my Login method via class instantiation nothing works, why is that? Am I calling it the wrong way?

Upvotes: 2

Views: 130

Answers (3)

Vinícius Gabriel
Vinícius Gabriel

Reputation: 450

To clarify, you had this problem because the tbxEmail and tbxPassword variables in your User class where not the same as the ones in your main class. You should create both variable at class scope:

public class User {

  TextBox tbxEmail; // could be strings
  PasswordBox tbxPassword;

  public User (TextBox tbxEmail, TextBox tbxPassword) {
    this.tbxEmail = tbxEmail;
    this.tbxPassword = tbxPassword;
  }
}

And then:

User user = new User(tbxEmail,tbxPassword);
user.Login();

Or, create a static method (static method can't use global variables, so everything you need have to be passed as parameter of the method or created inside of it).:

public static void Login (string email, string password){
  // code here
}

Upvotes: 1

Zer0
Zer0

Reputation: 7354

This should work, although I left comments on things that should be addressed.

User class:

public bool Login(SqlConnection con, string email, string password)
{
    const string query = "SELECT 1 FROM UsersTBL WHERE Email = @email AND UserPassword = @password";
    if (!string.IsNullOrWhiteSpace(email) && !string.IsNullOrWhiteSpace(password))
    {
        try
        {
            con.Open();
            var cmd = con.CreateCommand();
            cmd.CommandText = query;
            //Correct SqlDbTypes if necessary
            cmd.Parameters.Add("@email", SqlDbType.VarChar);
            cmd.Parameters["@email"].Value = email;
            cmd.Parameters.Add("@password", SqlDbType.VarChar);
            //Should NOT be storing passwords as plain text in the database
            cmd.Parameters["@password"].Value = password;
            if (cmd.ExecuteScalar() == 1)
                return true;
        }
        catch (Exception e)
        {
             //log e somehow or eliminate this catch block
        }
        finally
        {
             //Close the connection if still open
             if (con != null && con.State != ConnectionState.Closed)
                 con.Close();
        }
    }
    return false;
}

LoginWindow class:

public partial class LoginWindow : Window
{
    private void BtnSignup_Click(object sender, RoutedEventArgs e)
    {
        var u = new User();
        if (u.Login(con, tbxEmail.Text, tbxPassword.Text))
        {
            AppWindow a = new AppWindow();
            a.Show();
        }
        else
            lblMissingParameter.Content = "Incorrect Password or Email entered";
    }
}

Upvotes: 1

Bedir
Bedir

Reputation: 586

I wrote a rudimentary login page for one of my school projects similar to this:

private void signInButton_Click(object sender, EventArgs e)
        {
            DataProcedures data = new DataProcedures();
            User userInfo = new User(usernameTextbox.Text, passwordTextbox.Text);
            userInfo.userId = data.verifyUser(userInfo);

            if (userInfo.userId != -1)
            {
                AppWindow a = new AppWindow();
                 a.Show();
            }
            else
            {
                errorLabel.Show();
            }
        }

public int verifyUser(User userInfo)
        {
            MySqlConnection conn = new MySqlConnection(connectionString);

            int userId = -1;

            string returnedUserName;
            string returnedPassword;

            try
            {
                conn.Open();
                MySqlCommand checkUserNameCmd = conn.CreateCommand();
                checkUserNameCmd.CommandText = "SELECT EXISTS(SELECT userName FROM user WHERE userName = @username)";
                checkUserNameCmd.Parameters.AddWithValue("@username", userInfo.username);
                returnedUserName = checkUserNameCmd.ExecuteScalar().ToString();

                MySqlCommand checkPasswordCmd = conn.CreateCommand();
                checkPasswordCmd.CommandText = "SELECT EXISTS(SELECT password FROM user WHERE BINARY password = @password AND userName = @username)";//"BINARY" is used for case sensitivity in SQL queries
                checkPasswordCmd.Parameters.AddWithValue("@password", userInfo.password);
                checkPasswordCmd.Parameters.AddWithValue("@username", userInfo.username);
                returnedPassword = checkPasswordCmd.ExecuteScalar().ToString();



                if (returnedUserName == "1" && returnedPassword == "1")
                {
                    MySqlCommand returnUserIdCmd = conn.CreateCommand();
                    returnUserIdCmd.CommandText = "SELECT userId FROM user WHERE BINARY password = @password AND userName = @username";
                    returnUserIdCmd.Parameters.AddWithValue("@password", userInfo.password);
                    returnUserIdCmd.Parameters.AddWithValue("@username", userInfo.username);
                    userId = (int)returnUserIdCmd.ExecuteScalar();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception thrown verifying user: " + ex);
            }
            finally
            {
                conn.Close();
            }

            return userId;
        }

Hope this helps.

Upvotes: 0

Related Questions