Okay, I know I'm an amateur and I have asked a ton of questions recently. I've fixed it so I cannot input a duplicate record to my sql server database. Here is the code for that:
using System;
using System.Collections.Generic; using System.Linq;
using System.Web; using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Default2 : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Guid newGUID = Guid.NewGuid();
SqlConnection User = new SqlConnection("Data Source=CONNECTION STRING BLAH BLAH");
{
User.Open();
string checkuser = "select count(*) from userdatabase where Username = #username";
SqlCommand com = new SqlCommand(checkuser, User);
com.Parameters.AddWithValue("#username", InputUsername.Text);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
User.Close();
if (temp == 1)
{
Response.Write("Username is already in use");
}
if (temp == 0)
{
SqlCommand xp = new SqlCommand("Insert into userdatabase(ID,Username, Email, Password, Fname, LName, Addl1, AddL2,
City, County, Postcode, Country, Company)Values(#ID, #Username,
#Email, #Password, #FName, #LName, #AddL1, #AddL2, #City, #County,
#Postcode, #Country, #Company )", User);
xp.Parameters.AddWithValue("#ID", newGUID.ToString());
xp.Parameters.AddWithValue("#Username", InputUsername.Text);
xp.Parameters.AddWithValue("#Email", InputEmail.Text);
xp.Parameters.AddWithValue("#Password", InputPassword.Text);
xp.Parameters.AddWithValue("#FName", InputFname.Text);
xp.Parameters.AddWithValue("#LName", InputSname.Text);
xp.Parameters.AddWithValue("#AddL1", InputAddress1.Text);
xp.Parameters.AddWithValue("#AddL2", InputAddress2.Text);
xp.Parameters.AddWithValue("#City", InputCity.Text);
xp.Parameters.AddWithValue("#County", InputState.Text);
xp.Parameters.AddWithValue("#Postcode", InputPostcode.Text);
xp.Parameters.AddWithValue("#Country", InputCountry.Text);
xp.Parameters.AddWithValue("#Company",InputCompany.Text);
User.Open();
xp.ExecuteNonQuery();
User.Close();
}
if (IsPostBack)
{
InputUsername.Text = "";
InputPassword.Text = "";
InputEmail.Text = "";
VerifyPassword.Text = "";
InputFname.Text = "";
InputSname.Text = "";
InputAddress1.Text = "";
InputAddress2.Text = "";
InputCity.Text = "";
InputState.Text = "";
InputPostcode.Text = "";
InputCompany.Text = "";
Response.Redirect("Login.aspx");
}
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
} }
However, as you can see I've set it to write "username is already in use". But it doesn't display it and it doesn't input data onto the table. It also redirects it to the login.aspx page. Any help with stopping the page from redirecting to a new page and with the message displaying?
Edit
someone mentioned about a try/ catch method for this to work, would anyone be able to explain to me how this works, i've looked on YouTube but i haven't found anything that would be able to help with this
Related
I have a Website with 3 signup pages.
every page contains information, and all 3 pages are part of the signup process.
I know that INSERT command is used to create new rows. But in the UPDATE command, I must mention WHERE clause.
So, my question is, how can I UPDATE the same row I updated in the past pages.
I am using Visual Studio Community 2015.
Any help will be appreciated.
First page code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Sign_Up_SignUpMain_1_ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnNext_Click(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|Database.mdf;";
str += "Integrated Security= True";
string email, userName;
//Page
if (Page.IsValid == true)
{
email = txtEmail.Text;
userName = txtUserName.Text;
SqlConnection c = new SqlConnection(str);
SqlCommand sqlCommand = new SqlCommand("INSERT INTO [Table] (Email, UserName) VALUES (#email, #userName);", c);
sqlCommand.Connection = c;
sqlCommand.Parameters.AddWithValue("#email", email);
sqlCommand.Parameters.AddWithValue("#userName", userName);
c.Open();
sqlCommand.ExecuteNonQuery();
c.Close();
Response.Redirect("SignUp(2).aspx", true);
}
//Email
if (rfvEmail.IsValid == false || revEmail.IsValid == false)
{ txtEmail.CssClass = "txtError"; }
else
{ txtEmail.CssClass = "Text"; }
//User Name
if (rfvUserName.IsValid == false || revUserName.IsValid == false)
{ txtUserName.CssClass = "txtError"; }
else
{ txtUserName.CssClass = "Text"; }
}
}
Second page code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Sign_Up_SignUp_2_ : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnNext_Click(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|Database.mdf;";
str += "Integrated Security= True";
string password;
//Page
if (Page.IsValid == true)
{
password = txtPass.Text;
SqlConnection c = new SqlConnection(str);
SqlCommand sqlCommand = new SqlCommand("INSERT INTO [Table] (Email, UserName) VALUES (#email, #userName);", c);
Response.Redirect("SignUp(3).aspx", true);
}
//Password
if (revPass.IsValid == false || rfvPass.IsValid == false)
{ txtPass.CssClass = "txtError"; }
else
{ txtPass.CssClass = "Text"; }
//Confirm Password
if (rfvConPass.IsValid == false)
{ txtConPass.CssClass = "txtError"; }
else
{ txtConPass.CssClass = "Text"; }
//Compare Passwords
if (cvPasswords.IsValid == false)
{
txtPass.CssClass = "txtError";
txtConPass.CssClass = "txtError";
txtPass.Text = "";
txtConPass.Text = "";
}
else
{
txtPass.CssClass = "Text";
txtConPass.CssClass = "Text";
}
}
}
Ok I see your issue, you aren't passing the values that have already been inserted between pages. You can use the Session State to pass objects between parameters
On your current page, before redirecting to the next page, set all the information you want to retain in the session state:
Session["email"] = theirEmailAddress;
Session["username"] = theirUserName;
After storing the information you need in the session redirect to the next page and store the information on this page into the session as well.
Then finally on the last page you can access all of the session data and do a single SQL insert command. To access the session items you just do this:
string email = (string)(Session["email"]);
The code does connect to the database and actually check the username(number) and then exception runs when it has to get to verifying the password and a null reference is thrown
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Intellicell_CallCentreConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT COUNT(*) FROM Debtors WHERE MobilePhone='" + txtMobilePhone.Text + "'";
SqlCommand cmd = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string CheckPasswordQuery = "SELECT IDNumber from Debtors WHERE MobilePhone='" + txtPassword.Text + "'";
SqlCommand passCmd = new SqlCommand(CheckPasswordQuery, conn);
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
conn.Close();
if (password == txtPassword.Text)
{
Session["New"] = txtMobilePhone.Text;
Response.Write("Password is correct!");
Response.Redirect("Home.aspx");
}
else
{
Response.Write("Password is not correct!");
}
}
else
{
Response.Write("Please Provide valid Login details!");
}
}
}
it is on line
string password = passCmd.ExecuteScalar().ToString().Replace(" ","");
that it breaks.
I suggest you if you want write sql adhoc, use string.format
It's clean
string checkuser = string.Format("SELECT COUNT(*) FROM Debtors WHERE MobilePhone={0},txtMobilePhone.Text);
Secondly, you can use using syntax , in order to clean your connection properly
I think, In the second sql you are using txtPassword.Text instead of txtMobilePhone.Text
The question is why are you getting the null execption, see this: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
In summary ExecuteScaler returns a null (not a DBNull) if no rows are found, whence passCmd.ExecuteScalar().ToString().Replace(" ",""); null refences as its null.ToString()
You global logic looks flawed so hard to suggest exactly what to do, but passCmd.ExecuteScalar()?.ToString().Replace(" ","") will suppress the exeception.
I have values from controls txtUser and txtAppNum on a page webform1.aspx. I am bringing those values to a page, Login.aspx. The code from Login.aspx is below. In the login.aspx page, I want to take the values from the controls txtUserand txtAppNum in webform1.aspx page, I want to check the values against a database, if the values are in the database, I want the page to redirect back to webform1.aspx.
My questions is, when I run the code, only Page_Load but not CheckRecord. Basically when I run the page, I can see the values carried over from the webform1.aspx page to login.aspx, but then that's it, nothing else happens.
What am I doing wrong? Any thoughts, I would greatly appreciate it, I have been stuck on this for a few days. Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient; //to communicate with the Server database
using System.Configuration;
using System.Data; //to use DataSet or DataTable
using System.Text; //for StringBuilder
namespace BLAA_3
{
public partial class login : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
}
public void CheckRecord(object sender, EventArgs e)
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
}
}
Is CheckRecord an event handler? If not, you don't need the sender and eventArgs in your signature for CheckRecord it can be public void CheckRecord().
It's not being called because your load event isn't calling it. So, inside your Page_Load function.
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
CheckRecord();
}
public void CheckRecord()
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
Here is the schema of my Society Table:
Society(SocietyName, Email, Password, Status)
So basically I'm creating a login page in which user enters Email and password. If there is an email which matches the one in database then it checks that whether status is equal to president or faculty member or Student Affairs Office. Based on that , it redirects to different pages.
Following is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication3 {
public partial class WebForm1 : System.Web.UI.Page {
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String QueryStr;
String name;
protected void Page_Load(object sender, EventArgs e) { }
protected void clicked(object sender, EventArgs e) {
String ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(ConnString);
conn.Open();
String QueryStr2 = "";
QueryStr = "";
QueryStr = "Select * from the_society_circle.society WHERE Email= '" + Emailtxt.Text + "' And Psswd=' " + passwordtxt.Text + "'";
cmd = new MySql.Data.MySqlClient.MySqlCommand(QueryStr, conn);
reader = cmd.ExecuteReader();
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
name = "";
while (reader.HasRows && reader.Read()) {
name = reader["Email"].ToString();
}
if ((QueryStr2== "president" || QueryStr2 == "faculty member") && reader.HasRows ) {
Session["Email"] = name;
Response.BufferOutput = true;
Response.Redirect("WebForm2.aspx", true);
} else {
Emailtxt.Text = "invalid user";
}
conn.Close();
}
}
}
The problem is that if statement is never executed and it always prints invalid user.
PS: Im new to web development :D
You set QueryString2 to this value
QueryStr2 = "Select Status from the_society_circle.society where Email = '" + QueryStr + "'";
It can never be one of the values you check for.
As codemonkey already wrote, your condition will never come true.
You do the following: if ((QueryStr2== "president" || Quer... which evaluates to if (("Select Status from the_society_circle.society where Email = '" + QueryStr + "'"== "president" || Quer.... So you're comparing two different strings, which will never succeed.
I tried to refactor your code and came up with this (not tested, wrote from scratch):
First put your database-related code into a separate class (MySqlAccess) and dispose the database objects (put them into using-blocks which invokes Dispose() on leaving the block).
Don't use the user-inputs in your sql query directly. Remember "all input is evil". So better use parameterized-queries.
The reason your comparison failed was that you didn't execute your second query. Now the code executes just one query and returns the status of the user.
So to sum up:
Have SQL Injection and other malicious actions in mind. For example have a look at this article: http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx
And never store passwords as clear text in your database. That's the next thing you should care about. Edit your database to store the passwords as salted password hashes and just compare the hashes. For a starting point, have look at this article: http://www.codeproject.com/Articles/704865/Salted-Password-Hashing-Doing-it-Right
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
private string _connectionString;
protected void Page_Load(object sender, EventArgs e)
{
_connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Webappconstring"].ToString();
}
protected void Clicked(object sender, EventArgs e)
{
string email = Emailtxt.Text;
string password = passwordtxt.Text;
var mysqlAccess = new MySqlAccess(_connectionString);
string status = mysqlAccess.GetStatus(email, password);
if (status == Constants.Status.PRESIDENT || status == Constants.Status.FACULTY_MEMBER)
{
Session["Email"] = email;
Response.Redirect("WebForm2.aspx", true);
}
else
{
Emailtxt.Text = "invalid user";
}
}
}
internal class MySqlAccess
{
private readonly string _connectionString;
public MySqlAccess(string connectionString)
{
_connectionString = connectionString;
}
public string GetStatus(string email, string password)
{
using (var conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "SELECT Status FROM the_society_circle.society WHERE Email=#Email AND Psswd=#Password;";
using (var cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", password);
using (var reader = cmd.ExecuteReader())
{
if (reader.HasRows && reader.Read())
{
return reader["Status"].ToString();
}
}
}
}
return string.Empty;
}
}
internal class Constants
{
internal class Status
{
public const string PRESIDENT = "president";
public const string FACULTY_MEMBER = "faculty member";
}
}
}
I have this simple login page below ,
if I enter correct ID + pw -> success (which I want)
if I enter wrong ID -> wrong login (which I want)
But if I enter correct ID + wrong ID , I Want it to say wrong password.
How can I do it?
Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
if (TextBox1.Text == dr.GetString(0) || TextBox2.Text == dr.GetString(1))
{
Session["x"] = TextBox1.Text;
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong login";
}
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
while this doesn't answer your question, I see a MAJOR security flaw with your logic. I think no matter what failure your users encounter, invalid username or invalid password, you should always display the same "invalid login" message.
If you have someone who is attempting to break into the system, once you validate that a user account exists (invalid password) they can then begin to crack that specific account's password using brute force.
Just something to think about.
You are putting your logic wrongly here. the logic will be
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["X"] != null)
{
Response.Redirect("MemberPage.aspx");
}
}
SqlConnection cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
protected void Button1_Click(object sender, EventArgs e)
{
cnn.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName,LastName FROM Employees", cnn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
if (TextBox1.Text.Trim() == dr.GetString(0) || TextBox2.Text.Trim()== dr.GetString(1))
{
if (TextBox2.Text.Trim()== dr.GetString(1))
{
Session["x"] = TextBox1.Text.Trim();
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "wrong password";
}
}
else
{
Label2.Text = "wrong login";
}
}
cnn.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("Register.aspx");
}
}
You read the firstname and the lastname from the database, but then check for the password against the lastname. I doubt that this field contains a valid password
A part from this logic error, you should use a WHERE clause in your statement to check if the user is present or not in the database.
protected void Button1_Click(object sender, EventArgs e)
{
// Command with parameters that check if a user with the supplied credentials exists
// If the user exists then just one record is returned from the datatable....
string cmdText = "SELECT FirstName,LastName " +
"FROM Employees " +
"WHERE username=#uname and pass=#pwd";
using(SqlConnection cnn = new SqlConnection(.....))
using(SqlCommand cmd = new SqlCommand(cmdText, cnn))
{
cnn.Open();
cmd.Parameters.AddWithValue("#uname", TextBox1.Text);
cmd.Parameters.AddWithValue("#pwd", TextBox2.Text);
using(SqlDataReader reader = cmd.ExecuteReader())
{
// If the Read returns true then a user with the supplied credentials exists
// Only one record is returned, not the whole table and you don't need to
// compare every record against the text in the input boxes
if(reader.Read())
{
Session["x"] = reader.GetString(0);
Response.Redirect("MemberPage.aspx");
}
else
{
Label2.Text = "Invalid credentials";
}
}
}
}
Another point to keep in mind is the following. In the database you should not have a password in clear text. The correct way to store password is to store an hashed string corresponding to the password and then applying the hashing function to the user input and check for same hashed string in the database