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.
Related
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
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.
I am developing win forms and i have App config file .How can I write to connection strings section of app config file?
My current App.Config file is
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDbConnection" connectionString="" providerName="System.Data.OleDb" />
</connectionStrings>
</configuration>
and my C# code to change the Connection String is
var Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)Config.GetSection("connectionStrings");
ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + "";
Config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
however Exception is generated at 3rd Line it is
configuration error exception this configuration is read only
The code to change connection strings is called from an external class.I dont know where should i place the code to override IsReadonly() method .
Also app config does not have code behind file.
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
</configuration>
When you save your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.
ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];
ConnectionStringsSettings class provides properties to read connection string settings in your program as follows:
string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;
To write your connection string in App.config file you can use:
Create two settings, example: AppConnectionString (type: string) and ServerConnectionString (type: ConnectionString)
Modify settings code, on get property of ServerConnectionString setting change the return value to AppConnectionString.
By doing this you can modify, save, or reload AppConnectionString setting, and when you refer to ServerConnectionString on your application, it will return AppConnectionString setting. TRY IT.
I use System.Configuration.ConfigurationManager.AppSettings["key1"] in settings.designer.cs file. It's working fine in the development but after I moved all the .dll files into production it is not working.
In web.config file I added app settings in development and production both. What is the problem?
Code from settings.designer.cs file
get
{
return WebConfigurationManager.AppSettings["ConnectionString"];
//return (AppSettings["ConnectionString"]);
//return ((string)(this["ConnectionString"]));
}
I tried all three return statements. 3rd return is working fine in both dev & prod but it is not rendering from web.config.
Code in web.config
<add key="ConnectionString" value="connection string values are given here">
Don't use WebConfigurationManager.
Use System.Configuration.ConfigurationManager.AppSettings["key"] instead to read key-value pair kept in Web.config, e.g.:
<configuration>
<appSetttings>
<add key="key1" value="value1" />
</appSetttings>
</configuration>
and System.Configuration.ConfigurationManager.ConnectionStrings["name"].ConnectionString to read connection string, e.g.:
<configuration>
<connectionStrings>
<add name="name" connectionString="value1" />
</connectionStrings>
</configuration>
You have to add configuration setting (connectionstring) to last execution program 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);