The connectionstring property has not been initialized - AppSettings - c#

Below is my connection string and I don't know where I am getting error.
<appSettings>
<!-- Default database to use... -->
<add key="Database_default" value="DB_Servername"/>
<!-- Datamart database connection to use -->
<add key="Database_datamart" value="MED_PROD"/>
<!-- Development Datamart Database Server -->
<add key="MED_PROD" value="Initial Catalog=REPORT_MED;Data Source=DB_Servername;UID=app_UID;PWD=******;"/>
<!-- Dev Server - Port Reference-->
<add key="va3fin01" value="Initial Catalog=acc;Data Source=DB_Servername;UID=med_UID;PWD=*******;"/>
<!-- MEDFIN_DEV -->
<add key="MED_DEV" value="Initial Catalog=MED_DEV;Data Source=DB_Servername;UID=med_UID;PWD=********;"/>
</appSettings>
I cannot change any back end code. They asked me to change server. After changing servers I am getting "The connectionstring property has not been initialized" on a working app. Please let me know if there is anything I could take care of only on web.config
Please help!
Thanks
Edited
Below is the method using for getting the connection string.
private void GetConnectionString()
{
string _settingname;
// if its empty, update it with "default"
if (this._database.Trim().Length == 0) this._database = "default";
// get the setting...
_settingname = ConfigurationSettings.AppSettings["Database_" + this._database];
if (_settingname == null)
{
throw new Exception("Unable to determine connection settings for specified database.");
}
else
{
// retrieve the connection string from the specified database...
this._ConnectionString = ConfigurationSettings.AppSettings[_settingname];
}
}

Normally, connection strings are inside connectionstring tag inside web.config.
For example,
<connectionStrings>
<add name="MED_PROD" connectionString="Initial Catalog=REPORT_MED;Data Source=DB_Servername;UID=app_UID;PWD=******;" providerName="System.Data.SqlClient"/>
<add name="va3fin01" connectionString="Initial Catalog=acc;Data Source=DB_Servername;UID=med_UID;PWD=*******;" providerName="System.Data.SqlClient"/>
<add name="MED_DEV" connectionString="Initial Catalog=MED_DEV;Data Source=DB_Servername;UID=med_UID;PWD=********;" providerName="System.Data.SqlClient"/>
</connectionStrings>

Related

ASP.Net can't see my database from the ISS

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

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.

Save Configuration settings dynamically [duplicate]

update app.config file programmatically with
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
this is my xml
<configuration>
<configSections>
<section name="nhibernateSettings" type="ProjectBase.Data.OpenSessionInViewSection, ProjectBase.Data" />
</configSections>
<appSettings>
<add key="NHibernateConfigPath" value="D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\NHibernate.config" />
<!--<add key="NHibernateConfigPath" value="C:\_ZAGON\ViaMura\CurrencyApp\at\NHibernate.config" />-->
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<connectionStrings>
<add name="connectionString" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Viamura_at;Data Source=.\SQL2008" providerName="System.Data.SqlClient" />
<!--<add name="connectionString" connectionString="server=193.37.152.24\SQL2008;User Id=DBUser;password=Lualah8991;database=Viamura_at" providerName="System.Data.SqlClient" />-->
</connectionStrings>
<nhibernateSettings>
<!-- List every session factory that will be needed; transaction management and closing sessions
will be managed with the open-session-in-view module -->
<sessionFactories>
<clearFactories />
<sessionFactory name="WebCrawlerFactory" factoryConfigPath="D:\PROJEKTI\crawler\WebCrawlerSuite\ViaMura.Web\NHibernate.config" isTransactional="true" />
<!--<sessionFactory name="WebCrawlerFactory" factoryConfigPath="C:\_ZAGON\ViaMura\CurrencyApp\at\NHibernate.config" isTransactional="true" />-->
</sessionFactories>
</nhibernateSettings>
how can I programmatically edit WebCrawlerFactory? I am using
Configuration config =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
You can use the following code:
private void UpdateConfig(string key, string value, string fileName)
{
var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
configFile.AppSettings.Settings[key].Value = value;
configFile.Save();
}
Where: fileName is the full path + application name (c:\project\application.exe)
In your case, change the AppSetting by Sections:
configFile.Sections["nhibernateSettings"]
The ProjectBase.Data.OpenSessionInViewSection indicates that there is already a custom config section defined that will allow access to the config settings. It may, however be protected or internal to NHibernate.
See if you can reference that class to access the settings.
You could also create a custom configuration section yourself, however it would cause NHibernate to be improperly configured since it would not be able to load the config section properly.
see How to: Create Custom Configuration Sections Using ConfigurationSection

Get connection string from web.config to use in EF POCO?

I've noticed that when I create model-first database using EF it is ignoring web.config connection strings and doing it's own thing in the background. Then I found a way to set my own connection string in constructor like so.
public class MainDataContext : DbContext
{
public MainDataContext()
{
this.Database.Connection.ConnectionString = "MY CONNECTION STRING THAT IS ACTUALLY USED";
}
}
Question: How can I force/set it to use connection string from web.config?
I've been told that if you name your connection string just like your data context it will work but it doesen't for me. I know for sure that it does not work if I name it DefaultConnectionString.
<add name="MainDataContext" providerName="System.Data.SqlClient"
connectionString="Server=(LocalDB)\\v11.0;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|ProjectDB.mdf;" />
Error occurred when I try to do update-database -v -f from console.
You can try something like this:
public MainDataContext() :
base(typeof(MainDataContext).Name)
{
}
Are you sure your connection string declaration in the Web.config is correct? Like this:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyDatabase" connectionString="server=localhost;User Id=user;password=password;Persist Security Info=True;database=mydatabase" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>

Can we declare variables in the 'app.config' file?

I have a form which needs to get connected to SQL Server, and I have a drop down for selecting the list of databases and perform operations like primary key checking, etc.
But presently my connection string looks like this:
SqlConnection sConnection = new SqlConnection("Server=192.168.10.3;DataBase=GoalPlanNew;User Id=gp;Password=gp");
But apart from the given database, I need to take it variable, so that I can connect it to the database I select from the dropdown.
How can I do this?
Hmm you can declare your variables like this
<appSettings>
<add key="SmtpServerHost" value="********" />
<add key="SmtpServerPort" value="25" />
<add key="SmtpServerUserName" value="******" />
<add key="SmtpServerPassword" value="*****" />
</appSettings>
and read like
string smtpHost = ConfigurationManager.AppSettings["SmtpServerHost"];
int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpServerHost"]);
I think he wants a "semi constant":
Web.Config
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<add name="YourName" providerName="System.Data.ProviderName" connectionString="Data Source={0}; Initial Catalog=myDataBase; User Id=myUsername; Password=myPassword;" />
</connectionStrings>
</configuration>
CS file
String Servername = "Test";
String ConnectionString = String.Format(ConfigurationManager.ConnectionStrings["YourName"].ConnectionString, ServerName);
you can use the connectionStrings tag in the app.config configuration. You can add as many as you want (giving them each a separate key) and then retrieve them
example app.config xml (set providerName to a valid provider, for example System.Data.SqlClient, and the appropriate connection string) :
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<connectionStrings>
<clear />
<add name="firstDb"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
<add name="secondDb"
providerName="System.Data.ProviderName"
connectionString="Valid Connection String;" />
</connectionStrings>
</configuration>
example on getting them and listing them (in your case, you would create the appropriate items in the dropdown and set the values) :
ConnectionStringSettingsCollection settings =
ConfigurationManager.ConnectionStrings;
if (settings != null)
{
foreach(ConnectionStringSettings cs in settings)
{
Console.WriteLine(cs.Name);
Console.WriteLine(cs.ProviderName);
Console.WriteLine(cs.ConnectionString);
}
}
You could use the AppSettings section. Read here for an example.

Categories