Getting sql connection string from web.config file - c#

I am learning to write into a database from a textbox with the click of a button. I have specified the connection string to my NorthWind database in my web.config file. However I am not able to access the connection string in my code behind.
This is what I have tried.
protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
I get a tooltip error for
SqlConnection sql = new SqlConnection(constring);
as
System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.
I want to load the connection string from the web.config in constring

You can simply give a Name to your ConnectionString in web.config file and do this:
web.config:
<add name="ConnectionStringName" connectionString=YourServer"; Initial Catalog=YourDB; Integrated Security=True"/>
Code Behind:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringName"].ToString());

That's because the ConnectionStrings collection is a collection of ConnectionStringSettings objects, but the SqlConnection constructor expects a string parameter. So you can't just pass in constring by itself.
Try this instead.
SqlConnection sql = new SqlConnection(constring.ConnectionString);

try this
readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["northwindconnect"].ToString());

I will suggests you to create a function rather than directly access the web.config file as follow
public static string GetConfigurationValue(string pstrKey)
{
var configurationValue = ConfigurationManager.AppSettings[pstrKey];
if (!string.IsNullOrWhiteSpace(configurationValue))
return configurationValue;
throw (new ApplicationException(
"Configuration Tag is missing web.config. It should contain <add key=\"" + pstrKey + "\" value=\"?\"/>"));
}
And use this function in you application

Related

ASP.NET Web service - How to connect it to database using connection string ?

I want to retrieve all the registered users from my application using web service in ASP.NET. However, I have problem with connection string.
public static String getRegisteredUsers(string usernameCode)
{
string username = "";
SqlConnection con = new SqlConnection("MyDatabaseConnectionString1");
SqlCommand cmd = new SqlCommand("Select Username from Users where usernameCode = '" + usernameCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
username = dr["username"].ToString();
}
dr.Close();
con.Close();
return username;
}
This MyDatabaseConnectionString1 is the connection string that I use for the table that I want to retrieve the information from. It works for that table, but not when it comes to web service.
<add name="MyDatabaseConnectionString1" connectionString= "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Korisnik\Desktop\Fitness\App_Data\MyDatabase.mdf;Integrated Security=True"/>
Should I use the same connection string for web service or it's done somehow differently ?
This is the error:
You should not use MyDatabaseConnectionString1 (name of the connection string) directly as input for SqlConnection (which expects connection string as the input). Do this instead:
string connStr = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(connStr);
... //continue as what you have done
You declare your MyDatabaseConnectionString1 in the .config file. The SqlConnection does not read your .config file but take the connStr input. Thus you get the error. You should read your connection string in the .config file by using ConfigurationManager available in the System.Configuration namespace. Then you use the connStr resulting from reading the .config file
Ensure System.Configuration assembly is referenced.
Use this syntax:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString);

Personalized database Connection string for C# application

I am trying to have a personalized database connection string for the machines i install the C# application into. I have created a database using Visual Studio but that only points the location of the database to my personal directory and that is not something general.
Now when i try to publish the application and try to install it in some other computer, the database gives me an error that it wasnt found, which makes sense because the connection string is pointing to my personal computers directory.
Here is part of my code:
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;");
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Can anyone please guide me towards the right path to solve this issue and to generate a personalized connection string for every computer the database gets installed to?
In your app.config or web.config file (Whichever is relevant to you) add the following connection string under configuration tag.
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
</connectionStrings>
If you already have a connection strings section then add only the
<add name="DbConnection" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Hydrolec Inc\\PanelProgressLogger\\PanelProgress.mdf;Integrated Security=True;User Instance=True;" />
Then in your C# code instead of hard coding the connection string you can use the config value.
string connectionString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;
private void button13_Click_1(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(connectionString);
sda = new SqlDataAdapter(#"SELECT [Panel Progress].*
FROM [Panel Progress]", con);
fill_grid();
}
catch (Exception error)
{
label6.Text = error.Message;
}
}
Build it. Then when you deploy the application in to another machine all you have to do is change your connection string in the app.config or web.config(whichever is relevant for you) to the new file location without changing hard coded values and rebuilding the application again.

how do I make my oledb program work on a different pc

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;
}

asp.net cannot open database login failed

I'm using the following to retrieve data from a database but the SqlConnection won't open. It throws an error at scon.Open(). I'm sure it's elementary but I can't work it out.
protected void Page_Load(object sender, EventArgs e) {
SqlConnection scon = new SqlConnection("Data Source = .\\SQLEXPRESS; Database = populate.mdf; Integrated Security = true; Initial Catalog = populate");
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
I'm using this link https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx as one of my references. I'm also using SQL Server 2008 R2 Express if these information are of any help.
Here's part of the error message:
SqlException (0x80131904): Cannot open database "populate" requested
by the login. The login failed.
Any help would be greatly appreciated.
Quoted from https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx#sse, if you want to use .mdf file as a database, you should use the following connection string containing AttacheDbFileName.
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True" />
I solved it. All the connection string and other code was correct. The database just needed connecting to the Management Studio with some extra attention.

C#: SQL Server Connection String

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;

Categories