Storing user credentials for next program startup - c#

Got an issue here. I have a program that when it starts a loginForm dialog pops up. Now on this loginForm I've added a rememberMe (onthoudMij) button. So if the user selects this box log's in, closes the program and then opens it again, his user credentials will already be filled in.
Here's my code for my loginButton.
private void loginButton_Click(object sender, EventArgs e)
{
try
{
var sr = new System.IO.StreamReader("C:\\" + inlogNaamTextbox.Text + "\\Login.txt");
gebruikersnaam = sr.ReadLine();
passwoord = sr.ReadLine();
sr.Close();
if (gebruikersnaam == inlogNaamTextbox.Text && passwoord == inlogPasswoordTextbox.Text)
{
classUsername.name = inlogNaamTextbox.Text;
MessageBox.Show("Je bent nu ingelogd!", "Succes!");
this.Dispose();
}
else
{
MessageBox.Show("Gebruikersnaam of wachtwoord fout!", "Fout!");
}
}
catch (System.IO.DirectoryNotFoundException ex)
{
MessageBox.Show("De gebruiker bestaat niet!", "Fout!");
}
}
NOW MY PROBLEM IS:
I have searched the web for options on remember me implementation, but they always use SQL databases etc. I just have a login that stores the username & password in a txt file as you can see in the code.
Question is..
So no my question is; How can I implement this remember me checkbox? I already know I should use System.Net , but what else for this to work without sql databases or anything like that?

If your problem is the saving part, you could use something like 3DES encryption to have a somewhat save solution to save the username and password.
You could use your current code and add something like in this SO article to encrypt and decrypt the password: How to implement Triple DES in C# (complete example)
If the problem is just how to do read/save this?
I would create a text, something like this:
private void CallOnFormLoad()
{
string[] allLines = File.ReadAllLines(#"C:\passwordfile.txt");
if (allLines.Length > 1)
{
// at least one 2 lines:
inlogNaamTextbox.Text = allLines[0];
inlogPasswoordTextbox.Text = allLines[1];
}
}
private void loginButton_Click(object sender, EventArgs e)
{
try
{
var sr = new System.IO.StreamReader("C:\\" + inlogNaamTextbox.Text + "\\Login.txt");
gebruikersnaam = sr.ReadLine();
passwoord = sr.ReadLine();
sr.Close();
if (gebruikersnaam == inlogNaamTextbox.Text && passwoord == inlogPasswoordTextbox.Text)
{
classUsername.name = inlogNaamTextbox.Text;
MessageBox.Show("Je bent nu ingelogd!", "Succes!");
File.WriteAllLines(#"C:\passwordfile.txt", string.Format("{0}\n{1}", inlogNaamTextbox.Text, inlogPasswoordTextbox.Text))
// Don't call Dispose!
// this.Dispose();
}
else
{
MessageBox.Show("Gebruikersnaam of wachtwoord fout!", "Fout!");
}
}
catch (System.IO.DirectoryNotFoundException ex)
{
MessageBox.Show("De gebruiker bestaat niet!", "Fout!");
}
}

Related

C# - Can't get if statement to work as it should - Throw new system.ArgumentException

I am new to learning C#, and i'm attempting to create a WPF application that asks the user questions. I then convert those answers into strings and export them to a CSV file.
One of the questions is "Pick a number between 1-5". I need to make this so that if a number is less than 1, or more than 5, it asks the user to pick a different number. I tried to achieve this by using the below code. It somewhat works because when i click save as, nothing will happen if i use a wrong number. But it doesn't ask the user like i want it to. Please could someone take a look at my code and let me know why this isn't working?
private void btnSaveClick(object sender, RoutedEventArgs e)
{
try
{
string firstName = tbFirstName.Text;
string lastName = tbLastName.Text;
string jobTitle = tbJobTitle.Text;
string chickenEgg = tbChickenEgg.Text;
string _oneFive = tbNumber.Text;
int oneFive = Convert.ToInt32(_oneFive);
if ((oneFive > 5) || (oneFive < 1))
{
throw new System.ArgumentException("Please use a number between 1-5");
}
string csvContent = string.Format("{0},{1},{2},{3},{4}", FormatCSV(firstName), FormatCSV(lastName), FormatCSV(jobTitle), FormatCSV(chickenEgg), FormatCSV(_oneFive));
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV file (*.csv)|*.csv";
if (saveFileDialog.ShowDialog() == true)
File.WriteAllText(saveFileDialog.FileName, csvContent);
tbFirstName.Clear();
tbLastName.Clear();
tbJobTitle.Clear();
tbChickenEgg.Clear();
tbNumber.Clear();
tbFirstName.Focus();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
static string FormatCSV(string _input)
{
try
{
string result = "";
if ((_input.Contains(",")) || (_input.Contains(" ")))
{
result = string.Format("\"{0}\"", _input.Trim());
}
else
{
result = _input.Trim();
}
return result;
}
catch (Exception e)
{
throw e;
}
When i get to the catch block, nothing displays or seems to happen.
Thank you in advance!
Instead of throwing an exception, you could display a MessageBox to the user:
private void btnSaveClick(object sender, RoutedEventArgs e)
{
string firstName = tbFirstName.Text;
string lastName = tbLastName.Text;
string jobTitle = tbJobTitle.Text;
string chickenEgg = tbChickenEgg.Text;
string _oneFive = tbNumber.Text;
int oneFive = Convert.ToInt32(_oneFive);
if ((oneFive > 5) || (oneFive < 1))
{
MessageBox.Show("Please use a number between 1-5", "", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
string csvContent = string.Format("{0},{1},{2},{3},{4}", FormatCSV(firstName), FormatCSV(lastName), FormatCSV(jobTitle), FormatCSV(chickenEgg), FormatCSV(_oneFive));
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV file (*.csv)|*.csv";
if (saveFileDialog.ShowDialog() == true)
File.WriteAllText(saveFileDialog.FileName, csvContent);
tbFirstName.Clear();
tbLastName.Clear();
tbJobTitle.Clear();
tbChickenEgg.Clear();
tbNumber.Clear();
tbFirstName.Focus();
}
}
The user can then click "OK" to dismiss the message box and then enter a new number and hit the "Save" button again. This is basically how GUI applications tend to work.
If you want to tell the user something, the simple way to do it is with a message box
MessageBox.Show("enter a number between 1 and 5");
A better, but a little bit more complicated is to use binding validation. This will reject input as soon as it is entered.
It might be a good idea to read Best practices for exceptions, one rule is to handle common conditions without throwing exceptions, and an incorrect input value would be one of these common cases.

My File accdb is missing but Data still can entry

In my C# apps "MyApps.Exe", i use Provider Microsoft.ace.oledb.12.0 to access my accdb file..
I set data source with
Data Source="+Application.StartupPath+"\\databaseFile.accdb
So my apps will read the databaseFile.accdb in the same folder with Exe file. The folder name is CurrentFolder.
I have compile my apps and install it in : "C:\Program Files(x86)\CurrentFolder"
Peculiarities occur, when file "databaseFile.accdb" has been deleted from folder "CurrentFolder".
When I run "MyApps.exe", then login entry username and password, and then Entry ,read data. The Apps is still running.
This should not happen because "databaseFile.accdb" has been deleted.
Why it can happen? I am confused for this happen.
Anyone can explain this ? why my Apss still can access/read database.accdb
eventough the database was deleted.
Thanks in advance.
--Addition Information --
Before, i share folder "C:\Program Files(x86)\CurrentFolder" to network. and add Permissions to Everyone Full Control.
I hope this information can help our problem analysis.
Here source code my connection.cs
public Connection()
{
try
{
alamat = "Provider=Microsoft.ace.Oledb.12.0; Data Source="+Application.StartupPath+"\\databaseFile.accdb";
koneksi = new OleDbConnection(alamat);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static Connection GetInstance(){
if(Connection.connection == null){
Connection.connection = new Connection();
}
return Connection.connection;
}
//this is for check wether the file databaseFile.accdb is exist in that folder
public int cekDb(string locasi)
{
int a=0;
if (File.Exists(locasi))
{
a = 1;
}
return a;
}
public int CekLogin(string user,string pass)
{
koneksi.Close();
koneksi.Open();
perintah = new OleDbCommand("select * from [user] where username = '" + user + "' and password = '" + pass + "';", koneksi);
myReader = perintah.ExecuteReader();
int count = 0;
while (myReader.Read())
{
leveluser = myReader["type"].ToString();
count++;
}
koneksi.Close();
return count;
}
In my login.cs
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "")
{
MessageBox.Show("Please Fill your Username or Password");
textBox1.Focus();
}
else
{
if(connection.cekDb(Application.StartupPath+"\\databaseFile.accdb")==1){
int cek = connection.CekLogin(textBox1.Text.Trim().Replace("'", "''"), textBox2.Text.Trim().Replace("'", "''"));
if (cek != 0)
{
DashBoard entry = new DashBoard();
entry.Show();
UseWaitCursor = false;
}
else if (cek == 0)
{
// konek.Disconnect();
MessageBox.Show("Please Check your username and password !!");
}
else
{
MessageBox.Show(cek.ToString());
}
}
else
{
MessageBox.Show("File DatabaseFile.accdb Not Found !!");
}
}
}

MessageBox showing unwanted result

I'm new at this world of developing a software. So this may sound silly.
I'm working on developing a simple Login System at college, and I want to speed things up a little bit, my professor can be a tad, disorganized and it jeopardize the little time we have to learn a million things about programming.
I could get the program running and only opening the Main Form if the username and password are valid.
Before I researched and made a register button that will write data in my database, the message box was working properly.
But now, I cannot seem to make the message box show up saying if it is either, a successful login or if it is not.
My code is as following for the Login button:
private void VLogin_Click(object sender, EventArgs e)
{
try
{
string ConnectionString = "User ID=*****;Password=*******;" +
"Database=C:\\Users\\marqu_000\\Documents\\WindowsFormsApplication13\\Sistema.GDB;" +
"DataSource=localhost";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
string SQLCommandText = "select * from LOGIN where USERNAME=#username and PASSWORD=#password";
FbCommand addDetailsCommand = new FbCommand(SQLCommandText, addDetailsConnection);
addDetailsCommand.Parameters.Add("#username", FbDbType.VarChar, 15).Value = userName.Text;
addDetailsCommand.Parameters.Add("#password", FbDbType.VarChar, 15).Value = userPassword.Text;
FbDataReader reader = addDetailsCommand.ExecuteReader();
while (reader.Read())
{
this.Visible = false;
MainWin MWin = new MainWin();
MWin.ShowDialog();
Application.Exit();
}
MessageBox.Show("Login Successful");
}
catch (Exception x)
{
MessageBox.Show("Invalid username or password");
MessageBox.Show(x.Message);
}
}
And this is my code for the register button:
private void registerUser_Click(object sender, EventArgs e)
{
try
{
string ConnectionString = "User ID=****;Password=****;" +
"Database=C:\\Users\\marqu_000\\Documents\\WindowsFormsApplication13\\Sistema.GDB;" +
"DataSource=localhost";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
FbCommand SQLCommandTextInsert = new FbCommand("INSERT INTO LOGIN(USERNAME, PASSWORD, LEVEL) VALUES (#username,#password,#level)", addDetailsConnection);
SQLCommandTextInsert.Parameters.AddWithValue("username", registerUsername.Text);
SQLCommandTextInsert.Parameters.AddWithValue("password", registerPassword.Text);
SQLCommandTextInsert.Parameters.AddWithValue("level", registerLevel.Text);
SQLCommandTextInsert.ExecuteNonQuery();
MessageBox.Show("Registration completed!");
}
catch (FbException fbex)
{
//throw fbex;
MessageBox.Show("Invalid information, please verify!");
MessageBox.Show(fbex.Message);
}
}
If there is any good-for-nothing lines in there, and easiest ways to make those things, I would like to know.
I thank you all in advance for the help.
Marco.
ShowDialog is a blocking call, that means no code will run until that call completes. Which in this case is when your MWin closes. You'll need to display the success message before calling ShowDialog or call it from MWin.
Your Login failed message will only show when an exception occurs. I think if i read your code correctly if the reader returns no results (failed login) then you'll display "Login Succesful" and then doing nothing else.
You can use an if to determine if the database returned results and login failed is your else condition.
I finally made it!
I searched how to validate with a IF and could do it. This is how my code is now:
try
{
string ConnectionString = "User ID=*****;Password=*******;" +
"Database=C:\\Users\\marqu_000\\Documents\\WindowsFormsApplication13\\Sistema.GDB;" +
"DataSource=localhost";
FbConnection addDetailsConnection = new FbConnection(ConnectionString);
addDetailsConnection.Open();
string SQLCommandText = "select * from LOGIN where USERNAME=#username and PASSWORD=#password";
FbCommand addDetailsCommand = new FbCommand(SQLCommandText, addDetailsConnection);
addDetailsCommand.Parameters.Add("#username", FbDbType.VarChar, 15).Value = userName.Text;
addDetailsCommand.Parameters.Add("#password", FbDbType.VarChar, 15).Value = userPassword.Text;
FbDataReader reader = addDetailsCommand.ExecuteReader();
if (reader.Read())
{
this.Visible = false;
MessageBox.Show("Login Successful!");
MainWin MWin = new MainWin();
MWin.ShowDialog();
}
else
{
MessageBox.Show("Invalid username or password!");
}

Send Email the user password, if password Incorrect

private void button1_Click(object sender, EventArgs e)
{
try
{
var sr = new System.IO.StreamReader("C:\\" + textBox1.Text + "\\login.text");
username = sr.ReadLine();
password = sr.ReadLine();
email = sr.ReadLine();
sr.Close();
if (username == textBox1.Text && password == passwordtextbox.Text)
MessageBox.Show("Success!");
}
catch(System.IO.DirectoryNotFoundException )
{
MessageBox.Show("Error, please check your email for password, else try again.");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
My Goal is to send the user their password, if the password is entered incorrectly. But however that username must match the email! So, How would I do that?
You would just want to tack on an else if statement
if (username == textBox1.Text && password == passwordtextbox.Text)
{
MessageBox.Show("Success!");
}
else if(textBox1.Text == email)
{
//Send email
}
But my guess is that you're trying to handle this in the catch statement, which won't work. Your logic is flawed. The exception you're catching gets thrown when a login file can't be found for the username provided. That means you haven't read anything, and username, eamil, and password don't have a value in the catch statement. In this case, your catch logic should prompt the user to try a different username. Then the if-else logic above will work.

facebook desktop app C#

I am trying to build a desktop app to use facebook api and get data from friends.
Anyways I am stuck in the log in stage.
I have used some advice and made the log in to facebook with WebBrowser. It works great.
I am stuck at trying to make it give me status = Failed or success
I tried doing it like this at the end of the button_1 method
if (!w.DocumentText.Contains(#"<div class=""linkWrap noCount"">Messages</div>"))
{
w.Navigate(#"http://www.facebook.com/login.php");
MessageBox.Show("Login error. Wrong username or password!");
}
else
{
MessageBox.Show("Logged in successfully");
}
the < div class=""linkWrap noCount"">Messages< /div> is only shown while logged in so thats why I use it to see if a user is logged in
but the problem is it always gives me an error (wrong user and pass) becasue it reads it before the browser finishes to navigate to the page. I tried threads and thread sleep and even timers but it doesnt seem to work
an ideas?
here is the code:
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();
string email = textBox1.Text;
string password = textBox2.Text;
// create a new browser
WebBrowser w = new WebBrowser();
w.Dock = DockStyle.Fill;
this.Controls.Add(w); // you may add the controll to your windows forms if you want to see what is going on
// latter you may not chose to add the browser or you can even set it to invisible...
// navigate to facebook
w.Navigate(#"http://www.facebook.com/login.php");
// wait a little
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
HtmlElement temp=null;
// while we find an element by id named email
while (temp == null)
{
temp = w.Document.GetElementById("email");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once we find it place the value
temp.SetAttribute("value", email);
temp = null;
// wiat till element with id pass exists
while (temp == null)
{
temp = w.Document.GetElementById("pass");
System.Threading.Thread.Sleep(10);
System.Windows.Forms.Application.DoEvents();
}
// once it exist set its value equal to passowrd
temp.SetAttribute("value", password);
// if you already found the last fields the button should also be there...
var inputs = w.Document.GetElementsByTagName("input");
int counter = 0;
bool enableClick = false;
// iterate through all the inputs in the document
foreach (HtmlElement btn in inputs)
{
try
{
var att = btn.GetAttribute("tabindex");
var name = btn.GetAttribute("id");
if (enableClick)// button to submit always has a differnt id. it should be after password textbox
{
btn.InvokeMember("click");
counter++;
}
if (name.ToUpper().Contains("PASS") || att=="4")
{
enableClick = true; // button should be next to the password input
}
// try a max of 5 times
if (counter > 5)
{
break;
}
}
catch
{
}
}
}
Checkout the facebook-sharp SDK for Windows forms:
https://github.com/facebook-csharp-sdk/facebook-winforms
I recommend you use Facebook C# SDK. It uses the OAuth protocol, for user-authentication.
Down an code example how to get user friends with Facebook-C#-SDK:
using Facebook; //add reference to facebook dll for it work
declare the fields:
private FacebookOAuthResult result;
private FacebookOAuthClient OAuth;
and
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Url.AbsolutePath == "/login.php")
{
// do login..
}
if (FacebookOAuthResult.TryParse(e.Url, out result))
{
if (result.IsSuccess)
{
FacebookClient fbClient = new FacebookClient(result.AccessToken);
dynamic friends = fbClient.Get("/me/friends"); //User friends
// do something..
}
else
{
string errorDescription = result.ErrorDescription;
string errorReason = result.ErrorReason;
string msg = String.Format("{0} ({1})", errorReason, errorDescription);
MessageBox.Show(msg, "User-authentication failed!");
}
}
}
and then for start user-authentication:
//..
OAuth = new FacebookOAuthClient();
OAuth.AppId = appId; // see link above,you can find how to get it
OAuth.AppSecret = appSecret; // see link above,you can find how to get it
Uri loginUrl = OAuth.GetLoginUrl(paramenters);
webBrowser1.Navigate(loginUrl.AbsoluteUri);

Categories