executescalar returning null value - asp.net

string checkuserQuery = "select username from usersign where Username=' " + TextBox1.Text + " ' ";
SqlCommand usercom = new SqlCommand(checkuserQuery, conn);
string user1 = string.Empty;
Object val = usercom.ExecuteScalar();
if (val != null)
{
user1 = val.ToString();
if (user1 == TextBox1.Text)
{
string checkpasswordQuery = "select password from usersign where Username=' " + TextBox1.Text + " ' ";
SqlCommand passcom = new SqlCommand(checkpasswordQuery, conn);
string password = passcom.ExecuteScalar().ToString();
if (password == TextBox2.Text)
{
Session["New"] = TextBox1.Text;
Label5.Text = "password is correct";
Response.Redirect("user.aspx");
}
else
{
Label5.Text = "password is not correct";
}
}
}
else
{
Label5.Text = "val is null";
}
}

ExecuteScalar() will return null if the query doesn't return a value.
Returns the first column of the first row in the result set, or a null
reference (Nothing in Visual Basic) if the result set is empty.
Source
This line will throw a null reference exception:
passcom.ExecuteScalar().ToString();
Building queries using string concatenation is error prone. More importantly, it is vulnerable to SQL injection. The code suggests that passwords are stored in the database in plain text.
SQL injection and plain text passwords are a serious concern for any application. Parameterize your queries (it is very easy with ADO.Net) and hash your passwords.
The lack of a match is probably caused by the following line:
string checkpasswordQuery = "select password from usersign where Username=' " + TextBox1.Text + " ' ";
Note the extra spaces added in the string concatenation. Whatever is in TextBox1 will be preceded/followed by whitespace, causing the match to fail.

the problem could be the space characters in the following (i have put a * where space
is incorrectly used)
where Username='*" + TextBox1.Text + "*' "
So the above will mean that your query is trying to get a user name that has
a space character in start and at the end, so just remove those spaces
another point is, such query should be used with parameters as it is prone to
SQL injection type of attacks

Related

Update user profile in website

In my website made by asp.net, we can update the email address, password, place and about myself of a user given the old password is correct. Now what I do is, login, then use this code to update:
protected void update_profile(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString;
using (SqlConnection connection = new SqlConnection(constr))
{
string user_email = (string)(Session["User"]);
string pass = encrypt_pass(old_password.Text);
if (pass != (string)(Session["Password"]))
{
pass_err_message.Text = "Wrong password";
pass = (string)Session["Password"];
}
else
{
pass = encrypt_pass(new_password.Text);
}
string insertQuery = "update dbo.users set user_password=#new_password, user_place = #new_place, user_about=#new_about where user_email =" +user_email;
SqlCommand com = new SqlCommand(insertQuery, connection);
connection.Open();
com.Parameters.AddWithValue("#new_password", pass);
com.Parameters.AddWithValue("#new_about", new_about.Text);
com.Parameters.AddWithValue("#new_place", new_place.Text);
try
{
com.ExecuteNonQuery();
upload_err_message.Text = "Successfully uploaded";
connection.Close();
}
catch (Exception ex)
{
profile_settings_err_message.Text = "Update error: " + ex.Message;
}
}
}
But when I try to update it is saying: Update error: The multi-part identifier "abcde#gmail.com" could not be bound. And my session is gone! I thought maybe it was due to foreign key, so I removed all the foreign keys of the database, but it is still happening. What's wrong here?
EDIT: I have added back the foreign keys, since I need them to on delete cascade. I just deleted them to see if it works.
I am just taking a guess, but I believe your issue will be found right here:
"... user_email =" +user_email;
Try doing something like
"... user_email = #email";
com.Parameters.AddWithValue("#email", user_email);
That's the better way... however if you want to get lackadaisical you should be able to just surround the email in single quotes.
"... user_email = '" + user_email + "'";
I hope this helps!

asp:textarea control to allow the user to input text to place into the body of an e-mail

I'm using an asp:textarea control to allow the user to input text and then place that text into the body of an e-mail. in the code behind, what is the syntax for adding html tags inside this text area.
For example, For my email i want to have default text to populate the text area. Some of this text is being pulled from my sql server DB.
"Dear [UserName],
The reason your booking was cancelled is because [Reason]
Kind Regards,
[LoggedIn Admin]"
The example above is the template i want to set. The [] indicate where i want to populate from my db.
So far i have been able to enter in the UserName but i cant seem to get a tag to create a space to format the text properly.
The code below is what i have so far and the commented out lines are my attempts.
Id appreciate any help, Thanks
private void GetSelectedBooking()
{
//Database connection setup
string strConnString = ConfigurationManager.ConnectionStrings["BookingDb"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
//Populate form with Booking Details for logged in user
BookingId += Session["BookingId"];
try
{
con.Open();
SqlCommand comm = new SqlCommand();
//preparing a query which will select all properties matching the User that is logged in at that moment
comm.CommandText = (#"select bd.BookingId, ud.Name, bd.Date, bd.StartTime, bd.EndTime ,bd.MemberType, bd.PitchSection, bd.Description ,bd.AmountPaid , ud.Email
from dbo.BookingDetails bd
join UserDetail ud
on ud.UserId = bd.UserId
where BookingId ='" + Session["BookingId"] + "'");
comm.Connection = con;
SqlDataReader rd = comm.ExecuteReader();
if (rd.HasRows)
{
while (rd.Read())
{
Booking.Text = BookingId;
to.Text = rd["Email"].ToString();
subject.Text = "Your Booking Has been Cancelled";
string Name = rd["Name"].ToString();
body.Text = "Dear " + Name.Trim() + "" +", reason";
//Literal ltrl = new Literal();
//ltrl.Text = "<BR />";
//body.Text = "Dear" + ltrl + Name + "reason";
//Literal ltrl2 = new Literal();
// body.Text = "<Description=" + rd["Name"].ToString() + "'><BR />View Address";
// e.Cell.Controls.Add(ltrl2);
// body.Text = "Dear " + "<BR />" + rd["Name"].ToString() + "' + reason";
// body.Text = "Dear " + "<BR /> " + rd["Name"].ToString() + "'";
}
}
rd.Close();
}
catch (Exception ex)
{
Response.Write(ex);
}
finally
{
con.Close();
}
}
Your question is only about Asp.net Webforms and html.
In order to add a line break in a Textarea control, you should use \n.
You can use a multi line string if you want to. To render a multi line string in C#, you use the # sign, like this:
void Main()
{
var message = #"Dear [UserName],
The reason your booking was cancelled is because [Reason]
Kind Regards,
[LoggedIn Admin]";
var dictionary = new Dictionary<string, string>();
dictionary.Add("UserName", "johndoe");
dictionary.Add("Reason", "you already have another booking for the same day.");
dictionary.Add("LoggedIn Admin", "Booking Staff");
foreach (var entry in dictionary.Keys)
{
message = message.Replace(string.Format("[{0}]", entry), dictionary[entry]);
}
// You Should now assign the message variable to the textarea.text
// textarea.Text = message;
Console.WriteLine(message);
}
A better approach would be if you not build the text programmatically, but instead read it from a file or a database.
Hope this helps,
I went with this solution
https://social.msdn.microsoft.com/Forums/en-US/47af2197-26b4-4b9e-90e8-bfa9d5cd05b4/what-is-the-deference-between-r-n-and-rn-?forum=csharplanguage
it uses /r/n to create the new line i need. so now i have:
to.Text = rd["Email"].ToString();
subject.Text = "Your Booking Has been Cancelled";
string Name = rd["Name"].ToString();
body.Text = "Dear " + Name.Trim() + "" +", reason" + "\r\n" + "new line test" + "\r\n" + "hi" ;
This outputs:
Dear [UserName], reason
new line test
hi

SQLite error unrecognized token Unity

I am using Unity, here is a little snippet of my code. All I want to do is to put the data.token and the data.expire into SQLite. For some reason it keeps throwing me an error that is:
SqliteException: SQLite error
unrecognized token: "587503bc773a565d52401c87"
Mono.Data.Sqlite.SQLite3.Prepare (Mono.Data.Sqlite.SqliteConnection cnn, System.String strSql, Mono.Data.Sqlite.SqliteStatement previous, UInt32 timeoutMS, System.String& strRemain)
Mono.Data.Sqlite.SqliteCommand.BuildNextCommand ()
I have no idea how the token is unrecognized, In SQLite the Token field is a STRING and the Expire field is an INTEGER.
IncomingTokenData data = IncomingTokenData.CreateFromJSON(www.text);
string conn = "URI=file:" + Application.dataPath + "/MyDataBase.s3db"; //Path to database.
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES(" + data.token +", " + data.expire + ")";
if(!string.IsNullOrEmpty(www.error)) {
ErrText.text = "Error: " + www.error;
}else{
if(data.pass == "1"){
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
dbcmd.CommandText = sqlQuery;
dbcmd.ExecuteNonQuery();
In SQL queries, you should enclose string values in single quotes (in this case, place quotes around data.token):
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES('" + data.token +"', " + data.expire + ")";
Note that string concatenation isn't the best way to build up SQL queries - a more robust way to avoid these problems is to use placeholders, like the built-in functionality IDbCommand has for adding parameters:
var sqlQuery = "INSERT INTO MyDataBase(Token, Expire) VALUES(#token, #expire)";
if(!string.IsNullOrEmpty(www.error)) {
ErrText.text = "Error: " + www.error;
}else{
if(data.pass == "1"){
IDbConnection dbconn;
dbconn = (IDbConnection) new SqliteConnection(conn);
dbconn.Open(); //Open connection to the database.
IDbCommand dbcmd = dbconn.CreateCommand();
dbcmd.Parameters.Add("#token", SqlDbType.VarChar).Value = data.token;
dbcmd.Parameters.Add("#expire", SqlDbType.Int).Value = data.expire;
dbcmd.CommandText = sqlQuery;
dbcmd.ExecuteNonQuery();
Using this method, the values are properly formatted according to their data type.

Login Page to verify NIC number

I am facing the followingj problem: I have a database on Access 2010 with fields NIC,Active and Page, all are of number types. I want to create a login page that takes NIC (numeric) as an input from the user and then redirects them to specific page as per their NICs.
Different people will see different pages.. I am getting an error in ExecuteScalar command, maybe my query is not correct or maybe ExecuteScalar can't hold the query... I am getting data type mismatch error.
try
{
FirsstPage f = new FirsstPage();
SecondPage second = new SecondPage();
oledcon.Open();
string NIc = ( TextBox1.Text);
// string query = "select * from LogINTable where NIC='" + NIc + "'AND Active=0 AND page=1";
//string query = "select * from LogINTable where NIC='" + nic + "'AND Active=0";
string query = "SELECT * FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1";
//string query = "select
OleDbCommand comm = new OleDbCommand( query,oledcon);
string a = (string) comm.ExecuteScalar();
if (a != null)
{
Response.Redirect("FirsstPage.aspx");
string update = "update into LogINTable Active='1' where NIC='" + NIc + "' ";
//OleDbCommand com = new OleDbCommand();
//int b = Convert.ToInt32( com.ExecuteScalar());
}
else
{
Response.Redirect("SecondPage.aspx");
string update = "update into LogINTable Active='1' where NIC='" +NIc + "' ";
}
oledcon.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
oledcon.Close();
}
Problem is that you are using ExecuteScalar with wrong query.
string a = (string) comm.ExecuteScalar();
ExecuteScalar() will return single value as a result from query.
Please change your query to the query like blow which return single value from database in place of entire colomn
Select NIC FROM LogINTable WHERE NIC= '" + NIc + "' AND Active=0 AND page=1"
Source :http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
I hope it will help you.

Secure website from SQL Injection ' using ASP.net and an Access database

I currently have a website with a normal registration and login, coded with ASP.net.
I am using an Access database, while using a C# class my friend wrote for handling most of the database actions (executeQuery, executeRead, isExits...).
Now that I've almost finished building my website, I want to start adding security - mostly to my database. I have searched for a while now for a tutorial on the subject, but I could not find anything good exept an old microsoft msdn article which I couldn't realy get its code to work.
The furthest I've got now is just no allowing any dangerous characters in the username and password, (such as ',--,;), but it kind of feels as if it is the worse solution that i can use (why shouldn't my users use this characters?).
I think that the best solution I've found is somehow insertion the variables into the query string after declaring it (something to do with "WHERE username=#user" or something like that), but i couldn't get it to work with Access and with my oleDBManager.
here is my current registration code. handle() is removing all ' from the string, and Validate() checks for dangerous parts in the string.
string username = user.Text;
string password = pass.Text;
bool isThingy = false;
if (handle(ref password)) isThingy = true;
if (handle(ref username)) isThingy = true;
if (username != "" && username != null)
{
if (password != "" && password != null)
{
if (Validate(username, password))
{
if ((db.IsExist("SELECT * FROM Table1 WHERE username='" + username + "'") == false))
{
int a = db.ExecuteQuery("INSERT INTO `Table1`(`username`, `password`, `logins`, `email`, `fname`, `lname`, `country`, `city`, `birthday`, `userid`) VALUES ('" + username + "', '" + password + "', '0', '', '', '', '', '', '', '" + Convert.ToString(Convert.ToInt32(db.ExecuteCellRead("SELECT MAX(userid) FROM Table1")) + 1) + "');");
if (!isThingy) errorLabel.Text = "Your user has been successfully registered";
else errorLabel.Text = "The ' token is invalid. your user was registered absence the '.";
}
else
errorLabel.Text = "This username is already taken";
}
else errorLabel.Text = "Invalid name format";
}
else errorLabel.Text = "Please enter a password";
}
else errorLabel.Text = "Please enter a user name";
as for the oleDBManager (named db in my code):
private OleDbConnection link; // The link instance
private OleDbCommand command; // The command object
private OleDbDataReader dataReader; // The data reader object
private OleDbDataAdapter dataAdapter; // the data adapter object
private DataTable dataTable; // the data table object
private string dbName; // the Database filename
private int version; // the usersTableG office version
private string connectionString; // the connection string for the database connection
private string provider; // the matching driver string for the connection string
private string path; // the path to the database file
...
public int ExecuteQuery(string query)
{
this.link.Open();
int rowsAffected;
// ---
this.command = new OleDbCommand(query, this.link);
try
{
rowsAffected = this.command.ExecuteNonQuery();
}
catch (InvalidOperationException e)
{
if (e.Data == null)
throw;
else
rowsAffected = -1;
}
finally
{
this.command.Dispose();
this.link.Close();
}
// ---
return rowsAffected;
}
public bool IsExist(string query)
{
this.link.Open();
// ---
this.command = new OleDbCommand(query, this.link);
this.dataReader = this.command.ExecuteReader();
bool a = this.dataReader.Read();
// ---
this.command.Dispose();
this.link.Close();
// ---
return a;
}
public string ExecuteCellRead(string query)
{
string output = "";
this.dataTable = this.ExcecuteRead(query);
foreach (DataRow row in this.dataTable.Rows)
{
foreach (object obj in row.ItemArray)
{
output += obj.ToString();
}
}
return output;
}
So, as you might see, the main problem is that the user now can not use characters as '.
It suppose the best solution would be using the # variables in the SQL queries, but I have no idea how.
[thanks for your help]
PS. i HAVE changed my tables' name ;)
edit: most of you are telling me to use these parameterized queries, but it would be great if you could give me an example of how to use them, since i've never done that
So, thanks to #Remou, my FINAL code is:
db.DoWeirdStackOverFlowStuff(
"INSERT INTO `Table1`(`username`, `password`, `logins`) VALUES (#username, #password, '0');"
, new string[] { "#username", "#password" }
, new string[] { username, password });
and
public int DoWeirdStackOverFlowStuff(string query, string[] vars, string[] reps)
{
this.link.Open();
int rowsAffected;
// ---
this.command = new OleDbCommand();
this.command.CommandText = query;
this.command.CommandType = System.Data.CommandType.Text;
this.command.Connection = this.link;
//Parameters in the order in which they appear in the query
for (int i = 0; i < vars.Length; i++)
this.command.Parameters.AddWithValue(vars[i], reps[i]);
try
{
rowsAffected = this.command.ExecuteNonQuery();
}
catch (InvalidOperationException e)
{
if (e.Data == null)
throw;
else
rowsAffected = -1;
}
finally
{
this.command.Dispose();
this.link.Close();
}
// ---
return rowsAffected;
}
for whoever needs this =]
Some notes
In MS Access, I have a saved query called UpdateUser, it looks like this:
UPDATE INTERNETSETTINGS
SET url = [#url],
databasename = [#databasename],
port = [#port],
username = [#username],
[password] = [#password]
I can refer to this query by name in my code, using a command object:
OleDbCommand Command = new OleDbCommand();
Command.CommandText = "UpdateUser"; //saved query
Command.CommandType = System.Data.CommandType.StoredProcedure;
Command.Connection = cn; //a connection to the database
//Parameters in the order in which they appear in the query
Command.Parameters.AddWithValue("#url", "a"); //a,b,c etc for my test run
Command.Parameters.AddWithValue("#databasename", "b");
Command.Parameters.AddWithValue("#port","c");
Command.Parameters.AddWithValue("#username", "d");
Command.Parameters.AddWithValue("#password", "e");
Command.ExecuteNonQuery();
I don't remember whether Access does the same thing as SQL Server here, but in SQL Server you can escape the single quote mark by doubling it:
username = username.Replace("'", "''");
So you can include single-quote marks in the string, you can store them in the database, and they can't be used as malicious string terminators.

Resources