views:

61

answers:

2

I have simple 3 tier web application and have mostly CRUDE functionalities. Recently I required to add new console application to the existing solution in which I call data layer methods for retrieving data from DB but I get an exception "The type initializer for threw an exception." When I debugged I found that the exception is thrown at datalayer on first line of class where I get connectionstring from web.config, the code is
public static readonly string CONNECT_STRING = ConfigurationManager.ConnectionStrings["DbConnectString"].ConnectionString;

Now if I hardcode the connection string value like public static readonly string CONNECT_STRING = "Data Source=XYZ;uid=sa;password=XXX;initial catalog=ABC;"

it works fine.I don't understand what is the issue here as web application works fine with this datalayer. Any suggestions?

+1  A: 

Console apps do not have web.config. It needs an 'app.config'.

leppie
Thanks! adding app.config to my console app solved the problem. But can't I use web.config as if there is any change in connection/other keys I need to update it in both files.
Pramodtech
@Pramodtech: Not really, you can create a symlink (with mklink in Vista or higher) from one to the other.
leppie
A: 

A console app can read a web.config

ConnectionStringSettingsCollection connections = ConfigurationManager.ConnectionStrings;
    foreach (ConnectionStringSettings connection in connections)
    {


    }
TheGeekYouNeed
Not on any .NET I know.... Edit: Did you bother checking what is actually in the connection setting presented to you?
leppie
leppie - look at the "Example" on this link http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx "The following example shows how to use the ConfigurationManager class in a console application. The code shows the following:". You can remove the down vote because obviously it can be done.
TheGeekYouNeed
@TheGeekYouNeed: You fail to understand how .NET find it's config files, which is clearly noted on that page; 'The name and location of the application configuration file depend on the application's host.' Read that, and then say sorry.
leppie
@TheGeekYouNeed: Also, that page makes no reference to `web.config`.
leppie