I’m trying to work out how to validate a user in my application but i don’t know how. I wish create a form with Username and Password to enter in the application(WPF) using Linq toSql to store and validate Username and password in the database but i don’t know so much about Linq to Sql so i keep in stuck now. I have a database with this fields’UserID,UserTypeID,Name,Surname,Username,Password,Email’ and here there is the code that i use :
public Window1() { InitializeComponent(); } public bool ValidateApplicationUser(string userName, string password) { bool validUser = false; try { // var conn = 'Data Source=MAMMA-PC/SQLMAMMA;Initial Catalog=MyWebSite;Integrated Security=True'; DataClasses1DataContext dc = new DataClasses1DataContext(); Table<User> users = dc.GetTable<User>(); var query = from c in dc.Users where (c.Username == userName.ToLower() && c.Password == password.ToLower()) select c; validUser = (query != null); } catch (Exception ex) { if (ex != null) { } } return validUser; } private void mahhh(object sender, RoutedEventArgs e) { bool authenticated = true; // var conn = 'Data Source=MAMMA-PC/SQLMAMMA;Initial Catalog=MyWebSite;Integrated Security=True'; DataClasses1DataContext dc = new DataClasses1DataContext(); Table<User> users = dc.GetTable<User>(); var query = from c in dc.Users where (c.Username == usernameTextBox.Text.ToString() && c.Password == passwordTextBox.Text.ToString()) select c; /* foreach (User user in query) { user.Username = usernameTextBox.Text.Trim(); user.Password = passwordTextBox.Text.Trim(); } */ { if (usernameTextBox.Text !='' && passwordTextBox.Text != '') { authenticated = ValidateApplicationUser(usernameTextBox.Text , passwordTextBox.Text); } } if (!authenticated) { MessageBox.Show('Invalid login. Try again.'); } else { MessageBox.Show('Congradulations! You're a valid user!'); // Window2 c = new Window2(); // c.ShowDialog(); this.Close(); } }
When i insert the password and username the form validate also wrong username and password so i receive always the message ‘Congradulations! You’re a valid user!’!!!
DO you have any advice where i wrong?
Bye
Firstly its a best practice to Hash Passwords(one way encryption) with a Salt (random string you tag on the end of your password), I know it sounds complex but it isn’t.
It isn’t a good practice to wrap everything around with try, unless you are
The Linq Code Would Be
Salt Could Be Done Using Database Or C#
http://blog.stevex.net/index.php/c-code-snippet-creating-an-md5-hash-string/