tags:

views:

107

answers:

1

Okay so I am trying to compare a login textbox password and username with a custom validator using linq to get information from the database it always returns false though on the validator could someone please tell me where my code below is going wrong. This will be very much appreciated... thank you in advanced...

protected void LoginValidate(object source, ServerValidateEventArgs args)
{
    TiamoDataContext context = new TiamoDataContext();

    var UsernameCheck = from User in context.Users
                      where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
                      select User.Username;

    var PasswordCheck = from User in context.Users
                    where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
                    select User.Password;

    String test1 = PasswordCheck.ToString();
    String test2 = UsernameCheck.ToString();

    if (test1 == TextBoxLogInPassword.Text && test2 == TextBoxLoginUsername.Text)
    {
        args.IsValid = true;
        Session["Username"] = TextBoxLoginUsername;
        Response.Redirect("UserProfile.aspx");

    }
    else 
    {
        args.IsValid = false;
    }

}

I dont know where I am going wrong I know its most probably some sort of silly mistake and me being inexperienced at this...

+2  A: 

UsernameCheck and PasswordCheck are going to be collections, not single values. Therefore the ToString() method isn't returning what you think it should.

It's probably returning "IEnumerable<string>"

You need to force your LINQ queries to return a single result rather than a collection.

var user = context.Users.Where(u => u.Username==TextBoxLoginUsername.Text && 
                                    u.Password == TextBoxLogInPassword.Text)
               .FirstOrDefault();

string userNameCheck = user.Username;
string passwordCheck = user.Password;

As a side note, this is why using the var keyword is a little dangerous if you're not absolutely positive of the return type of the statement you're writing. If you would change your vars to strings, the compiler would have caught the type mismatch at compile time.

Justin Niessner
Thank you this worked like a charm, I had an error nullpointerexception I just added an if(user != null){}; and it worked... just a side question is this the best way to auth users what are the standards in the asp.net world
Anicho
The best would be to use one of the ASP.NET Membership Providers (or write your own custom one). I would make that a question on its own...or search and make sure it's not a duplicate. And as another suggestion for a new user, be sure to accept correct answers when you get them. If you don't, your badge will show a low acceptance rating and some people won't answer your questions in the future.
Justin Niessner
Thanks Justin :)
Anicho