1

I am new to c# asp.net. got this code from a tutorial but I am getting an error. My label says log in failed though I entered the correct data. Please help me :( and it says: Object reference not set to an instance of an object when I entered an incorrect data.

here's my ConnectionClass.cs

public class ConnectionClass
 {
 private static SqlConnection conn;
 private static SqlCommand command;

static ConnectionClass()
{
    string connectionString = ConfigurationManager.ConnectionStrings["CoffeeDBConnectionString"].ToString();
    conn = new SqlConnection(connectionString);
    command = new SqlCommand("", conn);
}

public static User LoginUser(string login, string password)
{ 
    //Check if user exists
    string query = string.Format("SELECT COUNT(*) FROM SkyMusic.dbo.user WHERE username = '{0}'", login);
    command.CommandText = query;

    try
    {
        conn.Open();
        int numofUsers = (int) command.ExecuteScalar();

        if (numofUsers < 1)
        {
            //user exists, check if the passwords match
            query = string.Format("SELECT password FROM user WHERE username = '{0}'", login);
            command.CommandText = query;
            string dbPassword = command.ExecuteScalar().ToString();

            if (dbPassword == password)
            {
                //Passwords match
                query = string.Format("SELECT email, user_type FROM users WHERE username = '{0}'", login);
                command.CommandText = query;

                SqlDataReader reader = command.ExecuteReader();
                User user = null;

                while (reader.Read())
                {
                    string email = reader.GetString(0);
                    string type = reader.GetString(1);

                    user = new User(login, password, email, type);
                }
                return user;
            }
            else
            {
                //passwords do not match
                return null;
            }
        }
        else
        {
            return null;
        }
    }
    finally
    {
        conn.Close();
    }

}

my login:

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
 </asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<div id="formcont">
<table>
<tr>
<td><asp:Label ID="Label1" runat="server" Text="Username:"></asp:Label></td>
<td><asp:TextBox ID="TextBox1" runat="server" Width="142px"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label ID="Label2" runat="server" Text="Password:"></asp:Label></td>
<td><asp:TextBox ID="TextBox2" runat="server" Width="142px"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2"></br><asp:Button ID="Button1" runat="server" Text="Log In" />
    <br />
    </td>
</tr>
</table>
<p>Don't have an account? Click <a href="Register.aspx" runat="server">here</a>!</p>
</div>
</asp:Content>

and

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        User user = ConnectionClass.LoginUser(txtUname.Text, txtPass.Text);


        if (user != null)
        {
            Session["login"] = user.login;
            Session["type"] = user.type;
            Response.Redirect("Home.aspx");
        }
        else
        {
            lblError.Text = "Login Failed";
        }
     }

please help :( here's my db id, username, password, email, user_type

missellorin
  • 389
  • 2
  • 5
  • 23
  • this might help http://www.codingdefined.com/2014/06/object-reference-not-set.html – CodingDefined Nov 27 '14 at 05:57
  • As I know, I am checking for nulls. :( – missellorin Nov 27 '14 at 05:58
  • Use breakpoints and debug the program. – kelsier Nov 27 '14 at 05:59
  • 1
    @Fel - Debug your code it'll provide you an answer within a minute! – Rahul Singh Nov 27 '14 at 05:59
  • Didn't you try to debug your code at all? Do you know from which line the error is thrown? – Sam Nov 27 '14 at 05:59
  • 1
    @Fel - `command.ExecuteScalar().ToString();` must be throwing error, if no password found then. – Rahul Singh Nov 27 '14 at 06:02
  • 1
    Hey @Fel I think your check, `if (numofUsers < 1)` is wrong. You see when the value is less than 1 which means wrong userID, you're checking for password. On the other hand when the value is 1 i.e., correct UserID you're directly throwing the `null` value. Change this condition to `if (numofUsers >= 1)`. You should be good to go. – Piyush Nov 27 '14 at 06:18
  • Hi, @P.K.! Yes, it worked already. But when I enter wrong data, it gives me the null reference error. What part of the code should be fixed? :( – missellorin Nov 27 '14 at 06:22
  • @Fel What's the current check condition you're using instead of `if (numofUsers < 1)` ?? – Piyush Nov 27 '14 at 06:43
  • if (numofUsers <= 1) @P.K. – missellorin Nov 27 '14 at 06:48
  • 1
    Why `<=` ?? You should be using `if (numofUsers >= 1)`. if the value of **numofUsers** is less than 1, then it means wrong userID. SO there's no need to test for password. You're must be thrown from the line, `string dbPassword = command.ExecuteScalar().ToString();` Since, the USerID is wrong the password will be null. Calling `.ToString()' on `null` will give you this error. – Piyush Nov 27 '14 at 06:51
  • @Chaturvedi's > 0 worked! – missellorin Nov 27 '14 at 06:56

1 Answers1

1

There are two problems or error
1. You can not login with correct credential:
Check this.

if (numofUsers < 1)
    {
        //user exists, check if the passwords match
        query = string.Format("SELECT password FROM user WHERE username = '{0}'", login);

If no of user is less than 1 how can a user exists in system.

2. Null reference error:
In case user does not exists then this method returned null you should be handling null and showing incorrect credential or user does not exists

EDIT Rahul seems to be correct in comments of question. Debug your code first.

EDIT

As per your comment you were using
if (numofUsers < 1)
then you changed to if (numofUsers <= 1)
Use it as if (numofUsers > 0)

Chaturvedi Dewashish
  • 1,469
  • 2
  • 15
  • 39