How to check for the database if username is not found - c#

string constr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jettp\Downloads\MockTest\MockTest\Database1.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, Weight FROM MyWeight where Name ='" + txt_Name.Text + "'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (txt_Name.Text != null)
{
sdr.Read();
MessageBox.Show("Username is found");
txt_Name.Text = sdr["Name"].ToString();
txt_Weight.Text = sdr["Weight"].ToString();
con.Close();
}
else
{
lbl_WarningMsg.Text = "Name not found";
con.Close();
}
}
}
}
I tried using this command to search for the username which is in not found database, but database message kept saying that the name is found in the database. This is the error I get:
System.InvalidOperationException: 'Invalid attempt to read when no data is present.'

You are getting that Username is found because your if condition is always true. Change your if condition to this :
if (sdr.HasRows)
{
//your code
}

Related

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

Can't Load Data to ComboBox C#

I Inserted Data to ComboBox using Folloowing Code in FormLoad Block
try
{
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
it does the Job. in the Form You can Create a Category and Delete By Selecting The Name of the category from ComboBox Here is a ScreenShot the Form. I used the following code to Delete and Load the items to ComboBox after Deleting.
try
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "DELETE FROM CategoryTable WHERE CategoryName='" + SelectCategoryComboBox.SelectedItem.ToString() + "'";
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully deleted " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
catch
{
StatusLabel.Text = "An Error occured while deleting " + SelectCategoryComboBox.SelectedItem.ToString() + " Category";
}
finally
{
try
{
SelectCategoryComboBox.Items.Clear();
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
string query = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(query, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
}
catch
{
StatusLabel.Text = "An error occured while loading Data";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
code for Creating new item Given below
if (CategoryNameText.Text == "")
{
StatusLabel.Text = "You have to provide a name to create a category";
}
else
{
String conString = ConfigurationManager.ConnectionStrings["mfcdb"].ConnectionString;
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
}
StatusLabel.Text = "You have successfully created " + CategoryNameText.Text + " Category";
try
{
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = "An Error Occured while Loading Data!";
}
finally
{
SelectCategoryComboBox.SelectedItem = null;
SelectCategoryComboBox.SelectedText = "Choose Category";
}
CategoryNameText.Focus();
}
catch
{
Thread.Sleep(3000);
StatusLabel.Text = ("An ERROR occured While creating category!");
}
finally
{
CategoryNameText.Text = "Enter Category Name";
}
}
}
This Code Deletes Items Perfectly.But If I delete an Item Which is Already in the ComboBox, it does the Job i.e it deletes and Load the Remaining items to ComboBox.but, if I Created an Item,and Deleted it Before Closing the Form, it deletes the item.But Fails to Load the remaining items.it shows all the items already exist in the ComboBox Before Deleting. Would be a great help if you can help me solve this problem. Here SelectCategoryComboBox is the Name of the ComboBox.
I find the problem occur in the following sentence.
String query = "INSERT INTO CategoryTable(CategoryName) VALUES('" + CategoryNameText.Text + "')";
I have two solutions.
First, Please set the Allow nulls for other field.
Like the following:
Second, you can use the following code to replace the original code.
string query = string.Format("INSERT INTO Student(CategoryName, CategoryId, Age) VALUES('{0}','{1}','{2}')",textBox1.Text,textBox2.Text,textBox3.Text);
I found What went Wrong...
Change Following Code
using (SqlConnection scon = new SqlConnection(conString))
{
string locQuery = "SELECT CategoryName,Categoryid FROM CategoryTable";
SqlDataAdapter da = new SqlDataAdapter(locQuery, scon);
scon.Open();
DataSet ds = new DataSet();
da.Fill(ds, "CategoryTable");
SelectCategoryComboBox.ValueMember = "Categoryid";
SelectCategoryComboBox.DisplayMember = "CategoryName";
SelectCategoryComboBox.DataSource = ds.Tables["CategoryTable"];
}
To
using (SqlConnection con = new SqlConnection(conString))
{
SelectCategoryComboBox.Items.Clear();
string squery = "SELECT CategoryName FROM CategoryTable";
con.Open();
SqlDataReader sdr = new SqlCommand(squery, con).ExecuteReader();
while (sdr.Read())
{
SelectCategoryComboBox.Items.Add(sdr.GetValue(0).ToString());
}
}
it Worked for me.

How to prevent 2 connection open in database?

I try something good code about prevent duplication of entries but I got error about connection. How can I fix this? Here's my code.
if(label1.Text == "" || label2.Text == "" || label3.Text == "") {
MessageBox.Show("Please Select Data");
} else {
String query = "Select * from Attendance where empIn=#empIn";
MySqlCommand cmd1 = new MySqlCommand(query, con);
cmd1.Parameters.AddWithValue("empIn", label2.Text);
MySqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows) {
MessageBox.Show("This Person has already IN");
} else {
insert();
}
}
}
public void insert()
{
int i;
con.Open();
MySqlCommand cmd = new MySqlCommand("INSERT INTO Attendance (Name,Date,empIn)VALUES(#Name,#Date,#empIn)", con);
cmd.Parameters.Add("#Name", MySqlDbType.VarChar).Value = label3.Text;
cmd.Parameters.Add("#Date", MySqlDbType.Date).Value = Convert.ToDateTime(label1.Text);
cmd.Parameters.Add("#empIn", MySqlDbType.VarChar).Value = label3.Text;
i = cmd.ExecuteNonQuery();
if (i > 0) {
MessageBox.Show("Data Inserted");
label2.Text = "";
label3.Text = "";
label4.Text = "";
} else {
MessageBox.Show("Not Deleted");
}
con.Close();
you can simply use the "using" state which will create and close the connection automatically
public object getQueryScaller(string sqlQuery)
{
object value = null;
using (SqlConnection conn = new SqlConnection(_connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
conn.Open();
value = cmd.ExecuteScalar();
}
}
return value;
}
This will Automatically control the connection problem you will have no need to take care of it. just passing the parameter into the function as SQL statement and it will work.

"ExecuteReader:Connection Property has not been initialized."

private void btnSave_Click(object sender, EventArgs e)
{
try
{
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
if (rdr.Read())
{
MessageBox.Show("Company Name Already Exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtStaffID.Text = "";
txtStaffID.Focus();
}
else
{
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string Query = "insert into PersonsData (StaffID, FullName, Email, Address, Picture) values('" + this.txtStaffID.Text + "','" + this.txtFullname.Text + "','" + this.txtEmail.Text + "','" + this.txtAddress.Text + "',#img)";
if (con.State != ConnectionState.Open)
con.Open();
cm = new SqlCommand(Query, con);
cm.Parameters.Add(new SqlParameter("#img", img));
int x = cm.ExecuteNonQuery();
con.Close();
MessageBox.Show(x.ToString() + "Successfully Saved!");
}
}
catch (Exception ex)
{
con.Close();
MessageBox.Show(ex.Message);
}
}
This is my code i don't understand why I'm getting this error:
ExecuteReader:Connection Property has not been initialized.
I'm making a save button where the Staffid will be checked first if already.
Before executing the command, you need to say which connection is to be used. In your case, it is:
cm.Connection = con;
Take a note that, include this line of code after opening the connection and after creating the instance of SqlCommand.
con = new SqlConnection("Data Source = LENOVO; Initial Catalog = MainData; Integrated Security = True");
con.Open();
string CheckID = "select StaffID from PersonsData where StaffID='" + txtStaffID.Text + "'";
cm = new SqlCommand(CheckID);
cm.Connection = con; //Assign connection to command
You didn't assign connection to SqlCommand used in the reader
The error message is clear enough, You have to assign the connection for the Command, either through assignement or through the constructor, That is:
cm = new SqlCommand(CheckID);
cm.Connection = con; // Should be added
SqlDataReader rdr = cm.ExecuteReader();
Or else you can use the constructor to initialize the command like this:
cm = new SqlCommand(CheckID,con);
Hope that you are aware of these things since you ware used it correctly in the else part of the given snippet
Make sure that you assign the SqlConnection to your Command-Object. You can do this via Constructor or Property:
con = new SqlConnection(//Your Connectionstring)
//assign via Constructor
cm = new SqlCommand(CheckID, con);
//or via Property
cm.Connection = con;
SqlDataReader rdr = null;
rdr = cm.ExecuteReader();
Further I would recommend you to use a using-block to make sure that the Command and Connection gets destroyed after using it.
using (var con = new SqlConnection())
{
using (var cm = new SqlCommand())
{
}
}

Retrieving Hash Password error

I am trying to log on with a username and original password that already stored in the database with a hashed password.
But, when I am trying to log on, I received the message says that value cannot be null on if (salt == null) {
throw new ArgumentNullException("salt");
}
I am using BCrypt.cs for hashing the password in the database. BCrypt.cs
Here is my code for register the user:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
Password.Hashed = BCrypt.HashPassword(this.textBox2.Text, BCrypt.GenerateSalt(12));
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType]) VALUES (#Username, #Password, #UserType)";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = Password.Hashed;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.comboBox1.SelectedItem;
cmd.ExecuteNonQuery();
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
Login _login = new Login();
_login.ShowDialog();
this.Close();
}
}
conn.Close();
}
Here is my code for log on the user:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType] FROM [Member] WHERE [Username] = #Username AND [Password] = #Password";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = BCrypt.CheckPassword(this.textBox2.Text, Password.Hashed);
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
this.Hide();
this.Close();
}
else
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
dReader.Close();
conn.Close();
}
}
}
Here is the password class:
public static string Hashed
{
get;
set;
}
Any help would be appreciated and your answer much appreciated!
Thank you so much.
EDITED:
My database looks like this:
That password was hashed (salt) and my original password that I use for the login is Kaoru. That password was generated from original password, which is Kaoru
Try the following code:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType] FROM [Member] WHERE [Username] = #Username";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
bool isValidPassword = false;
if (dReader.Read())
{
string password = (string)dReader["Password"];
bool isValidPassword = BCrypt.CheckPassword(this.textBox2.Text, password);
if (isValidPassword)
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
this.Hide();
this.Close();
}
}
if (!isValidPassword)
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
}
}
}

Categories