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();
}
}
Related
I am facing the error at "GetConnectionInfo"
Private string GetConnectionInfo(string ConName)
{
string PKey;
PKey = GetKeyInfo();
System.Data.OleDb.OleDbDataReader rs;
System.Data.OleDb.OleDbConnection oCon = new System.Data.OleDb.OleDbConnection();
System.Data.OleDb.OleDbCommand oComm = new System.Data.OleDb.OleDbCommand();
string sSql;
string ConfConnection;
try
{
ConfConnection = Dts.Connections("Config").ConnectionString.ToString();
oCon.ConnectionString = ConfConnection;
oCon.Open();
sSql = "SELECT [CNCTN_NM],[USER_ID],[PSWRD_TXT],[DATA_SRC_NM],[CATLG_NM],[PRVDR_NM], [INTEGRATED_SECURITY] FROM [TDW_ETL_CONNECTSTRING] WHERE [CNCTN_NM] = '" + ConName + "'";
oComm.CommandText = sSql;
oComm.Connection = oCon;
oComm.CommandTimeout = 600;
rs = oComm.ExecuteReader();
string CNCTN_NM;
string USER_ID;
string PSWRD_TXT;
string dUSER_ID;
string dPSWRD_TXT;
string DATA_SRC_NM;
string CATLG_NM;
string PRVDR_NM;
bool INTEGRATED_SECURITY;
while (rs.Read())
{
// Get The Data from the table
CNCTN_NM = System.Convert.ToString(rs.GetValue(0));
if (rs.IsDBNull(1) == false)
USER_ID = System.Convert.ToString(rs.GetValue(1));
if (rs.IsDBNull(2) == false)
PSWRD_TXT = System.Convert.ToString(rs.GetValue(2));
DATA_SRC_NM = System.Convert.ToString(rs.GetValue(3));
CATLG_NM = System.Convert.ToString(rs.GetValue(4));
PRVDR_NM = System.Convert.ToString(rs.GetValue(5));
INTEGRATED_SECURITY = System.Convert.ToBoolean(rs.GetBoolean(6));
// Decrypt the userid and password
if (INTEGRATED_SECURITY == false)
{
dUSER_ID = DecryptTripleDES(USER_ID, PKey);
dPSWRD_TXT = DecryptTripleDES(PSWRD_TXT, PKey);
}
}
Here i am getting the error ====>
GetConnectionInfo = GenerateConnectionString(PRVDR_NM, dUSER_ID, dPSWRD_TXT, INTEGRATED_SECURITY, DATA_SRC_NM, CATLG_NM);
}
finally
{
if (!rs.IsClosed)
rs.Close();
oComm.Dispose();
oCon.Dispose();
}
}
You are trying to assign a value to a method. That is not possible.
I think what you want to achive could be something like:
string connectionInfo = GetConnectionInfo(GenerateConnectionString(PRVDR_NM, dUSER_ID, dPSWRD_TXT, INTEGRATED_SECURITY, DATA_SRC_NM, CATLG_NM));
I connected SQL server database and I using username and password value return xml boolean true. But I want to get sicilKod value according to the results of the username query. How can I do it?
This returning boolean value according to username and password
[WebMethod]
public bool login(string unamePI, string passPI)
{
DataTable mytable = new DataTable();
bool mydeger = false;
mytable = GetTableWithQueryParams("select * from UYE where USERNAME ={0} and PASSWORD={1}", unamePI, passPI);
if (mytable.Rows.Count > 0)
{
mydeger = true;
}
else
{
return mydeger;
}
string de = mytable.Rows[0].ToString();
return mydeger;
}
Database connect:
public static DataTable GetTableWithQueryParams(string SQLCommandText, params object[] myParametres)
{
string aConnectionString = "Data Source = ..; Initial Catalog = mydatabase; Persist Security Info = True; User ID = ..; Password = ..";
SqlConnection SqlConn = new SqlConnection(aConnectionString);
SqlCommand MyCommand = new SqlCommand("", SqlConn);
DataTable MyTable = new DataTable();
try
{
int i = 0;
SqlConn.Open();
foreach (object MyObject in myParametres)
{
if (SQLCommandText.Contains("{" + i.ToString() + "}"))
{
SQLCommandText = SQLCommandText.Replace("{" + i.ToString() + "}", "#Prm" + i.ToString());
MyCommand.Parameters.AddWithValue("Prm" + i.ToString(), MyObject);
i++;
}
}
MyCommand.CommandText = SQLCommandText;
SqlDataReader MyReader = MyCommand.ExecuteReader();
MyTable.Load(MyReader);
SqlConn.Close();
MyReader.Dispose();
}
catch (Exception ex)
{
throw new Exception(SQLCommandText + "\n" + ex.Message);
}
finally
{
SqlConn.Dispose();
MyCommand.Dispose();
}
return MyTable;
}
change your method to this.
public string login(string unamePI, string passPI)
{
DataTable mytable = new DataTable();
string result = "";
mytable = GetTableWithQueryParams("select * from UYE where USERNAME ={0} and PASSWORD={1}", unamePI, passPI);
if (mytable.Rows.Count > 0)
{
result = string.Format("Welcome {0}", mytable.Rows[0]["sicilKod"].ToString());
}
return result;
}
then check if login method return value is empty or not.
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);
...
}
}
Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.
Do anyone know how to insert data into database only once during runtime? because right now whenever i run my system, the data would be always inserted into the database. its there any way just to insert the data only once even if i have run the program for many times?Here are my codes
public async void getUserName()
{
LiveConnectClient client = new LiveConnectClient(session);
LiveOperationResult operationResultUserID = await client.GetAsync("me");
dynamic resultUserID = operationResultUserID.Result;
userID = resultUserID.id;
//getUserInfo();
Service1Client client1 = new Service1Client();
name = await client1.RetrieveNameAsync(userID);
dob = await client1.RetrieveDOBAsync(userID);
aboutMe = await client1.RetrieveAboutMeAsync(userID);
country = await client1.RetrieveCountryAsync(userID);
email = await client1.RetrieveEmailAddressAsync(userID);
gender = await client1.RetrieveGenderAsync(userID);
//status = await client1.RetrieveUserStatusAsync(userID);
UserImage = await client1.RetrieveUserImgAsync(userID);
vote = await client1.retrieveVotesAsync(userID);
count = await client1.retrievecountLearningstoryAsync(userID);
txtAboutmeDisplay.Text = aboutMe;
txtCountryDisplay.Text = country;
txtDOBDisplay.Text = dob;
txtEmailDisplay.Text = email;
txtGenderDisplay.Text = gender;
txtName.Text = name;
txtvotes.Text = vote;
txtCountDisplay.Text = count.ToString();
int numberofvotes = int.Parse(txtvotes.Text);
if (numberofvotes >=1000)
{
txtstars.Text = "Gold";
}
else if (numberofvotes >= 700)
{
txtstars.Text = "Silver";
}
else if (numberofvotes >= 500)
{
txtstars.Text = "Bronze";
}
//txtstars.Visibility == false;
InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();
DataWriter writer = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
writer.WriteBytes(UserImage);
await writer.StoreAsync();
// Create bitmap image
BitmapImage b = new BitmapImage();
b.SetSource(randomAccessStream);
// Update Image on XAML Page
imgProfilePic.Source = b;
int countstory = int.Parse(txtCountDisplay.Text);
if (countstory >= 7)
{
achievement = await client1.updateachievementAsync(userID, "wisemen");
}
else if (countstory == 6)
{
achievement = await client1.updateachievementAsync(userID, "Smartboy");
}
else if (countstory == 5)
{
achievement = await client1.insertAchievementAsync(userID, "novice");
}
}
My webservice codes
public string insertAchievement(string userid, string achievements)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string insertInterBadges = "Insert into [Achievement] (UserID, Achievement) VALUES " + " (#userid,#achievements)";
SqlCommand cmd = new SqlCommand(insertInterBadges, con);
cmd.Parameters.AddWithValue("#userId", userid);
cmd.Parameters.AddWithValue("#achievements", achievements);
int check = cmd.ExecuteNonQuery();
con.Close();
if (check > 0)
{
return "Success";
}
else
{
return "Fail";
}
}
public string updateachievements(string userid, string achievements)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string updateAchievements = "UPDATE Achievement SET Achievement=#achievement Where UserID=#userid";
SqlCommand cmd = new SqlCommand(updateAchievements, con);
cmd.Parameters.AddWithValue("#userId", userid);
cmd.Parameters.AddWithValue("#achievement", achievements);
int check = cmd.ExecuteNonQuery();
con.Close();
if (check > 0)
{
return "Success";
}
else
{
return "Fail";
}
}
my reference.cs
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IService1/updateachievement", ReplyAction = "http://tempuri.org/IService1/updateachievement")]
System.Threading.Tasks.Task<string> updateachievementAsync(string userId, string achievements);
[System.ServiceModel.OperationContractAttribute(Action = "http://tempuri.org/IService1/insertAchievement", ReplyAction = "http://tempuri.org/IService1/insertAchievement")]
System.Threading.Tasks.Task<string> insertAchievementAsync(string userId, string achievements);
public System.Threading.Tasks.Task<string> updateachievementAsync(string userId, string achievements)
{
return base.Channel.insertAchievementAsync(userId, achievements);
}
public System.Threading.Tasks.Task <string> insertAchievementAsync(string userId, string achievements)
{
return base.Channel.insertAchievementAsync(userId, achievements);
}
i am using webservice by the way
By the looks of your code, specifically the UPDATE statement, a single user can only be assigned a single achievement. That limitation makes the easy-way-out of creating a unique index on UserId, AcheivementId not a viable option (this index, if created, would prevent duplicate entries via a SQL insertion error).
The alternative, more correct, solution is to query the table prior to inserting to see if the values already exist:
SELECT COUNT(*) FROM Achievement WHERE UserId = #userId AND Achievement = #achievement
This could be used in a block like:
using (SqlConnection conn = new SqlConnection(connectionString)) {
conn.Open();
bool isNewValue = true;
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Achievement WHERE UserId = #userId AND Achievement = #achievement")) {
cmd.Parameters.AddWithValue("#userId", userid);
cmd.Parameters.AddWithValue("#achievement", achievements);
isNewValue = ((int)cmd.ExecuteScalar() == 0);
}
if (isNewValue) {
// insert user achievement / etc
}
}