Login page : not able to compare string values - asp.net

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");
}

Related

How to move data in the table for the same database and delete it in asp.net?

I have a database name test.dbo. In the database it have two table named Equipment and backup. I want to move some data in the table Equipment to table backup and delete the data in the table Equipment. So, what is the query to use to do it?
I have use this query but it only move the data to table backup without deleting it in table Equipment. Moreover, if i use the query again , error show that the table name already exits.
protected void Button5_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=5CG50749V3\\SQLEXPRESS;Initial Catalog=test;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * into test.dbo.[backup] from test.dbo.[Equipment] where (SerialNumber = '" + TextBox2.Text + "' or EquipmentID = '" + TextBox1.Text + "' )", con);
cmd.ExecuteNonQuery();
con.Close();
}
For this, instead of the SELECT * INTO, use a DELETE statement with an OUTPUT INTO clause.
Reference: https://msdn.microsoft.com/en-us/library/ms177564.aspx

Response.write only shows the first record from the database (this.session.sessionid)

I've got a problem for the past few days. I will explain short what i've did.
I have a table created in the database called 'Cart'. This Cart cointains: ClientID, Artical number, and quantity. In the ClientID, a session.sessionID stored. In the Artical just a number like 1012. And in quantity a number like 1 or 3.
What I would like to, is retrieve all the records, with the session.session id of the user.
It does work in the page, but only the first record of the like 4-5 records that are in the cart table is shown. I think i comes due the problem that it looks for this.session.sessionidand when it found one, it doesn't look any further then that.
I've tried to loop through the query where sessions is. But it won't let me loop because it doesn't know for? Even if I loop the whole query outside of it like this:for (int i = 0; i < sessies.Length; i++) It will show more records.. but they are all the first records.. I know that was a stupid try but I can always try..
Looked for all over the internet but couldn't find the solution to this.
Hope to get a response soon from somebody. It would be gratefull.
Used the following code:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["GarageConnectionString"].ToString()))
{
string sessions = this.Session.SessionID;
SqlCommand cmd = new SqlCommand("SELECT * FROM cart where ClientID='" + sessions + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
rdr.Read();
TextBox1.Text = rdr[2].ToString();
Response.Write("<br>" + ("Sessie id "+rdr[1].ToString()));
Response.Write("<br>" + ("Artikel nummer "+rdr[2].ToString()));
Response.Write("<br>" + ("Aantal "+rdr[3].ToString()));
cn.Close();
}
SqlDataReader advances to the next record in the set: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read%28v=vs.110%29.aspx
Call Read() in a loop, like so:
using (SqlConnection cn = newSqlConnection(ConfigurationManager.ConnectionStrings["GarageConnectionString"].ToString()))
{
string sessions = this.Session.SessionID;
SqlCommand cmd = new SqlCommand("SELECT * FROM cart where ClientID='" + sessions + "'", cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TextBox1.Text = rdr[2].ToString();
Response.Write("<br>" + ("Sessie id "+rdr[1].ToString()));
Response.Write("<br>" + ("Artikel nummer "+rdr[2].ToString()));
Response.Write("<br>" + ("Aantal "+rdr[3].ToString()));
}
cn.Close();
}
You should loop through the datareader: ie:
while (rdr .Read())
{
Console.WriteLine("{0}\t{1}", rdr .GetInt32(0),
rdr .GetString(1));
}
Each call to SqlDataReader.Read() gets a single row, unless there are no more rows when it returns false.
So you need to loop to get all rows:
while (rdr.Read()) {
// Use rdr methods to access the values from the current row.
}
Use While Loop- Example
if (rdr .HasRows)
{
while (rdr .Read())
{
Console.WriteLine("{0}\t{1}", rdr .GetInt32(0),
rdr .GetString(1));
}
}
else
{
Console.WriteLine("No rows found.");
}
rdr .Close();

Saving checked status from a checkbox into the database in asp.net

I'm working on a online test application in asp.net and i'm finding trouble in saving the checked answer status back to database, i.e once i click on next button in my aspx page these 2 things should happen
1)It should capture the currently checked option and add the value for that particular option as true into my database IS_Marked column.
2)It also should pull out the next set of question and Options
The latter is fine but i'm not getting any clue about how to save the checkd answer back into database
My aspx has 4 check boxes
and my next button click event is as follows,
protected void BtnNext_Click(object sender, EventArgs e)
{
if (qid == maxid)//checks whether current que id is equal to last que id in DB
{
BtnNext.Enabled = false; //if its last que then next button is disabled
}
else
{
BtnPrevious.Enabled = true; // if not last question next button is enabled
QuestionSet q = new QuestionSet(); //Question set is an entity to hold que text and options list
StudentB b = new StudentB(); //object of my business class
q = b.GetQuestion(1, 1, qid, 'N', 0);//passing student id, test id, question id, action taken, i.e button clicked(prev, next, last, first) and selected question(i.e any question that is present)
qid = Convert.ToInt32(q.Question_Id);
LblQStn.Text = q.Question_Text;
CheckBox1.Text = q.Options[0].Option_Text;//talking to business and model layer and getting que and ans from database and giving to checkboxes
CheckBox2.Text = q.Options[1].Option_Text;
CheckBox3.Text = q.Options[2].Option_Text;
CheckBox4.Text = q.Options[3].Option_Text;
}
}
now when he checks any answer i need to save its status as marked into the database
Any solution is highly appreciated,
thanks in advance
Well first you need to set up the connection to database. example:
//sqlString is your connectionstring//
dbconn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlString"))
dbconn.Open()
strsql = "INSERT INTO IS_Marked ([Mark]) VALUES ('" + Bedrijf + "')"
dbcomm = New SqlCommand(strsql, dbconn)
dbcomm.ExecuteNonQuery()
dbconn.Close()
This will be your basic sql command.
As you can see I ues ([yourvalue]) that what we are going to do next.
Dim dbconn As SqlConnection
Dim dbcomm As SqlCommand
Dim strsql, Checked_Mark As String
Mark = YourCheckBox.CheckedValue
So your final result will be like this:
Dim dbconn As SqlConnection
Dim dbcomm As SqlCommand
Dim strsql, Mark As String
Mark = YourCheckBox.CheckedValue
dbconn = New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlString"))
dbconn.Open()
strsql = "INSERT INTO IS_Marked ([Mark]) VALUES ('" + Bedrijf + "')"
dbcomm = New SqlCommand(strsql, dbconn)
dbcomm.ExecuteNonQuery()
dbconn.Close()

using the querystring parameter in my where clause to generate insert operation

here,using request.Querystring i find the companyname and job title of particular Job.when user logsin using username in texbix.i want the Companyname,jobtitle and username in the same row of a table.But when i generate my query it inserts the (companyName & jobtitle) in the first row and username in second row.How can i fulfill my task.Some people said,i have to keep the companyname and jobtitle in a variable...then execute.
is it a parfect solution?
if it is,how can i do that?
code:
protected void ButtonApply_Click(object sender, EventArgs e) {
String str = Request.QueryString.Get("JobNo");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CompanyName,JobTitle) select CompanyName,JobTitle from Jobs where JobNo='"+str+"'" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
try {
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("ApplyJob.aspx?JobNo="+str);
}
in the apply.aspx i have following code:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string apply = "INSERT INTO Company (CandidateInformation) Values (#CandidateInformation)" ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation", TextBoxaun.Text);
insertApply.ExecuteNonQuery();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
Inserting two times will always result in two new rows.
You can do it all in the first insert statement:
string apply = "INSERT INTO Company (CompanyName,JobTitle, CandidateInformation) select
CompanyName,JobTitle, #CandidateInformation from Jobs where JobNo=#JobNo ;
SqlCommand insertApply = new SqlCommand(apply, conn);
insertApply.Parameters.AddWithValue("#CandidateInformation",
TextBoxaun.Text);
insertApply.Parameters.AddWithValue("#JobNo", str);
try
{
insertApply.ExecuteScalar();
conn.Close();
Response.Redirect("CompanyInfo.aspx");
}
Then you won't need the second page.
Use
Update Company Set CandidateInformation = #CandidateInformation where JobNo='"+str+"'" ;
instead of
string apply = "INSERTINTO Company (CandidateInformation) Values
(#CandidateInformation)" ;
If you will use Insert statement again, then it will always create new record in the table.
Update is used to update an already existing record of the table.

asp.net Login Website from database

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?

Resources