Get Logged In User details in WPF Application using C#

Last Reply 15 days ago By dharmendr

Posted 15 days ago

Hello all,

I have a login method to check if a user is a member in my DB. My login method is only a bool and I am wondering how can I grab that current users data so I can pass it to the next window. I am checking textboxes to see if the text is valid.

One way I know I could solve this is to change my login method so it returns a user then I would have that specific user but I would like to see if I could grab the user data by checking if the data is in the DB.

Here is what I have:

        //Login XAML window.
        private void BtnLoginUser_Click(object sender, RoutedEventArgs e){
            if (string.IsNullOrEmpty(txtUsername.Text)) {
                //verify and enter username.
                MessageBox.Show("Enter your username.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information);                txtUsername.Focus();
                return;
            }
            else if (string.IsNullOrEmpty(txtPassword.Password)) {
                MessageBox.Show("Enter your password.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information);                txtPassword.Focus();
                return;
            }
            else {
                try {
                    if(SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password)){

                    }
                }
            }
        }

        //SQL login method
        public static bool UserLogin(string username, string password) {
            bool valid = false;
            //SQL Login Query.
            string SQLloginQuery = "SELECT * FROM Users WHERE Username=@username AND Password=@password";
            SqlCommand cmdLogin = new SqlCommand(SQLloginQuery, connection);
            cmdLogin.Parameters.AddWithValue("@username", username);
            cmdLogin.Parameters.AddWithValue("@password", password);
            try {
                connection.Open();
                int result = (int)cmdLogin.ExecuteScalar();
                if (result > 0) {
                    valid = true;
                    MessageBox.Show("Login success");
                }
                else   MessageBox.Show("Login Failed");
            }
            catch (Exception ex) {
                ex.Message.ToString();
                throw ex;
            }
            finally{
                connection.Close();
            }
            return valid;
        }

        //This is a method I use to get the user
        public static User GetUserById(int userId{            
            string SQLreadQuery = "SELECT Username, Password, IsAdmin, UserCreatedDate " +
                                  "FROM Users WHERE UserId = " + userId; //or SELECT ea column or *.
            SqlCommand cmdRead = new SqlCommand(SQLreadQuery, connection);
            try{
                connection.Open();
                SqlDataReader reader = cmdRead.ExecuteReader(CommandBehavior.SingleRow);
                if(reader.Read()){
                    User user = new User();
                    user.UserID = Convert.ToInt32(reader["UserId"]);
                    user.Username = reader["Username"].ToString();
                    user.Password = reader["Password"].ToString();
                    user.IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
                    user.UserCreatedDate = Convert.ToDateTime(reader["UserCreatedDate"]);
                    return user;
                }
                else{
                    return null;
                }
            }
            catch(Exception ex){
                ex.Message.ToString();
                return null;
            }
            finally{
                connection.Close();
            }
        }

 

You are viewing reply posted by: dharmendr 15 days ago.
Posted 15 days ago

Hi bigbear,

Instead of returning boolean value from UserLogin function return string or integer value based on your datatype.

Then you can check the condition on button click for null or empty vale and fetch the User details.

Refer the below modified code.

private void BtnLoginUser_Click(object sender, RoutedEventArgs e)
{
    if (string.IsNullOrEmpty(txtUsername.Text))
    {
        //verify and enter username.
        MessageBox.Show("Enter your username.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information); 
        txtUsername.Focus();
        return;
    }
    else if (string.IsNullOrEmpty(txtPassword.Password))
    {
        MessageBox.Show("Enter your password.", "Empty", MessageBoxButton.OK, MessageBoxImage.Information); 
        txtPassword.Focus();
        return;
    }
    else
    {
        try
        {
            if (!string.IsNullOrEmpty(SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password)))
            {
                MessageBox.Show("Login success");
                string userId = SQLuserAccess.UserLogin(txtUsername.Text, txtPassword.Password);
                User user = new User();
                user = SQLuserAccess.GetUserById(Convert.ToInt32(userId));
            }
            else
            {
                MessageBox.Show("Login Failed");
            }
        }
    }
}
//SQL login method
public static string UserLogin(string username, string password)
{
    string result;
    //SQL Login Query.
    string SQLloginQuery = "SELECT UserId FROM Users WHERE Username=@username AND Password=@password";
    SqlCommand cmdLogin = new SqlCommand(SQLloginQuery, connection);
    cmdLogin.Parameters.AddWithValue("@username", username);
    cmdLogin.Parameters.AddWithValue("@password", password);
    try
    {
        connection.Open();
        result = Convert.ToString(cmdLogin.ExecuteScalar());
    }
    catch (Exception ex)
    {
        ex.Message.ToString();
        throw ex;
    }
    finally
    {
        connection.Close();
    }

    return result;
}
//This is a method I use to get the user
public static User GetUserById(int userId)
{
    string SQLreadQuery = "SELECT Username, Password, IsAdmin, UserCreatedDate " +
                            "FROM Users WHERE UserId = " + userId; //or SELECT each column or *.
    SqlCommand cmdRead = new SqlCommand(SQLreadQuery, connection);
    try
    {
        connection.Open();
        SqlDataReader reader = cmdRead.ExecuteReader(CommandBehavior.SingleRow);
        if (reader.Read())
        {
            User user = new User();
            user.UserID = userId;
            user.Username = reader["Username"].ToString();
            user.Password = reader["Password"].ToString();
            user.IsAdmin = Convert.ToBoolean(reader["IsAdmin"]);
            user.UserCreatedDate = Convert.ToDateTime(reader["UserCreatedDate"]);

            return user;
        }
        else
        {
            return null;
        }
    }
    catch (Exception ex)
    {
        ex.Message.ToString();
        return null;
    }
    finally
    {
        connection.Close();
    }
}