asp.net registration page not working properly - c#

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

Related

How do I get around my ExecuteScalar returning null?

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

C# System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'table'.'

I create a table named Table with members (first name, last name, address). The program is throwing the error "incorrect syntax near the keyword 'table'". The application is to insert the data into the table. The code is for the new button exception handler.
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 Week4
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Testing.mdf;Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
private void btnNew_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into [Member] values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + txtAddress.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Member added successfully");
}
private void btnEdit_Click(object sender, EventArgs e)
{
}
private void btnCancel_Click(object sender, EventArgs e)
{
}
private void btnSave_Click(object sender, EventArgs e)
{
}
}
}
You need to use parameters to avoid sql injection
string sql = "insert into Member(col1, col2, col3) values(#val1, #val2, #val3)";
using (SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\cvyc8\Documents\Testing.mdf;Integrated Security=True;Connect Timeout=30"))
{
connection.Open();
using (SqlCommand cmd= new SqlCommand(sql, connection))
{
md.Parameters.Add("#val1", SqlDbType.Varchar, 50).value = txtFirstName.Text;
cmd.Parameters.Add("#val2", SqlDbType.Varchar, 50).value = txtLastName.Text;
cmd.Parameters.Add("#val3", SqlDbType.Varchar, 50).value = txtAddress.Text;
cmd.ExecuteNonQuery();
}
MessageBox.Show("Member added successfully");
}
table is a reserved keyword in SQL including MSSQL.
See all reserved keywords: https://learn.microsoft.com/en-us/sql/odbc/reference/appendixes/reserved-keywords?view=sql-server-ver15
Below code could work, but I strongly recommend not to use reserved keyword for a table name. (related answer: https://stackoverflow.com/a/695626/361100 )
cmd.CommandText = ("insert into [table] values ('"+txtFirstName.Text+"', '"+txtLastName.Text+"', '"+txtAddress.Text+"'))");
The error is general because it is not able to understand the '[Member]' in your code. It seems suspicious in [Member]. Your table name is Table, but you cannot use it since it is a reserved keyword. Try writing this way.
private void btnNew_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Member("FirstName","LastName","Address") values ('" + txtFirstName.Text + "', '" + txtLastName.Text + "', '" + txtAddress.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Member added successfully");
}
Note: The ("FirstName","LastName","Address") are your table fields. Make sure your Table matches the cases (upper and lower) with that of your database table.
Hope this helps.

SqlException when querying database

when I developing just registration page this error occurred
error:An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
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;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
String checkuser = "select count(*) from [UserData] where User Name='"+ TextBox1UN.Text +"'";
SqlCommand comm = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(comm.ExecuteScalar().ToString());
if(temp==1)
{
Response.Write("user allready exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
String InserQuery = "insert into [UserData](UserName,Email,Password,Country)values(#Uname,#email,#pass,#country)";
SqlCommand comm = new SqlCommand(InserQuery, conn);
comm.Parameters.AddWithValue("#Uname", TextBox1UN.Text);
comm.Parameters.AddWithValue("#email", TextBox2EI);
comm.Parameters.AddWithValue("#pass", TextBox3PW);
comm.Parameters.AddWithValue("#country", DropDownList1cont.SelectedItem.ToString());
comm.ExecuteNonQuery();
Response.Write("Registration is succesful");
Response.Write("Administrator.aspx");
conn.Close();
}
catch (SqlException ex)
{
Response.Write("Error:"+ex.ToString());
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
}
aspx file:
<asp:SqlDataSource ID="SqlDataSourceRegistration"
runat="server"
ConnectionString="<%$ConnectionStrings:RegistrationConnectionString %>"
OnSelecting="SqlDataSourceRegistration_Selecting"
SelectCommand="SELECT * FROM [UserData]" >
</asp:SqlDataSource>
Your Query is not valid there is space between User Name and User is a keyword in sql. Your query should look like this
"select count(*) from [UserData] where UserName=#username";
Use Parameterized SQL
Add parameters to the command instead of concatenating values
comm.Parameters.AddWithValue("#username",TextBox1UN.Text);
A tip: Your code is very hackable / unsecure... because you put user input into the sql string you should use parameters instead.
You also have a space in your field name 'User Name' which I'm guessing is your issue so I put it as 'UserName'.
You should also put your code into a try catch statement so you can read the error.
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
using (SqlCommand command = new SqlCommand(
"SELECT COUNT(*) from [UserData] where UserName= #Name", connection))
{
// Add new SqlParameter to the command.
command.Parameters.Add("#Name", SqlDbType.NVarChar).Value = TextBox1UN.Text;
int temp = Convert.ToInt32(command.ExecuteScalar().ToString());
if(temp==1)
{
Response.Write("user allready exists");
}
}
}
catch (Exception ex)
{
// Display the exception's data dictionary.
foreach (DictionaryEntry pair in ex.Data)
{
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
}

C# insert data into database windows form app

I need to build a application where people can make a reservation but before doing that they need to fill in some information. I get this error code at the moment when i try to save the data: An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BonTemps
{
public partial class Home : Form
{
public Home()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var Form1 = new Form1();
Form1.Show();
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Home_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'bonTempsDBDataSet.Tafel' table. You can move, or remove it, as needed.
this.tafelTableAdapter.Fill(this.bonTempsDBDataSet.Tafel);
}
private void btnOpslaan_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = (#"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres), VALUES ('" + txtNaam.Text + "','" + txtAdres.Text + "','" + txtWoon.Text + "','" + txtTel.Text + "','" + txtMail.Text + "'");
com.ExecuteNonQuery();
sc.Close();
}
}
}
Remove the comma Before VALUES.
If that is not enough, you can debug and copy the generated string from Command Text and try running it directly in SQL Server Mangement Studio or similar
A typographical error remove the COMMA before the word VALUES.
You have to pass an open SqlConnection to your SqlCommand to make it work:
com.Connection = sc;
Also, consider using named parameters to pass data to your query to make your query more error-proof:
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.ConnectionString = ("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True");
sc.Open();
com.Connection = sc;
com.CommandText = #"INSERT INTO Klant (Naam, Adres, Woonplaats, Telefoonnummer, EmailAdres) VALUES (#naam, #adres, #woon, #tel, #mail)";
com.Parameters.AddWithValue("#naam", txtNaam.Text);
com.Parameters.AddWithValue("#adres", txtAdres.Text);
com.Parameters.AddWithValue("#woon", txtWoon.Text);
com.Parameters.AddWithValue("#tel", txtTel.Text);
com.Parameters.AddWithValue("#mail", txtMail.Text);
com.ExecuteNonQuery();
sc.Close();
using (var sc = new SqlConnection("Data Source=ACER;Initial Catalog=BonTempsDB;Integrated Security=True"))
{
using (var com = new SqlCommand("sql cmd text", sc))
{
try
{
sc.Open();
com.ExecuteNonQuery();
}
catch
{
}
}
}

Why is authentification failing? C# ASP.NET

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

Categories

Resources