"Incorrect syntax near 'admin' - asp.net

this programm when i enter username and password go to data base and compare from table,but when i enter username admin ,password admin(exist in table)
compalier show error "Incorrect syntax near 'admin'" in line
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
else
{
Response.Redirect("Error.aspx");
}
}

The error is simply caused by the missing equals before the values concatenated in the sql command text.
But also fixing it, your code is wrong for other reasons.
You should ALWAYS use a parameterized query to avoid Sql Injection and parsing problems,
You could remove the COUNT function that causes an unnecessary load of all records just to confirm the existence of your searched data
You need to identify your user searching for both password and
username on the SAME record, as it is now, the code above search first the username
and then a password, but I can type an existing user name (first if passed) and use
a password of a different user (second if passed) and then gain access to
your site.
.
string checkuser = "IF EXISTS(select 1 from [Users] where Username = #usr AND Password=#pwd)
SELECT 1 ELSE SELECT 0";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand com = new SqlCommand(checkuser,conn))
{
conn.Open();
com.Parameters.AddWithValue("#usr", TextBoxUserName.Text);
com.Parameters.AddWithValue("#pwd", TextBoxPassword.Text);
int temp = Convert.ToInt32(com.ExecuteScalar());
if (temp == 1)
Response.Redirect("Welcome.aspx");
else
Response.Redirect("Error.aspx");
}
Other things changed in the example above are the USING STATEMENT to be sure that your connection and command are disposed at the end of the operation also in case of exceptions

Try changing this line
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
to this
string checkuser = "select count(*) from [Users] where Username = '" + TextBoxUserName.Text + "'";
you are missing an = sign
you'll need to do the same to your password select as well, you also missed the = sign there.
string checkpassword = "select Password from Users where Password = '" + TextBoxPassword.Text + "'";

When checking the Password, you should also include the UserName:
string checkpassword = "select Password from Users where UserName = '" + TexBoxUserName.Text + "' AND Password = '" + TextBoxPassword.Text + "'";
If you do not include the UserName the it is only validating that some user has that password.
The following code will prevent SQL injection by paramterizing the command text
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "SELECT Count(UserName) FROM USERS WHERE UserName = #UserName";
SqlCommand com = new SqlCommand(checkuser,conn);
SqlParameter parmUserName = new SqlParameter("UserName", TextBoxUserName.Text);
com.Parameters.Add(parmUserName);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "SELECT Password FROM USERS WHERE UserName = #UserName AND Password = #Password";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
SqlParameter parmPassword = new SqlParameter("Password", TextBoxPAssword.Text);
com.Parameters.Add(parmUserName);
com.Parameters.Add(parmPassword);
string password = passComm.ExecuteScalar().ToString();

Related

Sqlite code not displaying any Debug log?

Very new to sqlLite and trying to make a very simple bit of code which will display the values of username and password in the table just using the debug log for ease. When running the code nothing is display in the debug log. Could someone suggest a fix?
IDbConnection dbconn;
dbconn = (IDbConnection)new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
string sqlQuery = "SELECT username, password " + "FROM user";
dbcmd.CommandText = sqlQuery;
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string username = reader.GetString(0);
string password = reader.GetString(1);
Debug.Log("Username: " + username + " Password:" + password);
}
reader.Close();
reader = null;
dbcmd.Dispose();
dbcmd = null;
dbconn.Close();
dbconn = null;
}
}
You can try to get the parameter out of the reader like that:
IDataReader reader = dbcmd.ExecuteReader();
while (reader.Read())
{
string username = reader["username"];
string password = reader["password"]
Debug.Log("Username: " + username + " Password:" + password);
}

ASP ServerVariables logon user

In my code behind, I have this
{
Label2.Text = "[" + HttpContext.Current.User.Identity.Name + "]";
}
to identify the username in domain. So far so good. It works properly in IIS.
However, I would like to store the username into a database. How can I do that?
The idea is to record the person who answer to this:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile) VALUES (#Business,#Business2,#Mobile)";
using (Conn)
{
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}
I have the answer inserted into the database, but how can I save the person who answer? Can I save the label into the database table? Or is it impossible?
Just add a username field to your table and add another parameter:
string insertCmd = "INSERT INTO worker(Business,Business2,Mobile,username) VALUES (#Business,#Business2,#Mobile,#username)";
using (Conn) {
Conn.Open();
OleDbCommand myCommand = new OleDbCommand(insertCmd, Conn);
myCommand.Parameters.AddWithValue("#Business", business.Text);
myCommand.Parameters.AddWithValue("#Business2", business2.Text);
myCommand.Parameters.AddWithValue("#Mobile", mobile.Text);
myCommand.Parameters.AddWithValue("#username", HttpContext.Current.User.Identity.Name);
myCommand.ExecuteNonQuery();
Label1.Text = "Saved Successfull!";
Label1.ForeColor = System.Drawing.Color.Green;
}

How to update only some columns of database?

The problem occuring on updating only email all other blanks get null . Even if i unchecked allow null in sql server 2008 .my code is-
protected void Updateinfo_Click(object sender, EventArgs e)
{
string radiogender;
if (Radiochngmale.Checked == true)
radiogender = Radiochngmale.Text.ToString();
else
radiogender = Radiochngfemale.Text.ToString();
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["Con"].ConnectionString;
con.Open();
if (con.State == ConnectionState.Open)
{
SqlCommand cmd = new SqlCommand();
Random r = new Random();
int next = r.Next();
if (FileUpload2.HasFile)
{
string myMap = MapPath("~/").ToLower();
string ImageName = FileUpload2.PostedFile.FileName;
sImageFileExtension = ImageName.Substring(ImageName.LastIndexOf(".")).ToLower();
if (sImageFileExtension == ".gif" || sImageFileExtension == ".png" || sImageFileExtension == ".jpg" || sImageFileExtension == ".jpeg" || sImageFileExtension == ".bmp")
{
string ImageSaveURL = myMap + "UserImage/" + next + sImageFileExtension;
FileUpload2.PostedFile.SaveAs(ImageSaveURL);
}
else
Response.Write("Invalid File");
}
cmd.Connection = con;
if(chngfname.Text==null)
chngfname.Text="Select Firstname from Login where Email='"+Session["UserName"]+"'";
if (chnglastname.Text == null)
chnglastname.Text = "Select Lastname from Login where Email='" + Session["UserName"] + "'";
if (chngage.Text == null)
chngage.Text = "Select age from Login where Email='" + Session["UserName"] + "'";
if (chngemail.Text == null)
chngemail.Text = "Select Email from Login where Email='" + Session["UserName"] + "'";
if (radiogender == null)
radiogender = "Select gender from Login where Email='" + Session["UserName"] + "'";
if (chngpassword.Text == null)
chngpassword.Text = "Select Password from Login where Email='" + Session["UserName"] + "'";
if ( FileUpload2.HasFile==null)
sImageFileExtension = "Select profile_pic from Login where Email='" + Session["UserName"] + "'";
if (chngfname.Text == null)
chngfname.Text = "Select Firstname from Login where Email='" + Session["UserName"] + "'";
cmd.CommandText = "Update Login set FirstName = '"+chngfname.Text+"',LastName='"+chnglastname.Text+"',Email='"+chngemail.Text+"',Password='"+chngpassword.Text+"' ,gender='"+radiogender+"',age='"+chngage.Text+"' , profile_pic='"+ next + sImageFileExtension + "' where Email='"+Session["UserName"]+"'";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
Why didn't it is taking the previous values even if i mentioned it to take.Please check it out and sort it out
This is happening because TextBox.Text is never null so your SQL query ends up looking like this:
Update Login
set FirstName = '',
LastName = '',
where Email = 'John.doe#nowhere.net'
-- etc...
Except for the one or two fields where the data is actually set to something. Here's probably what you wanted it to look like:
update login
set FirstName = 'John',
LastName = (select Lastname from login where email = 'John.doe#nowhere.net'),
etc...
where email = 'John.doe#nowhere.net'
But, there no need for the subqueries. If you want to avoid overwriting values where a value is null or empty string, then you want your SQL to look like the following, use Parameters and set them to DbNull when the textbox is empty.
cmd.Parameters.AddWithValue("#FirstName", (chngfname.Text == String.Empty) ? DbNull.Value : chngfname.Text;
update login
set FirstName = coalesce(#firstName, FirstName),
LastName = coalesce(#LastName, LastName),
etc...
where Email = #Email
The other option is select the record first (which I'm sure you've already done) and simply use the same value that's already in the database.
if (chngfname.Text == String.Empty) chngfname.Text = Session["CurrentUserEntity"].FirstName;
Additionally, you need to change this to a parametrized query:
string sql = "update login set FirstName = #firstName, LastName = #lastName, etc... where email = #email;
cmd.Parameters.Add(...);
You should try to use a parametrized query instead of the current string concatenation method.
This will resolve the quoting problems and prevent sql injiection attacks
cmd.CommandText = "Update Login set FirstName = #First, LastName=#Last, " +
"Email=#Mail, Password=#Pass, gender=#Gend,age=#Age, " +
"profile_pic=#Prof " +
"where Email=#oldMail";
cmd.Parameters.AddWithValue("#First", chngfname.Text);
cmd.Parameters.AddWithValue("#Last", chnglastname.Text);
cmd.Parameters.AddWithValue("#Mail", chngemail.Text);
cmd.Parameters.AddWithValue("#Pass", chngpassword.Text);
cmd.Parameters.AddWithValue("#Gend", radiogender);
cmd.Parameters.AddWithValue("#Age", chngage.Text);
cmd.Parameters.AddWithValue("#Prof", next + sImageFileExtension );
cmd.Parameters.AddWithValue("#oldMail", +Session["UserName"]);
However, as I have said in my previous comment, your code doesn't seems correct.
First a TextBox.Text cannot be null, it is an empty string. This will skip your text for null values above and you end with setting a blank value in the database. At least try to change the test with
if(string.IsNullOrEmpty(chngfname.Text))
......
But at this point you should change the code inside each if above. If your intentions is to retrieve the old values from the database and use them in case of empty string, you need to execute that string, not store it in the textbox.
EDIT: Before to start your update process you need to load the old values of the record you are trying to update. This could be done using the same connection
SqlDataAdapter da = new SqlDataAdapter("SELECT * from Login where EMail = #oldMail", con);
da.SelectCommand.Parameters.AddWithValue("#oldMail", Session["UserName");
DataTable dt = new DataTable();
da.Fill(dt);
now you have in a datatable all of your old values for that user, so when you reach the check of the old values you could write something like this
if(string.IsNullOrEmpty(chngfname.Text))
cngfname.Text = (dt.Rows["FirstName"] == DBNull.Value ? string.Empty : dt.Rows["FirstName"].ToString());
and remove that sql string because you have already retrieved the values for every potentially missing field

SqlException in Asp.net - Incorrect syntax near 'Van'

I have problem with my SqlCommand everything I open the page I get the error:
System.Data.SqlClient.SqlException: Incorrect syntax near 'Van'.
I cannot find the problem because 'Van' is only found once in the entire project, and in the title..
This is my code in the Page_Load:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = " + User.Identity.Name, con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
}
The database connectionstring is correct because it works for all my other pages.. i'm trying to get the department where an employee works so he/she can only view memo's from their own department.
You need to close the parentheses after the last name provided.
SELECT (SELECT Memo_ID, Dep_Name FROM Department
WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName
FROM Staff WHERE (FirstName + SPACE(1) + LastName = 'xxx' )
Here is what it should look like:
using (SqlConnection con = new SqlConnection(RoleEnvironment.GetConfigurationSettingValue("DatabaseConnectionString")))
{
var cmd = new SqlCommand("SELECT (SELECT Memo_ID, Dep_Name FROM Department WHERE (Department_ID = Staff.Depar_ID)) AS DepartmentName FROM Staff WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "')", con);
cmd.Connection.Open();
var sqlReader = cmd.ExecuteReader();
while (sqlReader.Read())
{
String result = sqlReader.GetString(0);
DropDownList1.DataBind();
DropDownList1.Items.FindByValue(result).Selected = true;
//Fill some data like : string result = sqlReader("SomeFieldName");
}
sqlReader.Close();
cmd.Connection.Close();
cmd.Dispose();
You need to quote the last name. You probably want to convert to a parameterized query too.
I'd have expected your WHERE clause to wrap the User.Identity.Name in quotes:
WHERE (FirstName + SPACE(1) + LastName = '" + User.Identity.Name + "'" ...
Could "van" be in the username?
This isn't a very secure query either - but SQL injection's another issue!

Inserting new values in database Asp .Net

I have a code for inserting values in ASP.net using vb. I'm having problem with my code says login failed, cannot open database.
Dim struser, strpass, stremail As String
struser = TextBox1.Text
strpass = TextBox2.Text
stremail = TextBox4.Text
'declaring sql connection.
Dim thisConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("DatabaseConnection").ConnectionString)
'Create Command object
Dim nonqueryCommand As SqlCommand = thisConnection.CreateCommand()
Try
' Open Connection
thisConnection.Open()
Dim strcommand As String
strcommand = "Insert into Account (Username,Password, Email) values ('" + struser + "','" + strpass + "','" + stremail + "')"
Dim sqlcomm As New SqlCommand(strcommand, thisConnection)
Dim o As String = sqlcomm.ExecuteNonQuery()
Catch ex As SqlException
' Display error
MsgBox(ex.ToString())
Finally
' Close Connection
MsgBox("Success")
thisConnection.Close()
End Try
connection string:
<add name="DatabaseConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=o2database.mdf;Integrated Security=SSPI" providerName="System.Data.SqlClient"/>
1) Initial catalog must be name of the schema you are accessing
2) You may use 'Server Explorer' & try to just connect to the database
from there. Once succeeded just copy the connection string from
properties & replace your current connection string.
I think your Initial Catalog is wrong. your pointing at a file you should use here the database-name. I guess o2database.
if this is not the case - you are using SSPI to login - maybe your user does not have the permission to do so.
another thing is that your web-application is not configured in the iis to pass on your domain-user credentials - so it cannot work using SSPI to login.
your code is right, the problem is with your sql server configuration, you cannot access sql server with integrated security, so, you need to configure it to work fine, take a look at this post:
http://support.microsoft.com/kb/914277
if you're in IIS, you should able the remote access on sql server too.
Look how to access using SSI:
http://msdn.microsoft.com/en-us/library/aa984236(v=vs.71).aspx
http://msdn.microsoft.com/pt-br/library/bsz5788z.aspx
Warning : You are giving rise to SQL Injection in your code.
Sample Stored Procedure
Create Proc ProcedureName
#UserName Varchar(50),
#Password Varchar(50),
#Email Varchar(50)
As
SET NOCOUNT ON
SET XACT_ABORT ON
Begin Try
Begin Tran
Insert into Account (Username,Password, Email)
Values(#UserName, #Password, #Email)
Commit Tran
End Try
Begin Catch
Rollback Tran
End Catch
Sample code in C Sharp
private void InsertRecord()
{
String struser = string.Empty, strpass = string.Empty, stremail = string.Empty;
using (SqlConnection con = new SqlConnection("Your Connection String"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure name";
SqlParameter[] param = new SqlParameter[3];
param[0].Direction = System.Data.ParameterDirection.Input;
param[0].ParameterName = "UserName";
param[0].Value = struser;
cmd.Parameters.Add(param[0]);
param[1].Direction = System.Data.ParameterDirection.Input;
param[1].ParameterName = "Password";
param[1].Value = strpass;
cmd.Parameters.Add(param[1]);
param[2].Direction = System.Data.ParameterDirection.Input;
param[2].ParameterName = "Email";
param[2].Value = stremail;
cmd.Parameters.Add(param[2]);
cmd.ExecuteNonQuery();
}
}
}
Sample Code in VB.Net
Private Sub InsertRecord()
Dim struser As [String] = String.Empty, strpass As [String] = String.Empty, stremail As [String] = String.Empty
Using con As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand()
cmd.Connection = con
cmd.CommandType = System.Data.CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure name"
Dim param As SqlParameter() = New SqlParameter(2) {}
param(0).Direction = System.Data.ParameterDirection.Input
param(0).ParameterName = "UserName"
param(0).Value = struser
cmd.Parameters.Add(param(0))
param(1).Direction = System.Data.ParameterDirection.Input
param(1).ParameterName = "Password"
param(1).Value = strpass
cmd.Parameters.Add(param(1))
param(2).Direction = System.Data.ParameterDirection.Input
param(2).ParameterName = "Email"
param(2).Value = stremail
cmd.Parameters.Add(param(2))
cmd.ExecuteNonQuery()
End Using
End Using
End Sub

Resources