Change app.config connection string depending on PC - c#

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

Related

Can you split up a connection string in app.config?

I am very new to app.config files:
In an app.config file which look like this
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connectionstring" connectionString="Server=server;User ID=bar;Password=foobar" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
I want to split up the connection string into various sections like Server, UserId, etc in a different file and then concat it together in my app.config:
Pseucode
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="connectionstring" connectionString=Server+UserId+Password providerName="System.Data.SqlClient />
</connectionStrings>
</configuration>
Is this possible?

Config file structure

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.

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;

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>

How to declare a variable in the app.config file?

I am working on a Windows application.
I have a form with labels like
HOST:
UserName:
Password:
How I can declare the connection string in the app.config file so that it takes the initial catalog, userID and password as variables that I can use in further to check the user whether which database the user wants to get connected with the entered userID and password.
I am using SQL Server 2008 and Visual C# 2008 Express Edition.
As I'm reading your question, you want to have a generic connection string that you want to inject username/password variables into. To do that you would need to have a key with this format:
<add name="myDBKey" connectionString="Data Source=myDB;Initial Catalog={0};Persist Security Info=True;User ID={1};Password={2}" providerName="System.Data.SqlClient"/>
Then in your code, you would need to have these variables declared and assigned, and then use String.Format to complete it.
string dbCatalog = "myCatalog";
string dbUser = "myUser";
string dbPW = "myPW";
string myDBConnectionString = String.Format(
ConfigurationManager.ConnectionStrings["myDBKey"].ConnectionString,
dbCatalog, dbUser, dbPW);
This will inject your variables into the string.
There is a <connectionString> section to the app.config file.
<connectionStrings>
<add name="MyDatabase" connectionString="Data Source=sqlserver,1433;Network Library=DBMSSOCN;Initial Catalog=MyDatabase;User ID=xxx;Password=xxxx;" />
</connectionStrings>
For your Host, User ID and Password, you can define these in the <appSettings> section.
Try this
<connectionStrings>
<add name="ConString" connectionString="Server=Servernae;Database=DBName;User Id=username;password=yourpassword"/>
</connectionStrings>
For more information try Connection Strings
Start by declaring the variables by going to your project's property tab, then going to the Settings tab (on the left), declaring your variables by mentioning the name, default value, and scope (which will be Application).
In your code, to fetch the values:
using System.Configuration;
//....
ConfigurationSettings.AppSettings["ConnectionString"].ToString();
// or
ConfigurationSettings.AppSettings.ConnectionString;
Please note that you can't change the value in code for an Application setting.
EDIT:
Alternately, there is also the connectionStrings node which can be set (but it must be done in the app.config file itself. See MSDN for documentation.
Example of XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ConnStr1" connectionString="LocalSqlServer: data source=127.0.0.1 Integrated Security=SSPI;Initial Catalog=aspnetdb"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
In C#, you will get a System.Coonfiguration.ConnectionStrings, which is a collection of ConnectionStringSettings.
Example of usage in C# code: http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx
You can do some thing like this,
<appSettings>
<add key="SettingName" value="SettingValue" />
</appSettings>
or go to "Variables within app.config/web.config".
My library Expansive is designed with this as a primary use-case.
Moderate Example (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Domain" value="mycompany.com"/>
<add key="ServerName" value="db01.{Domain}"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid=uid;pwd=pwd;Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
or
Use the Dynamic ConfigurationManager wrapper "Config" as follows (Explicit call to Expand() not necessary):
var serverName = Config.AppSettings.ServerName;
// returns "db01.mycompany.com"
var connectionString = Config.ConnectionStrings.Default;
// returns "server=db01.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"
Advanced Example 1 (using AppSettings as default source for token expansion)
In app.config:
<configuration>
<appSettings>
<add key="Environment" value="dev"/>
<add key="Domain" value="mycompany.com"/>
<add key="UserId" value="uid"/>
<add key="Password" value="pwd"/>
<add key="ServerName" value="db01-{Environment}.{Domain}"/>
<add key="ReportPath" value="\\{ServerName}\SomeFileShare"/>
</appSettings>
<connectionStrings>
<add name="Default" connectionString="server={ServerName};uid={UserId};pwd={Password};Initial Catalog=master;" provider="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Use the .Expand() extension method on the string to be expanded:
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
connectionString.Expand() // returns "server=db01-dev.mycompany.com;uid=uid;pwd=pwd;Initial Catalog=master;"

Categories

Resources