I am using ADO.net and my requirement is to change server dynamically based on some condition.
So in my web.config I have saved 2 connections as below. One names REMOTE and DBCS
<add name="REMOTE" connectionString="Server=;Initial Catalog=;Persist Security Info=False;User ID=;Password=;MultipleActiveResultSets=true;Encrypt=True;
TrustServerCertificate=False;Connection Timeout=0" providerName="System.Data.SqlClient"/>
<add name="DBCS" connectionString="Server=;Initial Catalog=;Persist Security Info=False;User ID=;Password=;MultipleActiveResultSets=true;Encrypt=True;
TrustServerCertificate=True;Connection Timeout=0" providerName="System.Data.SqlClient"/>
And below is the if condition that will change the server.
I want to use the same con variable throughout the code.
if (some condition)
{
string connectionString = ConfigurationManager.ConnectionStrings["REMOTE"].ConnectionString;
con = new SqlConnection(connectionString);
}
But while reassigning the new connectionstring to con variable, I am getting error.
Error:
Cannot assign to 'con' because it is a 'using variable'
As I am new to C#, I am having difficult handling this situation.
You (correctly) have the con instance being created in a using block. Pass the correct connection string at the time you create the SqlConnection instance, do not reassign after it is created
string connectionString = (some condition)
? ConfigurationManager.ConnectionStrings["REMOTE"].ConnectionString
: ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using(var con = new SqlConnection(connectionString))
{
// code using your SqlConnection instance
}
It seems you are using a using block and try to assign a new value within that block, which is not allowed.
The documentation states:
Within the using block, the object is read-only and cannot be modified or reassigned.
Related
Hey I'm new to programming and have never made an actual program that needs to work on another pc. The program is connected with a databank. When I'm on another pc i change program.exe.config file so that i can apply the right location of the databank but its still doesn't work. here is the code i have, maybe something is wrong here.
app.config:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
in standard code:
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb");
The first thing is that you are specifying a connection string in your application configuration file:
<connectionStrings>
<add name="Program.Properties.Settings.InventoryDBConnectionString"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb"
providerName="System.Data.OleDb" />
</connectionStrings>
You aren't using the connection string from your Program.exe.config, instead you are copying-and-pasting the connection string.
If you change your code slightly, perhaps you can see what i mean:
//Get the connection string to use
String connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\School\Stage\Program testen\Program\bin\Debug\InventoryDB.accdb";
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
What you should be doing is pulling the connection string from your application's configuration:
//Get our connection string setting, and the connectionString it contains
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
String connectionString = cs.ConnectionString;
//Open a connection to the database
OleDbConnection con = new OleDbConnection(connectionString);
There is one more change that you can make. Your connection string entry itself specifies which provider you want to use:
providerName="System.Data.OleDb"
But then you go ahead and use that provider yourself:
OleDbConnection con = new OleDbConnection(...);
If you changed your connection string to use a different provider:
providerName="System.Data.SqlClient"
your code would still be using the OleDbConnection, rather than the provider given in the application configuration.
Fortunately, the .NET framework has a handy little helper function, where it can create the correct provider for you:
public static DbConnection GetConnection()
{
//Get the connection string info from our application config
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["Program.Properties.Settings.InventoryDBConnectionString"];
if (cs == null)
throw new Exception("Could not find connection string settings");
//Get the factory for the given provider (e.g. "System.Data.OleDbClient")
DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName);
if (factory == null)
throw new Exception("Could not obtain factory for provider \"" + cs.ProviderName + "\"");
//Have the factory give us the right connection object
DbConnection conn = factory.CreateConnection();
if (conn == null)
throw new Exception("Could not obtain connection from factory");
//Knowing the connection string, open the connection
conn.ConnectionString = cs.ConnectionString;
conn.Open();
return conn;
}
I am trying to use a button that will add to my two columns in my database. I have placeholder values in there currently but will eventually be using 2 pop ups to read in those values.
My question is: how do I get the connection string? I don't know what to put there or where to get that data.
private void button_AddPartNumber_Click(object sender, EventArgs e)
{
string cmdString = "INSERT INTO Part_Numbers (Part_Number, Barcode_Number) VALUES (#val1, #val2)";
string connectionString = "I DONT KNOW WHAT TO PUT HERE";
using (SqlCommand connection = new SqlCommand(connectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = connectionString;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("#val1", "L-0G004-0830-xx"); //placeholder value
comm.Parameters.AddWithValue("#val2", "asdf1234"); // placehold value
}
}
} // end button_AddPartNumber_Click()
Well, what database are you using? For example, SQLServer? Oracle? MySQL?
In SQLServer, at least, the connection string is defined in the web.config, or app.config, and has syntax similar to the following:
<appSettings>
<add key="ConnectionStringName" value="AppName"/>
</appSettings>
<connectionStrings>
<add name="AppName" connectionString="Data Source=DataSourceName; Initial Catalog=DataBaseName; user id=UserID; password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
Something like that. There's probably something I'm missing, but without testing it out in your code, I'm blanking on what that might be.
This how you extract the connection string from your code if the connection string is properly set in the web.config:
var connectionString = ConfigurationManager.ConnectionStrings["AppName"].ConnectionString;
we are working on a project in which we need to show places on google map. For places, we are providing latitude and longitude from database. we are facing null reference exception error in the following place:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
How to resolve this error please guide me.
Cause of Exception:-
When you say:
System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"]
Since there is no connection string with name Data Source=KhUSHAL.., thus ConnectionStrings will return null and on that you are trying to access ConnectionString property which will result in Null reference exception. Read about this error here.
Basically you are mixing both, either do this:-
string CS ="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;Integrated Security=True";
using (SqlConnection con = new SqlConnection(CS))
{
//Your code
}
Or fetch it from Web.Config(Preferred way):-
First define the connection in Web.Config:
<connectionStrings>
<add name="Test" connectionString="Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Then read it like this:-
using (SqlConnection con = new SqlConnection(System.Configuration
.ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
{
//Your code
}
Do you have the ConnectionString in the Web.Config of the UI project?
Fix:
Copy that ConnectionString and Paste in your Web.Config
Your code,
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.
ConnectionStrings["Data Source=KHUSHALI\\SERVER;Initial Catalog=gis;
Integrated Security=True"].ConnectionString))
is Invalid, this is not the way to declare connection string and access them.
How can we declare Connection Strings and can Access them??
No1:>In a Page
string strConnectionString="server=localhost;database=myDb;uid=myUser;password=myPass;;
Integrated Security=True";
using (SqlConnection con = new SqlConnection(strConnectionString))
{
}
No2.>Web.Config you can declare then under configuration and appSeting
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings("myConnectionString")))
{
}
No3>Web.Config you can declare then under configuration and connectionStrings
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
And Can Access Like:
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
}
I can't seem to be able to access the app.config database connection string in my c# winforms app.
app.config code
<connectionStrings>
<add name="MyDBConnectionString" providerName="System.Data.SqlClient"
connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
</connectionStrings>
C# code:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["MyDBConnectionString"];
When I try the C# code, I get a message:
Warning 1 'System.Configuration.ConfigurationSettings.AppSettings' is obsolete: '
This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.AppSettings'
However, when I try to use:
conn.ConnectionString = System.Configuration!System.Configuration.ConfigurationManager.AppSettings["MyDBConnectionString"];
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
This is all you need:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Use ConfigurationManager instead of ConfigurationSettings. It has a ConnectionStrings property that you should use for connection strings in the connectionStrings section:
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
You are using the ConnectionStrings collection, not the AppSettings.
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ConnectionString" value="Data Source=MY-PC;Initial Catalog=DB2013;User ID=sa;Password=MYSQL123" />
</appSettings>
</configuration>
using System.Configuration;
using System.Data.SqlClient;
namespace OnlineDelete_W2013
{
public partial class CommodityEdit : Form
{
SqlConnection MyConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
public CommodityEdit()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MyConnection.Open();
}
catch (Exception)
{
throw;
}
}
}
}
try this
ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SQLConnection"].ToString()))
{
....(your code here) ...
}
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["MyDBConnectionString"].ConnectionString;
try
{
conn.Open();
}
catch (Exception)
{
throw;
}
The answers stating to use the line
ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
are correct.
If an error appears stating that ConfigurationManager does not exist, it's because your project hasn't referenced System.Configuration.
To do that in .NET Framework, in Solution Explorer, in the project where you want to use this line of code, right-click in References, choose Add Reference..., then choose Assemblies on the left-side and Framework under it. Pick System.Configuration on the list and click Ok.
About this:
I get an error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
I just declared a var like this and solved the problem:
var strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["MyDBConnectionString"].ConnectionString;
Please try below code. this is as you are expecting:
SqlConnection MyConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)