We have several c# selenium test suites that are run on several servers by several testers.
I want to simplify the settings if possible. Currently we have multiple c# selenium projects each with their own app.config. When I want to change the server, I need to change each and every app.config. My app.config currently looks something like this:
<connectionStrings>
<add name="Company"
connectionString="Data Source=func3_db1;Initial Catalog=CompanyProduction;Integrated Security=SSPI;"/>
<add name="CompanyProductionEntities"
connectionString="metadata=res://*/DataAccess.CompanyEntities.csdl|res://*/DataAccess.CompanyEntities.ssdl|res://*/DataAccess.CompanyEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=func3_db1;initial catalog=CompanyProduction;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
We also have some settings in Windows Environment variables. It's kind of an obscure way of doing it but it works pretty well. To access these settings, we just do something like this:
var value = Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User);
So, we have a variable called "CompanyTestBrowser" which can be set to "Firefox" or "Chrome" or "IE".
I like environment variables because the powershell scripts that run all of our selenium tests can easily alter the variables whenever they need to.
However, I can't seem to pull those DB strings out of this app.config. How can I move them into something that can be a bit more global & dynamic. Ideally I only have to set in 1 single place? Ideally, I could move them into environment variables like the other or a config file that sits outside the c# project.
Thanks!
My advise would be, have the connection strings maintained in a xml file in a networklocation ex. \machine-name\DBConnectionString.config as below format
<connectionStrings>
<add name="Company"
connectionString="Data Source=func3_db1;Initial Catalog=CompanyProduction;Integrated Security=SSPI;"/>
<add name="CompanyProductionEntities"
connectionString="metadata=res://*/DataAccess.CompanyEntities.csdl|res://*/DataAccess.CompanyEntities.ssdl|res://*/DataAccess.CompanyEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=func3_db1;initial catalog=CompanyProduction;integrated security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
At your application startup routine, read \machine-name\DBConnectionString.config file and update application config file using the below code snippet,
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
// Create a connection string element and
// save it to the configuration file.
//Read the \\machine-name\DBConnectionString.config file
// Create a connection string element.
ConnectionStringSettings csSettings =
new ConnectionStringSettings("My Connection",
"LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" +
"Initial Catalog=aspnetdb", "System.Data.SqlClient");
// Get the connection strings section.
ConnectionStringsSection csSection =
config.ConnectionStrings;
// Add the new element.
csSection.ConnectionStrings.Add(csSettings);
// Save the configuration file.
config.Save(ConfigurationSaveMode.Modified);
Hope this helps.
You could add a key to app.config which has a path to an XML file which has all the common settings in it and then write a new ConfigurationManager class to first try to pull out a value from app.config and if not found, open the XML file and look for it in there
Something like this:
<appSettings>
<add key="ConfigFileSettings" value="\\MyServer\CommonSetting\settings.xml"/>
I used the accepted solution above. This is my exact code (which is only slightly different than above).
This solutions effectively keeps my current app.config file. All other settings in that app.config file are kept, except I "override" the "connectionString" part with my custom one.
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
System.Console.WriteLine("Starting to write app.config stuff");
//Change the Admin's app.config where name=companyProductionEntities
config.ConnectionStrings.ConnectionStrings["companyProductionEntities"].ConnectionString =
string.Format(#"metadata=res://*/DataAccess.companyEntities.csdl|res://*/DataAccess.companyEntities.ssdl|res://*/DataAccess.companyEntities.msl;provider=System.Data.SqlClient;provider connection string=';data source={0};initial catalog=companyProduction;integrated security=True;multipleactiveresultsets=True;App=EntityFramework';", SeleniumConfiguration.SimpleDatabaseConnectionString);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
Related
<add key="DBconnection"
value="USER=harc, PASSWORD=imp, FOR_USER=ra005" />
I have this line of config in my web.config.
I am getting this value in my C# code as
string connect = System.Configuration.ConfigurationManager.AppSettings["DBconnection"];
How do I get the USER and PASSWORD values individually from this configuration?
Assuming this is a SQL Server connection string, pass it to a SqlConnectionStringBuilder:
var builder = new SqlConnectionStringBuilder(
ConfigurationManager.AppSettings["DBconnection"]
);
// use builder.UserID and builder.Password here
If it's a connection string for another database, you'll have to know the proper provider -- or store it as a <connectionString> so the provider is included.
Note that actually including a user ID and password as plain text in a configuration setting is not recommended. See Connection Strings and Configuration Files, especially the section "Encrypting Configuration File Sections Using Protected Configuration".
You can add key value pair in webconfig file
<add key="UserName" value="test" />
<add key="Password" value="test" />
and read it like System.Web.Configuration.WebConfigurationManager.AppSettings["UserName"]
I decided to learn how to make a simple ASP.Net project, with a reference to a database project through the Repository Pattern.
I have my Controller calling for a List<Weight> to handle:
public IActionResult MyWeight()
{
var repo = new Database.Repositories.WeightRepository();
var data = repo.GetWeight().Result;
return View(data);
}
When repo.GetWeight() is called, I get an AggregateException error, with an inner exception saying:
"No connection string named 'MyDatabaseConnection' could be found in the application config file."
So for clarity, let me outline the solution's structure:
aspProj
Controllers
Views
Service
App.config (1)
Web.config
...
Database
Entities
Repositories
App.config (2)
...
Database.Test
Test.cs
App.config (3)
...
I've added the following connectionString to all App.configs and the Web.config:
<connectionStrings>
<add
name="MyDatabaseConnection"
connectionString="Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
I have tested the database both from Visual Studio's Server Explorer, and through the Test.cs file from the test-project. I can insert data and retrieve without a problem.
But when the ASP.Net-part wants to access it, there is no love.
I thought it might be the ISS which did not know the path from where it is...
Any thoughts?
__
Edit:
My Web.config:
My AppSetting.json:
Well the problem is clear - ASP.NET is trying to access the database using a connection string with the name MyDatabaseConnection:
<connectionStrings>
<add name="MyDatabaseConnection" connectionString="put the connection to the db here..." />
</connectionStrings>
And in your Web.config you only have a connection string with the name WeightDatabaseConnection:
<connectionStrings>
<add name="WeightDatabaseConnection" connectionString="put the connection to the db here..." />
</connectionStrings>
Just add a new element for MyDatabaseConnection under <connectionStrings> in the Web.config file and it should work
I have created a console application and an app.config file and Connections.config file.
The app.config file has a connectionstring property source pointing to the Connections.config
When I tried to read the connection string in the application, I get a ConfigurationErrorException
This is my main method.
static void Main(string[] args)
{
var settings = ConfigurationManager.ConnectionStrings;
if (settings != null)
{
foreach (ConnectionStringSettings setting in settings)
{
Console.WriteLine(setting.ConnectionString);
}
}
}
App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings configSource="Connections.config"></connectionStrings>
</configuration>
Connections.config file
<?xml version="1.0" encoding="utf-8" ?>
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Here I observed two things.
First: If I specify configSource I am unable to read the connection string (throwing exception.)
Second: If I put same connection string in App.config file and tried to read then the code is working but getting two connection string (which supposed to be return only one which is empty string)
The first connection string is sqlexpress connection string like this
data source=.\SQLEXPRESS;Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
second connection string it returning is empty string (This is expected).
I want to read connection string from external file like in my scenario. How to do that? What am I missing here?
MSDN says:
Do not include any additional elements, sections, or attributes.
You need to remove the XML encoding.
Edit
Also, you need to set the properties of your config file to Copy to Output Directory = Copy if newer or Copy always.
Edit 2
To build on what Dave said, you add the clear element to your external file. Your final Connections.config file should look exactly like this:
<connectionStrings>
<clear/>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Your Connections.config file should be as shown below without the xml header
<connectionStrings>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
Also for it to correctly locate the file in your console application, please set the Copy to Output Directory to Copy Always or Copy If Newer.
That first connection string you are getting is inherited from the machine.config. This is described in the MSDN documentation. http://msdn.microsoft.com/en-us/library/bf7sd233(v=vs.90).aspx
You can use the Clear tag in your config file to remove inherited connection strings.
http://msdn.microsoft.com/en-us/library/ayb15wz8(v=vs.90).aspx
<connectionStrings>
<clear/>
<add name="SQLDBConnecion"
providerName="System.Data.ProviderName"
connectionString="" />
</connectionStrings>
There is a nice article on MSDN: https://msdn.microsoft.com/en-us/library/ms254494(v=vs.110).aspx.
Quote from the article:
To store connection strings in an external configuration file, create
a separate file that contains only the connectionStrings section. Do
not include any additional elements, sections, or attributes. This
example shows the syntax for an external configuration file.
<connectionStrings>
<add name="Name"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
Hope this helps people who run into this question later.
Where to add the connection string in a C# project? Like this string?
<connectionStrings>
<add name="strConn"
connectionString="Data Source=abc;Password=pass;User ID=user"
providerName="Oracle.DataAccess.Client">
</add>
</connectionStrings>
And how can I call it from my program.cs file?
This will be added in the configuration file. If it is an ASP.NET application, then this would be the web.config file. If it is a Winforms/Console application this would be the app.config file.
To call it from the application, you'd have to use the System.Configuration namespace like so:
using System.Configuration;
string YourConnectionString =
ConfigurationManager.ConnectionStrings["yourConnStringName"].ConnectionString;
Where "yourConnStringName" is the name of your connectionString in your config file.
The connection string like the one you posted is placed in a configuration file called app.config and whenever you want to get a connectionstring you can get it like:
string strConn = ConfigurationManager.ConnectionStrings["strConn"].ConnectionString;
see this
Add it to your app.config under <configuration> and to call it from your program.cs use:
ConfigurationSettings.AppSettings["strConn"]
This is for a Windows Application.
In a class I want to referee to my connectionstring called freighthelper which is located in the settings.settings file in my project. How do I do this?
I have tried with this without success.
_connection.ConnectionString = FreightHelper.Properties.Settings.Default.freighthelper;
Why do you need to store your connection string in a settings file? It is usually put in the config file and retrieved like this: http://msdn.microsoft.com/en-us/library/ms254494%28VS.80%29.aspx
try this: _connection.ConnectionString=Settings.Default. freighthelper; to read form a setting files.
NOte: connection string better to place in App.confing
E.g:
<connectionStrings>
<add name="Name" connectionString="Data Source=Instance Name;Integrated Security=True;MultipleActiveResultSets=True;"
providerName="System.Data.EntityClient" />