Why aren't new connection strings in Web.config file retrieved? - c#

In my ASP.NET project I added a new connection string in the Web.config file having the name "Proba":
<connectionStrings>
<add name="Users" connectionString="Data Source=.\SQLExpress;Initial Catalog=Registratura;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="Test" connectionString="Data Source=.\SQLExpress;Initial Catalog=REGDATABASE;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="Proba" connectionString="Data Source=.\SQLExpress;Initial Catalog=AnotherReg;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
This piece of code should list all the 3 connection strings:
List<String> conns = new List<string>();
foreach (ConnectionStringSettings conn in System.Configuration.ConfigurationManager.ConnectionStrings)
{
if(conn.Name != "LocalSqlServer")
conns.Add(conn.Name);
}
But it only detects the former 2 strings. I have built and rebuilt, closed Visual Studio and then reopened it, but nothing changed.
I have also tried to update the database in the Package Manager Console, but once again the connection is not found and the following red error occurs:
No connection string named 'Proba' could be found in the application
config file.
Why could it happen?

After different attempts, I came to realize that the Web.config file onto which I had imprinted the new connection strings was kind of a phantom of the real Web.config that needed to be changed. It had been opened before some configuration settings I made, so it was no more available. That is why the code written in it was not considered.

Related

ASP.NET and Visual Studio 2019: how to set up Web.Debug and Web.Release if you have configSource in Web.config?

In my ASP.NET web form, this is what my connection string looks like in my Web.config file:
<connectionStrings configSource="MySecrets.config"/>
I know that I can use Web.Debug and Web.Release to change the connection strings so that they are not exposed when the web app is released.
However, the examples provided by Visual Studio mention:
In the example below, the "SetAttributes" transform will change the value of
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
finds an attribute "name" that has a value of "MyDB".
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
However, this references a <connectionStrings> section in the Web.config file that I don't have in the first place, because in my project I have:
<connectionStrings configSource="MySecrets.config"
How can I set up the Web.Release to replace the MySecrets.config file so that it's not visible once published?
use the preprocessor to switch between connectionstring, for this you should have both connectionstrings.
web.config
<connectionStrings>
<add name="Project.Properties.Settings.ConnString_A" connectionString="" providerName="System.Data.SqlClient" />
<add name="Project.Properties.Settings.ConnString_B" connectionString="" providerName="System.Data.SqlClient" />
</connectionStrings>
code behind
public SqlConnection conn { get; set; }
public DbContext()
{
#if DEBUG
conn = new SqlConnection(Properties.Settings.Default.ConnString_A);
#else
conn = new SqlConnection(Properties.Settings.Default.ConnString_B);
#endif
}
reference: #if (C# Reference)

Add new connection in connectionString

I have the next connectionstring file:
<?xml version="1.0"?>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Application Name=CalculatorTest;Server=PC01;Initial catalog=MyDB;Integrated Security=true" />
</connectionStrings>
I want to add a new connection, for example "MyDBTest", staying:
<?xml version="1.0"?>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Application Name=CalculatorTest;Server=PC01;Initial catalog=MyDB;Integrated Security=true" />
<add name="NewDefaultConnection"
connectionString="Application Name=CalculatorTest;Server=PC01;Initial catalog=MyDBTest;Integrated Security=true" />
</connectionStrings>
How do I do it from C# Mvc 5?
Right click on your project and add an Entity Data Object, then enter the name you want it to be called; chose code first from database, then enter the server address and you can also select which tables from the db you want.
This will create the connection string for you. I would however recommend doing this in a separate class library so it’s easier to maintain. Note: if you do use it in a separate class library, you will need to look in the Web.config and copy it over to your main application web.config. Also you will want to add the reference of it in your project references.

How do I modify my web.config file to support SQL Server 2016?

I'm totally new to C#/.Net development. I've read extensive documentation about the web.config file on msdn and still am unsure what to change.
If answered would you please provide an example of what I should do? I can provide more info if necessary.
You don't have to provide information about SQL Server, You just need to give correct connection string, which points to your database.
Something like:
<connectionStrings>
<add name="myConnectionString"
connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
This is one way if you are just using some local database.
Otherwise you can set it up like this:
<connectionStrings >
<add
name="myConnectionString"
connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
providerName="System.Data.SqlClient"/>
And then in your code you should write:
using System.Web.Configuration;
And then at last you can set up your connection variable something like this:
SqlConnection con = new SqlConnection( WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
Are you using the entity framework? Because then it can be generated automatically.

How do I stop Visual Studio 2015 connecting to every connection string on project load?

When trying to open a solution which contains a large number of connection strings, Visual Studio 2015 attempts to connect to each and every one when loading the project.
Each developer on our team uses a local instance of SQL Server during development. This instance can have multiple copies of our main database which include different levels of migrations - we're a small team, so often end up switching tasks half-way through.
To allow for this, we have a number of connection strings which are machine-specific, and when creating our DbContext we use the machine name to determine which connection string to use:
<connectionStrings>
<!-- Steve -->
<add name="MachineConnection_LT4" providerName="System.Data.SqlClient"
connectionString="Data Source=LT4\SQL2012;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx;MultipleActiveResultSets=True" />
<!-- Sean -->
<add name="MachineConnection_DESKTOP-UQV58RL" providerName="System.Data.SqlClient"
connectionString="Data Source=DESKTOP-UQV58RL\SQLEXPRESS;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx;MultipleActiveResultSets=True" />
<!-- Sarah -->
<add name="MachineConnection_Dev-3" providerName="System.Data.SqlClient"
connectionString="Data Source=Dev-3\;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx;MultipleActiveResultSets=True" />
<!-- Graham -->
<add name="MachineConnection_lt5" providerName="System.Data.SqlClient"
connectionString="Data Source=.;Initial Catalog=xxx;Integrated Security=True;MultipleActiveResultSets=True" />
<add name="MachineConnection_graham-surface3" providerName="System.Data.SqlClient"
connectionString="Data Source=.;Initial Catalog=xxx;Integrated Security=True;MultipleActiveResultSets=True" />
<add name="MachineConnection_graham-pc-10" providerName="System.Data.SqlClient"
connectionString="Data Source=.;Initial Catalog=xxx;Integrated Security=True;MultipleActiveResultSets=True" />
<!-- Alex -->
<add name="MachineConnection_Dev9" providerName="System.Data.SqlClient"
connectionString="Data Source=Dev9;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx;MultipleActiveResultSets=True" />
<!-- Reuben -->
<add name="MachineConnection_ReubenPC" providerName="System.Data.SqlClient"
connectionString="Data Source=REUBENPC\SQLEXPRESS;Initial Catalog=xxx;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
Our context is then initialised like so:
public class TTDataContext : DbContext
{
public const string CacheKey = "dbContext";
public TTDataContext()
: base(SqlConnections.GetConnectionStringName())
{
}
...
}
And uses this to help:
public class SqlConnections
{
private const string DefaultConnectionStringName = "DefaultConnection";
/// <summary>
/// Get the name of the connection string to use.
/// This attempts to find a machine-specific connection string e.g. MachineConnection_LT4, and falls back to
/// the default connection string if a machine-specific connection string is not found
/// </summary>
/// <returns></returns>
public static string GetConnectionStringName()
{
// This enables a connection string to be completely overridden in the cloud service configuration
try
{
var cloudConnectionString = CloudConfigurationManager.GetSetting("TTDatabaseConnectionString");
if (!String.IsNullOrEmpty(cloudConnectionString)) return cloudConnectionString;
}
catch
{
// Deliberately empty - an exception will be thrown if not running on AppFabric
}
string machineSpecificConnectionStringName = string.Format("MachineConnection_{0}", Environment.MachineName);
string connectionString = ConfigurationManager.ConnectionStrings[machineSpecificConnectionStringName] == null
? DefaultConnectionStringName
: machineSpecificConnectionStringName;
return connectionString;
}
}
When Visual Studio 2015 loads the project (either initally, or on changing Git branch), it tries to establish connections to every single connection string specified in the list (confirmed by removing all but 1 of them) and as they're all local to each relevant machine it stops responding until the connection times out, throwing this error:
Visual Studio 2013 had no issue with this set-up. Is there a way to persuade Visual Studio 2015 to behave in the same way?
This was caused by an extension - specifically the Karma Test Adapter (version 1.1.3) which seems to automatically run some code on project load.
Disabling this extension solved the issue.

Dynamics Connection SQL Server C#

I would like some explanations on how to create and set up a dynamic connection to SQL Server DB engine in a C # project
if you want connection string in config and read it than you need to do like this , put possible connectionstring in config
<connectionStrings>
<add name="CharityManagement"
connectionString="Data Source=.;Initial Catalog=CharityManagement;Integrated Security=True"/>
<add name="CharityManagement_two"
connectionString="Data Source=.;Initial Catalog=CharityManagement_two;Integrated Security=True"/>
</connectionStrings>
and than read it base on condition using configurationmanager class
//to read first connection string
var connectionString=ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
//to read second connection string
var connectionString=ConfigurationManager.ConnectionStrings["CharityManagement_two"].ConnectionString;
This is what you're after
In the config file
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Then to read the connection string in your code you will do
string connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
Don't forget to use using System.Configuration;
Further reading here

Categories