This is baffling me. I have this line of code that is causing the problem
string prodID = DBTools.getProdID(args[0]).ExecuteScalar().ToString();
When I run this in my program I eventually get an error.
public static SqlCommand getProdID(string server)
{
string sql = "SELECT Password FROM UTrainID";
SqlCommand cmd = createCmd(server, "AACSMapping", sql);
cmd.Connection.Open(); // this generates the System.NullReferenceException
return cmd;
}
The thing that is baffling me about this is that I have a UnitTest that tests this that works perfectly.
[TestMethod]
public void getProdIDTest()
{
string ID = UTrain.DBTools.getProdID("PN1173312").ExecuteScalar().ToString();
Assert.IsTrue(ID.Equals("XXXXXXXXX"));
}
When I run this console application I've checked that the Args[] values are right ie it's the same value that I have in the UnitTest. The other things that is bothersome about this is that when I try to debug it by stepping through the code it works fine! That tells me that it's a timing problems of some type but that's beyond me. Here is the code that creates the actual connection.
public static SqlConnection createConnection(string server, string initcat)
{
try
{
SqlConnectionStringBuilder strBuild = new SqlConnectionStringBuilder();
strBuild.IntegratedSecurity = true;
strBuild.InitialCatalog = initcat;
strBuild.DataSource = server;
SqlConnection conn = new SqlConnection(strBuild.ConnectionString);
return conn;
} // end try
catch (Exception e)
{
writeErrorMessage(e, "Could not create connection.");
return null;
}
}
I don't know that it makes any difference but the reason I break the code up like this is I'm connecting to a number of different databases so it makes it easier to do it like this I feel.
Thanks for the comments. I finally found the problem. It was throwing a error that was being written to the error log file. It was a "Type initializer for SqlConnection threw an exception" When I searched for that error message most concerns were with the app.config file. I checked that and it was not formatted correctly. There was an extra >. I can see why the unit test might have worked when running unit tests I guess they wouldn't load the app.config file, but I still don't understand why stepping through with the debugger would work correctly?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.