Why modify my app.config doesnt work? - c#

Here is my AppConfig File
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<connectionStrings>
<add name="Connection" connectionString="(local)\SQLexpress"/>
<add name="MainPrinter" connectionString=""/>
</connectionStrings>
</configuration>
And I want to change MainPrinter's Name
Here is what i'm trying to do:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["MainPrinter"].Value = "Epson";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
But i dont take any result

Related

Unrecognized element in connection string

Can't find what is wrong with my connection string:
I get this exception:
System.Configuration.ConfigurationErrorsException: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized element. (D:\C#\learncsharp\Data access\AsyncSQL\AsyncSQL\bin\Debug\AsyncSQL.exe.Config line 2)
This is my code:
string connectionString = null;
string MovieDBContext = null;
try
{
MovieDBContext = ConfigurationManager.ConnectionStrings["MovieDBContext"].ConnectionString;
connectionString = ConfigurationManager.ConnectionStrings["ProgrammingInCSharpConnection"].ConnectionString;
}
catch (Exception e)
{
Console.WriteLine( e.ToString() );
}
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="ProgrammingInCSharpConnection"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
What is wrong? And how to get details which element is wrong?
Make sure you have defined the section in the <configSections> element.Change your config as follows,
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections />
<connectionStrings>
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
<add name="ProgrammingInCSharpConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;"
/>
</connectionStrings>
</configuration>

How to access the default connection string from web.config in c#

I have my config file with below configurations:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data" />
</configSections>
<dataConfiguration defaultDatabase="myConnectionString" />
<connectionStrings>
<add name="myConnectionString" connectionString="Data Source=mydatasource;Max Pool Size=100;Pooling=true; Initial Catalog=MyDB;User ID=Myuser;Password=Password;Connection Timeout=60" providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
</startup>
</configuration>
As you can see, I have set the default dataconfiguration to use myConnectionString as the default connection string, but in code behind (c#) how can I access this connection string without having to provide the name i.e. myConnectionString
So in below code:
string connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection cnn = new SqlConnection(connectionString);
SqlBulkCopy sbc = new SqlBulkCopy(cnn);
I would like to skip hardcoding the name of the connection string.
var dataConfig = (Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings)System.Configuration.ConfigurationManager.GetSection(
"dataConfiguration");
string connectionString = ConfigurationManager.ConnectionStrings[dataConfig.DefaultDatabase].ConnectionString;
That's what I can tell from typical usage of custom config sections and DatabaseSettings class.
EDIT: I have tested it in LINQPad with your exact app.config, got result:
Data Source=mydatasource;Max Pool Size=100;Pooling=true; Initial Catalog=MyDB;User ID=Myuser;Password=Password;Connection Timeout=60

App.config can't find my element

I have a simple app.config file that doesn't quite pass the IDEs checker.
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="XmlRoot" type="System.String"/>
</configSections>
<connectionStrings>
<omitted/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<XmlRoot>
<add key="relativepath" value=""/>
</XmlRoot>
</configuration>
I added the <section name="XmlRoot" type="System.String" /> part to the config and then I tried to define the name and key here: <add key="relativepath" value=""/>. But for some reason the IDE gives me the following Messages:
I rarely use the app.config file so it could just be a noob mistake. How do I make it recognize my tags?
If it's just a simple string, you can use AppSettings to accomplish this.
<configuration>
<appSettings>
<add key="relativepath" value="mypath" />
</appSettings>
</configuration>
Access it from C# like this:
string path = ConfigurationManager.AppSettings["relativepath"]);
Try changing your type to System.Configuration.NameValueSectionHandler
this is how I define my sections:
<configSections>
<sectionGroup name="MySettings">
<section name="serverConfiguration" type="System.Configuration.NameValueSectionHandler"></section>
<section name="sqlSettings" type="System.Configuration.NameValueSectionHandler"></section>
</sectionGroup>
</configSections>
...
<MySettings>
<sqlSettings>
<add key="sqlTransactionTimeOut" value="0" />
</sqlSettings>
<serverConfiguration>
<add key="resolveDnsAsync" value="true" />
</serverConfiguration>
</MySettings>
Probably you need to use the section appSettings
<configuration>
<appSettings>
<!-- and Here you define the key and the value like you do-->
<add key="relativepath" value="path"/>
</appSettings>
</configuration>
then in your code write something like this to read it.
String path = ConfigurationManager.AppSettings["relativepath"].ToString();
hope it works for you.
:)

Updating .config file with data from the user

I am trying to save some settings to the appSettings section of my configuration file so I may use the data to carry out the processes of the program. On the click of a button I want the data coming from the user to be saved in the config file. The code I am using is:
private void button1_Click(object sender, EventArgs e)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["key1"].Value = "value1";
config.AppSettings.Settings["key2"].Value = "value2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
Before the code is executed my app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="roshane" value=""/>
<add key="email" value=""/>
<add key="super" value=""/>
<add key="phone" value=""/>
</appSettings>
<connectionStrings>
<add name="AutoReportEmailerConnectionString"
connectionString="Data Source=roshane\sqlexpress;Initial Catalog=ICR_v5.0;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
After the code is execute the programName.exe.config file is the same as the app.config. Is there something I am missing why the values are not being added to the programName.exe.config file?
config.Save(ConfigurationSaveMode.Modified) works only when you modify an exisint key in other words a key that was in the web config before if you need to actually add key values to the web config just call config.Save() with no parameters
If you want to add new Key to config file, need to add it first in Settings collection:
config.AppSettings.Settings.Add("Key", "Value");
Then call Save method.

How to write mysql connection string in app.config in c#?

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<Connectionstring>
<add key="questionpaper" value="server=localhost;database=Question_info;
UID=root;password=SATISH;"/>
</Connectionstring>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
this is my app.config but unable to connect to MySql server
so please tell me how to deal with this problem
How to write mysql connection string in app.config in c#
You need to pluralize the connectionStrings tag.
<connectionStrings>
<add name"ConnectionStringName" connectionString="Data Source=serverName;Initial Catalog=databaseName;Intergated Security=SSPI;Application Name=My.Application.Name" providerName="System.Data.SqlClient" />
</connectionStrings>
The add key/value tag is also the format to use for appSettings, not connectionStrings.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="questionpaper" connectionString="SERVER=localhost; DATABASE=Question_info; UID=root; PASSWORD=SATISH" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

Categories