Change connection strings in Winforms - c#

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.

Related

Changing connection string dynamically on runtime in WinForms

I am making Winform dekstop application. I am giving an option in my application that user can select database or set database path. when user select database or database path then connection string should be changed at runtime in APP.config.
You probably shouldn't try and change the connection string in the config at runtime. You could have a set of possible connection strings in the <connectionStrings> section of the config file, allow the user to choose what database they want to use and read the appropriate connection from the file.
Even if there is no special needing for connection strings being stored in the standard way in the configuration file,it could be convenient to have a bounch of named <connectionStrings> in the standard configuration file and you can enumerate it like this:
foreach (ConnectionStringSettings c in System.Configuration.ConfigurationManager.ConnectionStrings)
{
//present the name in some combo etc etc.
}
then the user can select the connection string based on a friendly name.
The configuration file for your app will look like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
.....
<connectionStrings>
<add name="connection1" connectionString="Data Source=your connection string 1" />
<add name="connection2" connectionString="Data Source=your connection string 2" />
<add name="connection3" connectionString="Data Source=your connection string 3" />
</connectionStrings>
....
Is the path of database file effects connection string??? One database is in my "C:\ProgramFiles\SQLEXPRESS\data\abc.mdf" and same database with same name is in "F:\mydb\abc.mdf" both database have same connection string or not????

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.

Trying to get String from App.config File

I'm desperately trying to make a working app.config file in which I want to save the connection strings for my database connections.
This is my app.config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Con" value="User Id = *******;password=**;data source= (DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ******)(PORT = 1525))(CONNECT_DATA =(SERVER = DEDICATED)(SID = emtst)))"/>
</appSettings>
</configuration>
And when I try to read it here:
string connStr = ConfigurationManager.AppSettings["Con"];
this.odacManager = new ODACManager(connStr);
I just get an empty string. I'm using System.Configuration.
I've also tried to use
ConfigurationManager.Connectionstring["Con"].ConnectionString
but that also didn't work.
You should be using the <connectionStrings> element in your config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Con"
connectionString="User Id=*******;password=**;data source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = ******)(PORT = 1525))(CONNECT_DATA =(SERVER = DEDICATED)(SID = emtst)))"/>
</connectionStrings>
</configuration>
and then read it out as:
string connStr = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
Update:
In .NET, class library projects cannot have their own config files - they won't be used and won't be evaluated at runtime.
If your class library needs any configuration, you need to put that configuration into the host application's app.config (or web.config) so that the class library can find it there (and use it).
try
System.Configuration.ConfigurationSettings.AppSettings["Con"].ToString();

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.

How do I write an external connection string config file and make my c# application recognize and read it?

My current c# windows form application is using the following code to connect to a database to retrieve information and the it is stored at Setting.cs
public static String connectionString ="Data Source=####; Initial Catalog=###; User ID=####; Password='####'";
I have written out an external Connection.config file and the content would be :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Connection" providerName="System.Data.providername"
connectionString="Data Source=####; Initial Catalog=###; User ID=###; Password='####!';" />
</connectionStrings>
</configuration>
is the above code written correctly? as I sort of just copied and paste online and editted the connection string part as i do not know what does the "add name" and providerName part does.
what i would like to ask is where should i write the code in my forms to read the connection string from my external config file so i can remove the one in my setting.cs file.
thank you.
don mind the ### as it is just replaced by me to represent the information.
You can use config source to split your config files. Example App/web.config:
<connectionStrings configSource="myExternalConfigSource.xml" />
External Config:
<connectionStrings>
<add name="Connection" providerName="System.Data.providername"
connectionString="Data Source=####; Initial Catalog=###; User ID=###; />
</connectionStrings>
More info: http://www.nikhilk.net/Entry.aspx?id=158
If you use this method, you can reference your config as normal and still have your configuration split out into seperate files.
Add the following in your web.config file right at the bottom above the closing config tag.
<connectionStrings>
<add connectionString="Data Source=Servernamegoeshere;Initial Catalog=databasenamehere;Persist Security Info=True;User ID=***;Password=***" name="nameyouwanttogivethisconnection" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
To reference the connection on the page load of the main form use this:
public void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["nameyouwanttogivethisconnection"].ConnectionString;
SqlConnection SqlConnection = new SqlConnection(connectionString);
SqlCommand SqlCommand = new SqlCommand("update table etc etc....",SqlConnection);
SqlConnection.Open();
SqlCommand.ExecuteNonQuery(); //This line is for updates and inserts, use SqlCommand.ExecuteReader(CommandBehavior.CloseConnection); for select statments
SqlConnection.Close();
}
Make sure you add these references to the top of the page you are using this code on:
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
You may then use that connection to create a Sqlcommand to run against your database.
we use:
<configuration>
<appSettings>
<add key="connection.string" value="Initial Catalog=XXX;server=localhost;User=YYY;Password=ZZZ;" />
</appSettings>
</configuration>
and then just:
ConfigurationManager.AppSettings["connection.string"];
You could also use ApplicationSettings, and forget about writing information in config files manually (It will be done automatically)
Right click on your project in solution explorer and select Properties.
Go to Settings tab.
Click on the link to create the settings file. (It will be called Settings.settings)
For Name, type the name you want to use for the connection string. (i.e. ConnectionString)
For Type, select Connection String
For Scope, select Application
For Value paste your connection string.
When you want to use it, just type
Application.Settings.Default.ConnectionString
i.e
SqlConnection connection = new SqlConnection(Application.Settings.Default.ConnectionString);

Categories

Resources