Using Visual Studio 2012 which was recently installed but now I can't connect to our SQL Server database.
These are the steps I'm following
create App1.config
type this in App1.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name ="xxx" connectionString="USER ID=xx;PASSWORD=xx;PERSIST SECURITY INFO=True;Data Source=xx;Initial Catalog=xx" />
</connectionStrings>
</configuration>
Add a reference to the project to System.Configuration
Create access to namespaces via:
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
implement the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace ConsoleApplication10 {
class Program {
static void Main(string[] args) {
SqlConnection conn = null;
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString);
}
}
}
I've created a new console app and added the above and I still get an error NullReferenceException was unhandled Object reference not set to an instance of an object. ...
EDIT
Via the immediate window I determined that the following is null:
ConfigurationManager.ConnectionStrings["xxx"].ConnectionString
If I hard-code the connection string into the constructor for SqlConnection then it connects ok
What am I missing - something really obvious!! Or is this in connection with my new VS ?
check what is in the ConfigurationManager.ConnectionStrings by excecuting at least the following:
if (ConfigurationManager.ConnectionStrings != null ) {
Console.WriteLine(ConfigurationManager.ConnectionStrings.Count);
Console.WriteLine(ConfigurationManager.ConnectionStrings[0].ConnectionString);
Console.WriteLine(ConfigurationManager.ConnectionStrings[0].Name);
....
} else {
Console.WriteLine("null");
}
This will highlight any obvious problems like duplication of the App.config file which could well be the case as you mentioned App1.config in the OP.
Check your output folder.
Assuming your application is called myapp.exe, there should be myapp.exe.config.
This should exist, and should contain the contents of your app.config file in Visual Studio.
If it doesn't, check whether you already have an app.config file elsewhere (I notice you called your file app1.config)
Have your tried checking what the value of ConfigurationManager.ConnectionStrings["xxx"].ConnectionString is and hardcoding with that value? Do you still get null?
Also it's advised to created the connection like this:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString))
{
//code
}
I would reply but I don't have enough rep yet ... :-(
Guessing from the fact that your code does not "do anything" with conn yet, I'm pretty sure that the ConfigurationManager returns null for the connection string name you pass in. An exception is thrown by the SqlConnection's constructor when passing in null instead of a valid connection string.
When you place your connection strings in Properties->Settings, as a connection string, access them with full namespace, and your done.
See my answer here
Related
var connection = ConnectionFactory.GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
And this is my App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test" connectionString="Data Source=.;Initial Catalog=OmidPayamak;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
But when my project runs this is my error:
Object reference not set to an instance of an object.
You can just do the following:
var connection =
System.Configuration.ConfigurationManager.
ConnectionStrings["Test"].ConnectionString;
Your assembly also needs a reference to System.Configuration.dll
Since this is very common question I have prepared some screen shots from Visual Studio to make it easy to follow in 4 simple steps.
string str = Properties.Settings.Default.myConnectionString;
Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.
First Add a reference of System.Configuration to your page.
using System.Configuration;
Then According to your app.config get the connection string as follow.
string conStr = ConfigurationManager.ConnectionStrings["Test"].ToString();
That's it now you have your connection string in your hand and you can use it.
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
return con;
}
Try this out
string abc = ConfigurationManager.ConnectionStrings["CharityManagement"].ConnectionString;
This worked for me:
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
Outputs:
Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"
It is possible that the OP in this question is trying to use an App.Config within a dll.
In this case, the code is actually trying to access the App.Config of the executable and not the dll. Since the name is not found, you get a Null returned, hence the exception shown.
The following post may be helpful:
ConnectionString from app.config of a DLL is null
1) Create a new form and add this:
Imports System.Configuration
Imports Operaciones.My.MySettings
Public NotInheritable Class frmconexion
Private Shared _cnx As String
Public Shared Property ConexionMySQL() As String
Get
Return My.MySettings.Default.conexionbd
End Get
Private Set(ByVal value As String)
_cnx = value
End Set
End Property
End Class
then when you want to use the connection do this in ur form:
Private Sub frmInsert_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New MySqlConnection(frmconexion.ConexionMySQL)
cn.open()
and thats it. You will be connected to the DB and can do stuff.
This is for vb.net but the logic is the same.
Have you tried:
var connection = new ConnectionFactory().GetConnection(
ConfigurationManager.ConnectionStrings["Test"]
.ConnectionString, DataBaseProvider);
I had the same Issue. my solution was built up from two projects. A Class library and a website referencing to the class library project. the problem was that i was trying to access the App.config in my Class library project but the system was searching in Web.config of the website. I put the connection string inside Web.config and ... problem solved!
The main reason was that despite ConfigurationManager was used in another assembly it was searching inside the runnig project .
The answers above didn't elaborate where the value in connectionStrings index comes from.
As mentioned above, to get your connection string, you say:
string conStr = ConfigurationManager.ConnectionStrings["XXX"].ToString();
To use the correct value of XXX, go to your main projects web.config file and look for the following piece of code:
<connectionStrings>
<add name="Authentication" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=Authentication;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Authentication.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Where it says name= , the text within those proceeding quotes is the value of XXX you use in the code above. In my example above, it happens to be Authentication
string sTemp = System.Configuration.ConfigurationManager.ConnectionStrings["myDB In app.config"].ConnectionString;
It seems like problem is not with reference, you are getting connectionstring as null so please make sure you have added the value to the config file your running project meaning the main program/library that gets started/executed first.
First you have to add System.Configuration reference to your project and then use below code to get connection string.
_connectionString = ConfigurationManager.ConnectionStrings["MYSQLConnection"].ConnectionString.ToString();
You can use this method to get connection string
using System;
using System.Configuration;
private string GetConnectionString()
{
return ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;
}
You can fetch the connection string by using below line of code -
using System; using System.Configuration;
var connectionString=ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Here is a reference :
Connection String from App.config
I referenced System.Configuration library and I have the same error.
The debug files had not their app.config, create manually this file.
The error is, I solved this copying the file "appname.exe.config" in debug folder. The IDE was not create the file.
I solved the problem by using the index to read the string and checking one by one. Reading using the name still gives the same error.
I have the problem when I develop a C# window application, I did not have the problem in my asp.net application. There must be something in the setting which is not right.
In order to read the connection string from app.cfg (in windows service application) the below code worked for me
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["CONNECTIONSTR"].ConnectionString = #"New Connection String";
Encountered this issue while placing ConfigurationManager.ConnectionStrings in UserControl's constructor, and none of the solution here worked for me.
After some research, seems like ConfigurationManager.ConnectionStrings would be null while trying to access it from the DesignTime.
And from this post, I came up with this following code to detect DesignTime as a workaround to the issue:
public class MyUserControl : UserControl
{
....
public MyUserControl ()
{
InitializeComponent();
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if (!designMode)
{
this.connectionString =
ConfigurationManager.ConnectionStrings["xxx"].ConnectionString;
}
}
}
I get always this exception, even if Database initializer is set to CreateIfNotExists.
Additional information: Cannot create file 'C:\\Users\\Krab\\Documents\\Visual Studio 2013\\Projects\\Customer_UI\\customers2.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Why is EF trying to create the database even if it already exists?
App.config
<connectionStrings>
<add name="Customer.CustomersContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\\Users\\Krab\\Documents\\Visual Studio 2013\\Projects\\Customer_UI\\customers2.mdf';Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
DbContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace Customer
{
public class CustomersContext : DbContext
{
public CustomersContext() : base("Customer.CustomersContext")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<CustomersContext>());
//Database.CreateIfNotExists();
//System.Console.WriteLine(Database.Connection.ConnectionString);
}
public DbSet<CustomerDb> Customers { get; set; }
public DbSet<Contact> Contacts { get; set; }
}
}
You don't have to escape backslashes in App.config files.
My guess is that whatever mechanism that checks for an existing database does not correctly resolve file paths with double directory separators (C:\\Users\\...).
EF would then go ahead and try to create a new database, but whatever mechanism that creates new databases does correctly resolve file paths with double directory separators. Resulting in an IOException because the file exists.
If my hunch is correct, simply unescaping the path would have fixed the problem.
Ok now it looks fine.
Changed name of connection string to another one
Removed that escaping from .mdf filename in connection string
Changed .mdf filename to another one, so i am not using the old one
The error is referring to a file on the SQL Server instance, wherever that is. In my case, it was a different machine. I had renamed the database in hopes of getting EF to recreate it
Hi every one I am getting the following error: "The name 'ConfigurationManager' does not exist in the current context"
// namespaces
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
namespace Database1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string GetConnectionString(string strConnection)
{
//variable to hold our connection string for returning it
string strReturn = "";
//check to see if the user provided a connection string name
//this is for if your application has more than one connection string
if (!string.IsNullOrEmpty(strConnection)) //a connection string name was
{
//get the connection string by the name provided
strReturn = ConfigurationManager.ConnectionStrings[strConnection].ConnectionString;
}
else //no connection string name was provided
{
//get the default connection string
strReturn = ConfigurationManager.ConnectionStrings["YourConnectionName"].ConnectionString;
}
//return the connection string to the calling method
return strReturn;
}
}
}
Have you added a reference to System.Configuration.dll?
You have to add reference to System.Configuration.dll
When you right click and click on the Add reference button
Click .Net tab in the open popup
There you should be able to locate the System.Configuration.dll file
This is the path:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Configuration.dll
also you can add reference to the :System:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Configuration.Install.dll
(hope it helps :))
Which version of .NET Framework and Visual Studio are you using?
ConfigurationManager is only available in .NET 2 and above. If you are using .NET Framework 1.x and Visual Studio 2002/2003, you won't be able to use this class at all.
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx
Click "Other versions" link in the top of this page and you will see all versions it supports.
I ran into same issue using .Net Core, but using .NET Running Install-Package System.Configuration.ConfigurationManager in Package manager solved it for me.
How can I read a connection string from a web.config file into a public class contained within a class library?
I've tried:
WebConfigurationManager
ConfigurationManager
But these classes are not recognized within my class library.
You need to add a reference to System.Configuration and then use:
System.Configuration.ConfigurationManager.
ConnectionStrings["connectionStringName"].ConnectionString;
Add System.Configuration as a reference.
For some bizarre reason it's not included by default.
C#
// Add a using directive at the top of your code file
using System.Configuration;
// Within the code body set your variable
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
VB
' Add an Imports statement at the top of your code file
Imports System.Configuration
' Within the code body set your variable
Dim cs as String = ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString
Add System.Configuration as a reference then:
using System.Configuration;
...
string conn =
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
I guess you need to add a reference to the System.Configuration assembly if that have not already been added.
Also, you may need to insert the following line at the top of your code file:
using System.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
C#
string constring = ConfigurationManager.ConnectionStrings["ABCD"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
BELOW WEB.CONFIG FILE CODE
<connectionStrings>
<add name="ABCD" connectionString="Data Source=DESKTOP-SU3NKUU\MSSQLSERVER2016;Initial Catalog=TESTKISWRMIP;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
In the above Code ABCD is the Connection Name
In VB : This should work
ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString
In C# it would be (as per comment of Ala)
ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString
You have to invoke this class on the top of your page or class :
using System.Configuration;
Then you can use this Method that returns the connection string to be ready to passed to the sqlconnection object to continue your work as follows:
private string ReturnConnectionString()
{
// Put the name the Sqlconnection from WebConfig..
return ConfigurationManager.ConnectionStrings["DBWebConfigString"].ConnectionString;
}
Just to make a clear clarification this is the value in the web Config:
<add name="DBWebConfigString" connectionString="....." /> </connectionStrings>
using System.Configuration;
string conn = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();
using System.Configuration;
string connString = ConfigurationManager.ConnectionStrings["ConStringName"].ToString();
Remember don't Use ConnectionStrings[index] because you might of Global machine Config and Portability
First add this:
using System.Configuration;
Everybody seems to be suggesting that adding
using System.Configuration;
which is true.
But might I suggest that you think about installing ReSharper's Visual Studio extension?
With it installed, instead of seeing an error that a class isn't defined, you'll see a prompt that tells you which assembly it is in, asking you if you want it to add the needed using statement.
I am trying to retrieve values from my App.config file which is stored in my working directory, however when I run the program it returns null. I am very confused why this is so, and have looked over the code many times in an attempt to spot an error.
Here is my App.config file code:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="provider" value="System.Data.SqlClient" />
</appSettings>
<connectionStrings>
<add name="connection" connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=Autos;Integrated Security=True;Pooling=False" />
</connectionStrings>
</configuration>
Here is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.Common;
namespace DataProviderFun
{
class Program
{
static void Main(string[] args)
{
string p = ConfigurationManager.AppSettings["provider"];
string c = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
...
When I run this code, p = null and c = null.
I have referenced System.Configuration.dll.
Did you ensure that the config file is placed correctly at the directory from which you're running the application? Is there actually a file called <app name>.exe.config in that directory?
I'm just guessing here - maybe you added the App.Config file in a different project then your exe assembly project...?
By the way, I copied your code and App.Config as is to a clean project, and this code worked for me. So I'd look in the direction of the config file itself and not in the code. The code is fine...
Hope this helps,
Ran
If your config file use in different class library you must change your name YourClasslibraryDllname.dll.config and you must change config file copy to output directory property
Ex:
YourSolution
ClassLibrary_1
ClassLibrary_1.dll.config
ApplicationConfigurationReader.cs
ConfigurationConst.cs
ClassLibrary_2
ConsoleApp
Rename your config file like this YourClasslibraryDllname.dll.config
Open Properties Window
Change Do Not Copy to Copy Always
Add reference -> Assembly -> System.Configuration
Add below clases in ClassLibrary_1 Project
ConfigurationConst Class using System.Configuration;
public static class ConfigurationConst
{
public static KeyValueConfigurationCollection Configs;
}
ApplicationConfigurationReader class using System.Configuration;
internal class ApplicationConfigurationReader
{
public void Read()
{
// read assembly
var ExecAppPath = this.GetType().Assembly.Location;
// Get all app settings in config file
ConfigurationConst.Configs = ConfigurationManager.OpenExeConfiguration(ExecAppPath).AppSettings.Settings;
}
}
Read Config using ClassLibrary_1;
static void Main(string[] args)
{
new ApplicationConfigurationReader().Read();
var Configval = ConfigurationConst.Configs["provider"].Value;
Console.ReadKey();
}
i Hope you can get clean help
In Case all the settings are correct but still if you get null values, Please check your app.config file and replace the xml code as below,
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
</configuration>
Now Run your Code, you might see the proper values
If you have .dll in your debug folder, then rename your confif file to yourprojectname.dll.config. This worked in my case