Converting to file-scoped namespaces

This commit is contained in:
2023-04-02 22:10:42 +02:00
parent 2637741703
commit 4f3a768432
11 changed files with 525 additions and 536 deletions

View File

@@ -1,14 +1,13 @@
namespace Common namespace Common;
{
class Config
{
public string PasswordStorePath { get; set; }
public string Recipient { get; set; }
public Config(string PasswordStorePath, string Recipient) class Config
{ {
this.PasswordStorePath = PasswordStorePath; public string PasswordStorePath { get; set; }
this.Recipient = Recipient; public string Recipient { get; set; }
}
public Config(string PasswordStorePath, string Recipient)
{
this.PasswordStorePath = PasswordStorePath;
this.Recipient = Recipient;
} }
} }

View File

@@ -1,9 +1,9 @@
using Microsoft.VisualBasic.FileIO; using Microsoft.VisualBasic.FileIO;
namespace Common namespace Common;
static class ConfigFileManager
{ {
static class ConfigFileManager
{
#region Config flags #region Config flags
/*Configuration: (format: fieldname=value) /*Configuration: (format: fieldname=value)
@@ -20,75 +20,74 @@ namespace Common
public static void Init() public static void Init()
{ {
bool success = false; bool success = false;
while (!success) while (!success)
{
if (File.Exists(CONFIGPATH))
{ {
if (File.Exists(CONFIGPATH)) StreamReader sr = new StreamReader(CONFIGPATH);
string? path = null, recipient = null;
while (!sr.EndOfStream)
{ {
StreamReader sr = new StreamReader(CONFIGPATH); string[]? fields = sr.ReadLine().Split(DELIMETER);
string? path = null, recipient = null; if (fields != null)
while (!sr.EndOfStream)
{ {
string[]? fields = sr.ReadLine().Split(DELIMETER); if (fields[0] == PATH)
if (fields != null)
{ {
if (fields[0] == PATH) path = fields[1];
{
path = fields[1];
}
else if (fields[0] == RECIPIENT)
{
recipient = fields[1];
}
} }
else //probably an empty line or something else if (fields[0] == RECIPIENT)
{ {
continue; recipient = fields[1];
} }
} }
else //probably an empty line or something
{
continue;
}
}
if (path != null && recipient != null) if (path != null && recipient != null)
{ {
Configuration = new Config(path, recipient); Configuration = new Config(path, recipient);
success = true; success = true;
}
else
{
throw new InvalidConfigurationException("One or more required fileds were missing from the configuration file.");
}
} }
else else
{ {
CreateDefaultConfig(); throw new InvalidConfigurationException("One or more required fileds were missing from the configuration file.");
} }
} }
else
{
CreateDefaultConfig();
}
}
} }
public static string GetPath() public static string GetPath()
{ {
return Configuration.PasswordStorePath; return Configuration.PasswordStorePath;
} }
public static string GetRecipient() public static string GetRecipient()
{ {
return Configuration.Recipient; return Configuration.Recipient;
} }
private static void CreateDefaultConfig() private static void CreateDefaultConfig()
{
try
{ {
try string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
{ StreamWriter sw = new StreamWriter(CONFIGPATH);
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name; sw.WriteLine(RECIPIENT + DELIMETER + user);
StreamWriter sw = new StreamWriter(CONFIGPATH); sw.WriteLine(PATH + DELIMETER + SpecialDirectories.CurrentUserApplicationData);
sw.WriteLine(RECIPIENT + DELIMETER + user); sw.Close();
sw.WriteLine(PATH + DELIMETER + SpecialDirectories.CurrentUserApplicationData); }
sw.Close(); catch (Exception e)
} {
catch (Exception e) MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
} }
} }

View File

@@ -1,9 +1,8 @@
namespace Common namespace Common;
class InvalidConfigurationException : Exception
{ {
class InvalidConfigurationException : Exception public InvalidConfigurationException() : base() { }
{ public InvalidConfigurationException(string message) : base(message) { }
public InvalidConfigurationException() : base() { } public InvalidConfigurationException(string message, Exception inner) : base(message, inner) { }
public InvalidConfigurationException(string message) : base(message) { }
public InvalidConfigurationException(string message, Exception inner) : base(message, inner) { }
}
} }

View File

@@ -1,39 +1,38 @@
using System.Text; using System.Text;
namespace Common namespace Common;
static class PasswordGenerator
{ {
static class PasswordGenerator private static string RandomStr(int length, bool no_symbols = false)
{ {
private static string RandomStr(int length, bool no_symbols = false) StringBuilder builder = new StringBuilder();
Random rnd = new Random();
for (int i = 0; i < length; i++)
{ {
StringBuilder builder = new StringBuilder(); if (rnd.Next(0, 101) <= 60) //60% chance for a character
Random rnd = new Random();
for (int i = 0; i < length; i++)
{ {
if (rnd.Next(0, 101) <= 60) //60% chance for a character char c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65))); //random character
if (no_symbols && Char.IsSymbol(c))
{ {
char c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65))); //random character while (Char.IsSymbol(c))
if (no_symbols && Char.IsSymbol(c))
{ {
while (Char.IsSymbol(c)) c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65))); //random character
{
c = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * rnd.NextDouble() + 65))); //random character
}
} }
builder.Append(c);
}
else //40% change for number
{
builder.Append(Convert.ToChar(rnd.Next(0, 10)));
} }
builder.Append(c);
}
else //40% change for number
{
builder.Append(Convert.ToChar(rnd.Next(0, 10)));
} }
return builder.ToString();
} }
public static string? New(string recipient, int length, bool no_symbols = false) return builder.ToString();
{ }
public static string? New(string recipient, int length, bool no_symbols = false)
{
return new ProcessBuilder().GetOutput("cmd.exe", $"echo {RandomStr(length, no_symbols)} | gpg --quiet --encrypt --recipient {recipient}"); return new ProcessBuilder().GetOutput("cmd.exe", $"echo {RandomStr(length, no_symbols)} | gpg --quiet --encrypt --recipient {recipient}");
}
} }
} }

View File

@@ -1,61 +1,60 @@
using System.Diagnostics; using System.Diagnostics;
using System.Text; using System.Text;
namespace Common namespace Common;
public delegate void ProcessSuccess();
public delegate void ProcessFailure(Exception e);
sealed class ProcessBuilder
{ {
public delegate void ProcessSuccess(); public event ProcessSuccess? ProcessFinished;
public delegate void ProcessFailure(Exception e); public event ProcessFailure? ProcessFailed;
sealed class ProcessBuilder
public void Run(string procName, string args)
{ {
public event ProcessSuccess? ProcessFinished; try
public event ProcessFailure? ProcessFailed;
public void Run(string procName, string args)
{ {
try Process.Start(procName, args);
{ ProcessFinished?.Invoke();
Process.Start(procName, args);
ProcessFinished?.Invoke();
}
catch (Exception e)
{
ProcessFailed?.Invoke(e);
}
} }
catch (Exception e)
public string? GetOutput(string procName, string args)
{ {
try ProcessFailed?.Invoke(e);
{
Process proc = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = procName,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
StringBuilder builder = new StringBuilder();
while (!proc.StandardOutput.EndOfStream)
{
builder.Append(proc.StandardOutput.ReadLine());
}
ProcessFinished?.Invoke();
return builder.ToString();
} catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
ProcessFailed?.Invoke(e);
}
return null;
} }
} }
public string? GetOutput(string procName, string args)
{
try
{
Process proc = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = procName,
Arguments = args,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
StringBuilder builder = new StringBuilder();
while (!proc.StandardOutput.EndOfStream)
{
builder.Append(proc.StandardOutput.ReadLine());
}
ProcessFinished?.Invoke();
return builder.ToString();
} catch (Exception e)
{
MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
ProcessFailed?.Invoke(e);
}
return null;
}
} }

View File

@@ -1,136 +1,135 @@
namespace GUI namespace GUI;
partial class GeneratePassword
{ {
partial class GeneratePassword /// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{ {
/// <summary> if (disposing && (components != null))
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) components.Dispose();
{
components.Dispose();
}
base.Dispose(disposing);
} }
base.Dispose(disposing);
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
passwordName = new TextBox();
label1 = new Label();
label2 = new Label();
passwordLength = new TextBox();
noSymbols = new CheckBox();
generate = new Button();
cancel = new Button();
SuspendLayout();
//
// passwordName
//
passwordName.Location = new Point(12, 33);
passwordName.Name = "passwordName";
passwordName.PlaceholderText = "website.com";
passwordName.Size = new Size(156, 23);
passwordName.TabIndex = 0;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 15);
label1.Name = "label1";
label1.Size = new Size(39, 15);
label1.TabIndex = 1;
label1.Text = "Name";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(12, 59);
label2.Name = "label2";
label2.Size = new Size(44, 15);
label2.TabIndex = 2;
label2.Text = "Length";
//
// passwordLength
//
passwordLength.Location = new Point(12, 77);
passwordLength.Name = "passwordLength";
passwordLength.PlaceholderText = "16";
passwordLength.Size = new Size(156, 23);
passwordLength.TabIndex = 3;
//
// noSymbols
//
noSymbols.AutoSize = true;
noSymbols.Location = new Point(12, 106);
noSymbols.Name = "noSymbols";
noSymbols.Size = new Size(89, 19);
noSymbols.TabIndex = 4;
noSymbols.Text = "No symbols";
noSymbols.UseVisualStyleBackColor = true;
//
// generate
//
generate.Location = new Point(93, 131);
generate.Name = "generate";
generate.Size = new Size(75, 23);
generate.TabIndex = 5;
generate.Text = "Generate";
generate.UseVisualStyleBackColor = true;
generate.Click += Generate;
//
// cancel
//
cancel.Location = new Point(12, 131);
cancel.Name = "cancel";
cancel.Size = new Size(75, 23);
cancel.TabIndex = 6;
cancel.Text = "Cancel";
cancel.UseVisualStyleBackColor = true;
cancel.Click += cancel_Click;
//
// GeneratePassword
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(187, 173);
Controls.Add(cancel);
Controls.Add(generate);
Controls.Add(noSymbols);
Controls.Add(passwordLength);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(passwordName);
Name = "GeneratePassword";
ResumeLayout(false);
PerformLayout();
}
private void Generate_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private TextBox passwordName;
private Label label1;
private Label label2;
private TextBox passwordLength;
private CheckBox noSymbols;
private Button generate;
private Button cancel;
} }
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
passwordName = new TextBox();
label1 = new Label();
label2 = new Label();
passwordLength = new TextBox();
noSymbols = new CheckBox();
generate = new Button();
cancel = new Button();
SuspendLayout();
//
// passwordName
//
passwordName.Location = new Point(12, 33);
passwordName.Name = "passwordName";
passwordName.PlaceholderText = "website.com";
passwordName.Size = new Size(156, 23);
passwordName.TabIndex = 0;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 15);
label1.Name = "label1";
label1.Size = new Size(39, 15);
label1.TabIndex = 1;
label1.Text = "Name";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(12, 59);
label2.Name = "label2";
label2.Size = new Size(44, 15);
label2.TabIndex = 2;
label2.Text = "Length";
//
// passwordLength
//
passwordLength.Location = new Point(12, 77);
passwordLength.Name = "passwordLength";
passwordLength.PlaceholderText = "16";
passwordLength.Size = new Size(156, 23);
passwordLength.TabIndex = 3;
//
// noSymbols
//
noSymbols.AutoSize = true;
noSymbols.Location = new Point(12, 106);
noSymbols.Name = "noSymbols";
noSymbols.Size = new Size(89, 19);
noSymbols.TabIndex = 4;
noSymbols.Text = "No symbols";
noSymbols.UseVisualStyleBackColor = true;
//
// generate
//
generate.Location = new Point(93, 131);
generate.Name = "generate";
generate.Size = new Size(75, 23);
generate.TabIndex = 5;
generate.Text = "Generate";
generate.UseVisualStyleBackColor = true;
generate.Click += Generate;
//
// cancel
//
cancel.Location = new Point(12, 131);
cancel.Name = "cancel";
cancel.Size = new Size(75, 23);
cancel.TabIndex = 6;
cancel.Text = "Cancel";
cancel.UseVisualStyleBackColor = true;
cancel.Click += cancel_Click;
//
// GeneratePassword
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(187, 173);
Controls.Add(cancel);
Controls.Add(generate);
Controls.Add(noSymbols);
Controls.Add(passwordLength);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(passwordName);
Name = "GeneratePassword";
ResumeLayout(false);
PerformLayout();
}
private void Generate_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
#endregion
private TextBox passwordName;
private Label label1;
private Label label2;
private TextBox passwordLength;
private CheckBox noSymbols;
private Button generate;
private Button cancel;
} }

View File

@@ -1,56 +1,55 @@
namespace GUI namespace GUI;
public delegate void MethodRequest();
public partial class GeneratePassword : Form
{ {
public delegate void MethodRequest(); private string currentPath;
public partial class GeneratePassword : Form private string recipient;
public event MethodRequest ReloadRequest;
public GeneratePassword(string currentPath, string recipient, MethodRequest ReloadRequest, string? name)
{ {
private string currentPath; InitializeComponent();
private string recipient; passwordName.Text = name;
public event MethodRequest ReloadRequest; this.currentPath = currentPath;
this.recipient = recipient;
this.ReloadRequest = ReloadRequest;
}
public GeneratePassword(string currentPath, string recipient, MethodRequest ReloadRequest, string? name) public void Generate(object sender, EventArgs e)
{
if (passwordName.Text == "" || passwordLength.Text == "")
{ {
InitializeComponent(); MessageBox.Show("You must fill in all fields to continue.", "Error: Empty fields", MessageBoxButtons.OK, MessageBoxIcon.Error);
passwordName.Text = name;
this.currentPath = currentPath;
this.recipient = recipient;
this.ReloadRequest = ReloadRequest;
} }
else
public void Generate(object sender, EventArgs e)
{ {
if (passwordName.Text == "" || passwordLength.Text == "") try
{ {
MessageBox.Show("You must fill in all fields to continue.", "Error: Empty fields", MessageBoxButtons.OK, MessageBoxIcon.Error); string filePath = $"{currentPath}\\{passwordName.Text}";
File.WriteAllText(
currentPath + $"\\{passwordName.Text}.gpg",
PasswordGenerator.New(
recipient,
Convert.ToInt32(passwordLength.Text),
noSymbols.Checked)
);
} }
else catch (FormatException)
{ {
try MessageBox.Show("Please enter a valid number for the password's length.", "Error: Invalid field", MessageBoxButtons.OK, MessageBoxIcon.Error);
{ }
string filePath = $"{currentPath}\\{passwordName.Text}"; catch (IOException error)
File.WriteAllText( {
currentPath + $"\\{passwordName.Text}.gpg", MessageBox.Show(error.ToString(), "IO Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
PasswordGenerator.New(
recipient,
Convert.ToInt32(passwordLength.Text),
noSymbols.Checked)
);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the password's length.", "Error: Invalid field", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (IOException error)
{
MessageBox.Show(error.ToString(), "IO Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
} }
ReloadRequest();
Close();
} }
ReloadRequest();
Close();
}
private void cancel_Click(object sender, EventArgs e) private void cancel_Click(object sender, EventArgs e)
{ {
Close(); Close();
}
} }
} }

217
GUI/MainForm.Designer.cs generated
View File

@@ -1,115 +1,114 @@
namespace GUI namespace GUI;
sealed partial class MainForm : Form
{ {
sealed partial class MainForm : Form /// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{ {
/// <summary> if (disposing && (components != null))
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) components.Dispose();
{
components.Dispose();
}
base.Dispose(disposing);
} }
base.Dispose(disposing);
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
SearchBox = new TextBox();
GeneratePassword = new Button();
ResultList = new PasswordListBox(PathRequest);
DecryptBtn = new Button();
Cancel = new Button();
SuspendLayout();
//
// SearchBox
//
SearchBox.Location = new Point(10, 20);
SearchBox.Margin = new Padding(3, 2, 3, 2);
SearchBox.Name = "SearchBox";
SearchBox.PlaceholderText = "Search for a password";
SearchBox.Size = new Size(225, 23);
SearchBox.TabIndex = 0;
SearchBox.TextChanged += ReloadResults;
//
// GeneratePassword
//
GeneratePassword.Location = new Point(241, 20);
GeneratePassword.Name = "GeneratePassword";
GeneratePassword.Size = new Size(75, 23);
GeneratePassword.TabIndex = 5;
GeneratePassword.Text = "Generate";
GeneratePassword.UseVisualStyleBackColor = true;
GeneratePassword.Click += OpenPasswordGenerator;
//
// ResultList
//
ResultList.ColumnWidth = 20;
ResultList.FormattingEnabled = true;
ResultList.HorizontalScrollbar = true;
ResultList.ItemHeight = 15;
ResultList.Location = new Point(10, 48);
ResultList.Name = "ResultList";
ResultList.Size = new Size(306, 274);
ResultList.TabIndex = 6;
//
// DecryptBtn
//
DecryptBtn.Location = new Point(241, 328);
DecryptBtn.Name = "DecryptBtn";
DecryptBtn.Size = new Size(75, 23);
DecryptBtn.TabIndex = 7;
DecryptBtn.Text = "Decrypt";
DecryptBtn.UseVisualStyleBackColor = true;
DecryptBtn.Click += Decrypt;
//
// Cancel
//
Cancel.Location = new Point(160, 328);
Cancel.Name = "Cancel";
Cancel.Size = new Size(75, 23);
Cancel.TabIndex = 8;
Cancel.Text = "Cancel";
Cancel.UseVisualStyleBackColor = true;
Cancel.Click += CancelPressed;
//
// MainForm
//
AcceptButton = DecryptBtn;
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(324, 374);
Controls.Add(Cancel);
Controls.Add(DecryptBtn);
Controls.Add(ResultList);
Controls.Add(GeneratePassword);
Controls.Add(SearchBox);
Margin = new Padding(3, 2, 3, 2);
Name = "MainForm";
Text = "Password Manager";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox SearchBox;
private Button GeneratePassword;
private PasswordListBox ResultList;
private Button DecryptBtn;
private Button Cancel;
} }
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
SearchBox = new TextBox();
GeneratePassword = new Button();
ResultList = new PasswordListBox(PathRequest);
DecryptBtn = new Button();
Cancel = new Button();
SuspendLayout();
//
// SearchBox
//
SearchBox.Location = new Point(10, 20);
SearchBox.Margin = new Padding(3, 2, 3, 2);
SearchBox.Name = "SearchBox";
SearchBox.PlaceholderText = "Search for a password";
SearchBox.Size = new Size(225, 23);
SearchBox.TabIndex = 0;
SearchBox.TextChanged += ReloadResults;
//
// GeneratePassword
//
GeneratePassword.Location = new Point(241, 20);
GeneratePassword.Name = "GeneratePassword";
GeneratePassword.Size = new Size(75, 23);
GeneratePassword.TabIndex = 5;
GeneratePassword.Text = "Generate";
GeneratePassword.UseVisualStyleBackColor = true;
GeneratePassword.Click += OpenPasswordGenerator;
//
// ResultList
//
ResultList.ColumnWidth = 20;
ResultList.FormattingEnabled = true;
ResultList.HorizontalScrollbar = true;
ResultList.ItemHeight = 15;
ResultList.Location = new Point(10, 48);
ResultList.Name = "ResultList";
ResultList.Size = new Size(306, 274);
ResultList.TabIndex = 6;
//
// DecryptBtn
//
DecryptBtn.Location = new Point(241, 328);
DecryptBtn.Name = "DecryptBtn";
DecryptBtn.Size = new Size(75, 23);
DecryptBtn.TabIndex = 7;
DecryptBtn.Text = "Decrypt";
DecryptBtn.UseVisualStyleBackColor = true;
DecryptBtn.Click += Decrypt;
//
// Cancel
//
Cancel.Location = new Point(160, 328);
Cancel.Name = "Cancel";
Cancel.Size = new Size(75, 23);
Cancel.TabIndex = 8;
Cancel.Text = "Cancel";
Cancel.UseVisualStyleBackColor = true;
Cancel.Click += CancelPressed;
//
// MainForm
//
AcceptButton = DecryptBtn;
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(324, 374);
Controls.Add(Cancel);
Controls.Add(DecryptBtn);
Controls.Add(ResultList);
Controls.Add(GeneratePassword);
Controls.Add(SearchBox);
Margin = new Padding(3, 2, 3, 2);
Name = "MainForm";
Text = "Password Manager";
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox SearchBox;
private Button GeneratePassword;
private PasswordListBox ResultList;
private Button DecryptBtn;
private Button Cancel;
} }

View File

@@ -1,32 +1,32 @@
namespace GUI namespace GUI;
sealed public partial class MainForm : Form
{ {
sealed public partial class MainForm : Form public event DataRequest PathRequest;
{
public event DataRequest PathRequest;
public event DataRequest? RecipientRequest; public event DataRequest? RecipientRequest;
public MainForm(DataRequest PathRequest, DataRequest? RecipientRequest = null) public MainForm(DataRequest PathRequest, DataRequest? RecipientRequest = null)
{ {
this.PathRequest = PathRequest; this.PathRequest = PathRequest;
this.RecipientRequest = RecipientRequest; this.RecipientRequest = RecipientRequest;
InitializeComponent(); InitializeComponent();
ResultList.SearchQueryRequest += () => SearchBox.Text; ResultList.SearchQueryRequest += () => SearchBox.Text;
ResultList.ReloadResults(); ResultList.ReloadResults();
} }
private void ReloadResults(object? sender, EventArgs? e) //proxy method for SearchBox.TextChanged private void ReloadResults(object? sender, EventArgs? e) //proxy method for SearchBox.TextChanged
{ {
ResultList.ReloadResults(); ResultList.ReloadResults();
} }
private void ReloadResults() private void ReloadResults()
{ {
ResultList.ReloadResults(); ResultList.ReloadResults();
} }
private void OpenPasswordGenerator(object sender, EventArgs e) private void OpenPasswordGenerator(object sender, EventArgs e)
{ {
if (RecipientRequest != null) if (RecipientRequest != null)
{ {
GeneratePassword gp = new GeneratePassword(PathRequest(), RecipientRequest(), ReloadResults, SearchBox.Text); GeneratePassword gp = new GeneratePassword(PathRequest(), RecipientRequest(), ReloadResults, SearchBox.Text);
@@ -36,34 +36,33 @@ namespace GUI
{ {
throw new InvalidOperationException("You cannot use the OpenPasswordGenerator method if you instantiated this form without a RecipientRequest event handler."); throw new InvalidOperationException("You cannot use the OpenPasswordGenerator method if you instantiated this form without a RecipientRequest event handler.");
} }
} }
private void CancelPressed(object sender, EventArgs e) private void CancelPressed(object sender, EventArgs e)
{ {
Close(); Close();
} }
private void CopyAndNotify(string? line, string fileName) private void CopyAndNotify(string? line, string fileName)
{ {
ProcessBuilder pb = new ProcessBuilder(); ProcessBuilder pb = new ProcessBuilder();
pb.ProcessFailed += (e) => MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); pb.ProcessFailed += (e) => MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (line != null) if (line != null)
{ {
Clipboard.SetText(line); Clipboard.SetText(line);
pb.Run("./ToastNotification.exe", $"\"{fileName} decrypted\" \"Password copied to clipboard\""); pb.Run("./ToastNotification.exe", $"\"{fileName} decrypted\" \"Password copied to clipboard\"");
} }
else else
{ {
pb.Run("./ToastNotification.exe", "\"Error\" \"No password copied\""); pb.Run("./ToastNotification.exe", "\"Error\" \"No password copied\"");
} }
} }
private void Decrypt(object sender, EventArgs e) private void Decrypt(object sender, EventArgs e)
{ {
ProcessBuilder pb = new ProcessBuilder(); ProcessBuilder pb = new ProcessBuilder();
pb.ProcessFailed += (e) => MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); pb.ProcessFailed += (e) => MessageBox.Show(e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
CopyAndNotify(pb.GetOutput("gpg.exe", $"--quiet --decrypt {PathRequest()}\\{ResultList.Text}"), ResultList.Text); CopyAndNotify(pb.GetOutput("gpg.exe", $"--quiet --decrypt {PathRequest()}\\{ResultList.Text}"), ResultList.Text);
Close(); Close();
}
} }
} }

View File

@@ -1,73 +1,72 @@
using System.Collections; using System.Collections;
namespace GUI namespace GUI;
{
public delegate string SearchQuery();
public class PasswordListBox : ListBox
{
public event DataRequest? PathRequest;
public event SearchQuery? SearchQueryRequest;
public PasswordListBox(DataRequest PathRequest, SearchQuery? SearchQueryRequest = null) : base() public delegate string SearchQuery();
public class PasswordListBox : ListBox
{
public event DataRequest? PathRequest;
public event SearchQuery? SearchQueryRequest;
public PasswordListBox(DataRequest PathRequest, SearchQuery? SearchQueryRequest = null) : base()
{
this.PathRequest = PathRequest;
this.SearchQueryRequest = SearchQueryRequest;
}
public PasswordListBox() : base() { }
/*do not instantiate this class using this constructor if you want to use the ReloadResults method afterwards.
Use this so that the MainForm.Designer.cs file doesn't have a stroke due to Event References, then re-instantiate the object
afterwards using the other constructor*/
public void ReloadResults(object? sender = null, EventArgs? arg = null)
{
DirectoryInfo d;
FileInfo[] files = new FileInfo[0];
try
{ {
this.PathRequest = PathRequest; if (PathRequest != null)
this.SearchQueryRequest = SearchQueryRequest; {
d = new DirectoryInfo(PathRequest());
}
else
{
throw new InvalidOperationException("You cannot use the ReloadResults method if you instantiated the object using the parameterless constructor");
}
files = d.GetFiles("*.gpg");
}
catch (ArgumentNullException e)
{
MessageBox.Show(e.ToString(), "Error: Invalid path", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
public PasswordListBox() : base() { } List<string> elements = new List<string>();
/*do not instantiate this class using this constructor if you want to use the ReloadResults method afterwards. for (int i = 0; i < files.Length; i++)
Use this so that the MainForm.Designer.cs file doesn't have a stroke due to Event References, then re-instantiate the object
afterwards using the other constructor*/
public void ReloadResults(object? sender = null, EventArgs? arg = null)
{ {
DirectoryInfo d; elements.Add(files[i].Name);
FileInfo[] files = new FileInfo[0]; }
try
{
if (PathRequest != null)
{
d = new DirectoryInfo(PathRequest());
}
else
{
throw new InvalidOperationException("You cannot use the ReloadResults method if you instantiated the object using the parameterless constructor");
}
files = d.GetFiles("*.gpg");
}
catch (ArgumentNullException e)
{
MessageBox.Show(e.ToString(), "Error: Invalid path", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
List<string> elements = new List<string>(); string[] copy = elements.ToArray();
for (int i = 0; i < files.Length; i++)
{
elements.Add(files[i].Name);
}
string[] copy = elements.ToArray(); string? searchQuery = SearchQueryRequest?.Invoke();
if (searchQuery != null) //we have a search query
string? searchQuery = SearchQueryRequest?.Invoke(); {
if (searchQuery != null) //we have a search query foreach (string s in copy)
{ {
foreach (string s in copy) if (!s.Contains(searchQuery))
{ {
if (!s.Contains(searchQuery)) elements.Remove(s);
{
elements.Remove(s);
}
} }
} }
}
this.DataSource = elements; this.DataSource = elements;
try try
{ {
SelectedIndex = 0; SelectedIndex = 0;
} catch (ArgumentOutOfRangeException) } catch (ArgumentOutOfRangeException)
{ {
SelectedIndex = -1; SelectedIndex = -1;
}
} }
} }
} }

View File

@@ -1,22 +1,21 @@
namespace GUI namespace GUI;
{
public delegate string DataRequest(); //Fire whenever a specific field of ProfileHandler.CurrentProfile is needed
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ConfigFileManager.Init();
ApplicationConfiguration.Initialize();
Application.Run(mainForm);
}
public static MainForm mainForm = new MainForm( public delegate string DataRequest(); //Fire whenever a specific field of ProfileHandler.CurrentProfile is needed
() => ConfigFileManager.GetPath(), internal static class Program
() => ConfigFileManager.GetRecipient() {
); //needed at creation so that MainForm may pass this method down to other classes in its constructor /// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ConfigFileManager.Init();
ApplicationConfiguration.Initialize();
Application.Run(mainForm);
} }
public static MainForm mainForm = new MainForm(
() => ConfigFileManager.GetPath(),
() => ConfigFileManager.GetRecipient()
); //needed at creation so that MainForm may pass this method down to other classes in its constructor
} }