Not sure how to 'call' the variable - c#

I have 3 methods, called getUserID, getgazeID and updateHeatmapURL
This is getUserID
private static int getUserID()
{
int returnValue = -1;
try
{
TextReader tr = new StreamReader("C:\\Users\\L31304\\Desktop\\user.txt");
string checkedSubject = tr.ReadLine();
tr.Close();
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = checkedSubject;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue for User-" + returnValue);
return returnValue;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return returnValue;
}
}
This is getgazeID
private static int getgazeID(int userID)
{
int returnValueGaze = -1;
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "SELECT gazeID from gazeperiod WHERE userID = #userID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
returnValueGaze = (int)selectGaze.ExecuteScalar();
Console.WriteLine("returnValue for Gaze-" + returnValueGaze);
return returnValueGaze;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception for gazePeriod-" + e.ToString());
return returnValueGaze;
}
}
and this is updateheatmapURL
private static int updateHeatmapURL()
{
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "UPDATE gazeperiod(heatmapURL) VALUES (#heatmapURL) WHERE userID = #userID AND gazeID = #gazeID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = dlg.FileName;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = gazeID;
selectGaze.ExecuteScalar();
Console.WriteLine("heatmapURL - " + dlg.FileName);
}
catch (Exception e)
{
Console.WriteLine("Exception for heatmapURL-" + e.ToString());
}
}
And this is where dlg comes from.
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
dlg.Filter = "JPEG Format - jpg|*.jpg|Bitmap Format - bmp|*.bmp|Graphics Interchange Format - gif|*.gif|Portable Networks Graphic - png|*.png|Tag Image File Format - tif|*.tif|Windows MetaFile Format - wmf|*.wmf";
dlg.FileName = "*.jpg";
dlg.AddExtension = true;}
However, the userID, gazeID and dlg.FileName says:
'the name does not exist in the current context.'
How do I call it in updateURL so that it exists?
public static bool ExportImageToFile(Image image)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "Please enter filename for image...";
dlg.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
//dlg.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "new_folder2");
bool saveToServer = false;
//check....
if (System.IO.File.Exists("C:\\Users\\L31304\\Desktop\\user.txt"))
{
dlg.InitialDirectory = #"\\111.11.111.111\c$\Users\L31303\person\EyeTrackerWeb\WebContent\uploadheatmap";
saveToServer = true;
}
//set bool to true
//end if
dlg.Filter = "JPEG Format - jpg|*.jpg|Bitmap Format - bmp|*.bmp|Graphics Interchange Format - gif|*.gif|Portable Networks Graphic - png|*.png|Tag Image File Format - tif|*.tif|Windows MetaFile Format - wmf|*.wmf";
dlg.FileName = "*.jpg";
dlg.AddExtension = true;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
ImageFormat format;
switch (dlg.FilterIndex)
{
case 1:
format = ImageFormat.Jpeg;
break;
case 2:
format = ImageFormat.Bmp;
break;
case 3:
format = ImageFormat.Gif;
break;
case 4:
format = ImageFormat.Png;
break;
case 5:
format = ImageFormat.Tiff;
break;
case 6:
format = ImageFormat.Wmf;
break;
default:
format = ImageFormat.Jpeg;
break;
}
try
{
image.Save(dlg.FileName, format);
Console.WriteLine("file name is" + dlg.FileName);
if (saveToServer == true)
{
connectDB();
OpenConnection();
int userID = getUserID();
int gazeID = getgazeID(userID);
CloseConnection();
}
else
{
}
//if bool == true, then do the following
//select userID from user table WHERE name is name from text file
//select gazePeriodID from gazePeriod where userID the above selected userID
//update image path to gazePeriod in heatmapimage
//delete text file
}
catch (Exception ex)
{
VGExceptionMethods.HandleException(ex);
return false;
}
}
return true;
}
private static int getUserID()
{
int returnValue = -1;
try
{
TextReader tr = new StreamReader("C:\\Users\\L31304\\Desktop\\user.txt");
string checkedSubject = tr.ReadLine();
tr.Close();
MySqlCommand selectUser = new MySqlCommand();
selectUser.Connection = c;
selectUser.CommandText = "SELECT userID from user WHERE name= #personName";
selectUser.CommandType = CommandType.Text;
selectUser.Parameters.Add("#personName", MySqlDbType.VarChar).Value = checkedSubject;
returnValue = (int)selectUser.ExecuteScalar();
Console.WriteLine("returnValue for User-" + returnValue);
return returnValue;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception-" + e.ToString());
return returnValue;
}
}
private static int getgazeID(int userID)
{
int returnValueGaze = -1;
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "SELECT gazeID from gazeperiod WHERE userID = #userID";
selectGaze.CommandType = CommandType.Text;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
returnValueGaze = (int)selectGaze.ExecuteScalar();
Console.WriteLine("returnValue for Gaze-" + returnValueGaze);
return returnValueGaze;
}
catch (Exception e)
{
Console.WriteLine("returnValue Exception for gazePeriod-" + e.ToString());
return returnValueGaze;
}
}
public class Form1 : Form
{
private static Form1 _instance;
public Form1()
{
this.InitializeComponent();
_instance = this;
}
private static int updateHeatmapURL()
{
try
{
MySqlCommand selectGaze = new MySqlCommand();
selectGaze.Connection = c;
selectGaze.CommandText = "UPDATE gazeperiod(heatmapURL) VALUES (#heatmapURL) WHERE userID = #userID AND gazeID = #gazeID";
selectGaze.CommandType = CommandType.Text;
var userID = getUserID();
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = _instance.dlg.FileName;
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userID;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userID);
selectGaze.ExecuteScalar();
Console.WriteLine("heatmapURL - " + _instance.dlg.FileName);
}
catch (Exception e)
{
Console.WriteLine("Exception for heatmapURL-" + e.ToString());
}
}
}
The class is
public class Images
{
private static MySqlConnection c;
private static string server;
private static string database;
private static string uid;
private static string password;

Try this
//update these lines in updateHeatmapURL mthod
// dlg.File name is not accessable because updateHeatmapURL method is static
// use instance to access dlg or remove static, if you remove static then you need to remove it from other two methods as well
var userId = getUserID();
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userId;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userId);
EDIT
public class Form1 : Form
{
private static Form1 _instance;
public Form1()
{
InitializeComponent();
_instance = this;
}
private static int updateHeatmapURL()
{
...
selectGaze.Parameters.Add("#heatmapURL", MySqlDbType.VarChar).Value = _instance.dlg.FileName;
var userId = getUserID();
selectGaze.Parameters.Add("#userID", MySqlDbType.Int64).Value = userId;
selectGaze.Parameters.Add("#gazeID", MySqlDbType.Int64).Value = getgazeID(userId);
...
}
}

Related

OleDbDataReader = null

I'm currently building a program which stores messages between users in a database and returns these messages to the user when the button below gets pressed. I'm using a SQL CE database using a OleDbConnection and using a DataReader.
private void button3_Click(object sender, EventArgs e)
{
string [] lec_name = new string [10] ;
string [] content = new string [10] ;
string conn = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\Users\\Leon\\Admin.sdf";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Contact_DB WHERE Student_ID =" + iD + " AND Direction = '" + "To the student" + "'";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
}
OleDbDataReader reader = command.ExecuteReader();
int up = 0;
int count = 0;
while (reader.Read())
{
lec_name[up] = reader["Lecturer_Name"].ToString();
content[up] = reader["Description"].ToString();
up++;
MessageBox.Show("The lecturer " + lec_name[count] + " has messaged you saying :" + "\n" + content[count]);
count++;
}
}
This code works for my Student class but when I reuse the code with minor changes within the Lecturer class the OledbDataReader says null, anyone know why?
Btw the values being returned aren't null the reader itself is null.
Below is the non working code.
private void button2_Click(object sender, EventArgs e)
{
string [] studentID = new string [10] ;
string [] content = new string [10] ;
string conn = "Provider=Microsoft.SQLSERVER.CE.OLEDB.3.5;Data Source=C:\\Users\\Leon\\Admin.sdf";
OleDbConnection connection = new OleDbConnection(conn);
OleDbCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Contact_DB WHERE Lecturer_Name =" + full + " AND Direction = '" + "To the lecturer" + "'";
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("" + ex.Message);
}
OleDbDataReader reader1 = command.ExecuteReader();
int up = 0;
int count = 0;
while (reader1.Read())
{
studentID[up] = reader1["Student_ID"].ToString();
content[up] = reader1["Description"].ToString();
up++;
}
MessageBox.Show("The student " + studentID[count] + " has messaged you saying :" + "\n" +content[count]);
}
}
Using Reflector:
OleDbCommand.ExcuteReader:
public OleDbDataReader ExecuteReader(CommandBehavior behavior)
{
OleDbDataReader reader;
IntPtr ptr;
OleDbConnection.ExecutePermission.Demand();
Bid.ScopeEnter(out ptr, "<oledb.OleDbCommand.ExecuteReader|API> %d#, behavior=%d{ds.CommandBehavior}\n", this.ObjectID, (int) behavior);
try
{
this._executeQuery = true;
reader = this.ExecuteReaderInternal(behavior, "ExecuteReader");
}
finally
{
Bid.ScopeLeave(ref ptr);
}
return reader;
}
The CommandBehavior is
default.the reader returned by this.ExecuteReaderInternal()---- >
private OleDbDataReader ExecuteReaderInternal(CommandBehavior behavior, string method)
{
OleDbDataReader dataReader = null;
OleDbException previous = null;
int num2 = 0;
try
{
object obj2;
int num;
this.ValidateConnectionAndTransaction(method);
if ((CommandBehavior.SingleRow & behavior) != CommandBehavior.Default) behavior |= CommandBehavior.SingleResult;
switch (this.CommandType)
{
case ((CommandType) 0):
case CommandType.Text:
case CommandType.StoredProcedure:
num = this.ExecuteCommand(behavior, out obj2);
break;
case CommandType.TableDirect:
num = this.ExecuteTableDirect(behavior, out obj2);
break;
default:
throw ADP.InvalidCommandType(this.CommandType);
}
if (this._executeQuery)
{
try
{
dataReader = new OleDbDataReader(this._connection, this, 0, this.commandBehavior);
switch (num)
{
case 0:
dataReader.InitializeIMultipleResults(obj2);
dataReader.NextResult();
break;
case 1:
dataReader.InitializeIRowset(obj2, ChapterHandle.DB_NULL_HCHAPTER, this._recordsAffected);
dataReader.BuildMetaInfo();
dataReader.HasRowsRead();
break;
case 2:
dataReader.InitializeIRow(obj2, this._recordsAffected);
dataReader.BuildMetaInfo();
break;
case 3:
if (!this._isPrepared) this.PrepareCommandText(2);
OleDbDataReader.GenerateSchemaTable(dataReader, this._icommandText, behavior);
break;
}
obj2 = null;
this._hasDataReader = true;
this._connection.AddWeakReference(dataReader, 2);
num2 = 1;
return dataReader;
}
finally
{
if (1 != num2)
{
this.canceling = true;
if (dataReader != null)
{
dataReader.Dispose();
dataReader = null;
}
}
}
}
try
{
if (num == 0)
{
UnsafeNativeMethods.IMultipleResults imultipleResults = (UnsafeNativeMethods.IMultipleResults) obj2;
previous = OleDbDataReader.NextResults(imultipleResults, this._connection, this, out this._recordsAffected);
}
}
finally
{
try
{
if (obj2 != null)
{
Marshal.ReleaseComObject(obj2);
obj2 = null;
}
this.CloseFromDataReader(this.ParameterBindings);
}
catch (Exception exception3)
{
if (!ADP.IsCatchableExceptionType(exception3)) throw;
if (previous == null) throw;
previous = new OleDbException(previous, exception3);
}
}
}
finally
{
try
{
if (dataReader == null && 1 != num2) this.ParameterCleanup();
}
catch (Exception exception2)
{
if (!ADP.IsCatchableExceptionType(exception2)) throw;
if (previous == null) throw;
previous = new OleDbException(previous, exception2);
}
if (previous != null) throw previous;
}
return dataReader;
}
this._executeQuery wraps the new instance of OleDbDataReader, if it doesn't run the dataReader will be null.
The only way the reader is returned as null is if the internal RunExecuteReader method is passed 'false' for returnStream, which it isn't.
Here is the only place where this._executeQuery is set to false, but this one is not called in parallel because of Bid.ScopeEnter and Bid.ScopeLeave.
public override int ExecuteNonQuery()
{
int num;
IntPtr ptr;
OleDbConnection.ExecutePermission.Demand();
Bid.ScopeEnter(out ptr, "<oledb.OleDbCommand.ExecuteNonQuery|API> %d#\n", this.ObjectID);
try
{
this._executeQuery = false;
this.ExecuteReaderInternal(CommandBehavior.Default, "ExecuteNonQuery");
num = ADP.IntPtrToInt32(this._recordsAffected);
}
finally
{
Bid.ScopeLeave(ref ptr);
}
return num;
}
Theoretically the data reader can be null if the query cannot be executed.
UPDATE:
https://github.com/Microsoft/referencesource/blob/master/System.Data/System/Data/OleDb/OleDbCommand.cs#L658

Issues with mysql in c#

I have a small problem with connecting c# with a mysql database. When im trying to insert a value from a textbox i get the error below. I was wondering if someone could help me/ explain to me what im doeing wrong.
This is the error that i'm getting:
Unknown column 'test' in 'field list'
This is my code for connecting to the database:
namespace Planner
{
internal class DBConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
private string _database;
private string _uid;
private string _password;
//private string _port;
//private bool succes = false;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
public void Initialize()
{
string connectionString2 = "Server=localhost;Port=3307;Database=test;Uid=root;Pwd=usbw";
//+ "Port:" + _port + ";"
_server = "localhost:3307";
//_port = "3307";
_database = "test";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString2);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
private List<string>[] Select()
{
string selectquery = "SELECT * FROM tabelname";
List<string>[] selectlist = new List<string>[3];
selectlist[0] = new List<string>();
selectlist[1] = new List<string>();
selectlist[2] = new List<string>();
MySqlCommand cmd = new MySqlCommand(selectquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
selectlist[0].Add(dataReader["waarde"] + "");
selectlist[1].Add(dataReader["waarde"] + "");
selectlist[2].Add(dataReader["waarde"] + "");
}
dataReader.Close();
return selectlist;
}
public void Insert(string textvalue)
{
string insertquery = "INSERT INTO testconnectie(text) VALUES ("+textvalue+")";
MySqlCommand cmd = new MySqlCommand(insertquery, _connection);
cmd.ExecuteNonQuery();
}
private void Update()
{
string updatequery = "UPDATE tabelnaam SET waarde='', waarde'' WHERE waarde=''";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = updatequery;
cmd.Connection = _connection;
cmd.ExecuteNonQuery();
}
private void Delete()
{
string deletequery = "DELETE FROM tabelnaam WHERE waarde=''";
MySqlCommand cmd = new MySqlCommand(deletequery, _connection);
cmd.ExecuteNonQuery();
}
public bool CloseConnection()
{
try
{
_connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
public void Backup()
{
try
{
DateTime Time = DateTime.Now;
int year = Time.Year;
int month = Time.Month;
int day = Time.Day;
int hour = Time.Hour;
int minute = Time.Minute;
int second = Time.Second;
int millisecond = Time.Millisecond;
//Save file to C:\ with the current date as a filename
string path;
path = "C:\\ChatBackup" + year + "-" + month + "-" + day +
"-" + hour + "-" + minute + "-" + second + "-" + millisecond + ".sql";
StreamWriter file = new StreamWriter(path);
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "Database Backup";
psi.RedirectStandardInput = false;
psi.RedirectStandardOutput = true;
psi.Arguments = string.Format(#"-u{0} -p{1} -h{2} {3}",
_uid, _password, _server, _database);
psi.UseShellExecute = false;
Process process = Process.Start(psi);
string output;
output = process.StandardOutput.ReadToEnd();
file.WriteLine(output);
process.WaitForExit();
file.Close();
process.Close();
}
catch (IOException ex)
{
MessageBox.Show("Error , unable to backup! " + ex);
}
}
}
}
Mainform
namespace Planner
{
public partial class MainForm : Form
{
private DBConnect mysql = new DBConnect();
public MainForm()
{
InitializeComponent();
mysql.Initialize();
mysql.OpenConnection();
}
private void _sendMessageButton_Click(object sender, System.EventArgs e)
{
string textvalue = _messageTextBox.Text;
mysql.Insert(textvalue);
}
}
}
Can someone explain to my what im doeing wrong, thanks in advance.
you miss single quote, use like this
string insertquery = "INSERT INTO testconnectie(text) VALUES ('"+textvalue+"')";
use parameters: it is safe and you can avoid most of the exceptions like you currently get
string insertquery = "INSERT INTO YourTableName ([yourColumnName]) VALUES (#ParameterName)";
using (var con = new MySqlConnection(connectionString))
using (var cmd = new MySqlCommand(insertquery, con))
{
cmd.Parameters.AddWithValue("#ParameterName", textvalue);
con.Open();
cmd.ExecuteNonQuery();
}

Issues with the c# datarow

I have a small problem with the c# DataRow Command in my code. Because when im trying to loop trough my mysql database and i have the foreach like this:
foreach (DataRow row in _login._database)
{
//And search for Username and Pass that match
if (row.ItemArray[0].Equals(username) && row.ItemArray[1].Equals(password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
break;
}
//If not, then show this message.
else
{
MessageBox.Show("Username/Password incorrect");
break;
}
}
This error will come up:
Error 1 Cannot convert type 'char' to 'System.Data.DataRow'
Can someone help/explain to me what im doeing wrong.
This is the rest of the code:
namespace Chat
{
public partial class StartupForm : Form
{
private LoginConnect _login = new LoginConnect();
public StartupForm()
{
InitializeComponent();
_login.OpenConnection();
}
private void _loginButton_Click(object sender, EventArgs e)
{
string username = _usernameTextBox.Text;
string password = HashPass(_passwordTextBox.Text);
//Loop through database
foreach (DataRow row in _login._database)
{
//And search for Username and Pass that match
if (row.ItemArray[0].Equals(username) && row.ItemArray[1].Equals(password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
break;
}
//If not, then show this message.
else
{
MessageBox.Show("Username/Password incorrect");
break;
}
}
_login.LoginQuery(username, password);
}
private void button1_Click(object sender, EventArgs e)
{
var register = new RegisterForm();
register.ShowDialog();
}
public string HashPass(string password)
{
MD5 mdvijf = new MD5CryptoServiceProvider();
//compute hash from the bytes of text
mdvijf.ComputeHash(ASCIIEncoding.ASCII.GetBytes(password));
//get hash result after compute it
byte[] result = mdvijf.Hash;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
//change it into 2 hexadecimal digits
//for each byte
strBuilder.Append(result[i].ToString("x2"));
}
return strBuilder.ToString();
}
}
}
LoginCOnnect.cs:
namespace Chat
{
class LoginConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
public string _database;
private string _uid;
private string _password;
//public String MessageRecieved;
private StringList _messagelist = new StringList();
//private string _table = "logingegevens";
private string _port;
//private bool succes = false;
public LoginConnect()
{
Initialize();
}
public void Initialize()
{
_server = "localhost";
_port = "3307";
_database = "testlogin";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
public void LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
int count = 0;
while (dataReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Login Succesfull");
}
else if (count > 1)
{
MessageBox.Show("Acces denied");
}
else
{
MessageBox.Show("Username or passowrd is not correct.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The problem is that in this statement
foreach (DataRow row in _login._database)
you are looping through a string, and so the enumeration of _login._database is an IEnumerable of chars and not of DataRow, so row variable would be a char and not a DataRow.
I suggest you to retrieve the data into an internal DataTable, your LoginConnect code would be like this:
namespace Chat
{
class LoginConnect
{
private MySqlConnection _connection = new MySqlConnection();
private string _server;
public string _database;
private string _uid;
private string _password;
private StringList _messagelist = new StringList();
private string _port;
private DataTable _dataTable;
public LoginConnect()
{
Initialize();
}
public DataTable Data
{ get { return _dataTable; } }
public void Initialize()
{
_server = "localhost";
_port = "3307";
_database = "testlogin";
_uid = "root";
_password = "usbw";
string connectionString = "Server=" + _server + ";" + "Port=" + _port + ";" + "Database=" +
_database + ";" + "Uid=" + _uid + ";" + "Pwd=" + _password + ";";
_connection = new MySqlConnection(connectionString);
}
public bool OpenConnection()
{
try
{
_connection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server");
break;
case 1042:
MessageBox.Show("Unable to connect to any of the specified MySQL hosts");
break;
case 1045:
MessageBox.Show("Invalid username/password");
break;
}
return false;
}
}
public void LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
_dataTable = new DataTable();
adp.Fill(_dataTable);
var count = _dataTable.Rows.Count;
}
catch{}//your handling
}
}
}
So you can loop through Data:
foreach (DataRow row in _login.Data.AsEnumerable())
THis line is wrong: (DataRow row in _login._database because _database is type of string. You have to iterate over something that have DataRow like DataTable.
Anyway I would change your code to this:
private void _loginButton_Click(object sender, EventArgs e)
{
string username = _usernameTextBox.Text;
string password = HashPass(_passwordTextBox.Text);
if (_login.LoginQuery(username, password))
{
_usernameTextBox.Text = String.Empty;
_passwordTextBox.Text = String.Empty;
MessageBox.Show("Login Success");
}
else
{
MessageBox.Show("Username/Password incorrect");
}
}
and LoginCOnnect.cs method LoginQuery to return bool
public bool LoginQuery(string username, string password)
{
string loginquery = "SELECT * FROM logingegevens WHERE Username='" + username + "'AND Password='" + password + "';";
try
{
MySqlCommand cmd = new MySqlCommand(loginquery, _connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
int count = 0;
while (dataReader.Read())
{
count = count + 1;
}
if (count == 1)
{
return true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return false;
}

C# Error using Base64 convert on hash

Basically I am getting a saved hash (converted to base64) from an access database and comparing it (after converting it back) with another and should return true if they match, but for some reason it returns false. There is data in the database. I think the problem occurs when the hash is converted back from base64. Can anyone see what I am doing wrong?
private static bool MatchSHA(byte[] p1, byte[] p2)
{
bool result = false;
if (p1 != null && p2 != null)
{
if (p1.Length == p2.Length)
{
result = true;
for (int i = 0; i < p1.Length; i++)
{
if (p1[i] != p2[i])
{
result = false;
break;
}
}
}
}
return result;
}
private static byte[] GetSHA(string userID, string password)
{
SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();
return sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(userID + password));
}
public void RunTest()
{
string userId = "test";
string password = "Password";
string enteredPassword = "Password";
var hashedPassword = GetSHA(userId, password);
string encodedPassword = Convert.ToBase64String(hashedPassword);
try
{
string connString = (#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|Password.accdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId";
cmd.Parameters.AddWithValue("#UserId", userId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var compareHash = Convert.FromBase64String(dbReader["Password"].ToString());
errorLabel.Text = "Hash from DB: " + dbReader["Password"].ToString();
if (MatchSHA(compareHash, GetSHA(userId, enteredPassword)))
{
loginLabel.Text = "EnteredPassword. True";
}
else
{
loginLabel.Text = "EnteredPassword. False";
}
}
conn.Close();
}
catch (OleDbException obe)
{
errorLabel.Text = obe.ToString();
}
}

creating a search button

I want to create a button on my c# form and when I type in a clients id or surname and I press the search button, it should display all his info on the c# form.
This is not working, a message box displays 'clientid' when the button is clicked.
Code in Class
public bool searchpersonDetails(string personid, string personname)
{
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
conn.ConnectionString = "Data Source=pc101;Initial Catalog=REMITTANCE;User ID=sa;Password=mike";
conn.Open();
if (personid == null)
{
Fom1 frm = new Fom1();
frm.ShowDialog();
personid = client_id;
}
SqlCommand cmd = new SqlCommand();
string sqlQuery = null;
//sqlQuery = "select *,floor(datediff(curdate(),dateofbirth)/365) AS AGE from tblspersonaldetails where client_id='" + personid + "'";
sqlQuery = "select * from tblspersonaldetails where client_id='" + personid + "'";
cmd.Connection = conn;
cmd.CommandText = sqlQuery;
cmd.CommandType = System.Data.CommandType.Text;
SqlDataReader dr = null;
dr = cmd.ExecuteReader();
if (dr.Read())
{
client_id = dr["clientid"].ToString();
surname = dr["surname"].ToString();
othername = dr["othername"].ToString();
gender = dr["gender"].ToString();
date_ofbirth = (DateTime) dr["dateofbirth"];
nationality = dr["nationality"].ToString();
//age = dr["Age"];
residential_address = dr["residentialaddress"].ToString();
postal_address = dr["postaladdress"].ToString();
contact_number = dr["telephonenumber"].ToString();
marital_status = dr["maritalstatus"].ToString();
spouse_name = dr["spousename"].ToString();
email = dr["email"].ToString();
occupation = dr["occupation"].ToString();
typeof_id = dr["typeofid"].ToString();
id_number = dr["idnumber"].ToString();
id_expirydate = (DateTime) dr["idexpirydate"];
remarks = dr["remarks"].ToString();
picture = dr["picture"].ToString();
return true;
cmd.CommandText = null;
}
else
{
return false;
}
conn.Close();
}
And codes behind
private void lklSearch_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
conn.ConnectionString = "Data Source=pc101;Initial Catalog=REMITTANCE;User ID=sa;Password=mike";
conn.Open();
try
{
Personal person = new Personal();
if (person.searchpersonDetails(txtClientid.Text, txtSurname.Text))
{
var
_with3 = this;
txtClientid.Text = person.ID.ToString();
_with3.txtSurname.Text = person.Sname.ToString();
_with3.txtOthername.Text = person.Oname.ToString();
if (person.sex.ToString() == "Male")
{
optMale.Checked = true;
}
else
{
optFemale.Checked = true;
}
_with3.dtpDob.Value = person.BirthDate;
_with3.txtNationality.Text = person.country.ToString();
_with3.txtResidentialaddress.Text = person.addressResidential.ToString();
_with3.txtPostaladdress.Text = person.AddressPostal.ToString();
_with3.txtContactnumber.Text = person.NumberContact.ToString();
string mstatus = person.statusMarital.ToString();
switch (mstatus)
{
case "Single":
this.cboMaritalstatus.Text = "Single";
break;
case "Married":
_with3.cboMaritalstatus.Text = "Married";
break;
case "Widow(er)":
_with3.cboMaritalstatus.Text = "Widow(er)";
break;
case "Divorce":
_with3.cboMaritalstatus.Text = "Divorce";
break;
}
_with3.txtSpousename.Text = person.nameSpouse.ToString();
_with3.txtEmail.Text = person.mail.ToString();
_with3.txtOccupation.Text = person.Work.ToString();
string iType = person.idtype.ToString();
switch (iType)
{
case "Bank ID Card":
this.cboIdtype.Text = "Bank ID Card";
break;
case "Driver Licence":
_with3.cboIdtype.Text = "Driver Licence";
break;
case "Passport":
_with3.cboIdtype.Text = "Passport";
break;
case "National Identification":
_with3.cboIdtype.Text = "National Identification";
break;
case "NHIS":
_with3.cboIdtype.Text = "NHIS";
break;
case "SSNIT":
_with3.cboIdtype.Text = "SSNIT";
break;
case "Voters ID":
_with3.cboIdtype.Text = "Voters ID";
break;
}
_with3.txtIdnumber.Text = person.numberID.ToString();
_with3.dtpExpiringdate.Value = person.expirydateID;
_with3.txtRemarks.Text = person.myremarks.ToString();
btnPUpdate.Enabled = true;
/// this.txtChurchID.Text = this.txtID.Text;
///this.txtChurchID.ReadOnly = true;
person.searchpersonDetails(txtClientid.Text = "", txtSurname.Text = "");
}
else
{
MessageBox.Show("Record not found");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// Close data reader object and database connection
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
Is it Client_id or 'Clientid' in your database? In your query, you mentioned:
sqlQuery = "select * from tblspersonaldetails where client_id='" + personid + "'";
A few lines down, and you have:
client_id = dr["clientid"].ToString();
You should either change query to Clientid or change the code to dr[client_id] (depending on what the column name is in your database.

Categories

Resources