C# linq to sql access app.config file - c#

I am having a linq to sql problem with a C# 2010 windows form application when it is changed to a dll and accessed by other applications. The purpose of the calling the code as a dll is for performance reasons and to share the code accross multiple applications.
When the application is on its own, it runs fine.
Basically when the linq to sql was dragged to the desktop, a default linq to sql connection was setup by the .net framework. However I changed the *.designer.cs to use the system.configuration namespace,
added a reference to the system.configuration namespace, and changed the default linq to sql connection to use the database connection obttained in app.config file. I also removed any refernces to the default database connections in the the 'properties or 'settings' section for each project file folder.
Now the problem is the default setting values to the database are reset by the .net framework. Thwe values in the app.config file are no longer being used.
Can you show me code, point me to a reference, and/or tell how I can make this application is the connection string values in the app.config file again?

A dll is run in the the context of the application calling it. It is not an application in its own right, so giving it an app.config file is useless. The configuration settings used by the dll are supplied by the calling application's .config file (it can be an app.config file or a web.config file). In your case, any application using the dll must have the database connection defined its own .config file.

Related

Using external config file for connection strings in multiple projects

I want to know if there is a better way to use connection strings in external files in my solution, since my solution has 8 separate projects, all using the same connection strings. According to this:
https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/connection-strings-and-configuration-files#using-external-configuration-files
using an external file (for connection strings) is trivial, and can be easily done (using something like configSource="connections.config). However, in order to make this work, We have to follow these guidelines:
The external file has to exist within the project folder
The external file has to have the property "CopyToOutputFolder" set to true
In my case, this can be done, but it's problematic to manage this throughout all 8 projects, especially if I need to add a new connection string, change one of the settings (target database, username, password), or when I need to add a new project.
--FYI: each of these projects are web jobs that are deployed to an Azure server. Adding a new web job for a new feature, new utility, etc., or removing an old web job for any number of reasons is not uncommon. This solution is constantly changing, which adds to the difficulty of managing these settings within each project separately. Also, connection string management on the production server is not problematic, since each web job inherits these connection strings from the parent app service.
I would like to know if any of the following is possible;
Can I use a separate file that is NOT within the project folder for the connection strings?
Can I load connection strings dynamically (at run-time) into the configuration manager? (one note on this - I know this is possible, but I need to be able to do it without affecting the underlying app.config file)
Is there another type of ConfigurationManager that is commonly used to load these connection strings into the solution, that will meet my requirements?
Although this question is over a year old, I thought an up-to-date answer would be useful for any Windows desktop coders wanting to reference connection strings outside the project folder's app.config etc. This would be useful for sharing 1 config file for multiple projects, having to only change connection string in 1 centralised file.
The basics of telling App.Config to use a different file for connection strings, is straightforward; however, .NET appears NOT to be able to parse this external file, if it is either NOT in the project's root folder, or a subfolder(s) within that project. Let's see this by looking at the most basic example:
in the project's App.config, within the <configuration> tag, use the code below ('configSource' points to another file to read the connection strings):
<configuration>
<connectionStrings configSource="ExternalConnectionStrings.config"/>
</configuration>
Create ExternalConnectionStrings.config, with the following code:
<connectionStrings>
<clear/>
<add name = "ConnString1"
connectionString = "Server=myServer;Trusted_Connection=True;Database=myDB;Persist Security Info=false"/>
<add name = "ConnString2"
connectionString = "Server=tcp:azureserver.database.windows.net,1433;Database=AzureDB;User ID=**;Password=**;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;Persist Security Info=false"/>
</connectionStrings>
Save this config file in the same folder as your project's App.config and mark this file's property to 'Copy to Output Directory' or 'Copy if newer'.
This is the 'textbook' way of referring to connection strings from another file other than App.config. However, this may not be that useful: how to have this external file in a completely different folder from the project folder?
To do this, copy that same ExternalConnectionStrings.config to a folder OUTSIDE the project or solution folder, eg. C:\ConnectionStringsFolder\. REMOVE this config file from the project folder where we previously copied/created it (otherwise the following instructions will not work).
Keep App.config the same (making sure the ExternalConnectionStrings.config is not present in the project folder). Use the Windows mklink command to associate ExternalConnectionStrings.config to an external folder, with the following command prompt command:
mklink ExternalConnectionStrings.config C:\ConnectionStringsFolder\ExternalConnectionStrings.config
Windows should return with a 'symbolic link created for....'; make sure you did NOT have that particular config file present in the project folder where app.config sits.
You should see the ExternalConnectionStrings.config listed within eg. Visual Studio; make sure you mark this to COPY to the output folder (I use 'Copy if newer', which will pick up any changes to the external config file ONLY after a rebuild of the project).
This answers Matt Spinks' question 1; for question 2, the following method will return all connection strings found within the external file (as pointed to by App.config):
using System.Diagnostics;
using System.Configuration;
static void GetConnectionStrings()
{
ConnectionStringSettingsCollection cStringsSettings = ConfigurationManager.ConnectionStrings;
if (cStringsSettings != null)
{
foreach (ConnectionStringSettings cstrings in cStringsSettings)
{
Debug.WriteLine(cstrings.Name);
Debug.WriteLine(cstrings.ConnectionString);
}
}
}
This is currently working in Visual Studio 2019, with .NET Core 3.1, a WPF application, on Windows 10.
You don't mention which version of dotnet you are using, however if you are using dotnet core the application configuration can be sourced from environment variables.
I think this could solve your problem because you don't need to track any additional files between your projects and in my opinion makes a lot of sense because any secure data would not be visible to any developer or be stored in any repository. Only devops would know about it when they set it initially. Also this gets your closer to the 12 factor app https://12factor.net/.
To use this make sure that your Startup.cs file includes a section to load the environment variables such as
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true)
.AddEnvironmentVariables()
.Build();
dotnet core Environment Variable cnfiguration provider
You can probably create a bat file to set everything initially
setx connection_string="Server=xxxxxxxxx" /M
This will create your environment variables and set the values you specity.
Hope you find this useful.

Why wont my application read my DataAccessLayer.dll.config file?

I'm trying to use application settings with a C#.NET project I am working on. But I can't seem to get it to return anything other then the default values. Through the project properties I've added a single setting, DBConnectionString, and set its value to a connection string I want to use. Its scope is set to "application".
Doing this created a number of files including Settings.settings, Settings.Designer.CS, and app.config. The Settings class then has custom, type safe, properties that can be used to set and retrieve each setting. The app.config file is a XML file that stores the actual settings values.
When I build my project it looks like the app.config file is copied to the target directory as DataAccessLayer.dll.config. My program runs fine and is able to use the default connection string.
Next I tried to edit the DataAccessLayer.dll.config file to change the connection string. I ran my program again, but it continued to use the default value.
This project is a class library that use to a Web project and sometimes the connection string can changes.
Builds will output config files named after the dll however those aren't actually what's read on app start up. You could put the setting in the web apps config (example here Equivalent to 'app.config' for a library (DLL)), those are the settings you'll actually be running with in this case.
If you want your library to be portable you'll have to either; 1) make your own config class/file 2) Read your dll's app config manually (example in the answer I linked to above) or 3) Put your setting in the importing projects app.config
In this case I would just put your connection string data in the web apps config. If DataAccessLayer.dll is only for internal use, this is in my experience the most common pattern, and doesn't really have many cons. Ultimately I would have these values set during my build or by a deploy utility like Salt or Chef. If you're manually editing the web apps config on or after deploy then you're doing it wrong.

No connection string named '' could be found in the application config file

I have a class library with a method that takes a string and returns an xml document. This library references another project - containing edmx models generated with EF6 db first.
I realize that my connection strings from the EF project must be moved into the "executing" application config file - this is fine in development as I have created a simple web client as my startup project and it's web.config contains the necessary connection strings.
When I deploy this solution to my QA server, the "executing" application is actually a VB6 app and I am getting this error. I have no idea what application config file is being used in this case.
Any suggestions?

Forcing Entity Framework and ASP.MVC to use the connection string from app.config of another assembly

Set & settings:
I use Entity Framework 5 and have a dll project with edmx file. In this project I have App.config with connection string for the EF model. I have also second project, ASP.MVC 4 web application which is a startup project. It references the database project. Important thing is - db is Oracle and EF uses Oracle custom providers.
Problem:
If I place my connection string in the ASP.MVC startup project is works fine. It's common advice to do this. But I don't want to. I don't see reason why I should. How can I force MVC/EF to find the connection string in App.config of the external library (which as a matter of fact is a data access layer)?
App.Config is used by WinForms, WPF and executable applications.
Web.Config is used in IIS (and is able to set IIS environment specific configurations)
It seems no App.Config will ever be merged to the Web.Config (source):
In using an App.config, file the configuration system merges the
App.config file with content of the Machine.config file when the
application starts and the configuration is applied. This mechanism
allows machine-wide settings to be defined in the Machine.config file.
The App.config file can be used to override the settings of the
Machine.config file; you can also lock in the settings in
Machine.config file so that they get used. In the Web.config case, the
configuration system merges the Web.config files in all directories
leading up to the application directory into the configuration that
gets applied. For more information about configuration and the setting
priorities, see topics in the System.Configuration namespace.
Perhaps you'll find a solution more appropriate to your needs by using Application Configuration Files.
Finally, after facing multiple issues, I've decided to move connection string of DAL into the Web.config of the web application. I was convinced by some arguments you can read here in the post of Chris Ammerman.

.NET including class library database (and other resources) with windows app deployment

I have a class library that attaches itself a tiny SQL Server database that resides in its Data Directory. When i'm using this class library with another windows application i see that once i compile my code, the database files get copied to the bin folder of my windows app project. However when i publish the windows app,install, and run it, i get the error 'An attempt to attach an auto-named database for file C:\Documents and Settings\User\Local Settings\Apps\2.0\Data..\DB.mdf failed.' Obviously this folder doesn't have the mdf files.
I guess this won't be a problem if i just add the database files to my windows application project. But surely there's a better way?
You could include an SQL script for creating the database into your "installation/run first time routine".
I guess that you've already stated that having a form of SQL Server is an installtion prerequisite.
For the data files I would recommend that you use a variable connection string for accessing your database. That way you can change the installation routine to include asking the user where they wish to have the data files installed and save that as part of your connection string to the app.config file.
Conversely you could also use the users selection of where to install the app to override the relative path stored for the database within your code (using the same connection string variable as mentioned above).

Categories