Read connection string from web.config - c#

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.

Related

Namespace could not be found

It can be seen and compiled inside the same file it is in inside the same project, the file is called default.aspx.cs.
However when I try to include the namespace in another file of the same project using the using DBConnStrings; statement -> I keep getting the compiler error "The type or namespace name 'DBConnStrings' could not be found".
The Code in the file which compiles called default.aspx.cs is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using DBConnStrings;
namespace DBConnStrings
{
public class GlobalStrings
{
public static string carSalesDBConnString =
ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
}
}
public void BindManu()
{
SqlConnection conn = new
SqlConnection(GlobalStrings.carSalesDBConnString); // Connect to Carsales database
conn.Open();
// .....
}
The other files can not see this namespace although they are in the same project.
How do I make them see it?
First of all, I'd suggest to put the method BindManu into the class, because I can't imagine this would work like that.
But to your problem: You have to specify the whole namespace. That means, if the file with the DBConnStrings namespace is in the folder test, you have to use using test.DBConnStrings to import the namespace. You should name the namespace like that as well to avoid confusion (namespace test.DBConnStrings).
But you actually don't have to specify the whole path, just the path within the project. That means, if your class is in C:\Users\Foo\Documents\Visual Studio 2017\Projects\BlaProject\DirectoryA\DirectoryB\MyClass with the project located in C:\Users\Foo\Documents\Visual Studio 2017\Projects\BlaProject, your namespace would be BlaProject.DirectoryA.DirectoryB. If the file your using isn't in your project folder, then you have to add a reference and use the path within the other project as above (but with another project name, obviously). If you want to add references, open the Solution Explorer, right click onto References, select add Reference, and select the reference to the project.
If you don't want to struggle with all that you can let vs do it for you. Simply type in the class you want from the other namespace, it will be marked as an error, click onto the lightbulb and select something like add using reference.
Furthermore, if you want to add a class to your project, don't do it with the explorer - simply right click onto the folder from your project you want to add the class to in your Solution Explorer, select Add, then New Item. In the popup select class and type in your name for the class. That's it!

Possible reasons why SqlConnection is NULL

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

The name 'ConfigurationManager' does not exist in the current context

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.

Problems converting VB.NET to C#

I am trying to convert some vb.net to C#, but I keep getting errors. At the moment, I am getting the following error:
The name 'Strings' does not exist in the current context
The problem line is:
strUser = Strings.LCase(Strings.Trim(strUserInitials[strUserInitials.GetUpperBound(0)])).ToString();
Anyone know why this is happening?
I have the following namespaces set:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Script;
using System.Web.Script.Services;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
I am working on a webservice (asmx file).
The Strings utility class is in the Microsoft.VisualBasic namespace.
You can add a reference to the library and use it from your C# code, or rewrite the calls:
strUser = strUserInitials[strUserInitials.GetUpperBound(0)].ToString().Trim().ToLower();
In c# there is no Strings class in System namespace. and in the string change LCase to ToLower, So:
strUser = string.ToLower(string.Trim(strUserInitials[strUserInitials.GetUpperBound(0)]));

'namespace used like a type' error when converting XAML to HTML

Coders, I am trying to convert a XAML string to HTML using a library I found here , but I have a problem with creating a new instance of the object that would let me use the library. I already added a reference to the library in my Asp.net project and I would like to use it in a WCF file.
The problem is that whenever I try to instantiate a new object with the new keyword, I get an error that says:
'MarkupConverter' is a 'namespace' but is used like a 'type'.
Here is my code, notice that I am creating a new object just like the example shown in the library link above, please help:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web.Services;
using System.Net.Mail;
using System.ServiceModel.Activation;
using System.Data.SqlClient;
using MarkupConverter;
namespace AspPersonalWebsite
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 //: IService1
{
private string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
private IMarkupConverter markupConverter;
[OperationContract]
public string convertXAMLToHTML(string XAMLtext)
{
string htmlText = "";
markupConverter = new MarkupConverter(); /*PROBLEM IS HERE*/
htmlText = markupConverter.ConvertXamlToHtml(XAMLtext);
return htmlText;
}
}
}
Confusion is arising because the actual type is MarkupConverter.MarkupConverter, the compiler seems to think your new MarkupConverter is an attempt to use a namespace as a type, rather than an attempt to instantiate a type inside your using namespace.
Simply change your problem line to:
markupConverter = new MarkupConverter.MarkupConverter(); /*SOLUTION HERE!*/
..and you should be fine.
In your case, you have a namespace MarkupConverter and a class with the same name (MarkupConverter again).
In the line markupConverter = new MarkupConverter(); /*PROBLEM IS HERE*/ the compiler is unable to tell that you intent to use the class. Since a namespace with the same name is present, the compiler picks it instead, because namespaces are linked with higher priority by the compiler.
You can resolve this by using the complete name of the class:
// supposedly MarkupConverter is the namespace of the MarkupConverter class
markupConverter = new MarkupConverter.MarkupConverter();
An alternative way to providing the fully-qualified name of the class is to use an alias, which takes the form of using {ALIAS} = {Fully qualified name of Type| Namespace}. Note that the {ALIAS} part can be any valid identifier.
The alias you can place either in your usings:
using System.Net.Mail;
using System.ServiceModel.Activation;
using System.Data.SqlClient;
using MarkupConverter;
using MarkupConverter = MarkupConverter.MarkupConverter; // this is aliasing
or after the namespace declaration:
using System.Data.SqlClient;
using MarkupConverter;
namespace AspPersonalWebsite
{
using MarkupConverter = MarkupConverter.MarkupConverter;
....
and you're good to go! At this point, if aliases are present, the line
markupConverter = new MarkupConverter()
will correctly pick the MarkupConverter class, because explicit aliasing has higher priority than the automatic binding done by the compiler.
That is pretty much self explanatory,
MarkupConverter is a namespace ,so shouldn't be used as a class to create an object
Can you show the MarkupConverter class you use please? The error is maybe in its declaration. In Where namespace is it? What is your file structure?
Maybe you have created a MarkupConverter namespace?
You should add a "using MarkupConverter" statement in the usings section. That will import all classes from that namespace.

Categories