A simple WPF Authentication - wpf

How to create a simple WPF Authentication for WPF application?
For example:
First time a user should registry then login.
Users login and password should be saved as txt file(encrypted).
If process of authentication is successful,then it should redirect to another existed window.
I'm a beginner in WPF.
I've searched about this question,but didn't find what I need.
I need a simple,step by step explanation of how to do it.
Thanks in advance! :)

I am also learning so in order to exercise a bit i have created a very simple example for you. It is probably unprofessional and unsafe but i think (hope) it is possible to extend it somehow :).
Firstly you need to create simple WPF windows (use txt/btn+Name naming convention):
For both windows add
using System.IO;
Then you need to add events for buttons and modify code for both windows:
public partial class LoginWindow : Window
{
public LoginWindow()
{
InitializeComponent();
}
// This is really bad/weak encryption method
String WeakDecryptMethod(String textIn)
{
Char[] temp = textIn.ToArray<Char>();
for (int i = 0; i < textIn.Length; i++)
{
temp[i] = (char)((int)temp[i] - 3);
}
return new String(temp);
}
private void btnRegister_Click(object sender, RoutedEventArgs e)
{
RegisterWindow newWindow = new RegisterWindow();
newWindow.ShowDialog();
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
// If file exist and login and password are "correct"
if (File.Exists("Users.txt")
&& txtLogin.Text.Length >= 4
&& txtPass.Text.Length >= 4)
{
using (StreamReader streamReader = new StreamReader("Users.txt"))
{
// While there is something in streamReader read it
while (streamReader.Peek() >= 0)
{
String decryptedLogin = WeakDecryptMethod(streamReader.ReadLine());
String decryptedPass = WeakDecryptMethod(streamReader.ReadLine());
if (decryptedLogin == txtLogin.Text && decryptedPass == txtPass.Text)
{
ProtectedWindow protectedWindow = new ProtectedWindow();
this.Close();
protectedWindow.Show();
break;
}
}
}
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
And code for Register window:
public partial class RegisterWindow : Window
{
public RegisterWindow()
{
InitializeComponent();
}
// This is really bad/weak method to encrypt files
String WeakEncryptMethod(String textIn)
{
Char[] temp = textIn.ToArray<Char>();
for (int i = 0; i < textIn.Length; i++)
{
temp[i] = (char)((int)temp[i] + 3);
}
return new String(temp);
}
private void btnRegister_Click(object sender, RoutedEventArgs e)
{
// If file exist and login and password are "correct"
if (File.Exists("Users.txt")
&& txtLogin.Text.Length >= 4
&& txtPass.Text.Length >= 4
&& txtPass.Text == txtPassCheck.Text)
{
StringBuilder stringBuilder = new StringBuilder();
using (StreamReader streamReader = new StreamReader("Users.txt"))
{
stringBuilder.Append(streamReader.ReadToEnd());
}
using (StreamWriter streamWriter = new StreamWriter("Users.txt"))
{
streamWriter.Write(stringBuilder.ToString());
streamWriter.WriteLine(WeakEncryptMethod(txtLogin.Text));
streamWriter.WriteLine(WeakEncryptMethod(txtPass.Text));
}
this.Close();
}
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
In order to work application need to have access to file "Users.txt" which needs to be placed in the same folder.
Notes:
It will be better if you will use some proper encryption functions and probably create separate class for it. Additionally i am almost sure that it will not work properly with login and password which contains the last 3 characters from the end of ASCII tables.
In my opinion it is a bad idea to store login and password data in *.txt file :).
As far i know C# code is very easily reverse engineered so probably it will be better to hide encryption/decryption part somehow. I do not know much about it, but u will be able to read more [here] 2 and probably uncle Google will be able to help.
Code is very simple and there is probably a lot of possibilities to extend it (more file handling stuff, TextBox validation for proper input and password strength calculations)

Related

WinForms Application: Russian Spell Checker

I'm trying to do a spell check of the Russian language in WinFormApp when entering a text field, but nothing comes out, tell me how to get out of the situation, what are your ideas? What is missing, maybe a dictionary, how to connect it and where is it stored?
public void richTextBox1_TextChanged(object sender, EventArgs e)
{
System.Windows.Forms.Integration.ElementHost elementHost1 = new System.Windows.Forms.Integration.ElementHost();
System.Windows.Controls.TextBox richTextBox1 = new System.Windows.Controls.TextBox();
richTextBox1.SpellCheck.IsEnabled = true;
richTextBox1.Language = XmlLanguage.GetLanguage("ru-RU");
elementHost1.Child = richTextBox1;
}

How to make a file download progress bar in WinForms?

I'm making a web browser with CefSharp. I just implemented downloads 2 days ago but there is no progress bar to go along with the download. How do I make the progress bar show download progress?
Edit: Making things clearer
Add a ProgressBar Control to your Form and add a BackgroundWorker Component alongside it to your form. Figure out your file size first:
Int64 bytes_total= Convert.ToInt64(client.ResponseHeaders["Content-Length"])
This is code from Alex's amazing answer which can be found here:
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
//Replace this code with a way to figure out how much of the file you have already downloaded and then use backgroundworker1.ReportProgress and send the percentage completion of the file download.
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}

Keep connection always open for datatable twoway bind?

I'm working on a WPF project which includes update/delete/insert operation on many tables. For simplicity, I use a datagrid for each table. The users can operate on these tables directly. Once done, click a button, the tables in database get updated. Twoway bind is perfect in this case. Below code seems working fine.
However, one thing I do not like is: the _DBConnection is always open. It is closed until the form exists. Usually, I always open connection whenever I need to, use it, close it immediately.
So, my question is: is below code the correct way to do the twoway bind?
thanks
public partial class MainWindow : Window
{
private OleDbConnection _DBConnection;
private OleDbDataAdapter _DataAdapterAdmin;
private DataSet _DataSetAdmin;
public MainWindow()
{
InitializeComponent();
}
private void InitAdminGrid()
{
string cmd = "SELECT * FROM Admin ORDER BY LastName";
_DataAdapterAdmin = new OleDbDataAdapter(cmd, _DBConnection);
_DataSetAdmin = new DataSet();
_DataAdapterAdmin.Fill(_DataSetAdmin);
dgAdministration.BeginInit();
dgAdministration.DataContext = _DataSetAdmin.Tables[0];
dgAdministration.Items.Refresh();
dgAdministration.EndInit();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
string connectionString = clsDataAccess.GetConnectionString();
_DBConnection = new OleDbConnection(connectionString);
_DBConnection.Open();
InitAdminGrid();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
try
{
OleDbCommandBuilder cmd = new OleDbCommandBuilder(_DataAdapterAdmin);
_DataAdapterAdmin.Update(_DataSetAdmin);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (_DBConnection != null)
{
_DBConnection.Close();
_DBConnection.Dispose();
}
}
}

How to work with webClient.OpenReadCompleted event handler?

I'm using the following code and it works nice
private void somethingButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += webClient_OpenReadCompleted;
webClient.OpenReadAsync(new Uri(myUri));
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if(e.Error != null)
{
messageTextBlock.Text = e.Error.Message;
return;
}
using (Stream s=e.Result)
{
XDocument document = XDocument.Load(s);
var q1 = from c in document.Descendants("result")
select new IndeedResult
{
Title =((string)c.Element("title")).Trim(),
ResultUri = ((string)c.Element("url")).Trim(),
Date = ((string)c.Element("date")).Trim(),
};
myDataGrid.ItemsSource = q1;
}
But I want to add another WebClient, webClient2 that will do exactly the same but has different uri and different structure so I will have webClient2_OpenReadCompleted...
The problem is that finally I need to merge (or do some logic before merge) var q1 from webClient_OpenReadCompleted and var q2 from webClient2_OpenReadCompleted and then
var mergedQs = q1.Union(q2).ToList();
myDataGrid.ItemsSource = mergedQs
Is there a simple way how to do it? I don't know how to do it using those event handlers.
Good question! Did it like this
void webClient_OpenReadCompleted( object sender, OpenReadCompletedEventArgs e )
{
Stream stream = (Stream)e.Result;
BinaryReader reader = new BinaryReader( stream );
byte[] buffer = reader.ReadBytes( (int)stream.Length );
Uri uri = (Uri)e.UserState;
streams.Add( uri.AbsoluteUri, new MemoryStream( buffer ) );
}
Note the usage of UserState in order to provide a unqiue key into my streams Dictionary. Works perfectly :-) This way you can work with as many files / images / binary data as you like!
See this to see just how powerful this can be....http://www.alansimes.com/warp3dsilverlighttestpage.html

Silverlight Asynchronous operation Foreach loop

I have a query for getting a list of prescriptions as below:
var PRSCRPTSQuery = GV.dbContext.Load(GV.dbContext.GetPRSCRPTQuery(GV.curCustomer.CustCode,
oOrdritemEdited.ProdCode, oOrdritemEdited.MedCode));
PRSCRPTSQuery.Completed += new EventHandler(PRSCRPTSQuery_Completed);
In the query completed event, I have the following code :
void PRSCRPTSQuery_Completed(object sender, EventArgs e)
{
lstPRSCRPT = GV.dbContext.PRSCRPTs.Where(p=>p.Status =="Activated").ToList();
if (lstPRSCRPT.Count > 0)
{
foreach (var rec in lstPRSCRPT)
{
var OrderItemQuery = GV.dbContext.Load(GV.dbContext.GetOrdritemsQuery(rec.PresNo));
OrderItemQuery.Completed += new EventHandler(OrderItemQuery_Completed);
}
}
}
The list lstPRSCRPT can contain more than one record. I presume, the foreach loop will advance to the next item in the loop without waiting for the OrderItemQuery_Completed event which is below:
void OrderItemQuery_Completed(object sender, EventArgs e)
{
lstOrderItem = GV.dbContext.OrderItems.ToList();
if (lstOrderItem.Count > 0)
{
foreach (var OrdrItemRec in lstOrderItem)
{
TotTonnes = (double)(TotTonnes + OrdrItemRec.Quantity);
}
}
}
Is there any work around for this situation? I am new to the asynchronous type of programming in SL
I see where your coming from and when i first started Silverlight programming i gripped to my preconceptions of synchronous execution so i know what i have when ive finished calling a query and also i know exactly where it's errored.
Silverlight however takes this concept and tries to rip it from you yelling "This way is better trust me!" and for the purpose it serves of enriching client side interactivity it certainly succeeds. It just takes time. You just need to learn more about the style of how to link it all together.
The link previously shown by Faster Solutions shows where C# is going in terms of asynchronous coding but it pays to know what its actually accomplishing for you. Some of which you've already grasped in the code you've linked in the question.
When i've faced the same situation you have where you have back to back async callbacks is to raise an event when i've finished doing what i'm doing. For example:
public event EventHandler<EventArgs> LoadComplete;
public int QueryCount {get;set;}
public int QuerysCompleted {get;set;}
public void GetItems()
{
var PRSCRPTSQuery = GV.dbContext.Load(GV.dbContext.GetPRSCRPTQuery
(GV.curCustomer.CustCode, oOrdritemEdited.ProdCode, oOrdritemEdited.MedCode));
PRSCRPTSQuery.Completed += new EventHandler(PRSCRPTSQuery_Completed);
LoadComplete += loader_LoadComplete;
}
void PRSCRPTSQuery_Completed(object sender, EventArgs e)
{
lstPRSCRPT = GV.dbContext.PRSCRPTs.Where(p=>p.Status =="Activated").ToList();
if (lstPRSCRPT.Count > 0)
{
QueryCount = lstPRSCRPT.Count;
foreach (var rec in lstPRSCRPT)
{
var OrderItemQuery = GV.dbContext.Load(GV.dbContext.GetOrdritemsQuery(rec.PresNo));
OrderItemQuery.Completed += new EventHandler(OrderItemQuery_Completed);
}
}
}
void OrderItemQuery_Completed(object sender, EventArgs e)
{
QueryCompleted++;
lstOrderItem = GV.dbContext.OrderItems.ToList();
if (lstOrderItem.Count > 0)
{
foreach (var OrdrItemRec in lstOrderItem)
{
TotTonnes = (double)(TotTonnes + OrdrItemRec.Quantity);
}
}
if(QueryCompleted == QueryCount)
{
RaiseLoadComplete();
}
}
public void RaiseLoadComplete()
{
if(LoadComplete != null)
{
LoadComplete(this, new EventArgs());
}
}
void loader_LoadComplete(object sender, EventArgs e)
{
//Code to execute here
}
I attach an event when starting the first query of what code to execute when i'm done. In the first query call back i initialise a count of how many responses i am expecting. Then in the second query callback i increment until i get the right amount and call the event to say im done.
The only caution with this approach is if one of the queries error, The final code will never get executed.
You might find that the VS Async CTP of interest. It introduces the new "async" keyword for handling asyncronous events. He's a blog explaining it: VS Async

Resources