System.ArgumentException: 'Keyword not supported: 'data source'.' - asp.net

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" />

Related

Keyword not supported: 'server(local); database'

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:

How to return other view in an action method?

I want to return the view of Index action method in create action method.I tried writing return View("Index"); in Index action method but nothing happened.Both my action methods are in the same controller. How can I do that?
Code:
public class GuestbookController : Controller
{
// GET: /Guestbook/
public ActionResult Index()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GuestbookContext"].ToString());
string query = string.Format("Select * from Guestbook");
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<GuestbookEntry> li = new List<GuestbookEntry>();
while (reader.Read())
{
GuestbookEntry GuestbookEntry = new GuestbookEntry();
GuestbookEntry.Name = Convert.ToString(reader["Name"]);
GuestbookEntry.Message = Convert.ToString(reader["Message"]);
GuestbookEntry.Id = Convert.ToInt32(reader["Id"]);
GuestbookEntry.DateAdded = Convert.ToDateTime(reader["DateAdded"]);
li.Add(GuestbookEntry);
}
conn.Close();
var mostRecentEntries =(from entry in li orderby entry.DateAdded descending select entry);
ViewBag.Entries = mostRecentEntries.ToList();
return View();
}
[HttpPost]
public ActionResult Create(GuestbookEntry entry)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GuestbookContext"].ToString());
string query = string.Format("Insert into [Guestbook] values ('{0}','{1}','{2}')", entry.Name, entry.Message, DateTime.Now);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
return View("Index");
}
}
You are only using the view, and not the action, so the ViewBag you are filling, wont be available.
You can use use RedirectToAction() to redirect the current action to the other action.
[HttpPost]
public ActionResult Create(GuestbookEntry entry)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["GuestbookContext"].ToString());
string query = string.Format("Insert into [Guestbook] values ('{0}','{1}','{2}')", entry.Name, entry.Message, DateTime.Now);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
return RedirectToAction("Index");
}
If you are trying to return to the index page as if it was called from the client then you should use:
return Index(); //If you don't care about adjusting URL on client's machine
Or
RedirectToAction("Index") //If you want to update client's URL
Please note that the second option does entail a full round trip to the client and back to the server and can not be used easily in case of Ajax calls, while the first option "stays on the server" and can be used with Ajax.

creating sql connection object once and using it several times

i'm creating login and register page in MVC asp.net but problem is that for each purpose i have to do all SQl connection, command, try open etc which really makes it slow so i as wondering that if i can get rid of creating ti again and again and just create sqlconnection thing once and calling it again and again for login, registration etc
namespace LoginSys.Models
{
public class database
{
public ConnectionStatus connectDB(String name, String email, String pwd, String conStr)
{
// var con = conStr;
SqlConnection sqlCon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand();
sqlCom.Connection = sqlCon;
sqlCom.CommandText = "insert into tblRegister (userName, userEmail, userPwd) values (#name, #email, #pwd)";
sqlCom.Parameters.AddWithValue("#name", name);
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
int row_aff;
try
{
sqlCon.Open();
row_aff = sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
finally
{
sqlCon.Close();
}
return connectStatus;
}
}
}
Actually you are not creating a new physical connection to the database. ADO.NET uses a connection pool. This means that even if you create a new instance of SqlConnection, you are not actually creating a new physical connection but are drawing one from the pool. Also when you call the .Close() method you are not actually closing the underlying connection. You are just returning it to the connection pool so that it can be reused.
So your code won't be slow because of that.
The only improvement I may recommend you to this code is to wrap the IDisposable objects in using statements:
public ConnectionStatus ConnectDB(string name, string email, string pwd, string conStr)
{
using (SqlConnection sqlCon = new SqlConnection(conStr))
using (SqlCommand sqlCom = sqlCon.CreateCommand())
{
sqlCon.Open();
sqlCom.CommandText = "insert into tblRegister (userName, userEmail, userPwd) values (#name, #email, #pwd)";
sqlCom.Parameters.AddWithValue("#name", name);
sqlCom.Parameters.AddWithValue("#email", email);
sqlCom.Parameters.AddWithValue("#pwd", pwd);
ConnectionStatus connectStatus = new ConnectionStatus();
try
{
sqlCom.ExecuteNonQuery();
connectStatus.Message = "OK";
}
catch(Exception ex)
{
connectStatus.Message = ex.Message;
}
return connectStatus;
}
}

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;

connecting to access database and query user login information not pulling data back

any help would be great thank you. not sure why its all ways returning a null
I'm not sure if its even connecting to the database.
my web config file
<configuration>
<connectionStrings>
<add name="accessConnectionString" providerName="Microsoft.Jet.OLEDB.4.0" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\***\Desktop\pratice\AccessTest\App_Data\TheList.mdb;Persist Security Info=True"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
</configuration>
middle tier code to check if user is in the database if they are return something if not return null
OleDbConnection sconn = new OleDbConnection();
OleDbCommand scmd = new OleDbCommand();
public DBMiddleTier()
{
try
{
// set up the connection strings
sconn.ConnectionString = ConfigurationManager.ConnectionStrings["accessConnectionString"].ToString();
}
catch(Exception ex)
{
throw ex;
}
}//end of constructor
//class to check membership
public object checkMembership(string logid, string password)
{
try
{
sconn.Open();
//set propertiers of the command
scmd.Connection = sconn;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "select * from SubDealers where LoginID = #InputUsername and Password = #InputPassword";
scmd.Parameters.Clear();
OleDbParameter checkUsername = scmd.Parameters.Add("#InputUsername", OleDbType.VarChar, 50);
checkUsername.Value = logid;
OleDbParameter checkPassword = scmd.Parameters.Add("#InputPassword", OleDbType.VarChar, 50);
checkPassword.Value = password;
object result = scmd.ExecuteScalar();
return result;
}
catch (OleDbException sqx)
{
throw sqx;
}
finally
{
sconn.Close();
}
}//end of method
my code behind page
try
{
object result = dm.checkMembership(txtLoginID.Text, txtPassword.Text);
if (result != null)
{
Response.Redirect("https://www.google.com/");
}
else
{
txtLoginID.Text = "";
txtPassword.Text = "";
Page.ClientScript.RegisterStartupScript(this.GetType(), "notAmember", "alert('Sorry wrong id or password');", true);
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
have you tried this?
select * from [SubDealers] where [LoginID] = #InputUsername and [Password] = #InputPassword"

Resources