SqlException after moving connection string to web.config - asp.net

I have to change my data source to the name of my server [server name]\SQLExpress after moving my connection string from Page_Load to web.config. Otherwise I get an SqlException at con.Open(). The app works fine both ways am just wondering why I need to change the datasource name after moving the connection string.
<connectionStrings>
<add name="CS"
connectionString="data source=[server name]\SQLEXPRESS; Initial Catalog = SampleDb; integrated security = true"
providerName="System.Data.SqlClient"/>
</connectionStrings>
(string cs = "data source=.\\SQLExpress; initial catalog = SampleDb; integrated security= true";)-moved to web.config
string CS = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
//pass the connection string to the SqlConnection() constructor
SqlConnection con = new SqlConnection(CS);
//tell sqlcommand what query to execute and which connection
SqlCommand cmd = new SqlCommand("select * from Electronics", con);
//open connection
con.Open();
//execute the command
GridView1.DataSource = cmd.ExecuteReader();
GridView1.DataBind();
//close the connection
con.Close();

Related

ConfigurationManager doesnt recognize my connection string

I'm trying to do a DropdownList from Database using ASP.Net Web Form.
Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
OracleConnection conn = new OracleConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["OraDbContext"].ConnectionString;
OracleCommand cmd = new OracleCommand("SELECT NOMPRE FROM HOPEMPL", conn); //HOPEMPL#HQ
OracleDataAdapter oda = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
oda.Fill(ds);
DDnompre.DataSource = ds;
DDnompre.DataTextField = "NOMPRE";
DDnompre.DataValueField = "NOMPRE";
DDnompre.DataBind();
}
Connection String:
<connectionStrings>
<add name="OraDbContext" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="DATA SOURCE=localhost:1521/xe;DBA PRIVILEGE=;PASSWORD=1234;USER ID=LOUG"" providerName="System.Data.EntityClient" />
</connectionStrings>
Error:
"System.ArgumentException : ''metadata' is not a valid connection
string attribute' "
I'm also working with a database first (EF)
try with :
<add name="{ConnectionName}"
connectionString="Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;"
providerName="Oracle.DataAccess.Client"/>

Enable to connect oracle database with asp.net windows service

<connectionStrings>
<add connectionString="provider=MSDAORA;Data Source=MyOracleDB;User Id=user;Password=****;" name="con"/>
</connectionStrings>
This is my connection string. i am using visual studio 2013 and oracle 10g version.
This is my code.
OleDbConnection conn = new OleDbConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
public DataTable GetTday()
{
conn.Open();
string query = "select * from tday";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
it shows 'ORA-12154: TNS:could not resolve the connect identifier specified' this error. please someone help

Object reference not set to an instance of an object. on my string

hi I have this error" Object reference not set to an instance of an object." In my string constr.
what does it mean?
thanks for answering =)
private void BindGrid()
{
string constr = ConfigurationManager
.ConnectionStrings["conString"].ConnectionString; //Error here
sql = "select * from LogDetails";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(sql, con);
DataTable t = new DataTable();
sda.Fill(t);
GridView1.DataSource = t;
GridView1.DataBind();
}
You need to add connection string in your web.config file.
<connectionStrings>
<add name="conString" connectionString="Data Source=serverName;Initial Catalog=Northwind;Persist Security Info=True;UserID=userName;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>

Calling a stored procedure with asp.net

If I have a connection string defined in my web.config file, how do I create a connection to the SQL db from C# code (sorry forgot to specify) and then call a stored procedure. I would then like to eventually use this data in some way as my DataSource for a GridView.
Here is how the connection string is defined in the web.config:
<connectionStrings>
<add name="db.Name" connectionString="Data Source=db;Initial Catalog=dbCat;User ID=userId;Password=userPass;" providerName="System.Data.SqlClient" />
</connectionStrings>
The db server is a Microsoft SQL server.
Here is what I was looking for:
ConnectionStringSettings conSet = ConfigurationManager.ConnectionStrings["db.Name"];
SqlConnection con = new SqlConnection(conSet.ConnectionString);
The code to get the data is fairly trivial. I was more interested in accessing it from a connectionString variable in the web.config file.
If it's a resource file like so:
private static readonly string connString = Resource1.connString;
Where connString is the name of the key. If it is a web.config file
Something like so:
private static readonly string connString = System.Configuration.ConfigurationManager.AppSettings["strConn"]; where conn is defined in your web config file.
<add key="strConn" value="User ID=test;Password=test;Initial Catalog=TestDB;Data Source=NameOfServer;"/>
Then call the sproc:
//connString = the string of our database app found in the resource file
using (SqlConnection con = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("EMPDLL_selClientByClientID", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ClientID", SqlDbType.VarChar).Value = cID;
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
if (reader.Read())
{
//more code
}
}
}
}
}
That's if you are coding in C#, VB.net its the same deal just a bit more wordier :), here's a small sample:
Public Sub DeleteEmployee(ByVal lVID As Long)
Dim conMyData As SqlConnection
Dim cmdDelete As SqlCommand
Try
conMyData = New SqlConnection(connString)
cmdDelete = New SqlCommand("delEmployee", conMyData)
With cmdDelete
.CommandType = CommandType.StoredProcedure
'add the parameters
.Parameters.Add("#LoginID", SqlDbType.BigInt).Value = lVID 'the request
conMyData.Open() 'open a connection
.ExecuteNonQuery() 'execute it
End With
Catch ex As Exception
Throw ex
Finally
cmdDelete = Nothing
conMyData.Close()
conMyData = Nothing
End Try
End Sub
Of course you should use a using statement instead of try/catch/finally to ensure you clean up your resources that are being used.
Something like this...
using (var con = new SqlConnection(_connectionString))
{
using (var cmd = new SqlCommand(_storedProcedureName, con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#pMyParamater", myParamaterValue);
con.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// do something with the row
}
}
}
}
This is all pretty simple stuff to be honest, you should be able to find everything you need from the ADO.NET documentation

How to use created connection string of Web.Config in my C# asp.net 4.0 project?

Actually I am new in this topic so required some help.
I have added connection string in Web.Config
<connectionStrings>
<add name="LocalSqlServer" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
and know that, to use it I have to put this statement in my C# code behind
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
That's all I know.
My Question is
What should I do if I want to execute some query for my aspnetdb.mdf dataabase (Built in db of ASP.NET built in login contols in Visual Studio 2010)
Earlier, I was doing this to accomplish my task
1) No connection string in Web.Config. and
2) Hard code in codebehind
SqlConnection con = new SqlConnection("data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true");
SqlCommand cmd = new SqlCommand();
protected void btnnameedit_Click(object sender, EventArgs e)
{
try
{
con.Open();
cmd.CommandText = "update tamhankarnikhil set fname = '" + fname.Text + "'";
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
fname.Text = "";
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
Here's what you could do:
protected void btnnameedit_Click(object sender, EventArgs e)
{
try
{
string connStr = ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
using (var conn = new SqlConnection(connStr))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE tamhankarnikhil SET fname = #fname";
cmd.Parameters.AddWithValue("#fname", fname.Text);
cmd.ExecuteNonQuery();
fname.Text = "";
}
}
catch (Exception a)
{
Response.Write(a.Message);
}
}
You will notice the usage of parametrized queries to avoid SQL injection to which your code was vulnerable to due to the string concatenations you were using when constructing the SQL query.
You will also notice that the SqlConnection and SqlCommand are wrapped in using statements to ensure their proper disposal even in the event of an exception.

Resources