-1

I keep on receiving a null reference when trying to connect to the SQL Server database via Visual Studio 2017. Below is where the reference is and how it is trying to connect to gather the data. Please help! Thank you!.

Profile.aspx

protected void updateProfile(object sender, EventArgs e)
    {
        // Database entry
        string message = "Your information has been updated accoridngly!<br><br>";
        double number;
        if (txtName.Text.Equals("") || ddlDegree.SelectedValue.Equals("") || txtExperience.Text.Equals("") || !Double.TryParse(txtExperience.Text, out number) || txtSalary.Text.Equals("") || txtStreet.Text.Equals("") || txtCity.Text.Equals("") || txtState.Text.Equals("") || txtZipcode.Text.Equals(""))
        {
            message += "However:<br>There was an error found in your entry fields, resulting in a failure to store field information. Make sure that all fields are filled and that the Experience field is a double value.";
        }
        else
        {
        **myDataLayer.updateStaff(Session["userid"].ToString(), txtName.Text, ddlDegree.SelectedValue, txtExperience.Text, txtSalary.Text, txtStreet.Text, txtCity.Text, txtState.Text, txtZipcode.Text);** - **Null Reference**
        }

Here is the data layer class it needs to reference to:

string _ConString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlConnection con; 
    SqlDataAdapter sda = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand();
    SqlDataReader data;

// Handles updating staff info
    public bool updateStaff(string userid, string full_name, string degree, string experience, string salary, string street, string city, string state, string zipcode)
    {
        try
        {
            con = new SqlConnection(_ConString);
            con.Open();
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "UPDATE staff SET [full_name] = '" + full_name + "', [degree] = '" + degree + "', [experience] = '" + experience + "', [salary] = '" + salary + "', [street] = '" + street + "', [city] = '" + city + "', [state] = '" + state + "', [zipcode] = '" + zipcode + "' WHERE userid = '" + userid + "'";
            cmd.ExecuteNonQuery();
            con.Close();
            return true;
        }
        catch (OleDbException e)
        {
            System.Diagnostics.Debug.WriteLine(e.ToString());
        }
        finally
        {
            con.Close();
        }

        return false;
    }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Where exactly do you get the NullReference, so what is the error message and stacktrace and why is it different than the other NullReference questions? – Capricorn Jul 28 '18 at 15:05
  • 1
    is `Session["userid"]` properly defined before going `ToString`? sometimes i forgot that. well, null refrerence error is hard to say where it originates unless you read the error message. – Bagus Tesa Jul 28 '18 at 15:05
  • Unrelated tips: `SqlConnection`, `SqlCommand`, `SqlDataReader` and `SqlDataAdapter` are all `IDisposable` so each should be a local variable in a `using` block. DRapp has pointed out the SQL injection vulnerability of your code. – Richardissimo Jul 28 '18 at 17:08

1 Answers1

0

Your validations are weak and never go with building sql commands for insert, update, delete without parameterizing them. You are prone for SQL-INJECTION.

First, basic validation. By using IsNullOrWhiteSpace, you are preventing nulls to begin with (hence your error), but also a start for your SQL-Injection.

if( string.IsNulllOrWhiteSpace( txtName.Text )
  || string.IsNullOrWhiteSpace( ddlDegree.SelectedValue )
   … )
   message back about failed values

Now the SQL. User Parameters. What happens if you have a name O'Connor. The first quote would kill your string single-quote balancing.

cmd.Connection = con;
cmd.CommandText = 
@"UPDATE staff SET 
      full_name = @parmFullName,
      degree = @parmDegree,
      experience = @parmExperience,
      salary = @parmSalary,
      street = @parmStreet,
      city = @parmCity,
      state = @parmState,
      zipcode = @parmZIP,
   where
      userid = @parmUserID";

// pulling the parameters from the parameters you pass to your UpdateStaff() call

cmd.Parameters.AddWithValue( "parmFullName", full_name );
cmd.Parameters.AddWithValue( "parmDegree", degree );
cmd.Parameters.AddWithValue( "parmExperience", experience );

cmd.Parameters.AddWithValue( "parmSalary", salary );
cmd.Parameters.AddWithValue( "parmStreet", street);
cmd.Parameters.AddWithValue( "parmCity", city );
cmd.Parameters.AddWithValue( "parmState", state );
cmd.Parameters.AddWithValue( "parmZIP", zipcode );

cmd.Parameters.AddWithValue( "parmUserID", userid );

So, for the most-part, you should be good. No Null values, no mismatched single-quoted strings. This is not the ultimate in validation, you should definitely read more on SQL-Injection and data cleansing though.

In my example, I explicitly add a prefix "parm" to the parameters to differentiate between the actual VALUES you are trying to work with.

Also, if the data columns are of date, integer, double, string, let them remain the type they are intended. The parameters will pass to through correctly.

DRapp
  • 47,638
  • 12
  • 72
  • 142
  • May be worth taking a look at [can we stop using AddWithValue](https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/). – Richardissimo Jul 28 '18 at 17:09