Unrecognized element in connection string - c#

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>

Related

Why modify my app.config doesnt work?

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

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

Enterprise Library: Redirecting connectionStrings section does not add new ConnectionStrings to ConfigurationManager.ConnectionStrings

I am trying to move connectionStrings to external file using EntLib, but
ConfigurationManager.ConnectionStrings gives me only default ASP.NET database, which is not even in config.
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
I expected to see there two connection string from shared.config.
What can be the problem, or do I have a wrong understanding this feature?
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<enterpriseLibrary.ConfigurationSource selectedSource="System Configuration Source">
<sources>
<add name="System Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.SystemConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="Shared" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
filePath="shared.config" />
</sources>
<redirectSections>
<add sourceName="Shared" name="connectionStrings" />
</redirectSections>
</enterpriseLibrary.ConfigurationSource>
</configuration>
shared.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connStr1" connectionString="Data Source=local;Initial Catalog=DB1;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="connStr2" connectionString="Data Source=local;Initial Catalog=DB2;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Actually, ConfigurationManager.ConnectionStrings does not know anything about Enterprise Library infrastructure.
By default, sections cannot be redirected with Enterprise Library's ConfigurationSource.
You should use configSource attribute, which is feature of .NET Framework, not Enterprise Library.
app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="sharedConnectionStrings.config" />
</configuration>
sharedConnectionStrings.config:
<?xml version="1.0" encoding="utf-8" ?>
<connectionsStrings>
<add name="connStr1"
connectionString="Data Source=local;Initial Catalog=DB1;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="connStr2"
connectionString="Data Source=local;Initial Catalog=DB2;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionsStrings>
Update: If you want to use Enterprise Library features, don't use ConfigurationManager.ConnectionStrings directly. Instead, use Enterprise Library features to create database connections like:
Database db = DatabaseFactory.CreateDatabase(“Tom’s Connection”);
Then you can use Enterprise Library's configuration sources.
I found this link with example useful.

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>

Why does ConfigurationManager.OpenMappedExeConfiguration have an extra connection string not in the file?

I'm unit testing my config file for a win forms application.
In the LocalTestRun.testrunconfig I set it to copy the app.config. I've checked the Environment.CurrentDirectory while the test was running and the file doesn't have this extra connection string either. This is the test method:
[TestMethod]
public void Configuration_ConnectionStrings_Connect()
{
Console.WriteLine(Environment.CurrentDirectory);
Assert.IsTrue(System.IO.File.Exists("App.Config"));
var configFileMap = new ExeConfigurationFileMap(){ ExeConfigFilename = "App.Config"};
var config= ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
foreach (ConnectionStringSettings connectionString in config.ConnectionStrings.ConnectionStrings)
{
//Assumes all connections are to Sql server, test must be updated if not
Assert.AreEqual("System.Data.SqlClient",connectionString.ProviderName,"Test was only designed for SQL clients");
using (var cn=new System.Data.SqlClient.SqlConnection(connectionString.ConnectionString))
{
cn.Open();
Assert.AreEqual(System.Data.ConnectionState.Open,cn.State);
}
}
}
However When I iterate the config.ConnectionStrings.ConnectionStrings I have an extra configuration string that is not in the file:
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
This isn't and never was an asp.net project.
Here's the config File:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="HLIT_Ticketing.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<connectionStrings>
<add name="HLIT_Ticketing.Properties.Settings.HomeQConnectionString"
connectionString="Data Source=******\*****;Initial Catalog=*****;Persist Security Info=True;User ID=*****;Password=******"
providerName="System.Data.SqlClient" />
</connectionStrings>
<userSettings>
<HLIT_Ticketing.Properties.Settings>
<setting name="AssociateRole" serializeAs="String">
<value>Associate</value>
</setting>
<setting name="DeveloperRole" serializeAs="String">
<value>Developer</value>
</setting>
</HLIT_Ticketing.Properties.Settings>
</userSettings>
Where is this extra connection string coming from?
That connection string is defined in the machine-level configuration file, machine.config.
If you look at the file C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config, you will see the following section:
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
Dave nailed the main answer - upvoted.
But: if you want to get rid of any connection string from the machine.config or any "up-stream" web.configs, you can always use:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="HLIT_Ticketing.Properties.Settings.HomeQConnectionString"
connectionString="Data Source=******\*****;Initial Catalog=*****;Persist Security Info=True;User ID=*****;Password=******"
providerName="System.Data.SqlClient" />
</connectionStrings>
That first <clear/> in the connection strings section wipes out any previously present connection strings and starts with a clean slate.

Categories