Config file structure - c#

I got mixed with app.config file.
I had config that failed to get connectionStrings:
<?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>
</configSections>
</configuration>
Problem was solved after placing <connectionStrings> outside of <connectionStrings> :
<?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>
But I found many samples with pattern below
<configSections>
<connectionStrings>
...
</connectionStrings>
</configSections>
It might work in some cases?
What is logic of configuration file in general and what kind of information might be located in each section?

No. It is not possible to have a valid app.config file and yet having a connectionStrings in your configSections node.
According to MSDN, this is the list of allowed elements:
section
sectionGroup
add
clear
connectionStrings isn't in the list and I don't expect an application to find the connection strings in that place.

The configSections node contains configuration section per namespace declarations, but is not usually used for connection strings, unless they are namespace - specific.
But I found many samples with pattern below
The patterns you found could never work since <connectionStrings> is not allowed to be nested directly under <configSections>.
This could be achieved, by stating a connection string variable under the <section> itself, and if the server code targets them via a specific namespace.
An example:
<configuration>
<configSections>
<section name="section1" type="System.MyNameSpace" />
</configSections>
<section1 connString="...conn.." />
</configuration>
In the example above the namespace System.MyNameSpace will now have a variable (field) called connString, so it can target it in code behind.
For conclusion, if your connection strings are not per namespace, the <connectionStrings> element should be nested directly under the <configuration> node and no where else.

Related

Multiple Groups of ConnectionStrings in App Config

Using ConnectionStrings in App.config, is it possible to have multiple groups/sections of connectionstrings? Some way to delineate between one set of connections and another. Either something like;
<configuration>
<connectionStrings>
<clear />
<add name="ConA" connectionString="Data Source=..."
<add name="ConB" connectionString="Data Source=..."
</connectionStrings>
<otherConnectionStrings>
<clear />
<add name="ConC" connectionString="Data Source=..."
<add name="ConD" connectionString="Data Source=..."
</otherConnectionStrings>
</configuration>
OR
<configuration>
<connectionStrings>
<clear />
<add name="ConA" Group="1" connectionString="Data Source=..."
<add name="ConB" Group="1" connectionString="Data Source=..."
<add name="ConC" Group="2" connectionString="Data Source=..."
<add name="ConD" Group="2" connectionString="Data Source=..."
</connectionStrings>
</configuration>
I know there are <configSections> which you can use to split up the config file, but I want to use ConnectionStringSettingsCollection settings = ConfigurationManager.ConnectionStrings; to access the connectionStrings if possible.
NEED
I have two dropdown boxes. One is populated with a list of possible connectionStrings. Selecting an option will populate the second dropdown with a sublist of the remaining connectionStrings based on the option selected in dropdown 1. How would you cleanly populate both? Perhaps I'll just need to create connectionStringName lists in code for each group of connections I could potentially need and have all my connections in a the single section in my config?
Thanks for the comments. It seems having separate connectionStrings sections isn't possible. In order to hold onto that functionality for all my connections I conceded to having them all together but prefixing their names based on the grouping (as per #Igor's suggestion), then in code using Linq to select only the connections I needed.
Note: In order to use Linq on ConnectionStringSettingsCollection you need to .Cast<ConnectionStringSettings>() as per; https://stackoverflow.com/a/26419656/1365650

C# connection string - Get from config section

Here is a snippet of my app.config file.
<MyProject>
<ConnectionStrings>
...
<Operational providerType="SqlServer" provider="" dataSource="<ServerName>" initialCatalog="<DBName>" security="" userName="<SomeUser>" password="<Password>" />
...
</ConnectionStrings>
</MyProject>
In my C# code, I have this value available in some variable, like...
string OperationalConnectionConfiurationPath = "MyProject/ConnectionStrings/Operational";
How can I get my SqlConnection object out of this?
connectionStrings are a child of the configuration section. Get rid of that <MyProject>stuff.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Operational" connectionString="Data Source=SERVER_NAME;Initial Catalog=DB_NAME;User Id=USER_ID;Password=PASSWORD;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
You can get the connection string by:
using System.Configuration;
var connectionString = ConfigurationManager.ConnectionStrings["Operational"].ConnectionString;

Changing connection string in app.config for Entity Framework

I am using Entity Framework. In app.config there is stored connection string that EF generates for my database.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="votemeEntities" connectionString="metadata=res://*/VoteModel.csdl|res://*/VoteModel.ssdl|res://*/VoteModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;User Id=root;database=voteme""
providerName="System.Data.EntityClient" />
<add name="VoteMe.Properties.Settings.votemeConnectionString"
connectionString="server=localhost;User Id=root;database=voteme"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
I need to set Charset in this connection string. How do I do it so my EF use this connection string without any problems?
Thanks
You can add the property at the end of the EF connection string, just before the ".
...abase=voteme;charset=UTF8;""
providerName="System.Data.EntityClient" />
Just make sure that the value is properly XML escaped (if needed), otherwise you will break the config file.

Mindscape.LightSpeed Database connectivity problem

I'm using Mindspace.Lightspeed in my C# desktop application for the first time but I'm getting errors and unable to connect to database.
My App.config contains the following code:
<?xml version="1.0" encoding="utf-8" ?><configuration>
<configSections>
<section name="lightSpeedContext" type="Mindscape.LightSpeed.Configuration.LightSpeedConfigurationSection,Mindscape.LightSpeed" /></configSections><connectionStrings>
<add name="DefectsConStr" connectionString="Data Source=.\sqlexpress2k5;Initial Catalog=Defects;Persist Security Info=True;User ID=sa;Password=123"
providerName="System.Data.SqlClient" /></connectionStrings> <lightSpeedContext>
<add name="Development" connectionStringName="DefectsConStr" dataProvider="SqlServer2005"/> </lightSpeedContext> </configuration>
I have managed to reproduce your problem, you need to change your configuration file so that the section name is
lightSpeedContexts and not lightSpeedContext
see my configuration file
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="lightSpeedContexts" type="Mindscape.LightSpeed.Configuration.LightSpeedConfigurationSection,Mindscape.LightSpeed"/>
</configSections>
<connectionStrings>
<add name="Blog" connectionString="Data Source=Blog.dat"/>
</connectionStrings>
<lightSpeedContexts>
<add name="Blog" connectionStringName="Blog" dataProvider="SQLite3" identityMethod="KeyTable" pluralizeTableNames="false"/>
</lightSpeedContexts>
</configuration>

Change app.config connection string depending on PC

I'm doing a c# course at university, and now I'm beginning linQ to xml, linQ to Sql-Server, etc.
I work with the example projects in two PCs (university PC and office PC)
Is there an easy way to change connection string (from app.config) at runtime, or designtime (using a constant in main.cs) so I can use a connection string at university, and a connection string at the office easily?
Thanks a lot in advance,
You could try something like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Environment" value="Home"/>
</appSettings>
<connectionStrings>
<add name="Work" connectionString="..."/>
<add name="Home" connectionString="..."/>
</connectionStrings>
</configuration>
and, later:
string environment = ConfigurationManager.AppSettings["Environment"];
ConfigurationManager.ConnectionStrings[environment].ConnectionString;
Another way of doing it:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="HomeEnvironment"
connectionString="Data Source=**HOME-COMPUTER**\SQLEXPRESS;Initial Catalog=**HomeDatabase**;Integrated Security=True;"
providerName="System.Data.SqlClient" />
<add name="WorkEnvironment"
connectionString="DataSource=**WORK-COMPUTER**\SQLEXPRESS;Initial Catalog=**WorkDatabase**;Integrated Security=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
and use it like this:
var environment = Environment.MachineName == "HOME-COMPUTER" ? "HomeEnvironment" : "WorkEnvironment";
var connectionString = ConfigurationManager.ConnectionStrings[environment].ConnectionString;
var dbContext = new **Databasename**ContextDataContext(connectionString);
Bold strings should be customised as required

Categories

Resources