I’m very new to ASP.net and have been following a few video tutorials to build a log in page. I successfully created my registration page fine that enters details into my table within the database fine however I can't get my log in page to work =/.I’ve been at this for a few hours and am not sure if any of you can help but it's worth a shot. The IDE I am using is visual studio (latest version).
I am getting the following error (clicking the image will give a closer view, but you probably already know that):
the error changes depending on who I try to log on as for example the above error was returned when trying to log in as john, the below error was returned trying to log in as admin.
shown below is my code used behind the log in button:
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 Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where [Login]'" + Loginbox.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string CheckPasswordQuery = "select Password from [Table] where [Login]='" + Loginbox.Text + "'";
SqlCommand Passcom = new SqlCommand(CheckPasswordQuery, conn);
string password = Passcom.ExecuteScalar().ToString().Replace(" ","");
if (password == Passwordbox.Text)
{
Session["New"] = Passwordbox.Text;
Response.Write("Password is correct");
}
else
{
Response.Write("Wrong password");
}
}
else {
Response.Write("User name does not exist");
}
}
}
Shown below is the form page view, which runs perfectly fine, the error gets returned when the log in button is pressed.
Shown below is the table definition:
And shown below is the data contained within the table:
Thank you all for your time and I appreciate any input any of you have to help solve this.
You have invalid syntax in your query. Please note that while many tutorials may show you to query like this, it's very insecure. You should use parameters. However, for the sake of this answer, you forgot the equal sign:
string checkuser = "select count(*) from [Table] where [Login] = '" + Loginbox.Text + "'";
Your syntax is incorrect, but it is actually safer if you parameterize it to avoid sql injection
string checkuser = "select count(*) from [Table] where [Login] = #user";
SqlCommand com = new SqlCommand(checkuser, conn);
com.Parameters.Add("#user", Loginbox.Text);
...
Related
Probably the worst part about using Microsoft Access and SQL is trying to connect through the OLEDB connection. The code is on the one drive and has been working without issue but this morning it has came up with this error;
"System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'"
Previously I was able to change the CPU from any to x86 which sometimes seemed to fix the problem but now it is not. I am running System.Data.OleDb 7.0.0 which I have not changed since starting this protect.
using System.Data.OleDb;
using System.Data;
using System;
namespace LOGIN_TAKE_FIVE
{
public partial class Form1 : Form
{
OleDbConnection connection = new OleDbConnection();
public Form1()
{
InitializeComponent();
connection.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:/Users/kiera/LOGIN TAKE FIVE/bin/Debug/net6.0-windows/dbNumber2.accdb");
}
private void btnAdd_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand cmd = new OleDbCommand();
string encryptUser = EncryptString(tbUsername.Text);
string encryptPassword = EncryptString(tbPassword.Text);
string regSQL = "INSERT INTO Users ([Username], [Password]) VALUES ('" + encryptUser + "', '" + encryptPassword + "')";
cmd = new OleDbCommand(regSQL, connection);
cmd.ExecuteNonQuery();
connection.Close();
}
this code was working in full no less than 5 days ago so I am unsure what the problem is. Any help would be greatly appreciated.
I would like to create a simple registration form for WINDOWS application. I am using SQLite database which can be embedded into the project as I need to create a .exe file and mail it to my friend.
Now my registration form has 2 text boxes.
textBox1 for name
textBox2 for password
I need to insert these 2 values into the table and I have written the following code.
using Finisar.SQLite;
namespace Task_Sa
public partial class Form2 : Form
{
string connectionString;
public Form2()
{
InitializeComponent();
connectionString = #"Data Source=database.db;Version=3;New=True;Compress=True;";
}
private void button1_Click(object sender, EventArgs e)
{
using (SQLiteConnection sqlite_conn = new SQLiteConnection(connectionString))
{
SQLiteCommand cmd = new SQLiteCommand();
cmd.CommandText = #"INSERT INTO TaskTable(UserName,PassWord) values(#userName,#passWord)";
cmd.Connection = sqlite_conn;
cmd.Parameters.Add(new SQLiteParameter("#userName",textBox1.Text)); -> ERROR
}
}
}
}
here I am getting the error as the parameters are not matching. 2 parameters should be of type string and dbType. Please help me to complete the code in this regard. I have copied and pasted SQLite dll file in debug folder of my project and I also have used the " using Finisar.SQLite; " name space.
Try this
cmd.CommandText = "INSERT INTO TaskTable(UserName,PassWord) values('"+ textBox1.Text +"','"+ textBox2.Text +"')";
Add a blank space before TaskTable and values:
Your version:
cmd.CommandText = #"INSERT INTO TaskTable(UserName,PassWord) values(#userName,#passWord)";
Modified version:
cmd.CommandText = #"INSERT INTO TaskTable (UserName,PassWord) values (#userName,#passWord)";
I keep getting run time SQL query errors in asp.net. I am using c#. The error always starts with Incorrect Syntax near '(some word)'. I have checked and rechecked my code for any syntactic errors but never found any.. In the code below the error is Incorrect Syntax near 'user'. Please help.
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;
public partial class LogIn : System.Web.UI.Page
{
SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
con.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users \Sony\Documents\Library\App_Data\Library.mdf;Integrated Security=True;User Instance=True";
cmd.Connection=con;
con.Open();
}
protected void txt_user_TextChanged(object sender, EventArgs e)
{
}
protected void txt_pass_TextChanged(object sender, EventArgs e)
{
}
protected void btn_log_Click(object sender, EventArgs e)
{
cmd.CommandText="select count(*) from user where Username='"+txt_user.Text+"' and Password='"+txt_pass.Text+"'";
int count =Convert.ToInt16(cmd.ExecuteScalar());
if (count==1)
{
Response.Redirect("Home.aspx");
}
else
{
Label1.Text="Invalid Username or Password. Please try again..";
}
}
The reason of your error is the word user. It is a reserved keyword for SqlServer.
You need to encapsulate it with square brakets
select count(*) from [user] ....
Said that, now let's address the biggest problem of your code. Sql Injection
cmd.CommandText="select count(*) from [user] where Username=#uname " +
"and Password=#upass";
cmd.Parameters.AddWithValue("#uname", txt_user.Text)
cmd.Parameters.AddWithValue("#upass", txt_pass.Text);
int count =Convert.ToInt16(cmd.ExecuteScalar());
......
Using a parametrized query like this, protects your application from malicious input (see the referenced question) that could compromise (or destroy) the information stored in your database. Also you avoid problems with inputs that contains problematic characters like strings with single quotes or numeric decimal separators or date formatting difficulties.
There is another problem as I can see from your code above. Do not store the connection in global variables. There is no performance hit if you open the connection when needed and close afterwards.
It is called Connection Pooling and you don't keep a valuable resource locked when you don't use it.
So to sum it all:
protected void btn_log_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
#"C:\Users\Sony\Documents\Library\App_Data\Library.mdf;" +
#"Integrated Security=True;User Instance=True")
{
con.Open();
using(SqlCommand cmd = new SqlCommand("select count(*) from [user] where "+
"Username=#uname and Password=#upass", con)
{
cmd.Parameters.AddWithValue("#uname", txt_user.Text)
cmd.Parameters.AddWithValue("#upass", txt_pass.Text);
int count =Convert.ToInt16(cmd.ExecuteScalar());
......
}
}
}
The thing is, that "user" is a reserved word in SQL. Apart form the injection problem, your query should read:
select ... from [user] where
'User' is a reserved keyword in SQL server. If you have a table name 'user', you should put it in brakets within queries
select count(*) from [user] where ...
I agree fully with all that has been said by Steve, Roman and Alex.
If I should add something it is that you should try to minimize the usage of ad-hoc queries, that has been used in this example. Rather you should prefer to put the most part of the sql code in sql functions and stored procedures, since that can give a hugh improvement of the performance since those queries can be compiled the first time they are executed and the times executed afterward the database can focus on just to retreive data. With ad-hoc queries the query has to be compiled every time, which can actually take some time for more complex queries.
You can then execute the Stored Procedure like this:
using(SqlCommand cmd = new SqlCommand("dbo.IsValidLogin", con)
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#username", txt_user.Text)
cmd.Parameters.AddWithValue("#password", txt_pass.Text);
var isValidLogin =Convert.ToBool(cmd.ExecuteScalar());
...
}
If you have a Procedure declared in the database like this:
CREATE PROC dbo.IsValidLogin
#username nvarchar(50),
#password nvarchar(50)
AS
BEGIN
SELECT count(1)
FROM [user]
WHERE Username=#username
AND Password=#password
END;
See a Sql Fiddle exemple here.
i'm new to asp.net, i'm writing a login & registration script for learning database application. But the script seems not work. it stills can add duplicated username. Here is the script
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
{
static string temp;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from [user] where UserName='" + TextBoxUN.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
Response.Write("User Name Already Exist....<br /> Please Choose Another User Name.");
}
}
}
protected void Submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["earchConnectionString"].ConnectionString);
con.Open();
string insCmd = "Insert into [user] (UserName, Password, EmailAddress, FullName, level) values (#UserName,#Password,#EmailAddress, #FullName, #level)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#UserName", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Password", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#level", level.SelectedValue.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
//Response.Redirect("Login.aspx");
Label1.Text = temp;
}
catch (Exception er)
{
Response.Write("Something wrong");
}
finally
{
//Any Special Action You Want To Add
}
}
}
Any can detect the problems?
thanks
You should do the check whether the username exists inside your Button_Click, not inside Page_Load. Ideally both queries should be executed within the same SQL transaction. Also you should absolutely use parametrized query for the first one (the same way you are doing in the second query) in order to prevent SQL injection.
Set primary key on the column UserName of the table user. So you don't have to check for the user existence in the database at the time of insertion, reducing an extra call to database. This way command.ExecuteNonQuery() won't allow you to insert duplicate users and throw exception and you can take necessary actions in the catch block of your code.
Make an unique field for your user login in SQL Database.
On account creation page on account creation button click event do it as following:
try
{
SqlCommand command = new SqlCommand("INSERT INTO Users(login,password) VALUES ('" + txtLogin.Text + "','" + txtPass.Text+ "');", con);
command.ExecuteNonQuery();
Response.Redirect("login.aspx");
}
catch (SqlException)
{
lblWrongLogin.Text = "Username already exists.";
}
Basically, when you try to write a duplicate login in SQL Database you get SQL exception, so you just catch it in your application and do whatever action you need (in most cases reload registration page).
P.S.:
consider using some hashing algorithm like MD5 to hash passwords before putting them in database. Also dont forget to hash passwords client-side when logging in.
P.P.S.: use SQL parameters for login, password and every other user-entered information to prevent SQL injection.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
My need is to write a code, which
creates a db
creates four tables
creates primary keys
creates foreign keys
and constraints like type int or boolean or string etc
Yes I know w3c shools has the sql codes, but the problem is I first need to detect if these things exists or not one by one.
And this is for me a great problem.
I tried to work with sql exceptions, but it does not provide way to categorize the exceptions --like databasethereexception--tablealreadythereEXCEPTION..
So please provide some coded examples or links for the above purpose,
note: yes I can google, but it is full full full of examples and codes, it gets too confusing, so hoping for straight professional examples please
Also a sample of the type of code i am working with
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;
public partial class Making_DB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//check or make the db
MakeDB();
CheckDB();
}
public void CheckDB()
{
try
{
string Data_source = #"Data Source=A-63A9D4D7E7834\SECOND;";
string Initial_Catalog = #"Initial Catalog=master;";
string User = #"User ID=sa;";
string Password = #"Password=two";
string full_con = Data_source + Initial_Catalog + User + Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
DataSet ds2 = new DataSet();
SqlCommand CheckDB = new SqlCommand("select * from sys.databases where name = 'my_db'", connection);
DBcreatingAdaptor.SelectCommand = CheckDB;
DBcreatingAdaptor.Fill(ds2);
GridView1.DataSource = ds2;
GridView1.DataBind(); // do not forget this//
Response.Write("<br />WORKING(shows zero if db not there) checking by gridview rows: " + GridView1.Rows.Count.ToString());
Response.Write("<br />NOT WORKING(keeps on showing one always!) checking by dataset tables: " + ds2.Tables.Count.ToString());
DBcreatingAdaptor.Dispose();
connection.Close();
//Inaccesible due to protection level. Why??
//SqlDataReader reader = new SqlDataReader(CheckDB, CommandBehavior.Default);
}//try
catch (Exception e)
{
Response.Write(" checking:: " + e.Message);
}//catch
}//check db
public void MakeDB()
{
try
{
string Data_source = #"Data Source=A-63A9D4D7E7834\SECOND;";
//string Initial_Catalog = #"Initial Catalog=replicate;";
string User = #"User ID=sa;";
string Password = #"Password=two";
string full_con = Data_source + User + Password;
SqlConnection connection = new SqlConnection(full_con);
connection.Open();
//SqlCommand numberofrecords = new SqlCommand("SELECT COUNT(*) FROM dbo.Table_1", connection);
SqlCommand CreateDB = new SqlCommand("CREATE DATABASE my_db", connection);
//DataSet ds2 = new DataSet();
SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter();
DBcreatingAdaptor.SelectCommand = CreateDB;
DBcreatingAdaptor.SelectCommand.ExecuteNonQuery();
//check for existance
//select * from sys.databases where name = 'my_db'
DataSet ds2 = new DataSet();
SqlCommand CheckDB = new SqlCommand(" select * from sys.databases where name = 'my_db'", connection);
DBcreatingAdaptor.SelectCommand = CheckDB;
//DBcreatingAdaptor.SelectCommand.ExecuteReader();
DBcreatingAdaptor.Fill(ds2);
GridView1.DataSource = ds2;
//if not make it
}//try
catch (Exception e)
{
Response.Write("<br /> createing db error: " + e.Message);
}//catch
}//make db
}
As I've already mentioned in my comment - I would NEVER write out directly to the Response stream from a function like this! Pass back a string with an error message or something - but do NOT write out to the stream or screen directly.
You should use the best practice of wrapping SqlConnection and SqlCommand into using(...){.....} blocks to make sure they get properly disposed. Also, populating a gridview from within this code is really bad - you're mixing database access (backend) code and UI frontend code - really really bad choice. Why can't you just pass back the data table and then bind it in the UI front end code to the grid??
public DataTable CheckDB()
{
DataTable result = new DataTable();
try
{
string connectionString =
string.Format("server={0};database={1};user id={2};pwd={3}"
"A-63A9D4D7E7834\SECOND", "master", "sa", "two");
string checkQuery = "SELECT * FROM sys.databases WHERE name = 'my_db'";
using(SqlConnection _con = new SqlConnection(connectionString))
using(SqlCommand _cmd = new SqlCommand(checkQuery, _con))
{
SqlDataAdapter DBcreatingAdaptor = new SqlDataAdapter(_cmd);
DBcreatingAdaptor.Fill(_result);
}
}//try
catch (SqlException e)
{
// you can inspect the SqlException.Errors collection and
// get **VERY** detailed description of what went wrong,
// including explicit SQL Server error codes which are
// unique to each error
}//catch
return result;
}//check db
Also - you're doing the MakeDB() method way too complicated - why a table adapter?? All you need is a SqlCommand to execute your SQL command - you already have a method that checks that a database exists.
public void MakeDB()
{
try
{
string connectionString =
string.Format("server={0};database={1};user id={2};pwd={3}"
"A-63A9D4D7E7834\SECOND", "master", "sa", "two");
string createDBQuery = "CREATE DATABASE my_db";
using(SqlConnection _con = new SqlConnection(connectionString))
using(SqlCommand _cmd = new SqlCommand(createDBQuery, _con))
{
_con.Open();
_cmd.ExecuteNonQuery();
_con.Close();
}
}//try
catch (SqlException e)
{
// check the detailed errors
// error.Number = 1801 : "database already exists" (choose another name)
// error.Number = 102: invalid syntax (probably invalid db name)
foreach (SqlError error in e.Errors)
{
string msg = string.Format("{0}/{1}: {2}", error.Number, error.Class, error.Message);
}
}//catch
}//make db
I am very sure of the cross-over between this and the other question - however, it sounds to me like you are approaching this from the wrong end.
I would write this as a TSQL script, making use of EXEC to avoid problems with the checker, for example:
USE [master]
if not exists ( ... database ...)
begin
print 'creating database...'
exec ('...create database...')
end
GO
USE [database]
if not exists( ... check schema tables for 1st thing ... )
begin
print 'Creating 1st thing...'
exec ('...create 1st thing...')
end
if not exists( ... check schema tables for 2nd thing ... )
begin
print 'Creating 2nd thing...'
exec ('...create 2nd thing...')
end
if not exists( ... check schema tables for 3rd thing ... )
begin
print 'Creating 3rd thing...'
exec ('...create 3rd thing...')
end
Then you can gradually extend this script as your schema changes, and all you need to do is re-run the script for it to update the database.
May be it is not directly you want, but for easy database creation & population from .Net review usage of wide migrate tool. My preference (Migrator.NET) but full review can be found there: http://flux88.com/blog/net-database-migration-tool-roundup/