ConfigurationManager.ConnectionString reads app.config from different location - c#

The app.config of my C# windows application has the following ConnectionString
<connectionStrings>
<add name="DS1" connectionString="Data Source=DataSource1;" providerName="" />
<add name="DS2" connectionString="Data Source=DataSource2;" providerName="" />
<add name="DS3" connectionString="Data Source=DataSource3;" providerName="" />
<add name="DS4" connectionString="Data Source=DataSource4;" providerName="" />
</connectionStrings>
After installing the setup, the same connection strings exist in the projectname.config of installation directory C:\ProgramFiles\ProjectName\ProjectName.config.
When i run the application, i have the following code to access the connection string
foreach (ConnectionStringSettings key in ConfigurationManager.ConnectionStrings)
{
Display ConfigurationManager.ConnectionStrings[key.Name].Name,
}
The Key names are not displaying as DS1, DS2, DS3 and DS4 .
Instead it is reading the ProjectName.config file present in
C:\Users\UserName\AppData\Local\VirtualStore\Program Files\ProjectName\ProjectName.exe.config
This was saved long back when project was installed but when uninstalled it doesn't get removed.
How can i make changes in C# to read the proper ProjectName.config file from installation dircectory and not from AppData folders.

Try this
string theConfigFileName ="FilePath";
ExeConfigurationFileMap userConfigFileMap = new ExeConfigurationFileMap() { ExeConfigFilename = theConfigFileName };
Configuration userConfig = ConfigurationManager.OpenMappedExeConfiguration(userConfigFileMap, ConfigurationUserLevel.None);
foreach (var item in userConfig.ConnectionStrings.ConnectionStrings)
{
}

On app startup you could check for the existence of the original config and delete it.
string originalConfig = string.Format("C:\Users\{0}\AppData\Local\VirtualStore\Program Files\ProjectName\ProjectName.exe.config", Environment.UserName);
if (System.IO.File.Exists(originalConfig))
{
System.IO.File.Delete(originalConfig);
}
If you wanted to do it during the uninstall, you could execute this code in a custom action:
System.IO.Directory.Delete("%APPDATA%\ProjectName");
See msdn for creating a custom action

Related

Can't read database name web project

Trying to read the database name but it's not working in the site. Using an asp.net web project with a solution file. I put this in the web.config. This will change depending on development database or production database PRODDB via the web configuration transform files and scripts.
<appSettings>
<add key="databaseName" value="DEVELDB"/>
<add key="operatingEnvironment" value="dev"/>
</appSettings>
Within the Global.asax.cs file:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var operatingEnvironment = WebConfigurationManager.AppSettings["operatingEnvironment"].ToString();
if (operatingEnvironment == "dev")
{
Application["DBE"] = WebConfigurationManager.AppSettings["databaseName"].ToString();
}
}
Within the login.cs class file:
internal static DatabaseConnection GetDatabaseConnection()
{
return
new DatabaseConnection(
new ConnectionProperties
{
User = Shared.User,
Application = Shared.Application,
DatabaseName = (string)HttpContext.Current.Application["DBE"]
});
}
and within the Web.Development.config file there is:
<appSettings>
<add key="databaseName" value="DEVELDB" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
<add key="operatingEnvironment" value="dev" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>
However, whenever I debug after login, it goes to the code below which is good (the same as coded above) but says Database name was not specified? I have it specified as DEVELDB and using "DBE" to reference it. However, it's not like it debugs to another area and to there, just straight to there and kills it?
...
{
User = Shared.User,
Application = Shared.Application,
DatabaseName = (string)HttpContext.Current.Application["DBE"]
});
Connections to databases go inside the "connectionstrings" tags in you "webconfig" file. If you need SqlServer it is shown below
<configuration>
<connectionStrings>
<add name="TwoWayConn" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\TwoWayData.accdb"
providerName="System.Data.OleDb" />
<add name="TWOWAYDATASQL" connectionString="Data Source=TBIRD\SQLEXPRESS1;Initial Catalog=TWOWAYDATASQL.MDF;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
</configuration>
Am I misunderstanding what you are trying to do?

Read connection string from web.config file when deploy to IIS7

It seems to be pretty simple question but not for me. I am trying to read connection string from web.config file.
I have WCF service application which have web.config file. In web.config file I defined connection strings.
Then I deployed wcf application on IIS7 under default web site(One template which comes when you install IIS7).
Now when we read connection string then it is not giving me connection strings which define in wcf web.config file. Somehow I am not able to access it. And while debugging when I found a connection string which is actually not connection string which I defined in wcf web.config but it is default web site connection string which I don't want.
I want to access connection string which I defined WCF web.config file only. I am stuck in it. I tried all but with no luck. For reference I am putting code which I tried and web.config code also.
Web.Config code.
<configuration>
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=2.4.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<appSettings>
<add key="ConnString" value=""/>
<!--<add key="ConnString" value=""/>-->
</appSettings>
<connectionStrings/>
<system.web>
<httpRuntime maxRequestLength="2097151"
useFullyQualifiedRedirectUrl="true"
executionTimeout="14400" />
<compilation debug="true" />
</system.web>
Code to read connstring
string connString = string.Empty;
string svcDir = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
DirectoryInfo rootDir = Directory.GetParent(svcDir);
string root = rootDir.FullName;
string webConfigFilePath = root + "\\Web.config";
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = webConfigFilePath;
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
var test = configuration.ConnectionStrings.ConnectionStrings;
string connectionString = "";
if (configuration.ConnectionStrings.ConnectionStrings["ConnString"].ConnectionString.Length > 0)
{
connectionString = configuration.ConnectionStrings.ConnectionStrings["ConnString"].ConnectionString;
}
//var connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnString"];
//if (connectionString != null)
//{
//}
return connString;
I am using .net framework 4.0, IIS 7, apppool is .net framework 4.0 and windows 7 machine.
Thanks,
Awadhendra
The web.config has a dedicated section for connection strings, and the code you are using is using the configuration manager to access the connection strings section in the web.config. The problem you have is that you haven't put the connection string in the connection strings section, you have put it in the app settings. Move the connection string out of app settings and put into the connection strings section, or change your code to read it from app settings. Now storing a connection string in app settings was the way it was done in .NET 2.0, but since then (.NET 3.5) there has been a dedicated section made for connection strings.
please refer here
e.g.
<connectionStrings>
<add name="ConnString" connectionString="xxxwhateveritisxxx" />
</connectionStrings>
or code to read it from app settings (if you must have it in app settings, although I wouldn't recommend):
string connectionString = ConfigurationManager.AppSettings["ConnString"];
Can u give a try to this :-
string connString = ConfigurationManager.AppSettings["ConnString"].ToString()
return connString;
It will read the app setting section of your web.config.

How to change the content of my app.config after installation of the application

I am working on WPF application that soon has to be ready for installation but there is a functionallity that allows the user to make changes to the app.config file and I don't know how to do that from the code-behind of the application.Also I don't know how this is going to work after the installation of the app.
Simply said: I have a window that allows the user to enter a text that is going to be searched for in the web.config of another application.So in my app.config I have a different searches and I want after the installation the user to be able (after entering values in the window's textoxes) enter new values in the app.config of the application.
Can somebody tell if that is possible and eventually how I could achieve this?
How I did in my application. I have app.config as following
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="StoreConnectionString"
connectionString="Data Source=.\;MultipleActiveResultSets=True;Initial Catalog=Store;Integrated Security=False;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ExportPath" value="D:\" />
<add key="CompanyName" value="My Company" />
<add key="mail" value="email#mail.com" />
<add key="phone" value="+992918254040" />
<add key="ExpDate" value="Pink" />
<add key="Print" value="No" />
<add key="EnforcePassw" value="Yes"/>
</appSettings>
</configuration>
So I can change and save app Settings from my application, here is code
private void btnSave(object sender, RoutedEventArgs e)
{
//returns path of folder where your application is
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
//combines path of folder and file
string configFile = System.IO.Path.Combine(appPath, "MyApp.exe.config");
//Defines the configuration file mapping for an .exe application
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["ExportPath"].Value = txtExport.Text;
config.AppSettings.Settings["CompanyName"].Value = txtComapny.Text;
config.AppSettings.Settings["mail"].Value = txtEmail.Text;
config.AppSettings.Settings["phone"].Value = txtPhone.Text;
config.AppSettings.Settings["Print"].Value = print;
config.AppSettings.Settings["EnforcePassw"].Value = password;
config.AppSettings.Settings["ExpDate"].Value = color;
config.Save();
}
Hope it will be help you!
If you want to add new strings use this code;
config.AppSettings.Settings.Add("Key", "Value");
this may be helpful
Configuring Application/User Settings in WPF the easy way.

Reading a connection string from a class library

I am currently struggling to read a connection string from the App.config inside my WinForms application from my Class Library (and Unit Testing).
I added a 'test' entry to the App.config;
<connectionStrings>
<add name="MyConnString" connectionString="Test;" />
</connectionStrings>
My TestMethod looks like this;
[TestMethod]
public void TestConnection1()
{
string connString = "";
if (ConfigurationManager.ConnectionStrings["MyConnString"] != null)
{
connString = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
}
string expected = "Test;";
string actual = connString;
Assert.AreEqual(expected, actual);
}
This, obviously, fails. Actual's value is empty.
What am I doing wrong?
you need to add connection string key into Test project's config as well.
Regarding your comment to DJ Kraze: "#DJ KRAZE, If I put 0 as index, it returns me a connectionstring for SQLExpress "aspnetdb.mdf". If I put 1 as index, I get an exception (IndexOutOfRangeException), so obviously my string is not found."
The problem is you forgot the configuration element. For example:
Referenced from MSDN: Storing and Retrieving Connection Strings
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<clear />
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
The machine.config file also contains a <connectionStrings> section, which contains connection strings used by Visual Studio. When retrieving connection strings by provider name from the app.config file in a Windows application, the connection strings in machine.config get loaded first, and then the entries from app.config. Adding clear immediately after the connectionStrings element removes all inherited references from the data structure in memory, so that only the connection strings defined in the local app.config file are considered.

Multiple SQL Server connection strings in app.config file

I'm interested in displaying in a Windows Forms app a list of N radio buttons for the user to choose a target database server. I would like to add the SQL Server connection strings in the app.config file, so they are read by the app at runtime and rendered in the windows form as radio buttons.
At first I thought of using a delimiter to separate the connections
<appSettings>
<add key="ConnectionString" value="connection1|user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30|connection2|user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</appSettings>
And then split the key value pairs.
Is it possible to do this in a different way?
To find all defined connection strings from your app.config, use the ConfigurationManager (from System.Configuration).
It has an enumeration: ConfigurationManager.ConnectionStrings which contains all entries in your <connectionStrings>.
You can loop over it with this code:
foreach(ConnectionStringSettings css in ConfigurationManager.ConnectionStrings)
{
string name = css.Name;
string connString = css.ConnectionString;
string provider = css.ProviderName;
}
The Name is just the symbolic name you give your connection string - it can be anything, really.
The ConnectionString is the connection string itself.
The ProviderName is the name of the provider for the connection, e.g. System.Data.SqlClient for SQL Server (and others for other database system). If you omit the providerName= attribute from your connection string in config, it defaults to SQL Server (System.Data.SqlClient).
Marc
Use the connectionStrings section to define your connection strings.
<connectionStrings>
<add name="connection1" connectionString="user id=user;password=123;server=10.0.0.1;database=myDatabase;connection timeout=30"/>
<add name="connection2" connectionString="user id=user;password=123;server=10.0.0.2;database=myDatabase;connection timeout=30"/>
</connectionStrings>
Yes, it is possible to do this in another way. Check the connectionStrings section that you can make in the app.config file.
<configuration>
<connectionStrings>
<add name="" connectionString=""/>
<add name="" connectionString=""/>
</connectionStrings>
</configuration>
We can declare multiple connection string under Web.Config or App.Config
<connectionStrings>
<add name="SourceDB" connectionString="..." />
<add name="DestinationDB" connectionString="..." />
</connectionStrings>
In DAL or .cs file you can access connection strings like this string SounceConnection = ConfigurationManager.ConnectionStrings["SourceDB"].ConnectionString;
string DestinationConnection = ConfigurationManager.ConnectionStrings["DestinationDB"].ConnectionString;
You can use the AppSettings class, get a list of all keys that start with ConnectionString and display them.
Your config file will look like this:
<appSettings>
<add key="ConnectionString_Name1" value="..."/>
<add key="ConnectionString_Name2" value="..."/>
<add key="ConnectionString_Name3" value="..."/>
</appSettings>
You can get the name, by splitting the key name (using "_" in this example).
BTW: You should also use the ConnectionStrings section, you are only interrested in connection strings.
This is how to use LINQ to get list of connection strings:
List<string> connectionStrings = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.Select(v => v.ConnectionString)
.ToList();
Or you can build a dictionary of it:
Dictionary<string/*name*/, string/*connectionString*/> keyValue = ConfigurationManager.ConnectionStrings
.Cast<ConnectionStringSettings>()
.ToDictionary(v => v.Name, v => v.ConnectionString);

Categories

Resources