Keyword not supported: 'server(local); database' - asp.net

my web.config is
<connectionStrings>
<add name="taraznegarConnectionString" connectionString="Data Source=.;Initial Catalog=taraznegar;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
and this is my code:
namespace taraz
{
public class DAL
{
string connection = "Data Source=.;Initial Catalog=taraznegar;Integrated Security=True";
SqlConnection con;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = connection;
cmd = new SqlCommand();
cmd.Connection = con;
da = new SqlDataAdapter();
da.SelectCommand=cmd;
dt = new DataTable();
}
public DataTable ExecuteReader(string SQL)
{
connect();
da.SelectCommand.Connection = con;
da.SelectCommand.CommandText = SQL;
try
{
da.SelectCommand.ExecuteReader();
}
catch
{
da = null;
}
disconnect();
da.Fill(dt);
return dt;
}
public string ExcuteNonQuery(string SQL)
{
string result=null ;
cmd.CommandText = SQL;
connect();
try
{
cmd.ExecuteNonQuery();
}
catch { result = "خطا"; }
disconnect();
return result;
}
public string ExecuteScalare(string sql)
{
string result = null;
cmd.CommandText = sql;
connect();
try {
result = cmd.ExecuteScalar().ToString();
}
catch { result = "خطا"; }
disconnect();
return result;
}
void connect()
{
if (con.State == ConnectionState.Closed)
con.Open();
}
void disconnect()
{
if (con.State == ConnectionState.Open)
con.Close();
}
}
}
and when I'm using this class in my project the error is:
Server Error in '/' Application.
Keyword not supported: 'server(local); database'.
what's the probleam?

When you have a ConnectionString in your webconfig file then in your application you don't need to create another connection. You should use that connection. In your class DAL you are creating a new connection string. Instead of that you should use something like this-
string connectionString = ConfigurationManager.ConnectionStrings["taraznegarConnectionString"].ConnectionString;

For Entity Framework (database-first or model-first; when you have a physical EDMX model file) you need to use a special type of connection string which is quite different from the straight ADO.NET connection strings everyone else has mentioned so far...
The connection string must look something like:
<connectionStrings>
<add name="testEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=.;Initial Catalog=taraznegar;Integrated Security=True;multipleactiveresultsets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
Inside this connection string, you'll find the provider connection string= attribute which is basically your ADO.NET connection string:

Related

System.ArgumentException: 'Keyword not supported: 'data source'.'

i keep getting this error and tried to delete the data source but that gave me another error and also tried to add another connection string also did not work how can i fix this?
https://ibb.co/4sVbnZt
DbsCarEntities1 dbs = new DbsCarEntities1();
string maincon = ConfigurationManager.ConnectionStrings["DbsCarEntities1"].ConnectionString;
public ActionResult Admin1()
{
return View();
}
[HttpPost]
public ActionResult Admin1(Admin x)
{
string maincon = ConfigurationManager.ConnectionStrings["DbsCarEntities1"].ConnectionString;
SqlConnection sqlcon = new SqlConnection(maincon);
string sqlquery = "select UserName,Password from [dbo].[Admin] where UserName=#UserName and Password=#Password";
sqlcon.Open();
SqlCommand sqlcom = new SqlCommand(sqlquery, sqlcon);
sqlcom.Parameters.AddWithValue("#UserName", x.UserName);
sqlcom.Parameters.AddWithValue("#Password", x.Password);
SqlDataReader sdr = sqlcom.ExecuteReader();
if (sdr.Read())
{
Session["UserName"] = x.UserName.ToString();
return RedirectToAction("Main2");
}
else
{
ViewData["Message"] = "Admin Login Details Does NOT match our data records!";
}
sqlcon.Close();
return View();
}
public ActionResult Main2()
{
return View(dbs.Cars.ToList());
}
You have to change the provider name to System.Data.SqlClient from System.Data.EntityClient in your connection.I think it will resolve your issue.
<add name="DbsCarEntities1"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;
AttachDbFilename=C:\Users\hamza\source\repos\CarSaleProjectUsingMVCandDataBase\CarSaleProjectUsingMVCandDataBase\App_Data\DbsCar.mdf;Integrated Security=True;" providerName="System.Data.SqlClient" />

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>

How do I write SQL connection string?

I have this as my connection string property:
Data Source="c:\users\perdanny\documents\visual studio 2012\Projects\WebApplication1\WebApplication1\App_Data\Users.sdf"
Now, how should I write it in my code:
sqlConnection = new SqlConnection(???);
try this:
string strConnection = ConfigurationManager.ConnectionStrings["Name of connection string key"].ConnectionString;
// Or, for a quick test you could also use
// string strConnection = "Data Source = c:\\users\\perdanny\\documents\\visual studio 2012\\Projects\\WebApplication1\\WebApplication1\\App_Data\\Users.sdf"
using (var conn = new SqlCeConnection(string.Format("Data Source={0}", strConnection)))
{
conn.Open();
try
{
System.Data.SqlServerCe.SqlCeCommand cmd = System.Data.SqlServerCe.SqlCeCommand;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Your sql stored proc name";
cmd.Connection = conn ;
cmd.ExecuteNonQuery();
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
string connStr = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
<add name="connectionString" connectionString="Data Source=SQLEXPRESS;Initial Catalog=dbsql;User ID=hello;Password=hello"
providerName="System.Data.SqlClient" />
use ConfigurationManager and
look at below code line:
string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;

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