asp.net Login Website from database - asp.net

I have a website with a login, from a database.
This is my code :
protected void SignIn_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
con.Open();
string cmdStr = "select count(*) from Users";
cmdStr += "where Username='" + UsernameSignIn.Text + "'";
cmdStr+= "AND Password='"+PasswordSignIn.Text+"'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
int i = Convert.ToInt16(cmd.ExecuteScalar());
if (i == 0)
{
ErrorSignIn.Text = "Sorry, Wrong Username or Password";
}
else
{
Response.Redirect("HomeAfter.aspx");
}
}
for some reason, I run into an error :
Incorrect syntax near '-'
.
(for this line : int i = Convert.ToInt16(cmd.ExecuteScalar()); )
Thanks,

There is no spacing. Your query looks like this:
select count(*) from Userswhere Username='...'AND Password='...'
Add spaces, like so:
string cmdStr = "select count(*) from Users";
cmdStr += " where Username='" + UsernameSignIn.Text + "'";
cmdStr+= " AND Password='"+PasswordSignIn.Text+"'";

Aside from the fact that this is particularly crude as a form of authentication (you really ought to consider using the built-in ASP.NET Membership provider(s)) you should at a minimum be using parameterized SQL queries, rather than concatenating plain text to create your SQL statement. Also, I notice that your "login" arrangement simply does a response.redirect to the HomeAfter.aspx page without storing anything to be re-used that will indicate the user has already successfully logged in, such as a cookie or a sesssion variable.
Is there any particular reason for all this, or is it because you're just starting out and you need to study up a bit?

Related

Can't Update Database from ASP.NET Webform

I can't get an ASP.NET webform to update a database. I'm trying to edit an existing record in the database. The webform populates the data from the record into the form. The user then changes data and updates the record in the database when the form is submitted.
The problem is that nothing is changed in the database when a modified form is submitted. What am I doing wrong here? The SQL works in MSSQL Management Studio.
Thanks.
private void SaveToDatabase ()
{
using (SqlConnection conn = new SqlConnection (_connectionString_Bluebook))
{
conn.Open ();
string sql = #"update Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=" + _accountNo;
using (SqlCommand command = new SqlCommand (sql, conn))
{
command.Parameters.Add (new SqlParameter ("#CompanyName", TextBox_CompanyName.Text));
command.Parameters.Add (new SqlParameter ("#AccountNo", TextBox_Account.Text));
command.ExecuteNonQuery ();
}
conn.Close ();
}
}
Try adding a parameter for the original account number to your query. The example below uses strongly-typed parameters for security and performance, taking a guess at your actual SQL data types and column lengths, which you should change to your actual definitions.
private void SaveToDatabase()
{
using (SqlConnection conn = new SqlConnection(_connectionString_Bluebook))
{
conn.Open();
string sql = #"update dbo.Companies
set CompanyName=#CompanyName, AccountNo=#AccountNo
where AccountNo=#OriginalAccountNo;
IF ##ROWCOUNT = 0 RAISERROR('Account number %s not found',16,1,#OriginalAccountNo)";
using (SqlCommand command = new SqlCommand(sql, conn))
{
command.Parameters.Add(new SqlParameter("#CompanyName",SqlDbType.VarChar,100).Value = TextBox_CompanyName.Text;
command.Parameters.Add(new SqlParameter("#AccountNo", SqlDbType.Char, 10).Value = TextBox_Account.Text;
command.Parameters.Add(new SqlParameter("#OriginalAccountNo", SqlDbType.Char, 10).Value = _accountNo;
command.ExecuteNonQuery();
}
}
}
If the row is still not updated as expected, make sure _accountNo contains the proper value.
EDIT:
I added a RAISERROR statement to the SQL batch to facilitate this, which you could leave in the code if the not found condition should never occur.
If the SQL Params are not working, then try this way:
comm = new SqlCommand("update student_detail set s_name= '" + txtname.Text + "', age= "+txtage.Text+" , course=' " + txtcourse.Text + "' where roll_no = " + txtrn.Text + " ", conn);
Try to place the debugger and provide the exact error of the compiler

Login page : not able to compare string values

Source Code:
SqlConnection con = new SqlConnection("Data Source=ANIRUDH;Initial Catalog=DB1;Integrated Security=True");
con.Open();
protected void Login_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("SELECT * FROM USER_LOGIN WHERE USERID='" + txtUserName.Text + "' AND PASSWORD='" + txtPassword.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
string userid = txtUserName.Text;
string password = txtPassword.Text;
dr.Read();
if((dr["USERID"].ToString() == userid) && (dr["PASSWORD"].ToString() == password))
{
Response.Redirect("/WebForm1.aspx", true);
}
else
{
Response.Write("Invalid");
}
}
Problem:
This always giving ... when am entering correct username and password as it is in database...
when I used LABELs to show the values come from database ... they r correct and showing ... but while comparing always showing INVALID
Besides all the usual SQL injection etc that people are making in the comments, you're actually testing twice. Rather than berate what you're doing, I'll attempt to help "WHY" it's not working.
First off you're selecting a row where the user and password equal inputs and then you're testing the contents of the datareader.
Rather than that, just check if your datareader actually contains anything. If it doesn't then nothing was selected based on your select and therefore the user and password are incorrect.
A simple dr.HasRows will let you know if the reader contains anything.
Granted, this may not cure WHY SQL isn't selecting anything.
One thing that might be catching you out is case sensitivity. with your (dr["USERID"].ToString() == userid case sensitivity will be important as a string "a" is NOT equal to a string "A".
UPDATE
To demonstrate what I mean with regards to HasRows, try this instead - you don't need all the additional if statements afterwards. If SQL didn't find a row with the where clause, then it's obvious the row doesn't exist with the user and password combo.
SqlCommand cmd = new SqlCommand("SELECT * FROM USER_LOGIN WHERE USERID='" + txtUserName.Text + "' AND PASSWORD='" + txtPassword.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows){
Response.Redirect("/WebForm1.aspx", true);
}else{
Response.Write("Invalid");
}

Increment a database value using asp.net

I am working on a project - online movie ticketing system....
In this when the user enters the number of seats he wants to book, he goes to payment page. On click of payment button, how can I decrement the number of seats entered by the user in SQL Server.
SqlConnection con;
SqlCommand cmd;
private void update()
{
string a, b;
int c;
con = new SqlConnection("server=.;uid=sa;pwd=mayank;database=movie");
a = Session["timings"].ToString();
b = Session["seats"].ToString();
c = Convert.ToInt32(b);
con.Open();
cmd = new SqlCommand("update bodyguard set silver_class = silver_class ' " + - c + " 'where timings = ' " + a + "' ", con);
cmd.ExecuteNonQuery();
con.Close();
}
With this code it is raising an exception....so please help me out.
Your SQL command is wrong, what you produce is this:
update bodyguard set silver_class = silver_class ' -[valueC] 'where timings = ' [valueA]'
You forgot a space before where for example, and I am not sure how the silver_class part is supposed to look, because it's not clear what you are trying to achieve there.
You had some single quotes around your integer value. try this
"update bodyguard set silver_class = (silver_class - " + c + ") where timings = '" + a + "'"
A little advice, you should use a try{}catch{} blocks to handle potential errors in your code. When you convert a number with Convert.toInt32(), you should try to catch a FormatException. And from con.open() to con.close you can try to catch the SQLException
Don't use concatenated strings to create your SQL statment, its really bad form. Do it this way:
cmd = new SqlCommand("update bodyguard set silver_class = silver_class - #c where timings = #a", con);
cmd.Parameters.AddWithValue("#c", c);
cmd.Parameters.AddWithValue( "#", a);
I recommend Parameterized Query instead of string concatenation which is vulnerable to SQL Injection. And I suggest that you should use Stored Procedure instead of Inline SQL.

Why do I get a incorrect syntax exception when I am trying to connect to a SQL server?

I am trying to connect to a SQL server from a web form but getting an incorrect syntax exception in the code.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["HRMSConnectionString1"].ToString());
{
SqlCommand cmd = new SqlCommand("select * from persons where User_Id="+uid.Text+"and Password!="+pswd.Text, cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); //exception in this line
rdr.Read();
Response.Write(rdr[0].ToString());
}
}
Please guide me where m going wrong.
The database wants to see quotes around the strings:
"select * from persons where User_Id='"+uid.Text+"'and Password!='"+pswd.Text+"'"
Try:
"Select * from persons where [User_Id] ='"+uid.Text+"'and [Password] <> '"+pswd.Text + "'"
Also: Protect your parameters! This is a must in order to prevent against SQL injection.
Looks like you are using this != operator for the purpose of Not-Equal, however that's in the progamming language. For Sql, you need to use <> operator
Also looks like you are using sql query with + which must be avoided under any cicumstances.
So your final code (in rough) should look like this
SqlCommand cmd = new SqlCommand("select * from persons where User_Id='#userid'
and Password<>'#password'",cn);
cmd.Parameters.Add(#userid,uid.Text);
cmd.Parameters.Add(#password,pswd.Text);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
Response.Write(rdr[0].ToString());
(Also I am not sure what is the purpose of this query, but you are fetching * and then only using one value. If you just want to check one value, you can use query like
Select count(1) from persons where User_Id='#userid' and Password<>'#password'
and then use it with ExecuteScalar method. Just a suggestion.

Update database in asp.net not working

i have in asp.net a few textboxes and i wish to update my database with the values that they encapsulate .
The problem is that it doesn't work and although it doesn't work, the syntax seems correct and there are no errors present . Here is my linkbutton :
<asp:linkbutton id="clickOnSave" runat="server"
onclick="Save_Click" Text="Save Profile" />
and my update function
protected void Save_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "DataSource=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\alex\\Documents\\seeubook_db.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
con.Open();
String commandString = "UPDATE users SET last_name='" + Text4.Text.Trim() + "' , first_name='" + Textbox1.Text.Trim() + "' , about_me='" + Textbox5.Text.Trim() + "' , where_i_live='" + Textbox2.Text.Trim() + "' , where_i_was_born='" + Textbox3.Text.Trim() + "' , work_place='" + Textbox4.Text.Trim() + "' WHERE email='" + Session["user"] + "'";
SqlCommand sqlCmd = new SqlCommand(commandString, con);
sqlCmd.ExecuteNonQuery();
con.Close();
}
I'm always a bit weary about the User Instance=true in a connection string..... at times, it tends to create a new MDF file "on the fly" and when you update that MDF, then your changes might be just "gone" one your app has completed running.... See MSDN docs on User Instances.
I would suggest that you:
attach your MDF file to SQL Server Express on your machine, using SQL Server Express Management Studio
then use a server-based approach to your SQL Server Express database rather than attaching a file...
In that case, your database connection string would then look something like:
server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;
And while you're at it, I would also recommend to:
wrap your SqlConnection and SqlCommand into using blocks to ensure proper disposal
open your connection as late as possible
use a parametrized query instead of concatenating together your SQL command - doing so is a wide open door for SQL injection attacks!
So your code would look something like this:
string connStr = "server=.\\SQLEXPRESS;database=YourDatabaseName;Integrated Security=SSPI;";
string cmdStmt = "UPDATE dbo.Users SET last_name = #lastName, " +
"first_name = #firstName, about_me = #aboutMe, where_i_live = #whereILive, " +
"where_i_was_born = #whereIWasBorn, work_place = #workPlace " +
"WHERE email = #userEMail";
using(SqlConnection sqlCon = new SqlConnection(connStr))
using(SqlCommand sqlCmd = new SqlCommand(cmdStmt, sqlCon))
{
// define parameters
sqlCmd.Parameters.Add("#lastName", SqlDbType.VarChar, 50);
sqlCmd.Parameters["#lastName"].Value = Text4.Text.Trim();
// and so on for all the parameters
sqlCon.Open();
sqlCmd.ExecuteNonQuery();
sqlCon.Close();
}
Debug! Look your LinkButton Click Event really go into Save_Click function. And then check 'sqlCmd.ExecuteNonQuery();' return result.
You need to write your code for filling Textbox's at page load as below :
public page_load()
{
if(!ispostBack)
{
// Write code to fill controls first time
}
}

Resources