Monday, March 26, 2012

Object reference not set to an instance of an object

I am receiving the above error when I try to read a database object. My connection string is : "server=JIMM;database=MIST01;Trusted_Connection=yes". I have added user JIMM\ASPNET to the database with public, db_datareader, and db_datawriter privileges. Permisssions have been selected for Select, Insert, Update, and Delete for all user defined objects. What am I missing? I can open the database connection, but it fails on an ExecuteScalar command.Can you provide us with some more code since the error can be in a few places...?
Most of the code is in the following snippet from the data access layer. The Read_ID function is called from the business logic layer. Read_ID uses the Connection String member and it calls the ExecuteScalar function. The error occurs when "return (int)cmd.ExecuteScalar();" is executed. I'm assuming that it is a permission error, but I just can't see it. Thanks for your help.

public class DataConfig
{
public DataConfig()
{

}
private static int _id;
private static string _ConnectString;
public static int IdentitySeed
{
get
{
return _id*1000000;
}
}
public static string ConnectionString
{
get
{
return _ConnectString;
}
set
{
_ConnectString = value;
}
}
public static int ReadID(string serverName)
{
// read inspector table to access identity seed

SqlCommand readID = new SqlCommand("SELECT InspectorID FROM Inspectors WHERE (HostName = '" + serverName + "')");

try
{
_id = (int) ExecuteScalar(readID);
return _id;
}
catch (Exception ex)
{
throw ex;
}
}
public static int ExecuteSQL(SqlCommand cmd)
{

try
{
cmd.Connection = new SqlConnection(DataConfig.ConnectionString);
cmd.Connection.Open();

return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmd.Connection != null)
{
if (cmd.Connection.State != ConnectionState.Closed)
{
cmd.Connection.Close();
}
}
}
}
public static int ExecuteScalar(SqlCommand cmd)
{

try
{
cmd.Connection = new SqlConnection(DataConfig.ConnectionString);
cmd.Connection.Open();

return (int)cmd.ExecuteScalar();
}
catch (InvalidCastException ex)
{
return 0;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cmd.Connection != null)
{
if (cmd.Connection.State != ConnectionState.Closed)
{
cmd.Connection.Close();
}
}
}
}

0 comments:

Post a Comment