C# Logging in system only works with first value of database - c#

I'm a beginner to C# so help would be much appreciated. I'm attempting to code a logging in system but I can only successfully log in with the first line of data (username=admin , password=admin). I can't seem to log in from other data in the database (username=bryan , password=123). This is the code.
searchOLEDB.CommandText = "SELECT * FROM LOGIN where Username='" + LoginIDTextBox.Text + "' AND Password='" + LoginPasswordTextBox.Text + "'";
searchOLEDB.Connection = cnnOLEDB;
OleDbDataReader dr = searchOLEDB.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Logged In");
}
else
{
MessageBox.Show("Invalid Password");
}
dr.Close();

First, you should never concatenate sql query like you did. This will allow SQL Injection. You should use parameters.
See this post for examples :
using parameters inserting data into access database
P.S. I would also recommend to not store password in clear into your database.

Related

How to create a login form using a XAMPP database and C#?

string query = "SELECT * FROM staff";
string mySQLConnectionString = "datasource=127.0.0.1;port=3306;username=root;password=;database=workshopdb;sslmode=none";
MySqlConnection databaseConnection = new
MySqlConnection(mySQLConnectionString);
MySqlCommand commandDatabase = new MySqlCommand(query, databaseConnection);
databaseConnection.Open();
MySqlDataReader myReader = commandDatabase.ExecuteReader();
if (myReader.HasRows) //checks whether the table is empty
{
while (myReader.Read()) //reads rows consequently
{
MessageBox.Show(myReader.GetString(0) + " " + myReader.GetString(1) + " " + myReader.GetString(3));
//get strings(x) are columns of the table in the db
}
}
databaseConnection.Close();
}
I used this code but It doesn't recognize the username and password that I entered. Instead of recognizing the entered user it shows all users in the database.
In C#, building platform is .NET. Most of the time we can use MSSQL for DB activities. To Configure we can use MSSQL Server Express. XAMPP runs on Apache server. But for the .NET development we need IIS server. At your end arise conflicts. Do more research abourt what are you doing and get know about the dependent technologies

Issue with comparing data in sqldatareader to log in details C# (Newbie)

I'm having an issue with an if statement in my code which for the life of me I can't figure out why the condition isn't coming back true.
private bool ValidationFunction(string UserName, string Password)
{
bool returnBool = false;
var strConnection = ConfigurationManager.ConnectionStrings["BankConnectionString"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(strConnection);
string query = "SELECT " + COLUMN_ID + ", " + COLUMN_MACHINEPIN + " FROM " + PERSON_TABLE + " WHERE " + COLUMN_ID + " = \'" + UserName + "\' AND " + COLUMN_MACHINEPIN + " = \'" + Password + "\'";
SqlCommand command = new SqlCommand(query, sqlConnection);
SqlDataReader rdr;
sqlConnection.Open();
rdr = command.ExecuteReader();
while(rdr.Read())
{
if (UserName == rdr["Id"].ToString() & Password == rdr["MachinePin"].ToString())
{
returnBool = true;
}
return returnBool;
}
rdr.Close();
return returnBool;
}
I have tried using both the name of the column and the constant I used in the query but neither works and I can't quite get it work. Any help would be appreciated
EDIT: Turns out that the data I was retrieving from the database had extra white space because I had used an nchar so I had to use the trim function.
You should use && not &.
& is a bit-wise "AND", meaning that it works on the bit level, whereas && is a logical "AND" meaning it works at boolean (true/false) level.
I'd also clean up your code a bit. By not parameterizing your inputs, you are opening yourself up to SQL Injection attacks.
You can also wrap your disposable objects in using blocks. It will make your code cleaner and more readable.
using (var conn = new SqlConnection("your connection"))
{
using (var cmd = new SqlCommand(sql, conn))
{
conn.Open();
using (var rdr = cmd.ExecuteReader())
{
...
}
}
}
Try this:
var username = rdr["Id"].ToString()
var password = rdr["MachinePin"].ToString())
Debugger.Break();
At the debugger statement open up the immediate windows and manually type in the comparisons until you determine root cause.
UserName==username;
Password = password;
Debuging Tips
Do you know how to open the Immediate Window? Go to Debug/Windows/Immediate. It allows you to type in C# statement at the debug point.
No Data can be read
If rdr["Id"] cannot be read e.g InvalidOperation etc. Then you have one of the following issues:
Connection string never opened connection
Wrong Database/Table
Incorrect Field Name
Security failure.
You should check status codes for each of your steps, if you are not seeing anything then this is most likely a security issue because banks don't advertise what went wrong (makes sense don't tell hackers anything).
Security Issue
If it's security issue you have to drop down to wire level. Take a trace and look at the Return codes. The other side will Fin the session first. You should see a security layer handshake prior to open communications, if that handshake doesn't work the session is immediately terminated with no further detail.
Tracing
Wireshark is simple to use, quick to download and shows everything on the wire. Use Wireshark to further dive into things the application layer cannot see.
Try the below:
if ((UserName == (string)rdr["Id"]) && (Password == (string)rdr["MachinePin"]))
{
returnBool = true;
}

Error when using insert in access: Could not Update; currently locked

I have a WebService that updates my access table from some terminals (10).
When I try to update I get this error from the error log:
Could not Update; Currently locked
Some terminals succeed and some do not.
I update like this:
using (Conn = new OleDbConnection(Work_Connect))
{
Conn.Open();
foreach (DataRow R in ds.Tables["MyCount"].Rows)
{
U_ID = ID;
U_Bar = R["Bar"].ToString().Trim();
U_Qty = R["Qty"].ToString().Trim();
U_Des = R["Des"].ToString().Trim();
SQL = "INSERT INTO MyTbl(ID,Bar,Qty,Des)VALUES('";
SQL += Convert.ToInt32(ID) + "','" + U_Bar + "','" + Convert.ToDouble(U_Qty) + "','" + U_Des + "')";
OleDbCommand Cmd2 = new OleDbCommand(SQL, Conn);
Cmd2.CommandText = SQL;
Cmd2.ExecuteNonQuery();
}
}
GC.Collect();
return true;
MsAccess has serious drawbacks for multi-user update. The Jet engine is not a database server, and will manage concurrence based on file system locking. If your problem is with a web service, I'd move the update to the server part, and implement queuing of simultaneous requests there. Thus, only the server, one process, will have access to the Access data. The other option is to use a real database server that will do that work for you. SQL Server Express is the usual option because it's easy to integrate, it's free as in beer, and is solid.
Also, if your problem happens always from the same terminals, that is, some terminals can never update anything, check the file access rights of these terminals' users to the database file, the lock file, and the database and lock file directory. Write rights are required for all of them.
Suggestions:
Convert your query to a parameterized query to avoid any potential strangeness with quoting. (You are converting text to numbers and then enclosing them in single-quotes in the SQL statement. That makes no sense.)
Don't force garbage collection on each call. According to the MSDN article here: "It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues."
Try something like this instead:
using (Conn = new OleDbConnection(Work_Connect))
{
Conn.Open();
foreach (DataRow R in ds.Tables["MyCount"].Rows)
{
U_ID = ID;
U_Bar = R["Bar"].ToString().Trim();
U_Qty = R["Qty"].ToString().Trim();
U_Des = R["Des"].ToString().Trim();
SQL = "INSERT INTO MyTbl (ID,Bar,Qty,Des) VALUES (?,?,?,?)";
using(OleDbCommand Cmd2 = new OleDbCommand(SQL, Conn))
{
// Cmd2.CommandText = SQL; redundant, the 'new' set the .CommandText
Cmd2.Parameters.AddWithValue("?", Convert.ToInt32(ID));
Cmd2.Parameters.AddWithValue("?", U_Bar);
Cmd2.Parameters.AddWithValue("?", Convert.ToDouble(U_Qty));
Cmd2.Parameters.AddWithValue("?", U_Des);
Cmd2.ExecuteNonQuery();
}
}
Conn.Close();
}
// GC.Collect(); // disabled for test purposes
return true;

using Service Based Database in VS2010 Ultimate

I have been working on a project related to database (.mdf). I have created some windows forms in visual studio using C#. Basically these forms work together to store, update and delete data from the Service Based Database i created.
The problem is when i build the project, it builds fine, no errors. It inserts a data provided from textboxes to the datagridview too as intended. But as soon as i stop the current debugging, and then rerun it again, all the data provided previously is lost from the datagridview!!
I cant understand why this is happening. anyone please help me. Im totally new to this stuff.. a bit of guidance would be heartily appreciated.
when i had previously used MySQL for the same purpose, the updated data would be permanently stored to the database, but since i migrated from the MySQL to SQL Server's Service Based Database, i get such confusing error.
......
void loadData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT SNo,Customer_ID, Citizenship_No, Name, Subscription_Date, Phone_No, Location,Locality,Bulbs,Deposit,Monthly_Charge FROM customerinformation;", con);
try
{
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewCustomerInformation.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
try
{
float m_chrg = Convert.ToInt64(textBoxBulbs.Text)*500;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO customerinformation(SNo,Customer_ID,Citizenship_No,Name,Subscription_Date,Location,Locality,Bulbs,Deposit,Phone_No,Monthly_Charge) values('" + textBoxSNo.Text + "','" + textBoxCustomerID.Text + "','" + textBoxCitizenshipNumber.Text + "','" + textBoxName.Text + "','" + textBoxSubscriptionDate.Text + "','" + textBoxLocation.Text + "','" + textBoxLocality.Text + "','" + textBoxBulbs.Text + "','" + textBoxDeposit.Text + "','" + textBoxPhoneNumber.Text + "','" + m_chrg + "')", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
dataGridViewCustomerInformation.DataSource = dt;
loadData();
MessageBox.Show("Entry Added!");
fillListbox();
textBoxSNo.Clear();
textBoxBulbs.Clear();
textBoxCitizenshipNumber.Clear();
textBoxCustomerID.Clear();
textBoxDeposit.Clear();
textBoxLocality.Clear();
textBoxLocation.Clear();
textBoxPhoneNumber.Clear();
textBoxName.Clear();
textBoxSubscriptionDate.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you have your MDF listed in your project files then the property Copy To Output Directory handles how your MDF file is copied to the output directory (BIN\DEBUG or BIN\RELEASE).
If this property is set to Copy Always, then when you run your program a fresh copy of your database file is copied from the project folder to the output effectively destroying every data that you have inserted, modified, deleted in the previous run of your program.
The best solution to this dilemma is to add the MDF file as a permanent database inside your current install of Sql Server and adjust your connection string. And of course set the property to Copy Never
In alternative you could set to Copy if newer. This will allow to change the database schema inside the Server Explorer and let the Visual Studio IDE copy the new structure only after you have made changes.
UPDATE BUT IMPORTANT Not related to your actual question, but your insert query is a serious problem. Do not use string concatenation to build a sql command text. Particularly if the partial text comes from user input. You could face syntax errors (if someone places a single quote inside a text box) or worst, a Sql Injection problem (see here for a funny explanation)
To find good examples of Insert search for 'parametrized query'

SQLite problem "unable to open the database file"

I come to you after a lot of hours googling and reading other discussions about SQLite on StackOverflow, but I definitely can't find any explanation to my problem, so here it is :
The context :
I'm developping an application for iPad wich has to deal with some "large" amounts of data, in several occasions. In one of them, I must import points coordinates from a .kml file (Google's xml for geographical data) into my database, in order to reuse them later with a MKMapView and load them faster than by parsing xml when it needs to show a specific layer.
The details :
The import thing is quite easy : when dealing with those files, I'm only concerned with 2 tables :
One containing zones definitions and details : for the moment, an integer as an id, and a text for naming.
One containing two real for coordinate storage and an integer referencing the first table for knowing which zone point is part of.
So as long as reading my file, I first create an entry for the new zone, and then I insert points into the second table, with ID of the last zone created in the first table...nothing complicated!
But...
The problem :
After running fine a while, I get an exception from SQLite with the famous message "Unable to open the database file", and then it comes I can't do anything more with the database. This exception can randomly occur in the zone creation or the points insertion methods.
My reflexions :
Considering the numerous points in those files, I suspected memory or disk saturation but other parts of my app discarded those points (to my mind).
First, memory : it comes that when the exception occurs, the app is using about 10 or 12 MB of RAM. It can seems quite huge, but it's due to the ~10MB .kml file loaded in memory, so it's explainable. And above it all, the MKMapView thing of my app deals with tons of high-res tiles layers above map, and so leads to memory peaks which can afford 20 or even 25MB without making the iPad to crash.
Second, disk : when reseting my database and filling only the 2 tables described above, the db file size when the exception occurs is always about 2.2 or 2.5MB, but when I fill other tables (the other parts of my apps works well!) the db file is about 6 or 7MB, and the device doesn't complain at all.
So what?!
CPU-angryness and panic? I don't think so because some of the other tables of my database are filled at the same rythm without problem... and running my app in simulator crashes too, with a core i7 just laughing at the job.
SQLite bad use? There we go! To my mind, it's the only solution left! But I really can't understand what's going on here because I process my requests the same way I do in other app's parts which - repeating myself - work like a charm!
SQLite details :
I have a DB class which is a singleton I use to avoid creating/releasing an SqliteConnection object each request I do, and all my methods dealing with database are contained in this class to be sure I don't play with the connection anywhere else without knowing it. Here are concerned methods of this class :
public void saveZone(ObjZone zone) { //at this point, just creates an entry with a name and let sqlite give it a new id
lock (connection) { //SqliteConnection object
try {
openConnection();
SqliteCommand cmd = connection.CreateCommand();
cmd.CommandText = zone.id == 0 ?
"insert into ZONES (Z_NAME) values (" + format(zone.name) + ") ;" :
"update ZONES set Z_NAME = " + format(zone.name) + " where Z_ID = " + format(zone.id) + " ;";
cmd.ExecuteNonQuery();
if (zone.id == 0) {
cmd.CommandText = "select Z_ID from ZONES where ROWID = last_insert_rowid() ;";
zone.id = uint.Parse(cmd.ExecuteScalar().ToString());
}
cmd.Dispose();
}
catch (Exception e) {
Log.failure("DB.saveZone(" + zone.ToString() + ") : [" + e.GetType().ToString() + "] - " +
e.Message + "\n" + e.StackTrace); //custom Console.WriteLine() method with some formating
throw e;
}
finally {
connection.Close();
}
}
}
public void setPointsForZone(List<CLLocationCoordinate2D> points, uint zone_id) { //registers points for a given zone
lock (connection) {
try {
openConnection();
SqliteCommand cmd = connection.CreateCommand();
cmd.CommandText = "delete from ZONESPOINTS where Z_ID = " + format(zone_id);
cmd.ExecuteNonQuery();
foreach(CLLocationCoordinate2D point in points) {
cmd.CommandText = "insert into ZONESPOINTS values " +
"(" + format(zi_id) + ", " + format(point.Latitude.ToString().Replace(",", ".")) + ", "
+ format(point.Longitude.ToString().Replace(",", ".")) + ");";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception e) {
Log.failure("DB.setPointsForZone(" + zone_id + ") : [" + e.GetType().ToString() + "] - " + e.Message);
throw e;
}
finally {
connection.Close();
}
}
}
And to be as clear as I can, here are some of the methods referenced in the two above (I use this custom openConnection() method because I use foreign keys constraints in most of my tables and cascading behaviours are not enabled by default, but I need them.) :
void openConnection() {
try {
connection.Open();
SqliteCommand cmd = connection.CreateCommand();
cmd.CommandText = "PRAGMA foreign_keys = ON";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception e) {
Log.failure("DB.openConnection() : [" + e.GetType().ToString() + "] - " + e.Message);
throw e;
}
}
public static string format(object o) {
return "'" + o.ToString().Replace("'", "''") + "'";
}
Well, sorry for the novel, I may already thank you for reading all that stuff, no?! Anyway, if I missed something that could be useful, let me know and I'll document it as soon as possible.
I hope someone will be able to help me, anyway, thank you by advance!
(And my apologies for my poor frenchie's english.)
EDIT
My problem is "solved"! After a few changes for debugging pourposes, no big modifications, and no success, I put back the code in the state I posted it... and now it works. But I really would appreciate if some someone could give me an explanation of what may have happened! It seems like SQLite behaviour (on iPad at least - never used it anywhere else) can be quite obscure at some times... :/
I wouldn't cross my fingers for this but I would try two things:
If possible, pre-process the KML file to a second SQLite database and use this database to import data in the main database (thinking of lower memory/processor requirements)
Transaction the imported data in small batches.
HTH
EDIT: you might have checked this already, but anyway: unable to open database.

Categories