SQL Server Error, 'Keyword not supported 'datasource' - c#

I'm currently trying to INSERT some values into a datasource, then display them on another page using the DataList control. However, after some testing and experimentation, I've found that the error comes from the very beginning.
Here is the code I have bound to my button.
protected void btnSend_Click(object sender, EventArgs e)
{
Page.Validate("vld2");
SendMail();
lblMsgSend.Visible = true;
txtPhone.Text = "";
txtEmail.Text = "";
txtName.Text = "";
txtComment.Text = "";
//SQL Server Database
SqlConnection conn; //manages connection to database
SqlCommand cmd; //manages the SQL statements
string strInsert; //SQL INSERT Statement
try
{
//create a connection object
conn = new SqlConnection("DataSource=localhost\\sqlexpress;" +
"Initial Catalog=RionServer;" +
"Integrated Security=True;");
//Build the SQL INSERT Document
strInsert = "INSERT INTO CommentsAdmin (Name,Phone,Email,Comments)"
+ "VALUES(#Name,#Phone,#Email,#Comments);";
//associate the INSERT statement with the connection
cmd = new SqlCommand(strInsert, conn);
//TELL the SqlCommand WHERE to get the data from
cmd.Parameters.AddWithValue("Name", txtName);
cmd.Parameters.AddWithValue("Phone", txtPhone);
cmd.Parameters.AddWithValue("Email", txtEmail);
cmd.Parameters.AddWithValue("Comments", txtComment);
//open the connection
cmd.Connection.Open();
//run the SQL statement
cmd.ExecuteNonQuery();
//close connection
cmd.Connection.Close();
//display status message on the webpage
lblMsgSend.Text = "Thank you for the comment! Please hit the 'Return to Main Page' to return to the Main Page!";
}
catch (Exception ex)
{
lblMsgSend.Text = ex.Message;
}
}
Here is the image of my webpage and the error it displays.
Please let me know if you need additional information.
Thanks in advance.

In your connection string, it should be "Data Source", not "DataSource". Just add a space.

Related

Visual Studio Login Page with local SQL server database

I'm creating a visual studio project that uses a local SQL server database as a data source, which is up and running correctly.
I need to create a login form for the project.
The form has a username textbox and a password textbox which the user will populate with their details, and then hit the 'login' button, which needs to execute the select sql statement.
Any references on how to do this?
The code I have tried is below.
It's throwing a NullReferenceException at the line that says "SqlDataReader dr = cmd.ExecuteReader();"
How do I Solve the nullreferenceexception?
Thank you!
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=MARKO-PC\\SQLEXPRESS;Initial Catalog=IS2B_G8_FundMeDB;Integrated Security=True";
con.Open();
String sql = "Select * from APPLICANT where applicant_ID_passport =#user AND password = #password";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add(new SqlParameter("#user", txtUserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", txtPassword.Text));
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
MessageBox.Show("Login Successful");
}
else
{
MessageBox.Show("Login Failed");
}
}
catch (SqlException sqle)
{
MessageBox.Show("Sql Exception");
}
}
Try this
string struser = txtUserName.Text;
string strpwd = txtPassword.Text;
String sql = "Select * from APPLICANT where applicant_ID_passport=" + struser + " AND password = " + strpwd +"";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
You need to do some research into using ADO.Net, specifically the SQLCommand class.
However I would refrain from using inline sql statements like above as this opens you up to SQL injection. Rather use paramaterised queries, stored procedures or LINQ to SQL.

Unable to connect MS Access DB in Server

I am trying to connect the MS Access Database from the server and finding no luck.
I see the below image("Insert Operation Error") message while trying to save the information.
Can anyone please help? What went wrong in the below code?
Insert Operation Error
protected void btnsave_Click(object sender, EventArgs e)
{
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
string SqlString = "Insert Into BUREAUXDETUDES (mail1,mail2,tel1,tel2) Values (#mail1,#mail2,#tel1,#tel2)";
OleDbConnection con = new OleDbConnection(constring);
try
{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.Parameters.AddWithValue("#mail1", txtemail1.Text);
cmd.Parameters.AddWithValue("#mail2", txtemail2.Text);
cmd.Parameters.AddWithValue("#tel1", txttel1.Text);
cmd.Parameters.AddWithValue("#tel2", txttel2.Text);
cmd.ExecuteNonQuery();
lblmessage.Text = "Your Information Saved Successfully";
}
catch (Exception emsg)
{
lblmessage.Text = emsg.Message;
}
finally
{
con.Close();
}
}
The Error is telling you that the location of your .db file is incorrect.
You can change the path to the file in this line.
string constring = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" + Server.MapPath("DB\\Contact.DB");
You need to install Microsoft Excel engine first.
You can download it from the link bellow
https://www.microsoft.com/en-us/download/details.aspx?id=13255

Cancel submit button event in ASP and C#

I am trying to cancel a submit event if a response is true. I have a submission button in which i am wanting to check if the textbox is same as a value in the database. If it is then it will not allow the update to go ahead.
My C# code
protected void SubmitBtn_Click(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
conn.Open();
string sql = "Select count(*) from Student Where Student_Username=#username";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("username", usernameTxt.Text);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists");
}
conn.Close();
}
//SQL Connection and SQL for inserting a new student
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
con.Open();
try
{
var sql = "INSERT INTO Student (Student_Username, Student_FName, Student_SName, Student_Email, Student_Password, Student_Status) " + "VALUES (#StudentName, #StudentFirstname, #StudentSurname, #StudentEmail, #StudentPassword, #StudentStatus);";
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#StudentName", usernameTxt.Text);
cmd.Parameters.AddWithValue("#StudentFirstname", firstnameTxt.Text);
cmd.Parameters.AddWithValue("#StudentSurname", surnameTxt.Text);
cmd.Parameters.AddWithValue("#StudentEmail", emailTxt.Text);
cmd.Parameters.AddWithValue("#StudentPassword", passwordTxt.Text);
cmd.Parameters.AddWithValue("#StudentStatus", statusTxt.Text);
cmd.ExecuteNonQuery();
}
greenPnl.Visible = true;
usernameTxt.Text = "";
firstnameTxt.Text = "";
surnameTxt.Text = "";
emailTxt.Text = "";
passwordTxt.Text = "";
retypePasswordTxt.Text = "";
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
con.Close();
}
How can i call the eventArgs to cancel it? I know you cant simply e.cancel = true;
You can't "cancel" an event like that in ASP.NET. ASP.NET is a request/response platform - when you do something in the browser (click a link, submit a form, etc) - you send an entire request back to the server, and the browser waits for a response. That response will be rendered completely by the browser.
So some options are:
Continue with the ASP.NET lifecycle, completely rendering the page with whatever message you want to send back.
Use AJAX or some other mechanism to send a light request to the server before sending the entire request.

Inserting data into SQL table from asp.net form

I am trying to build a registration web form which saves user data into an SQL table. This is what I have so far:
public static SqlConnection GetConnection()
{
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
}
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = GetConnection();
try
{
myConnection.Open();
String myQuery = "INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) values ('"
+fNameBox.Text+ "' ,'"+ lNameBox.Text+"' ,'"+emailBox.Text+"' ,'"
+ dobBox.Text+"', '"+userNameBox.Text+"' ,'"+passwordBox.Text+"';)";
SqlCommand myCommand = new SqlCommand(myQuery, GetConnection());
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
myConnection.Close();
}
}
The error occurs in my GetConnection() method where I return the connection. The error I get is:
An exception of type 'System.ArgumentException' occurred in
System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0.
I do not know how to get past this problem but any help is very appreciated.
Your problem lies in
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
your connectionString variable (connection in your case) is not set properly, there are multiple ways to do that just to list 2 of the most common ones.
Standard Connection with username and password:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();
Trusted Connection:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();
You might want to look at this question for example:
How to set SQL Server connection string?
Pijemcolu's answer is correct, but I think several things can be added to enhance your code:
1) use proper names for variables. E.g.: connection string is different from actual connection
public static SqlConnection GetConnection()
{
// if Windows Authentication is used, just get rid of user id and password and use Trusted_Connection=True; OR Integrated Security=SSPI; OR Integrated Security=true;
String connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=UserName;Password=Secret;";
return new SqlConnection(connStr);
}
2) Try to dispose disposable objects (i.e. implement IDisposable) should be properly disposed.
Also, commands should not constructed with string concatenation, but using parameters. This is particularly important when providing direct user input into the query, since malicious users might try to perform queries to compromise the data (read more about SQL injection here).
The connection can be closed only within finally block, since everything there is executed no matter what (exception raised or not in the catch block).
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = null;
try
{
using (myConnection = GetConnection())
{
myConnection.Open();
String myQuery = #"
INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password])
values (#firstName, #lastName, #eMail, #dob, #userName, #password)";
using (SqlCommand myCommand = new SqlCommand(myQuery, GetConnection())
{
myCommand.Parameters.AddWithValue("#firstName", fNameBox.Text);
myCommand.Parameters.AddWithValue("#lastName", lNameBox.Text);
myCommand.Parameters.AddWithValue("#eMail", emailBox.Text);
myCommand.Parameters.AddWithValue("#dob", dobBox.Text);
myCommand.Parameters.AddWithValue("#userName", userNameBox.Text);
myCommand.Parameters.AddWithValue("#password", passwordBox.Text);
myCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (myConnection != null)
myConnection.Close();
}
}
3) Password storage
It looks like your storing password typed by the user. It is strongly recommended to store a representation of the password (some sort of hash that it is easy to compute from a string, but the string is almost impossible to be retrieved from the hash). More details can be found here.

SqlCommand Method Error while executing INSERT query in WPF Application

I am working on WPF application in C#. Database is SQL Server 2008. I have a table "Employee" in database, I need to insert a row in it. I have successfully connected with database, but when I tried to execute this line:
cmd = new SqlCommand(cmdText, conn);
This errors comes up: The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(String, System.Data.SqlClient.SqlConnection)' has some invalid arguments.
Here is my code:
private void addbtn_Click(object sender, RoutedEventArgs e)
{
//FUNCTION TO ADD NEW EMPLOYEE RECORD IN DATABASE
try
{
conn.ConnectionString = "Data Source=AZEEMPC;" + "Initial Catalog=IEPL_Attendance_DB;";
conn.Open();
cmdText = "INSERT INTO Employee VALUES ('" + strCurrentString + "','" + emp_name.Text + "')";
cmd = new SqlCommand(cmdText, conn);
data_ad = new SqlDataAdapter(cmd);
data = new DataSet();
data_ad.Fill(data);
MessageBox.Show("Record Inserted Successfully!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any suggestions?
conn needs to be of type SqlConnection - can you confirm that it is?
SqlConnection conn;
Because it's a native SQL Server connection, you don't need to pass the driver name in the connection string.
conn.ConnectionString = "Server=AZEEMPC;Database=IEPL_Attendance_DB;Trusted_Connection=true;";

Categories