How do I check if a user name already exists in Database - c#

I've seen this question asked a couple times but I couldn't find a good answer. I've been stuck for hours on this.
Basically I have usernames saved in a database and when a new user registers I want to check if his username is available - and if it is available add him to the database. And they register through a textbox called FName. The table is called Users.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT FName FROM Users WHERE FName = ????? usernames????? ", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["text"].ToString());
}
How can I fix this code?

"SELECT FName FROM Users WHERE FName = #paramUsername"
and then you insert the parameter into the cmd like so:
cmd.Parameters.Add("paramUsername", System.Data.SqlDbType.VarChar);
cmd.Parameters["paramUsername"].Value = "Theusernameyouarelookingfor";

Check this out:
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string validationQuery = "SELECT * FROM Users WHERE FName = #name";
SqlCommand validationCommand = new SqlCommand(validationQuery, connection);
validationCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
SqlDataReader validationReader = validationCommand.ExecuteReader(CommandBehavior.CloseConnection);
if (!validationReader.Read())
{
string insertQuery = "INSERT INTO Users (FName) VALUES (#name)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.Add("#name", SqlDbType.VarChar).Value = loginUserSelected;
connection.Open();
insertCommand.ExecuteNonQuery();
insertCommand.Dispose();
connection.Close();
}
else
{
//Uh oh, username already taken
}
validationReader.Close();
validationCommand.Dispose();
Things to note:
Use parameters, avoid concatenating strings because it's a security vulnerability
Always Close and Dispose your ADO objects

Related

getting specified value from SQL table based on current user login to Full name

I have below data in SQL query, and am showing the current user "Domain" logged in I want to show the full name in label based on each user using the Windows form,
I got stuck here, how I can continue to find the value
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
label1.Text = userName.ToUpper();
SqlConnection con = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=db;User ID=AAA;password=******");
con.Open();
string command7 = "SELECT distinct [fullname] ,[Group] ,[Domain] FROM [tableA] where fullname is not null and [group] is not null and [Domian] = '"+ label1.Text + "'";
SqlCommand da7 = new SqlCommand(command7, con);
Full name
Group
Domain
Alex Sam J
A GROUP
test\Alex
Jon Pete F
B GROUP
test\Jon
You can get the value of full name this way :
...
SqlCommand cmd = new SqlCommand(command7, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
labelFullName.Text = da.Tables[0].Rows[0]["fullname"].ToString();
I solve it like this, thanks
SqlCommand cmd = new SqlCommand(da7, con);
cmd.CommandType = CommandType.Text;
//con.Open();
SqlDataReader reader = cmd.ExecuteReader();
//DataTable dt7 = new DataTable();
while (reader.Read())
{
label21.Text = reader["Technician"].ToString();
}
con.Close();

Checking if username is available in database

I'm trying to check if the username is already in use in C# database and it's giving me this error
SqlConnection cn = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\admin\Desktop\241 Project sem 1 2020-2021\Online Banking - ITIS 241 project group 9\UobBankDatabase.mdf; Integrated Security = True; Connect Timeout = 30");
cn.Open();
SqlCommand cmd = new SqlCommand("select * from LoginTable where user_name='" + textBox1.Text + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
dr.Close();
MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dr.Close();
}
and yes I'm a newbie
Use this:
SqlCommand cmd = new SqlCommand("Select count(*) from LoginTable where user_name='" + textBox1.Text + "'", cn);
Then:
var dr = cmd.ExecuteScalar();
if (dr != null)
{
//Exists
}
else
{
//Unique username
}
Google it please:
Since the error is SqlException: Invalid object name 'Movie' , that
means the table named 'Movie' has not created or the Database you are
referring has not created. To see if the Database or table 'Movie' has
created, open SQL Server Object Explorer and check the Database name
is the same as in appsettings. json
And Please tell us at what line do you get that?
Is that this line =>if (dr.Read())
Let's extract method for the check:
private static bool NameAvailable(string name) {
//DONE: wrap IDisposable into using
using (SqlConnection cn = new SqlConnection("Connection String Here")) {
cn.Open();
//DONE: keep Sql readable
//DONE: make Sql parametrize
//DONE: select 1 - we don't want entire record but a fact that record exists
string sql =
#"select 1
form LoginTable
where user_name = #prm_user_name";
using (var cmd = new SqlCommand(sql, cn)) {
cmd.Parameters.Add("#prm_user_name", SqlDbType.VarChar).Value = name;
using (var dr = cmd.ExecuteReader()) {
return !dr.Read(); // Not available if we can read at least one record
}
}
}
}
Then you can put
if (!NameAvailable(textBox1)) {
// Let's be nice and put keyboard focus on the wrong input
if (textBox1.CanFocus)
textBox1.Focus();
MessageBox.Show("Username Already exist please try another ",
"Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
some changes only.it is better to get what is the error than a temporary solution so print your query first and run it in the sqlserver . also add initial catalog instead of attacjing mdf files its way better in my opinion.
<connectionStrings>
<add name="stringname" connectionString="Data Source=mssql;Initial Catalog=databasename; Persist Security Info=True;User ID=sa;Password=*****;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
using a connection string instead also
SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["stringname"].ConnectionString);
cn.Open();
string query = "select * from LoginTable where user_name='" + textBox1.Text.ToString() + "'";
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dr = cmd.ExecuteReader();
//print query if error and comment the execute reader section when printing the query to know the error Respone.Write(query);
if (!dr.HasRows)
{
// ur code to insert InsertItemPosition values
}
else
{
//show username exist
}
dr.Close();
Try this:
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(UserName) as UserCount FROM LoginTable WHERE user_name = #user_name", con))
{
con.Open();
cmd.Parameters.AddWithValue("#user_name", TextBox1.Text);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(Convert.ToInt32(dr["UserCount"].ToString()) >= 1)
{
// Exists
}
else
{
// Doesn't Exist
}
}
}
con.Close();
}
}

How to validate Password and Username for website in c#

I have a simple login website, which is my first website project in Visual Studio 2015. I have successfully created a SQL database which contains user information like Username, Password, Email and Country, and I have also successfully created a user registration page where a new user can input there details and these details will be added to the database. This all works fine.
but I have hit a roadblock while attempting to validate the Username and Password against the stored values in the row containing the User data in the SQLdatabase to give the user access to the member only pages.
Heres my code snippet for when the user click the login button.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString);
con.Open();
string checkUser = "SELECT * FROM Members where Username= '" + TextBoxSignUser.Text + "' and Password= '" + TextBoxSignPass.Text + "'";
SqlCommand cmd = new SqlCommand(checkUser, con);
cmd.ExecuteNonQuery();
con.Close();
I know what I need to do is probably something like this pseudocode below, but I am unsure how to go about validating this information against stored values in the database.
if ("Username" and "Password" == the value of Username and Password TextBox.Text)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
else
{
Response.Write("Details incorrect, Please try again")
}
Fill the data-table using data adapter one you get the data into a data-table you can get the return values of the query and match the parameters
DataTable Dt = new Datatable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
if (dt.rows.count > 0 )
{
//MATCH FOUND
}
You can use like..
string query= "SELECT * FROM Members where Username= 'usr' and Password= 'pwd'";
SqlCommand cmd = new SqlCommand(query, con);
MySqlDataAdapter objda = new MySqlDataAdapter(cmd);
DataSet objDs = new DataSet();
objda.Fill(objDs);
if(objDs.Tables[0].Rows.Count>0)
{
Response.Write("Sign in successful");
Response.Redirect("MemberTestPage.aspx");
}
You could do as following without using Datasets,
var con = new SqlConnection("your connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT * FROM Members where Username= 'usr' and Password= 'pwd'", con);
bool result = false;
cmd.Connection.Open();
using (cmd.Connection)
{
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
result = true;
}
if (result == true)
// Login successful
else
// Login failed
string query = string.Format("SELECT TOP 1 * FROM [Table] WHERE Username = '{0}' and Password = '{1}'", txtUsername.Text, txtPassword.Text);
command = new OleDbCommand(query, con);
var reader = command.ExecuteReader();
if (reader.HasRows)
{
//successfully login
}
else
//error message
I think first of all it is better to use ADO.NET libraries for some reasons like best performance and high security. Here is my suggestion. hope to be useful for you:
using System.Data.SqlClient;
...
string conStr = ConfigurationManager.ConnectionStrings["MembersConnectionString"].ConnectionString;
string sql = "SELECT * FROM Members where Username = #user and Password = #pass";
SqlParameter pUser = new SqlParameter("#user", TextBoxSignUser.Text);
SqlParameter pPass = new SqlParameter("#pass", TextBoxSignPass.Text);
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.Add(pUser);
cmd.Parameters.Add(pPass);
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
// Successfully signed in
// Also you can access your fields' value using:
// 1. its index (e.x. reader[0])
// 2. or its name: (e.x. reader["Username"])
}
else
{
// Login failed
}
}
}
}

Asp.Net SQL Update Statement

I have an Asp.net application on my page the user requests for a user to be removed. This then populates my 'Admin_TaskList' db.
An administrator then goes in the secure area of the site and enters the users name and clicks a button. Upon the confirmation, the user is then deleted from my 'Users' db (already got this working) but I want my 'Admin_TaskList' db 'Status' column to change from 'To Do' to 'Completed'.
As I sad I have the delete bit working but I am struggling updating my other table.
Snippet of code I have tried
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
Full code
public void btnRemoveConfirmYes_Click(object sender, EventArgs e)
{
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
SqlConnection conn = new SqlConnection(connection);
conn.Open();
SqlCommand cmd1 = new SqlCommand("DELETE FROM Users WHERE Name = #Name", conn);
cmd1.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd1 = cmd1.ExecuteReader();
conn.Close();
conn.Open();
SqlCommand cmd2 = new SqlCommand("UPDATE FROM Admin_TaskList SET Status = 'Complete' WHERE Description = 'Remove User' AND Name = #Name", conn);
cmd2.Parameters.AddWithValue("#Name", txtRemoveUser.Text);
SqlDataReader rd2 = cmd2.ExecuteReader();
conn.Close();
txtRemoveUser.Text = "";
Response.Redirect("/AdminSide/TaskList.aspx");
}
Instead of using a SqlDataReader to update a value use SqlCommand.ExecuteNonQuery:
int updated = cmd2.ExecuteNonQuery();
Remember that you need to use ExecuteNonQuery on commands that modify your data like Delete, Insert or Update.
MSDN:
You can use the ExecuteNonQuery to perform catalog operations (for
example, querying the structure of a database or creating database
objects such as tables), or to change the data in a database without
using a DataSet by executing UPDATE, INSERT, or DELETE statements.
The complete method:
int deleted, updated;
string connection = ConfigurationManager.ConnectionStrings["PaydayLunchConnectionString1"].ConnectionString;
using (var conn = new SqlConnection(connection))
{
conn.Open();
string delSql = "DELETE FROM Users WHERE Name = #Name";
using (var cmd = new SqlCommand(delSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
deleted = cmd.ExecuteNonQuery();
}
string updSql = #"UPDATE Admin_TaskList
SET Status = 'Complete'
WHERE Description = 'Remove User'
AND Name = #Name";
using (var cmd = new SqlCommand(updSql, conn))
{
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtRemoveUser.Text;
updated = cmd.ExecuteNonQuery();
}
}

Get value from database not behaving as expected

I'm making an asp.net application, I'm trying to read data from sql tables, but data just wont compare, as I don't get the message "You don't have a bank account, you can't register to our website"
SqlConnection connection = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True");
connection.Open();
SqlDataReader reader = null;
SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber='" + accountnumber1.Text + "'", connection);
reader = command.ExecuteReader();
if (reader.Read())
{
string getAccountNumber = reader[0].ToString();
reader.Close();
if (getAccountNumber != accountnumber1.Text)
{
lblaccountnumber.Visible = true;
lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
}
}
The best way to find this issue is to put a break point on the line:
if (getAccountNumber != accountnumber1.Text)
and see why the values do not match.
My guess is that account number is not the first column in your SELECT * query, thus reader[0].ToString() is not really the account number, but another value. Instead get the column index via the column name, like this:
string getAccountNumber = reader.GetString(reader.GetOrdinal("Accountnumber"));
It would also be a great idea to use a parameterized query so you do not get a visit from Little Bobby Tables.
Here is your code using a parameterized query:
string theQuery = "SELECT * FROM ACCOUNTS WHERE Accountnumber=#AccountNumber";
SqlCommand command = new SqlCommand(theQuery, connection);
command.Parameters.AddWithValue("#AccountNumber", accountnumber1.Text);
reader = command.ExecuteReader();
I would check reader.HasRows property and show the message
using (SqlConnection connection = new SqlConnection(#"Data Source=SHKELQIM\SQLEXPRESS;Initial Catalog=E-Banking;Integrated Security=True"))
using(SqlCommand command = new SqlCommand("SELECT * FROM ACCOUNTS WHERE Accountnumber= #Accountnumber", connection))
{
command.Parameters.AddWithValue("Accountnumber", accountnumber1.Text);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
if (!reader.HasRows)
{
lblaccountnumber.Visible = true;
lblaccountnumber.Text = "You don't have a bank account, you can't register to our website";
}
}
}

Categories