How to access a connection string from within a library - c#

I have a web project (mvc) and data access layer in a separated class library project. I need to access to a connection string in app.config which sits in that library project.
ConfigurationManager.ConnectionStrings[0].ConnectionString pulls something strange. I don't have this kind of settings neither in the library's config nor in the web project's config files.
the App.config looks like that:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="DALConnectionString" connectionString="User ID=sa;Password=pass;Initial Catalog=db;Data Source=srv\SQL2005;" />
</connectionStrings>
</configuration>

Your library should use dependency injection in this case for inversion of control.
Your class in the data access layer (DAL) library should take the connection string as a constructor argument or a property value.
This will make sure that your DAL can be used in other projects also and is not tied to your your mvc web application.
Let the code which will consume the DAL read the connection string from the config file and inject it into your class's constructor.

By default, a class library can't access a config file.
The client of the class library, in this case your web project, can provide config settings.
Therefore, put all the relevant settings, the connection strings, in the web's config file. The ConfigurationManager code in the class library will use the web projects config settings.

you should add the fragment shown above in the web.config then at runtime the configuration manager will use it even if running inside your class library.

You cannot access a app.config for a DLL.
app.config only works for the entry point assembly or web.config for a web project.
Try copying the connection to the entry point config or load the config by parsing the configuration XML - not recommended.

Related

Considerations between OpenWebConfiguration and ConfigurationManager for a MVC5 App

I have a setting I need to read from Web.config for my ASP.NET MVC5 application.
<configuration>
<appSettings>
<add key="MyKey" value="MyValue" />
</appSettings>
</configuration>
I saw an example where someone recommended utilizing OpenWebConfiguration, but I normally use ConfigurationManager.AppSettings["MyKey"]. Checking the MSDN documentation, the OpenWebConfiguration looks older, but still valid. I plan to deploy my application to an IIS server. Did ConfigurationManager replace OpenWebConfiguration, or are they meant for different tasks?
Thank you,
Dan Chase
OpenWebConfiguration is something specifique to the web.config file.
ConfigurationManager is hybrid to configurations files, so it can read information from app.config, web.config and mobile.config files.
Another consideration is that the OpenWebConfiguration allows you to change the web configuration file easily. OpenWebConfiguration is available on the System.Web while the ConfigurationManager is on the System.Configuration.
Use the ConfigurationManager because it is hybrid and if you don't need to change the configuration file, just read the defined configurations. I always use ConfigurationManager in web, forms, services, etc to read appSettings and ConnectionStrings.

Getting web.config details in class library

I am working on an asp .net project in which I wrote a custom library for the logging of data. I am planning to refer this class library in my project and I need to pass some details like filename, filepath etc and from the web project to the class library.
Since this information will change usually, I am planning to give this data in web.config file in the web project. I can read this configuration file data and pass the info to the class library.
Is it possible to pass the whole configuration object to class library and read from there?
In web config add in "configuration" section:
<appSettings>
<add key="logpath" value="c:\logs\log.txt" />
</appSettings>
And in code:
ConfigurationManager.AppSettings["logpath"]

Why is app.config working abnormally?

My problem is solved but I don't quite understand the solution and why it worked. I made a class library "Business Layer" inside a solution which also contains a Windows forms project (C#). Within the class library I put an app.config file and defined a connection string inside it, which I used in SQL-connection code in the business layer. Then I called the database logic in the Windows forms application, but the project failed at the connection string part (i.e., it returned null). However, when I copied app.config to the application project it started working. Why? Why is it that if I am using all database code in the business layer that pasting the code in the application project worked?
Code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=HOME-PC;Initial Catalog=LMS;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
getting:
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString.ToString();
You are using the following code in your program:
string conStr = ConfigurationManager.ConnectionStrings["ConnectionString"]
.ConnectionString.ToString();
So, what does this do? Why is this important?
ConfigurationManager will look for the app.config or web.config (if you are making a web site) that corresponds to the running program. For example, if you have a program called "MyCoolProgram", you would have two output files called "MyCoolProgram.exe" and "MyCoolProgram.exe.config".
It's because of this naming structure that the ConfigurationManager is able to work.
But you already made an app.config, right? You made one in your referencing dll project. Why do you have to make another app.config with the same values?
So let's add in another project to our example. So far our example solution looks like this:
MyCoolProject (exe)
CommonLogic (dll)
If both projects have their own app.config file, the files listed in MyCoolProjects' bin folder would look like this:
MyCoolProject.exe
MyCoolProject.exe.config
CommonLogic.dll
So first, where is the config file for CommonLogic? It's not there. By default, a class library's config file is not copied over with the dll file, but you can see it still exists in CommonLogic's bin directory.
Second, so let's say that you do copy over CommonLogic's config file. You will have a file called CommonLogic.dll.config in MyCoolProject's bin directory. However, with "MyCoolProject.exe.config" empty, your code still can't find the connection string. It's strange because,
The connection string is set (only) in CommonLogic.dll.config
The code that is trying to get the connection string is from CommonLogic
So what gives?
Remember what I said before: ConfigurationManager will look for the app.config that corresponds to the running program, not the assembly that the code was ran from. No matter where your code is, the Configuration Manager is going to look at "MyCoolProject.exe.config" for any values. It's not going to look at anything else. For all intents and purposes, it doesn't even know about any other libraries or config files.
This means that you need to put your connection string (preferably exclusively) in the program that will be consuming the referencing library.
The class library should not be in charge of setting the connection string, that should be up to the program that uses it.
when I copied app.config in actual application project too then it started working, why ?
Because app.config is for the application, not the library. VS just gives you an app.config for a library to show you what should be put in the application configuration file.
It's perfectly reasonable to assume that a library can be used in multiple applications with different configurations, so tying the configuration to the library would make it harder to separate the configuration between applications.

Read config file from asp.net

I'm creating a web application, which calls a DLL to run unit tests, I also have another DLL(DataAccessLayer) which performs connections and performs queries to SQL which references the main DLL. Both the DLLs use the same config file to read settings.
When running application from VS, the application is working fine. However when the web app is deployed to IIS, it seems the DLLs are unable to read the settings from the config file.
After some research I found that I might have to explicitly define the configuration elements in the web.config file, however I don't know how to implement this. Can someone please point me in the right direction?
I'm actually retrieving the settings using the ConfigurationManager with the following code:-
public string GetValue(string key)
{
var appConfig = ConfigurationManager.OpenExeConfiguration("path to dll");
strKeyValue = appConfig.AppSettings.Settings[key].Value;
return strKeyValue;
}
Thanks.
Use WebConfigurationManager.AppSettings["HelloWorldKey"]; to read AppSettings from the web.config.
Just set all the appSettings values used by the DLL you mention, directly in the web.config PRIOR to deploying the app. You don't need to modify this at run-time (and you shouldn't anyway, since any modification to the web.config will cause the application to restart)
Add the connectionstring or AppSetting or ApplicationSettings used in you app.config into your web.config, I understand this is a manual task but is the only way that the config will read the settings.
Use following code to access connection string
string filePath= WebConfigurationManager.AppSettings["Pathfile"].ToString();
Web config Fie
<configuration>
....
<appSettings>
<add key="Pathfile" value="Path to dll"/>
</appSettings>
....
</configuration>

What is App.config in C#.NET? How to use it?

I have done a project in C#.NET where my database file is an Excel workbook. Since the location of the connection string is hard coded in my coding, there is no problem for installing it in my system, but for other systems there is.
Is there a way to prompt the user to set a path once after the setup of the application is completed?
The answers I got was "Use App.Config"... can anyone tell what is this App.config and how to use it in my context here?
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Overview (MSDN)
Connection String Configuration (MSDN)
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files like machine.config. Web also applications inherit settings from applicationHost.config.
Reading from the App.Config
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
Writing to the App.Config
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
Location of the App.Config at Runtime
Q: Suppose I manually change some <value> in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?
A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a ("text.exe.config" in .net framework) or ("text.dll.config" in .net core) in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.
1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.
.NET Core
New configuration options were introduced with .NET Core and continue with the unified .NET (version 5+). The way that *.config files works hasn't fundamentally changed, but developers are free to choose new, more flexible configuration paradigms.
As with .NET Framework configuration .NET Core can get quite complex, but implementation can be as simple as a few lines of configuration with a few lines of c# to read it.
Configuration in ASP.NET Core
Configuration in .NET Core
Simply, App.config is an XML based file format that holds the Application Level Configurations.
Example:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="key" value="test" />
</appSettings>
</configuration>
You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:
var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"
Note: ConfigurationSettings is obsolete method to retrieve configuration information.
var value = System.Configuration.ConfigurationSettings.AppSettings["key"];
App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
See this MSDN article on how to do that.
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases.
PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
Just adding one more point
Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below
ConfigurationSettings.AppSettings["Key"]
Application settings enable you to store application information dynamically. Settings allow you to store information on the client computer that shouldn't be included in the application code (for example a connection string), user preferences, and other information you need at runtime.
To add an application configuration file to a C# project:
In Solution Explorer, right-click the project node, and then select Add > New Item.
The Add New Item dialog box appears.
Expand Installed > Visual C# Items.
In the middle pane, select the Application Configuration File template.
Select the Add button.
A file named App.config is added to your project.
take a look at this article

Categories

Resources