468,135 Members | 1,402 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,135 developers. It's quick & easy.

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

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;
}
}


}

Nov 17 '05 #1
17 9293
Rodusa <rc**********@yahoo.com> wrote:
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.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2


*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #3
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

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #4
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

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5
Rodrigo Lueneberg <ro**************@hotmail.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
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?

Nov 17 '05 #7
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;
}

Nov 17 '05 #8
Rodusa <rc**********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #9
Rodusa <rc**********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #10
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;
}

Nov 17 '05 #11
Rodusa <rc**********@yahoo.com> wrote:
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())
{
....
}
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #12
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/247referenc...34/172272.aspx

Nov 17 '05 #13
Rodusa <rc**********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #14
thanks
Jon, can I e-mail you my VS.net project so that you can see the error.?

Nov 17 '05 #15
Rodusa <rc**********@yahoo.com> wrote:
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?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #16
It is thrown right here using(SqlDataReader r =
Command.ExecuteReader())

Nov 17 '05 #17
Rodusa <rc**********@yahoo.com> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #18

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Terrence | last post: by
5 posts views Thread by Vitling | last post: by
1 post views Thread by msnews.microsoft.com | last post: by
4 posts views Thread by Terry Mulvany | last post: by
27 posts views Thread by didacticone | last post: by
1 post views Thread by gcdp | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.