Can we declare variables in the 'app.config' file? - c#

I have a form which needs to get connected to SQL Server, and I have a drop down for selecting the list of databases and perform operations like primary key checking, etc.
But presently my connection string looks like this:
SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");
But apart from the given database, I need to take it variable, so that I can connect it to the database I select from the dropdown.
How can I do this?

Hmm you can declare your variables like this
<appSettings>
<add key="SmtpServerHost" value="********" />
<add key="SmtpServerPort" value="25" />
<add key="SmtpServerUserName" value="******" />
<add key="SmtpServerPassword" value="*****" />
</appSettings>
and read like
string smtpHost = ConfigurationManager.AppSettings["SmtpServerHost"];
int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpServerHost"]);

I think he wants a "semi constant":
Web.Config
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<add name="YourName" providerName="System.Data.ProviderName" connectionString="Data Source={0}; Initial Catalog=myDataBase; User Id=myUsername; Password=myPassword;" />
</connectionStrings>
</configuration>
CS file
String Servername = "Test";
String ConnectionString = String.Format(ConfigurationManager.ConnectionStrings["YourName"].ConnectionString, ServerName);

you can use the connectionStrings tag in the app.config configuration. You can add as many as you want (giving them each a separate key) and then retrieve them
example app.config xml (set providerName to a valid provider, for example System.Data.SqlClient, and the appropriate connection string) :
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<clear />
<add name="firstDb"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
<add name="secondDb"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
example on getting them and listing them (in your case, you would create the appropriate items in the dropdown and set the values) :
ConnectionStringSettingsCollection settings =
ConfigurationManager.ConnectionStrings;
if (settings != null)
{
foreach(ConnectionStringSettings cs in settings)
{
Console.WriteLine(cs.Name);
Console.WriteLine(cs.ProviderName);
Console.WriteLine(cs.ConnectionString);
}
}

You could use the AppSettings section. Read here for an example.

Related

Is it possible to reference the same connection string in multiple places in a config file?

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="DefaultConnection" connectionString="Server=test.com,1234;" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="serilog:write-to:MSSqlServer.connectionString" value="here reference the DefaultConnection connection string." />
</appSettings>
</configuration>
Same connection strings needs to be referenced in multiple places. For typo mistakes I would like to be able to reference a single connection string in the same file.
Is this possible?

Updating a config file adds additional config sections

My goal is to programatically update a .config file belonging to another application.
I start off with a simple config file that looks like this...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test1" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I then run my code to update the connection string named Test1 and rename it to Test2...
var configMap = new ExeConfigurationFileMap() { ExeConfigFilename = #"test\app.config" };
var externalConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
externalConfiguration.ConnectionStrings.ConnectionStrings[1].Name = "Test2";
externalConfiguration.Save(ConfigurationSaveMode.Minimal, true);
This saves the configuration file, but now looking at the file you will see some other data has been added to it...
ConfigurationSaveMode.Minimal
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test2" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<trust level="Full" />
<webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
</system.web>
</configuration>
ConfigurationSaveMode.Modified
Using the Modified setting I get even more "stuff"...
<configuration>
<appSettings />
<configProtectedData />
<system.diagnostics />
<system.windows.forms />
<uri />
<connectionStrings>
<add name="Test2" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.net>
<authenticationModules />
<connectionManagement />
<defaultProxy />
...snip...
What is this data and where has it come from? More importantly how can I stop it from being written into my file?
Try changing the ConfigurationSaveMode from
ConfigurationSaveMode.Minimal
to
ConfigurationSaveMode.Modified
Modified only saves the properties that you have changed.
From MSDN:
Full
Causes all properties to be written to the configuration file. This is useful mostly for creating information configuration files or moving configuration values from one machine to another.
Minimal
Causes only properties that differ from inherited values to be written to the configuration file.
Modified
Causes only modified properties to be written to the configuration file, even when the value is the same as the inherited value.
The way I have solved this was to set the Machine Configuration File to be the same as my EXE Configuration file, this way the .net Configuration object does not see that there is any difference between Machine and EXE when it is saving.
For example:
var fm = new ExeConfigurationFileMap();
fm.MachineConfigFilename = fm.ExeConfigFilename = #"C:\dude.config";
var c = ConfigurationManager.OpenMappedExeConfiguration(fm, ConfigurationUserLevel.None);
// Do Stuff
c.Save(ConfigurationSaveMode.Minimal, true);
This way you should not get the section in your config file upon save.

Is there anything wrong with ConfigurationManager in C#?

I read many topics related to configuration manager but could not resolve the issue. I just want to read the connection string as well some appsetting keys from a CLASS LIBRARY in the web application.
I have reference to System.Configuration Class.
This is my code:
using System.Configuration;
...
string constr = ConfigurationManager.ConnectionStrings["cbuddydb"].ConnectionString;
string strUserName = ConfigurationManager.AppSettings["username"];
string strPwd = ConfigurationManager.AppSettings["password"];
But it seems reading from a different config file. not from the web.config in my project. Because the value read is wrong.
My web.config is below:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.data>
<connectionStrings>
<clear />
<add name="cbuddydb" connectionstring=
"Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True;
User=#username;Password=#password;Option=3" providerName="MySql.Data.MySqlClient" password=""/>
</connectionStrings>
<appSettings >
<clear />
<add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/>
<add key="password" value =""/>
</appSettings>
</system.data>
</configuration>
The reason for this is because of configuration file inheritance. The connection string at index 0 may not be in your config file, but it may have been inherited from machine.config etc. Have a look at ASP.Net config file hierarchy and inheritance: http://msdn.microsoft.com/en-us/library/ms178685.aspx
You could clear the inherited connection strings by specifying the following in your web.config
<connectionStrings>
<clear />
<add name=”MyConnString” connectionString=“Whatever“ />
</connectionStrings>
EDIT: In your config, place your connectionStrings and appSettings tags directly below the configuration element. They should not be within the system.data element. They are direct children of the configuration element. And remove the extra password attribute after the providerName. I can't validate your connection string, since I don't know how you're using it.
<configuration>
<connectionStrings>
<clear />
<add name="cbuddydb" connectionString=
"Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase;Persist Security Info=True;
User=#username;Password=#password;Option=3" providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
<appSettings >
<add key="username" value ="6/0RUNnSmUBsbdNoCg+9Sw=="/>
<add key="password" value =""/>
</appSettings>
<system.data>
....
You should consider encrypting sensitive information in your config file, like passwords.

Getting configuration values rom XML file located in the same project

I am making a little program to copy pictures form one location to another. The information for the pictures are stored in a database so I need connections string and also I create a txt file with the final output from the operation and I want to store these two values in a App.Config.xml file.
The structure of my project is very simple :
And the XML files itself is :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
<createResultFile>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</createResultFile>
</configuration>
I want to use the connectionString and <createResultFile> value in my PictureTransferTool.cs. This is my first time working with XML file and C# (.NET in general) so I want what is the way to retrieve those config values?
You config file must be like below...
Config File :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</appSettings>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>
C# :
You can read Connection String like below
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
Console.WriteLine(connectionString);
You can read User Defined Settings like Below
var Resultfile = System.Configuration.ConfigurationManager.AppSettings["ResultFile"];
Console.WriteLine(Resultfile);
The Way I normally do user-defined parameters in my app.config is i put them in the appSettings tab.
<appSettings>
<add key="myStr" value="String Value" />
and then you can access it with
string myStr = System.Configuration.ConfigurationSettings.AppSettings["myStr"];
It works for me.
Linq;
using System.Xml.XPath;
...
var doc = XDocument.Load("test.xml");// You should put the way to your XML
var name = doc.XPathSelectElements("/configuration/connectionStrings/add").Value;
var name = doc.XPathSelectElements("/configuration/createResultFile/add").Value;

How to remove a ConnectionString using Config Transformations

I have a Web.config with several ConnectionStrings
<connectionStrings>
<add name="connStr1" connectionString="...
<add name="ConnStr2" connectionString="...
<add name="connStr3" connectionString="...
Is there a way using config transformations to remove a specific connectionstring? Something Like:
<connectionStrings>
<xdt:Remove connStr2?
Obviously no where near the correct syntax, but you get my drift...
This will remove a specific connection string based on its name.
<configuration>
<connectionStrings>
<add name="ConnStr2" xdt:Transform="Remove" xdt:Locator="Match(name)" connectionString=" " />
</connectionStrings>
</configuration>
Note that the connectionString value is not empty string, but is instead a space. Any non-empty value would do.
From the MSDN documentation on the subject:
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="Remove" />
</connectionStrings>
</configuration>
The Transform="Remove" is the magic you're looking for. There is also a Transform="RemoveAll" which you might be able to use in conjunction with a specific add(s).
EDIT
On second thought you may also be able to combine the Locator attribute with the Remove defined above to limit which elements you actually want to delete.
More definitively:
<configuration xmlns:xdt="...">
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[#name='ConnStr2'])" />
</connectionStrings>
</configuration>
Or similar should work.

Categories