Registering page accepts usernames that are already included in database, even though I included code to prevent that:
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtCustUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp > 0)
{
Response.Write("User already exists");
}
This is the whole code for register page:
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.Data;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtCustUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp > 0)
{
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT into Customers (CustFirstName, CustLastName, CustAddress, CustCity, CustProv, CustPostal, CustCountry, CustHomePhone, CustBusPhone, CustEmail, CustUserName, CustPassword) values (#custFirstName ,#custLastName ,#custAddress ,#custCity ,#custProv ,#custPostal, #custCountry ,#custHomePhone ,#custBusPhone ,#custEmail ,#custUserName ,#custPassword)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#custFirstName", txtCustFirstName.Text);
com.Parameters.AddWithValue("#custLastName", txtCustLastName.Text);
com.Parameters.AddWithValue("#custAddress", txtCustAddress.Text);
com.Parameters.AddWithValue("#custCity", txtCustCity.Text);
com.Parameters.AddWithValue("#custProv", txtCustProv.Text);
com.Parameters.AddWithValue("#custPostal", txtCustPostal.Text);
com.Parameters.AddWithValue("#custCountry", txtCustCountry.Text);
com.Parameters.AddWithValue("#custHomePhone", txtCustHomePhone.Text);
com.Parameters.AddWithValue("#custBusPhone", txtCustBusPhone.Text);
com.Parameters.AddWithValue("#custEmail", txtCustEmail.Text);
com.Parameters.AddWithValue("#custUsername", txtCustUserName.Text);
com.Parameters.AddWithValue("#custPassword", txtCustPassword.Text);
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration is successful" );
conn.Close();
}
catch(Exception ex)
{
Response.Write("Error:"+ex.ToString());
}
}
}
The login page marks all logins as "wrong username" even though the username and password are correct.
This is the 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;
using System.Data.SqlClient;
using System.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
}
protected void btnLogin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtUsername.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{
conn.Open();
string checkPasswordQuery= "SELECT password FROM Customers WHERE CustUserName='" + txtUsername.Text + "'";
SqlCommand passCom = new SqlCommand(checkPasswordQuery, conn);
string password = passCom.ExecuteScalar().ToString().Replace(" ","");
if(password == txtPassword.Text)
{
Session["New"] = txtUsername.Text;
Response.Write("Password is correct");
Response.Redirect("Manager.aspx");
}
else
{
Response.Write("Password is not correct");
}
}
else
{
Response.Write("Username is not correct");
}
}
}
Thank you.
What is the value of temp here during debugging?:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
If you have duplicate records in your table, the variable temp will never be 1.
Set CustUserName as a primary key on your Customers table to prevent duplicate entry.
Please try this.
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.Data;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationDatabaseConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT count(*) FROM Customers WHERE CustUserName='" + txtCustUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp > 0)
{
Response.Write("User already exists");
}
else
{
conn.Open();
string insertQuery = "INSERT into Customers (CustFirstName, CustLastName, CustAddress, CustCity, CustProv, CustPostal, CustCountry, CustHomePhone, CustBusPhone, CustEmail, CustUserName, CustPassword) values (#custFirstName ,#custLastName ,#custAddress ,#custCity ,#custProv ,#custPostal, #custCountry ,#custHomePhone ,#custBusPhone ,#custEmail ,#custUserName ,#custPassword)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#custFirstName", txtCustFirstName.Text);
com.Parameters.AddWithValue("#custLastName", txtCustLastName.Text);
com.Parameters.AddWithValue("#custAddress", txtCustAddress.Text);
com.Parameters.AddWithValue("#custCity", txtCustCity.Text);
com.Parameters.AddWithValue("#custProv", txtCustProv.Text);
com.Parameters.AddWithValue("#custPostal", txtCustPostal.Text);
com.Parameters.AddWithValue("#custCountry", txtCustCountry.Text);
com.Parameters.AddWithValue("#custHomePhone", txtCustHomePhone.Text);
com.Parameters.AddWithValue("#custBusPhone", txtCustBusPhone.Text);
com.Parameters.AddWithValue("#custEmail", txtCustEmail.Text);
com.Parameters.AddWithValue("#custUsername", txtCustUserName.Text);
com.Parameters.AddWithValue("#custPassword", txtCustPassword.Text);
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration is successful" );
conn.Close();
}
}
catch(Exception ex)
{
Response.Write("Error:"+ex.ToString());
}
}
}
Related
I am creating a basic registration page using ASP.NET websites and C# and am trying to link the logins to a database I have created in Visual Studio 2017 and am constantly getting the error -
'System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Data.Common.DbCommand.ExecuteScalar(...) returned null.
and cannot understand why, code below any help appreciated.
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 Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] WHERE UserName='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists, please enter a different username");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT INTO Table (UserName,Email,Password,Country) values(#Uname ,#email , #password ,#country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#Uname" , TextBoxUN.Text);
com.Parameters.AddWithValue("#email" , TextBoxEmail.Text);
com.Parameters.AddWithValue("#password" , TextBoxPass.Text);
com.Parameters.AddWithValue("#country" , DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}```
If you want to check if user exists, there's no need in ExecuteScalar() with value:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
when user doesn't exist, com.ExecuteScalar() returns null and you have a problem.
Code
private static bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)) {
conn.Open();
//DONE: parametrized query
//DONE: 1 instead of * - we don't want all columns to be returned
string sql =
#"select 1
from [Table]
where UserName = #userName";
using (SqlCommand com = new SqlCommand(sql, conn)) {
com.Parameters.Add("userName", SqlDbType.VarChar).Value = userName;
// user exists if cursor is not empty (we have at least one record)
return com.ExecuteScalar() != null;
}
}
}
protected void Page_Load(object sender, EventArgs e) {
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack && UserExists(TextBoxUN.Text))
Response.Write("User already exists, please enter a different username");
}
I am creating a simple registration page and I get an error which I believe has to do with not being able to find the table I have created, yet I made it locally.
Here is the error I get:
An exception of type 'System.Data.SqlClient.SqlException' occurred in
System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near the keyword 'Table'.
Any help would be fantastic.
Below I have posted the code that I have down so far:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Net.Mail;
public partial class Register : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string checkuser = userchecker();
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = changehere(com);
conn.Close();
if (temp == 1)
{
Response.Write("User Already Exists");
}
}
}
private string userchecker()
{
return "select count(*) from Table where UserName='" + TextBoxUN.Text + "'";
}
private static int changehere(SqlCommand com)
{
return Convert.ToInt32(com.ExecuteScalar().ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
Guid NEWguid = Guid.NewGuid();
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "insert into Table (ID, UserName, Email, Password) values (#ID, #Uname , #email, #password)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#ID", NEWguid.ToString());
com.Parameters.AddWithValue("#Uname", TextBoxUN.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#password", TextBoxPass.Text);
com.ExecuteNonQuery();
Response.Redirect("manager.aspx");
Response.Write("Registration successful");
conn.Close();
}
catch (Exception)
{
Response.Write("Error:");
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{
}
}
Try this:
private string userchecker()
{
return "select count(*) from [Table] where UserName='" + TextBoxUN.Text + "'";
}
See the [] around Table, this is because Table is a reserved word in all SQL variants and you should escape it
Change the name of the table, table is a reserved word in SQL
I am developing windows application .Net in C#
DB stored inside the C# Application ".....\SQliteExample\SQliteExample\bin\Debug\MyDatabase.sqlite"
I can insert,update ,view and Delete to the table with the above code and view its contents in another activity with no troubles at all. However, when I restart the application I found that what I have inserted data before I restart the application has gone!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SQLite;
namespace SQliteExample
{
public partial class Form1 : Form
{
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
public Form1()
{
InitializeComponent();
SQLiteConnection.CreateFile("MyDatabase.sqlite");
connection.Open();
string sql = "create table Employee1 (EmpID int,EmpName varchar(20), age int,Salary int,Phone int , Address Varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "insert into Employee1 (EmpID,EmpName,Age,Salary,Phone,Address) values (?,?,?,?,?,?)";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", textBox1.Text);
command.Parameters.AddWithValue("EmpName", textBox2.Text);
command.Parameters.AddWithValue("Age", textBox3.Text);
command.Parameters.AddWithValue("Salary", textBox4.Text);
command.Parameters.AddWithValue("Phone", textBox5.Text);
command.Parameters.AddWithValue("Address", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Saved");
Clear();
View();
}
private void Clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
}
private void View()
{
string sql3 = "select * from Employee1 order by EmpID asc";
SQLiteCommand command3 = new SQLiteCommand(sql3, connection);
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command3);
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
View();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "delete from Employee1 where EmpID = ?";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", int.Parse(textBox1.Text));
command.ExecuteNonQuery();
connection.Close();
Clear();
View();
}
else
{
MessageBox.Show("Please Enter EmpID");
}
}
}
}
Thanks in Advance,
On recompilation you recreate the database file and recreate the table "employee". Therefore all your previous data is lost.
I have problem with Arabic character display in textbox using SQL database. I use the nvarchar type in SQL and when I select a Latin character in item combobox its work perfectly (img1), but when i try to select an Arabic item in combobox nothing happen in textbox 1 and 2 (img2).
The code :
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;
namespace testconnection
{
public partial class Form1 : Form
{
private SqlConnection con;
private SqlCommand cmd;
private SqlDataAdapter da;
private DataTable dt;
private SqlDataReader dr;
public Form1()
{
InitializeComponent();
combo();
}
void combo()
{
con = new SqlConnection(
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\vemmi\Documents\user.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("SELECT usrs FROM usrtest", con);
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
comboBox1.Items.Add(dr["usrs"]);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button2_Click(object sender, EventArgs e)
{
Form2 c = new Form2();
c.ShowDialog();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con = new SqlConnection(
#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\vemmi\Documents\user.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("SELECT * FROM usrtest WHERE usrs like '" + comboBox1.Text + "' ");
cmd.Connection = con;
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string p = dr["pwd"].ToString();
string n = dr["nbr"].ToString();
textBox2.Text = p;
textBox3.Text = n;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
enter image description here
Try adding 'N' before the Arabic string in the query.
cmd = new SqlCommand("SELECT * FROM usrtest WHERE usrs like N'" + comboBox1.Text + "' ");
I'm not really sure where the SqlConnection, SqlCommand and the Open()/Close() goes. I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format.
EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.SqlTypes;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
txtBox1.Text = cmd.ToString();
con.Close();
}
}
}
you can create constant string to hold the connection string and then you can do as below in your button1_Click
you don't need to call the close method of sql connection when you use using block as below
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
con.Open();
txtBox1.Text =cmd.ExecuteScalar() as string;
}
And also if you need to read Pnt_Lname from database you better use ExecuteScalar method
You can use this structure. Use using to properly close and dispose of SqlConnection.
Also, you can define the connection string in your config file and use it from there.
using (SqlConnection conn = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
txtBox1.Text = (String)command.ExecuteScalar();
}
In case this would be of help to anyone, this is the answer to my question:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Book
{
public partial class frmBook : Form
{
SqlConnection con =
new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=XXDB; Integrated Security=SSPI");
SqlCommand cmd;
public frmBook()
{
InitializeComponent();
}
private void frmBook_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
txtID.Text = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ txtID.Text + "'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
con.Close();
btnSave.Enabled = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
int count = int.Parse(txtID.Text) + 1;
con.Open();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ count.ToString() +"'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
txtID.Text = count.ToString();
con.Close();
}
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtTitle.Text = "";
txtAuthor.Text = "";
btnNew.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
"VALUES ('"+ txtID.Text +
"','"+ txtTitle.Text +
"','"+ txtAuthor.Text +"');", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved!");
btnSave.Enabled = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}