System.NullReferenceException - Object reference not set to an instance of an object

R

Rodusa

I am getting this exception error which is driving me nuts.
System.NullReferenceException - Object reference not set to an instance
of an object

If I comment this line, I don't get any errors:
string Total_Dollar_Amount = GetTotal(sql,"test");



namespace SalesReport
{
/// <summary>
/// Summary description for SalesReport.
/// </summary>
public class SalesReport : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

private ArrayList GetRowsArray()
{
ArrayList Ar = new ArrayList();
SqlConnection Conn = Common.GetConnection("sonny");
string sql = "SELECT * from Sn_SalesReport";
SqlCommand Command = new SqlCommand(sql, Conn);
Command.Connection.Open();
SqlDataReader r = Command.ExecuteReader();
while (r.Read())
{
string sqlstatement = r["sqlstatement"].ToString();
Ar.Add(sqlstatement);
Response.Write(sqlstatement+"<br>");
}
r.Close();
Conn.Close();
return Ar;
}


private void Button1_Click(object sender, System.EventArgs e)
{
ArrayList Ar = GetRowsArray();
// create the Thread array
Thread[] t = new Thread[ Ar.Count ];
int lIdx;
ProcessSQL sr;

for ( lIdx = 0; lIdx < Ar.Count; lIdx ++ )
{
sr = new ProcessSQL(Ar[lIdx].ToString());
t[lIdx] = new Thread( new ThreadStart( sr.UpdateSalesReport ) );
t[lIdx].Start();
}

for ( lIdx = 0; lIdx < Ar.Count; lIdx ++ )
{
// waiting for all the Threads to finish.
t[lIdx].Join();
}

}
}

public class ProcessSQL
{
private string sql;
public ProcessSQL (string sql)
{
this.sql = sql;
}

public void UpdateSalesReport()
{
try
{
string Total_Dollar_Amount = GetTotal(sql,"test");
}
catch(Exception ex)
{
HttpContext.Current.Response.Write("Error########: "+ex.Message);
}
}

public string GetTotal(string sql, string database)
{
sql = "Select reportname from SN_SalesReport";
string result = string.Empty;
try
{
SqlConnection Conn = Common.GetConnection(database);
SqlCommand Command = new SqlCommand(sql, Conn);
Command.Connection.Open();
SqlDataReader r = Command.ExecuteReader();
if(r.Read())
{
// gets total
result = r.GetString(0);
}
r.Close();
if (Conn!=null)
{
Conn.Close();
}

}
catch(Exception ex)
{
HttpContext.Current.Response.Write("Error########: "+ex.Message);
}
return result;
}


}






}
 
J

Jon Skeet [C# MVP]

Rodusa said:
I am getting this exception error which is driving me nuts.
System.NullReferenceException - Object reference not set to an instance
of an object

If I comment this line, I don't get any errors:
string Total_Dollar_Amount = GetTotal(sql,"test");

Rather than printing out just the message, print out the full stack
trace. That way you should be able to see which line of your code is
throwing the exception.

Note that to make your code more robust you should be using "using"
statements for your connection/command/data reader, rather than calling
Close directly. (Currently if an exception is thrown, the connection
isn't closed.)
 
R

Rodrigo Lueneberg

Thanks Joh, but I am sorry, I don't have too much experience with
debuging in Asp.net. Could you please be more especific when you talk
about "print out the full stack
trace. " How do I do it? Furthermore, I have a feeling it is something
to do with ADO and threading. Whenever several threads because they are
trying to use the same database access method at the same time. I tried
to use thread.sleep before closing the connection, but it does not work.
I still get the exception. I am almost going back to a linear
programming. I need to get this stuff working by tomorrow.

Thank you

Rodrigo Lueneberg
 
R

Rodrigo Lueneberg

Thanks Joh, but I am sorry, I don't have too much experience with
debuging in Asp.net. Could you please be more especific when you talk
about "print out the full stack
trace. " How do I do it? Furthermore, I have a feeling it is something
to do with ADO and threading. Whenever several threads because they are
trying to use the same database access method at the same time. I tried
to use thread.sleep before closing the connection, but it does not work.
I still get the exception. I am almost going back to a linear
programming. I need to get this stuff working by tomorrow.

Thank you

Rodrigo Lueneberg
 
J

Jon Skeet [C# MVP]

Rodrigo Lueneberg said:
Thanks Joh, but I am sorry, I don't have too much experience with
debuging in Asp.net. Could you please be more especific when you talk
about "print out the full stack
trace. " How do I do it?

Well, you're currently printing out ex.Message. Instead, print out
ex.ToString().
Furthermore, I have a feeling it is something
to do with ADO and threading. Whenever several threads because they are
trying to use the same database access method at the same time. I tried
to use thread.sleep before closing the connection, but it does not work.
I still get the exception. I am almost going back to a linear
programming. I need to get this stuff working by tomorrow.

You shouldn't be trying to use the same connection from multiple
threads - if you're doing that, that's a mistake. You can, however, use
different connections from different threads.
 
R

Rodusa

I tried ex.ToString(), but the exception is being thrown by Visual
Studio, before it reaches the application. And when I try to debug, it
says "There is no source code available for the current location".
That's is why I am lost. I don't have any way to figure out.
Regarding, the connections, I heard about threadpool? Is that what you
mean? I had the wrong thought that GetTotal method had a privated
instance of Conn and it should automatically create different calls in
memory, causing no problems with opening and closing different
connections when using threads. Howevever, if this is not what you are
thinking, how can I create multiple instance Conn in this scenario?
 
R

Rodusa

Jon, I did implement the "using as you said". It doesn't seem to be a
connection problem because when I comment the datareader block the page
runs with no problem. It looks like it is something to do with the
datareader. The problem is I can't create a new instance of the
datareader.

public string GetTotal(string sql, string database)
{

sql = "Select reportname from SN_SalesReport";
string result = string.Empty;
try
{
using (SqlConnection Conn = new
SqlConnection(ConfigurationSettings.AppSettings[database]))
{
SqlCommand Command = new SqlCommand(sql, Conn);
Command.Connection.Open();
//using(SqlDataReader r = Command.ExecuteReader())
{
// if(r.Read())
// {
// gets total
// result = r.GetString(0);
// }
// r.Close();
// if (Conn!=null)
// {
// Conn.Close();
// }
}
}

}
catch(Exception ex)
{
HttpContext.Current.Response.Write("Error########:
"+ex.ToString());
}
return result;
}
 
J

Jon Skeet [C# MVP]

Rodusa said:
I tried ex.ToString(), but the exception is being thrown by Visual
Studio, before it reaches the application. And when I try to debug, it
says "There is no source code available for the current location".
That's is why I am lost. I don't have any way to figure out.
Regarding, the connections, I heard about threadpool? Is that what you
mean?

No, not quite.
I had the wrong thought that GetTotal method had a privated
instance of Conn and it should automatically create different calls in
memory, causing no problems with opening and closing different
connections when using threads. Howevever, if this is not what you are
thinking, how can I create multiple instance Conn in this scenario?

I suspect the problem you're seeing isn't related to not using a using
statement - that was just a separate bug in your code which was worth
pointing out before it hit you.
 
J

Jon Skeet [C# MVP]

Rodusa said:
Jon, I did implement the "using as you said". It doesn't seem to be a
connection problem because when I comment the datareader block the page
runs with no problem. It looks like it is something to do with the
datareader. The problem is I can't create a new instance of the
datareader.

What do you mean by "you can't create a new instance of the
datareader"? What happens when you try?

Note that the SqlCommand should be in a using block too, for
preference. (It probably doesn't matter, at least not at the moment,
but it's good practice.)

Also note that as you've got a using block, you don't need to call
Close on the connection or the reader - it disposes of them
automatically.
 
R

Rodusa

When I change SqlDataReader to this

using(SqlDataReader r = new SqlDataReader(Command.ExecuteReader()))

VStudio tells shows this error

Argument '1': cannot convert from 'System.Data.SqlClient.SqlDataReader'
to 'System.Data.SqlClient.SqlCommand'


I've included SqlCommand as you suggested, but no sucess:

public string GetTotal(string sql, string database)
{

sql = "Select reportname from SN_SalesReport";
string result = string.Empty;
try
{
using (SqlConnection Conn = new
SqlConnection(ConfigurationSettings.AppSettings[database]))
{
using (SqlCommand Command = new SqlCommand(sql, Conn))
{
Command.Connection.Open();
using(SqlDataReader r = Command.ExecuteReader())
{
if(r.Read())
{
result = r.GetString(0);
Common.ExecSQL("update SN_SalesReport set ");
}
r.Close();
if (Conn!=null)
{
Conn.Close();
}
}
}
}

}
catch(Exception ex)
{
//HttpContext.Current.Response.Write("Error########:
"+ex.ToString());
}
return result;
}
 
J

Jon Skeet [C# MVP]

Rodusa said:
When I change SqlDataReader to this

using(SqlDataReader r = new SqlDataReader(Command.ExecuteReader()))

VStudio tells shows this error

Argument '1': cannot convert from 'System.Data.SqlClient.SqlDataReader'
to 'System.Data.SqlClient.SqlCommand'

Ah, right. All you need is:

using (SqlDataReader r = Command.ExecuteReader())
{
....
}
 
R

Rodusa

Jon,

I was using like that before and that's where I was getting the
exception. I am trying to use new SqlDataReader to create a new
instance for each thread. The other thing that I found out in a
different forum is regarding the database and threads. It is very
interesting, but I don't know if it is really true.

"Why do you think using 10 threads will speed it up? If it does
anything it
would slow it down? The only reason you would want to use threads is if
some
of them were waiting for some ressource. In this case that ressource is
the
database connection, but that is what's taking your time - and the
database
connections are automaticly pooled to speed that up."

I don't agree with this, because it is not considering the processing
time, just database connection. I might be wrong. I am making sure that
I create a different connection for each request, so it should't be a
problem.

Look:
http://www.dotnet247.com/247reference/msgs/34/172272.aspx
 
J

Jon Skeet [C# MVP]

Rodusa said:
I was using like that before and that's where I was getting the
exception.

Where exactly though? Which line?
I am trying to use new SqlDataReader to create a new
instance for each thread.

There will already be a new instance for each thread, because you're
creating a new connection and calling ExecuteReader on it.
The other thing that I found out in a
different forum is regarding the database and threads. It is very
interesting, but I don't know if it is really true.

"Why do you think using 10 threads will speed it up? If it does
anything it would slow it down? The only reason you would want to use
threads is if some of them were waiting for some ressource. In this
case that ressource is the database connection, but that is what's
taking your time - and the database connections are automaticly
pooled to speed that up."

I don't agree with this, because it is not considering the processing
time, just database connection. I might be wrong. I am making sure that
I create a different connection for each request, so it should't be a
problem.

It shouldn't be a problem, but I agree with the other poster that it
may well not speed things up - it just gives the database 10 jobs to do
at once instead of one at a time. If your database server is a
multiprocessor machine, it *may* be faster - but it's not guaranteed,
particularly if all the tasks are using the same tables, potentially
introducing contention.

Starting all those threads, while not *hugely* expensive, isn't free
either. You should certainly benchmark both approaches and if I were
you I'd use the simpler "one at a time, no extra threads" solution
unless introducing threading gives a *significant* performance
improvement.
 
J

Jon Skeet [C# MVP]

Rodusa said:
Jon, can I e-mail you my VS.net project so that you can see the
error.?

I suspect it wouldn't really help without quite a lot of setup - you
should be able to work out what's going wrong without that. Have you
tried stepping through the code to work out where the exception is
being thrown?
 
J

Jon Skeet [C# MVP]

Rodusa said:
It is thrown right here using(SqlDataReader r =
Command.ExecuteReader())

And can you tell in the debugger that Command definitely isn't null?
(It shouldn't be.)

Are you able to reproduce this outside ASP.NET? That would make it a
lot easier for me to help you. If you could come up with a short but
complete program which demonstrates the problem, I'm sure we could sort
it out. See http://www.pobox.com/~skeet/csharp/complete.html for
details of what I mean by that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top