I’ve taken the following code from a guide so as to test it, and am experiencing an error saying that Object reference not set to an instance of an object.
Please note that this is NOT my code, and thus this problem is related to deciphering it.
public class ProductImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 id;
if (context.Request.QueryString["id"] != null)
id = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = GetFromDB(id);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream GetFromDB(int id)
{
string conn = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT Image FROM Products WHERE ID = @ID";
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", id);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
The error occurs in the following line:
int byteSeq = strm.Read(buffer, 0, 4096);
Does anyone have any idea as to what the problem could be?
Well, the only member access on the line itself is on
strm, so I would assume it is anullreference.Check what
GetFromDBreturns for the specific query. I assume it will return anullif theidis not found.To resolve this, either:
GetFromDBto not return anullidto ensure it is validstrmis notnullbefore using it