We have a certain database that has some employee information, and I just wrote a small class to access some of this information. This class contains with it an application configuration file that has a connection string to the database. There is only 3 files in this project.
Two .cs files and one App.config file.
The app.config file has this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="connString" value="server=myserver;uid=mysa;pwd=mypwd;database=mydb"/>
</appSettings>
</configuration>
One of my CS files I have a class like so:
namespace Employees.DAL
{
public static class DAL
{
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["connString"].ToString();
public static Employee GetEmployeeByID(long EmpID)
{
Employee e = null;
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("EMPDLL_selEmployeeByID", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@LoginID", SqlDbType.BigInt).Value = EmpID;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{ //todo: implement Employee class
e = new Employee((long)reader["LoginID"]
);
}
}
}
}
}
return e;
}
}
}
Fairly simple just grabs a record from the db and makes an employee out of it which is in the Employee.cs class:
namespace Employees.Objects
{
public class Employee
{
/// <summary>
/// ID of employee.
/// </summary>
public long LoginID { get; private set; }
public Employee( long LoginID)
{
this.LoginID = LoginID;
}
}
}
Now what I did was create a new console project in vs2010 and I add a reference to this .dll file that I built, namely Employees. I need to do this because I have to write this as a reusable class so that others can include it.
So then I just did some simple console app like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Employees.DAL;
using Employees.Objects;
namespace ConsoleEmployeesTest
{
class Program
{
static void Main(string[] args)
{
try
{
Employee e = DAL.GetEmployeeByID(68); //fails right here...
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
}
}
I get an exception
System.TypeInitilizationException: the type initializer for Employees.DAL.DAL threw an
exception –> System.NullReferenceException: Object reference not set to an instance of an
object.
Is this because the new app does not see the app.config file?
Consider adding the configuration file as a resource to your DLL and then at run time read the value out of the resource instead.