diff --git a/BSHash/BSHash.sln b/BSHash/BSHash.sln new file mode 100644 index 0000000..2fe68fc --- /dev/null +++ b/BSHash/BSHash.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.11.35312.102 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BSHash", "BSHash\BSHash.csproj", "{108DFC74-04DA-484E-BB6B-DA1070B26C1A}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {108DFC74-04DA-484E-BB6B-DA1070B26C1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {108DFC74-04DA-484E-BB6B-DA1070B26C1A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {108DFC74-04DA-484E-BB6B-DA1070B26C1A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {108DFC74-04DA-484E-BB6B-DA1070B26C1A}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {C6CACB7C-04A1-47E2-A248-E8B90455D44C} + EndGlobalSection +EndGlobal diff --git a/BSHash/BSHash/App.config b/BSHash/BSHash/App.config new file mode 100644 index 0000000..583c63d --- /dev/null +++ b/BSHash/BSHash/App.config @@ -0,0 +1,30 @@ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/BSHash/BSHash/BSHash.csproj b/BSHash/BSHash/BSHash.csproj new file mode 100644 index 0000000..2ed6cbf --- /dev/null +++ b/BSHash/BSHash/BSHash.csproj @@ -0,0 +1,89 @@ + + + + + Debug + AnyCPU + {108DFC74-04DA-484E-BB6B-DA1070B26C1A} + WinExe + BSHash + BSHash + v4.8 + 512 + true + true + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + Form + + + Main.cs + + + + + Main.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/BSHash/BSHash/Calculator.cs b/BSHash/BSHash/Calculator.cs new file mode 100644 index 0000000..c7c0e2a --- /dev/null +++ b/BSHash/BSHash/Calculator.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; +using System.Windows.Forms; + +namespace BSHash +{ + public class Calculator + { + private Logger _logger; + + public Calculator(Logger logger) + { + _logger = logger; + } + + public string CalculateHash(string filePath) + { + try + { + using (SHA256 sha256 = SHA256.Create()) + { + using (FileStream fileStream = File.OpenRead(filePath)) + { + byte[] hashBytes = sha256.ComputeHash(fileStream); + string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); + + _logger.Log("Hash " + hash + " calcolato per il file " + filePath.ToString(), LogType.INFO); + + return hash; + } + } + } + catch (Exception ex) + { + // Log the exception or handle it as needed + _logger.Log("Errore nella lettura o hash del file " + filePath.ToString() + ".\nErrore: " + ex.Message.ToString(), LogType.ERROR); + + return null; + } + } + } +} diff --git a/BSHash/BSHash/Database.cs b/BSHash/BSHash/Database.cs new file mode 100644 index 0000000..1ddae0b --- /dev/null +++ b/BSHash/BSHash/Database.cs @@ -0,0 +1,242 @@ +using System; +using System.Data; +using System.Data.SqlClient; + +namespace BSHash +{ + public class Database + { + private readonly string _connectionString; + + public Database() + { + string serverstring = Properties.Settings.Default.Server; + string databasestring = Properties.Settings.Default.Database; + string userstring = Properties.Settings.Default.User; + string passwordstring = Properties.Settings.Default.Password; + + // Ricompongo la stringa di connessione + _connectionString = $"Server={serverstring};Database={databasestring};User Id={userstring};Password={passwordstring};"; + } + + public bool ClearHash() + { + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + connection.Open(); + using (SqlTransaction transaction = connection.BeginTransaction()) + { + try + { + // Delete all rows from the Hash table + string deleteQuery = "DELETE FROM Hash"; + using (SqlCommand deleteCommand = new SqlCommand(deleteQuery, connection, transaction)) + { + deleteCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + return true; + } + catch + { + transaction.Rollback(); + return false; + throw; + } + } + } + } + + public bool HashExists(string hash) + { + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + try + { + connection.Open(); + + // Controlla se l'hash esiste già nel database + string checkQuery = "SELECT COUNT(*) FROM Hash WHERE Hash = (@Hash)"; + using (SqlCommand checkCommand = new SqlCommand(checkQuery, connection)) + { + checkCommand.Parameters.AddWithValue("@Hash", hash); + int count = (int)checkCommand.ExecuteScalar(); + + return count != 0; + } + } + catch + { + return true; + throw; + } + } + } + + public bool InsertHash(string path, string hash) + { + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + connection.Open(); + using (SqlTransaction transaction = connection.BeginTransaction()) + { + try + { + // L'hash non esiste quindi lo inserisco + string insertQuery = "INSERT INTO Hash (Path, Hash) VALUES (@Path, @Hash)"; + using (SqlCommand insertCommand = new SqlCommand(insertQuery, connection, transaction)) + { + insertCommand.Parameters.AddWithValue("@Path", path); + insertCommand.Parameters.AddWithValue("@Hash", hash); + insertCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + + return true; + } + catch + { + transaction.Rollback(); + return false; + throw; + } + } + } + } + + public bool UpdateHash(string path, string hash) + { + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + connection.Open(); + using (SqlTransaction transaction = connection.BeginTransaction()) + { + try + { + // L'hash esiste quindi aggiorno la data di ultima scansione + string updateQuery = "UPDATE Hash SET Path = (@Path) WHERE Hash = (@Hash)"; + using (SqlCommand updateCommand = new SqlCommand(updateQuery, connection, transaction)) + { + updateCommand.Parameters.AddWithValue("@Path", path); + updateCommand.Parameters.AddWithValue("@Hash", hash); + updateCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + + return true; + } + catch + { + transaction.Rollback(); + + return false; + throw; + } + } + } + } + + public bool InsertHistory(string hash) + { + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + connection.Open(); + using (SqlTransaction transaction = connection.BeginTransaction()) + { + try + { + + // L'hash esiste quindi aggiorno la data di ultima scansione + string updateQuery = "INSERT INTO History (Hash) VALUES (@Hash)"; + using (SqlCommand updateCommand = new SqlCommand(updateQuery, connection, transaction)) + { + updateCommand.Parameters.AddWithValue("@Hash", hash); + updateCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + + return true; + } + catch + { + transaction.Rollback(); + + return false; + throw; + } + } + } + } + + public void InsertLog(string message, LogType type = LogType.INFO) + { + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + connection.Open(); + using (SqlTransaction transaction = connection.BeginTransaction()) + { + try + { + string query = "INSERT INTO Log (Message, Type) VALUES (@Message, @Type)"; + using (SqlCommand command = new SqlCommand(query, connection, transaction)) + { + command.Parameters.AddWithValue("@Message", message); + command.Parameters.AddWithValue("@Type", type); + command.ExecuteNonQuery(); + } + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + } + } + + public DataTable GetHashes() + { + DataTable hashes = new DataTable(); + + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + string query = "SELECT * FROM Hash"; + + using (SqlCommand command = new SqlCommand(query, connection)) + { + connection.Open(); + using (SqlDataReader reader = command.ExecuteReader()) + { + hashes.Load(reader); + } + } + } + + return hashes; + } + + public DataTable GetLogs(string query) + { + DataTable logs = new DataTable(); + + using (SqlConnection connection = new SqlConnection(_connectionString)) + { + using (SqlCommand command = new SqlCommand(query, connection)) + { + connection.Open(); + using (SqlDataReader reader = command.ExecuteReader()) + { + logs.Load(reader); + } + } + } + + return logs; + } + } +} diff --git a/BSHash/BSHash/Icons/BSHash.ico b/BSHash/BSHash/Icons/BSHash.ico new file mode 100644 index 0000000..aa5a96e Binary files /dev/null and b/BSHash/BSHash/Icons/BSHash.ico differ diff --git a/BSHash/BSHash/Logger.cs b/BSHash/BSHash/Logger.cs new file mode 100644 index 0000000..ea23d30 --- /dev/null +++ b/BSHash/BSHash/Logger.cs @@ -0,0 +1,138 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using static System.Windows.Forms.VisualStyles.VisualStyleElement; + +namespace BSHash +{ + public enum LogType + { + INFO, + DEBUG, + WARN, + ERROR, + FATAL, + TEST + } + + public enum LogStatus + { + ATTESA, + PREPARAZIONE, + ELABORAZIONE, + FERMATA, + COMPLETATO, + ERRORE + } + + public class Logger + { + private Database databaseHelper; + private System.Windows.Forms.TextBox logTextBox; + + public Logger(System.Windows.Forms.TextBox logTextBox, Database databaseHelper) + { + this.logTextBox = logTextBox; + this.databaseHelper = databaseHelper; + } + + public void Log(string message, LogType type = LogType.INFO) + { + databaseHelper.InsertLog(message, type); + } + + public void LogEsecuzioneExecute(LogStatus stato, long spazioscansionato, long scansionati, int errori, int warning) + { + StringBuilder log = new StringBuilder(); + + log.Append("Stato procedura: " + LogStatusToString(stato) + Environment.NewLine); + log.Append("Totale spazio scansionato: " + ConvertBytesToReadableSize(spazioscansionato) + Environment.NewLine); + log.Append("Totale file scansionati: " + scansionati + Environment.NewLine); + log.Append("Errori: " + errori + Environment.NewLine); + log.Append("Warning: " + warning + Environment.NewLine); + + SetLogTextBox(log.ToString()); + } + + public void LogDispositivoFill(LogStatus stato, int creati, int salvati, long spaziototale, long spazioriempito, int errori, int warning) + { + StringBuilder log = new StringBuilder(); + + log.Append("Stato procedura: " + LogStatusToString(stato) + Environment.NewLine); + log.Append("Spazio totale da riempire: " + ConvertBytesToReadableSize(spaziototale) + Environment.NewLine); + log.Append("Spazio occupato: " + ConvertBytesToReadableSize(spazioriempito) + Environment.NewLine); + log.Append("Totale file generati: " + creati + Environment.NewLine); + log.Append("Files salvati: " + salvati + Environment.NewLine); + log.Append("Errori: " + errori + Environment.NewLine); + log.Append("Warning: " + warning + Environment.NewLine); + + SetLogTextBox(log.ToString()); + } + + public void LogDispositivoCheck(LogStatus stato, int totale, int elaborati, int inseriti, int presenti, int errori, int warning) + { + StringBuilder log = new StringBuilder(); + + log.Append("Stato procedura: " + LogStatusToString(stato) + Environment.NewLine); + log.Append("Totale da scansionare: " + totale + Environment.NewLine); + log.Append("Files scansionati: " + elaborati + Environment.NewLine); + log.Append("Files aggiornati: " + presenti + Environment.NewLine); + log.Append("Files inseriti: " + inseriti + Environment.NewLine); + log.Append("Errori: " + errori + Environment.NewLine); + log.Append("Warning: " + warning + Environment.NewLine); + + SetLogTextBox(log.ToString()); + } + + public string LogStatusToString(LogStatus status) + { + switch (status) + { + case LogStatus.ATTESA: + return "In attesa di avvio"; + case LogStatus.PREPARAZIONE: + return "Preparazione per l'elaborazione..."; + case LogStatus.ELABORAZIONE: + return "In elaborazione..."; + case LogStatus.FERMATA: + return "Stoppata dall'utente"; + case LogStatus.COMPLETATO: + return "Completato"; + case LogStatus.ERRORE: + return "Errore"; + default: + return "In attesa di avvio"; + } + } + + public void SetLogTextBox(string log) + { + if (logTextBox.InvokeRequired) + { + logTextBox.Invoke(new Action(() => logTextBox.Text = log + Environment.NewLine)); + } + else + { + logTextBox.Text = log + Environment.NewLine; + } + } + + public static string ConvertBytesToReadableSize(long bytes) + { + string[] sizes = { "B", "KB", "MB", "GB", "TB" }; + double len = bytes; + int order = 0; + + while (len >= 1024 && order < sizes.Length - 1) + { + order++; + len = len / 1024; + } + + return $"{len:0.##} {sizes[order]}"; + } + } +} diff --git a/BSHash/BSHash/Main.Designer.cs b/BSHash/BSHash/Main.Designer.cs new file mode 100644 index 0000000..95a9d0a --- /dev/null +++ b/BSHash/BSHash/Main.Designer.cs @@ -0,0 +1,507 @@ +using System.Windows.Forms; + +namespace BSHash +{ + partial class Main + { + private System.ComponentModel.IContainer components = null; + + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + + base.Dispose(disposing); + } + + private System.Windows.Forms.DataGridView dataGridViewLogRows; + private System.Windows.Forms.Label labelImpostazioniPassword; + private System.Windows.Forms.Label labelImpostazioniUser; + private System.Windows.Forms.TextBox textBoxImpostazioniPassword; + private System.Windows.Forms.TextBox textBoxImpostazioniUser; + private System.Windows.Forms.Label labelImpostazioniServer; + private System.Windows.Forms.TextBox textBoxImpostazioniServer; + private ToolTip toolTipCheck; + private System.Windows.Forms.Button buttonDispositivoSfoglia; + private System.Windows.Forms.Label labelDispositivoPath; + private System.Windows.Forms.TextBox textBoxDispositivoPath; + private System.Windows.Forms.ProgressBar progressBarDispositivo; + private System.Windows.Forms.Button buttonDispositivoStop; + private System.Windows.Forms.TextBox textBoxDispositivoLog; + private System.Windows.Forms.TextBox textBoxImpostazioniDatabase; + private System.Windows.Forms.Label labelImpostazioniDatabase; + private System.Windows.Forms.Button buttonImpostazioniSalva; + private System.Windows.Forms.Button buttonExecuteStop; + private System.Windows.Forms.Label labelImpostazioniPath; + private System.Windows.Forms.TextBox textBoxImpostazioniPath; + private System.Windows.Forms.Button buttonImpostazioniBrowse; + private System.Windows.Forms.Label labelLogQuery; + private System.Windows.Forms.TextBox textBoxLogQuery; + private System.Windows.Forms.Button buttonLogQuery; + private System.Windows.Forms.Label labelLogRecordNumber; + private System.Windows.Forms.Label labelLogRecord; + private System.Windows.Forms.Button buttonDispositivoStart; + private System.Windows.Forms.RadioButton radioButtonDispositivoClear; + private System.Windows.Forms.RadioButton radioButtonDispositivoCheck; + private System.Windows.Forms.RadioButton radioButtonDispositivoFill; + private System.Windows.Forms.GroupBox groupBoxDispositivoChoice; + + private void InitializeComponent() + { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main)); + this.tabHash = new System.Windows.Forms.TabControl(); + this.tabPageExecute = new System.Windows.Forms.TabPage(); + this.buttonExecuteStop = new System.Windows.Forms.Button(); + this.buttonExecuteStart = new System.Windows.Forms.Button(); + this.textBoxExecuteLog = new System.Windows.Forms.TextBox(); + this.tabPageDispositivo = new System.Windows.Forms.TabPage(); + this.groupBoxDispositivoChoice = new System.Windows.Forms.GroupBox(); + this.radioButtonDispositivoClear = new System.Windows.Forms.RadioButton(); + this.radioButtonDispositivoCheck = new System.Windows.Forms.RadioButton(); + this.radioButtonDispositivoFill = new System.Windows.Forms.RadioButton(); + this.buttonDispositivoStart = new System.Windows.Forms.Button(); + this.textBoxDispositivoLog = new System.Windows.Forms.TextBox(); + this.progressBarDispositivo = new System.Windows.Forms.ProgressBar(); + this.buttonDispositivoStop = new System.Windows.Forms.Button(); + this.buttonDispositivoSfoglia = new System.Windows.Forms.Button(); + this.labelDispositivoPath = new System.Windows.Forms.Label(); + this.textBoxDispositivoPath = new System.Windows.Forms.TextBox(); + this.tabPageLog = new System.Windows.Forms.TabPage(); + this.labelLogRecordNumber = new System.Windows.Forms.Label(); + this.labelLogRecord = new System.Windows.Forms.Label(); + this.labelLogQuery = new System.Windows.Forms.Label(); + this.textBoxLogQuery = new System.Windows.Forms.TextBox(); + this.buttonLogQuery = new System.Windows.Forms.Button(); + this.dataGridViewLogRows = new System.Windows.Forms.DataGridView(); + this.tabPageImpostazioni = new System.Windows.Forms.TabPage(); + this.buttonImpostazioniBrowse = new System.Windows.Forms.Button(); + this.labelImpostazioniPath = new System.Windows.Forms.Label(); + this.textBoxImpostazioniPath = new System.Windows.Forms.TextBox(); + this.buttonImpostazioniSalva = new System.Windows.Forms.Button(); + this.textBoxImpostazioniDatabase = new System.Windows.Forms.TextBox(); + this.labelImpostazioniDatabase = new System.Windows.Forms.Label(); + this.labelImpostazioniPassword = new System.Windows.Forms.Label(); + this.labelImpostazioniUser = new System.Windows.Forms.Label(); + this.textBoxImpostazioniPassword = new System.Windows.Forms.TextBox(); + this.textBoxImpostazioniUser = new System.Windows.Forms.TextBox(); + this.labelImpostazioniServer = new System.Windows.Forms.Label(); + this.textBoxImpostazioniServer = new System.Windows.Forms.TextBox(); + this.toolTipCheck = new System.Windows.Forms.ToolTip(this.components); + this.tabHash.SuspendLayout(); + this.tabPageExecute.SuspendLayout(); + this.tabPageDispositivo.SuspendLayout(); + this.groupBoxDispositivoChoice.SuspendLayout(); + this.tabPageLog.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewLogRows)).BeginInit(); + this.tabPageImpostazioni.SuspendLayout(); + this.SuspendLayout(); + // + // tabHash + // + this.tabHash.Alignment = System.Windows.Forms.TabAlignment.Left; + this.tabHash.Controls.Add(this.tabPageExecute); + this.tabHash.Controls.Add(this.tabPageDispositivo); + this.tabHash.Controls.Add(this.tabPageLog); + this.tabHash.Controls.Add(this.tabPageImpostazioni); + this.tabHash.Location = new System.Drawing.Point(12, 12); + this.tabHash.Multiline = true; + this.tabHash.Name = "tabHash"; + this.tabHash.SelectedIndex = 0; + this.tabHash.Size = new System.Drawing.Size(675, 300); + this.tabHash.TabIndex = 0; + // + // tabPageExecute + // + this.tabPageExecute.Controls.Add(this.buttonExecuteStop); + this.tabPageExecute.Controls.Add(this.buttonExecuteStart); + this.tabPageExecute.Controls.Add(this.textBoxExecuteLog); + this.tabPageExecute.Location = new System.Drawing.Point(23, 4); + this.tabPageExecute.Name = "tabPageExecute"; + this.tabPageExecute.Padding = new System.Windows.Forms.Padding(3); + this.tabPageExecute.Size = new System.Drawing.Size(648, 292); + this.tabPageExecute.TabIndex = 0; + this.tabPageExecute.Text = "Esecuzione"; + this.tabPageExecute.UseVisualStyleBackColor = true; + // + // buttonExecuteStop + // + this.buttonExecuteStop.Enabled = false; + this.buttonExecuteStop.Location = new System.Drawing.Point(313, 6); + this.buttonExecuteStop.Name = "buttonExecuteStop"; + this.buttonExecuteStop.Size = new System.Drawing.Size(327, 23); + this.buttonExecuteStop.TabIndex = 8; + this.buttonExecuteStop.Text = "Stop"; + // + // buttonExecuteStart + // + this.buttonExecuteStart.Location = new System.Drawing.Point(9, 6); + this.buttonExecuteStart.Name = "buttonExecuteStart"; + this.buttonExecuteStart.Size = new System.Drawing.Size(298, 23); + this.buttonExecuteStart.TabIndex = 4; + this.buttonExecuteStart.Text = "Avvia"; + this.buttonExecuteStart.Click += new System.EventHandler(this.StartButton_Click); + // + // textBoxExecuteLog + // + this.textBoxExecuteLog.BackColor = System.Drawing.SystemColors.MenuText; + this.textBoxExecuteLog.ForeColor = System.Drawing.SystemColors.Menu; + this.textBoxExecuteLog.Location = new System.Drawing.Point(9, 35); + this.textBoxExecuteLog.Multiline = true; + this.textBoxExecuteLog.Name = "textBoxExecuteLog"; + this.textBoxExecuteLog.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal; + this.textBoxExecuteLog.Size = new System.Drawing.Size(631, 251); + this.textBoxExecuteLog.TabIndex = 7; + // + // tabPageDispositivo + // + this.tabPageDispositivo.Controls.Add(this.groupBoxDispositivoChoice); + this.tabPageDispositivo.Controls.Add(this.buttonDispositivoStart); + this.tabPageDispositivo.Controls.Add(this.textBoxDispositivoLog); + this.tabPageDispositivo.Controls.Add(this.progressBarDispositivo); + this.tabPageDispositivo.Controls.Add(this.buttonDispositivoStop); + this.tabPageDispositivo.Controls.Add(this.buttonDispositivoSfoglia); + this.tabPageDispositivo.Controls.Add(this.labelDispositivoPath); + this.tabPageDispositivo.Controls.Add(this.textBoxDispositivoPath); + this.tabPageDispositivo.Location = new System.Drawing.Point(23, 4); + this.tabPageDispositivo.Name = "tabPageDispositivo"; + this.tabPageDispositivo.Padding = new System.Windows.Forms.Padding(3); + this.tabPageDispositivo.Size = new System.Drawing.Size(648, 292); + this.tabPageDispositivo.TabIndex = 1; + this.tabPageDispositivo.Text = "Dispositivo"; + this.tabPageDispositivo.UseVisualStyleBackColor = true; + // + // groupBoxDispositivoChoice + // + this.groupBoxDispositivoChoice.Controls.Add(this.radioButtonDispositivoClear); + this.groupBoxDispositivoChoice.Controls.Add(this.radioButtonDispositivoCheck); + this.groupBoxDispositivoChoice.Controls.Add(this.radioButtonDispositivoFill); + this.groupBoxDispositivoChoice.Location = new System.Drawing.Point(9, 32); + this.groupBoxDispositivoChoice.Name = "groupBoxDispositivoChoice"; + this.groupBoxDispositivoChoice.Size = new System.Drawing.Size(160, 82); + this.groupBoxDispositivoChoice.TabIndex = 14; + this.groupBoxDispositivoChoice.TabStop = false; + this.groupBoxDispositivoChoice.Text = "Funzionalità"; + // + // radioButtonDispositivoClear + // + this.radioButtonDispositivoClear.AutoSize = true; + this.radioButtonDispositivoClear.Location = new System.Drawing.Point(6, 59); + this.radioButtonDispositivoClear.Name = "radioButtonDispositivoClear"; + this.radioButtonDispositivoClear.Size = new System.Drawing.Size(55, 17); + this.radioButtonDispositivoClear.TabIndex = 12; + this.radioButtonDispositivoClear.Text = "Pulisci"; + this.radioButtonDispositivoClear.UseVisualStyleBackColor = true; + // + // radioButtonDispositivoCheck + // + this.radioButtonDispositivoCheck.AutoSize = true; + this.radioButtonDispositivoCheck.Checked = true; + this.radioButtonDispositivoCheck.Location = new System.Drawing.Point(6, 39); + this.radioButtonDispositivoCheck.Name = "radioButtonDispositivoCheck"; + this.radioButtonDispositivoCheck.Size = new System.Drawing.Size(66, 17); + this.radioButtonDispositivoCheck.TabIndex = 11; + this.radioButtonDispositivoCheck.TabStop = true; + this.radioButtonDispositivoCheck.Text = "Controlla"; + this.toolTipCheck.SetToolTip(this.radioButtonDispositivoCheck, resources.GetString("radioButtonDispositivoCheck.ToolTip")); + this.radioButtonDispositivoCheck.UseVisualStyleBackColor = true; + // + // radioButtonDispositivoFill + // + this.radioButtonDispositivoFill.AutoSize = true; + this.radioButtonDispositivoFill.Location = new System.Drawing.Point(6, 19); + this.radioButtonDispositivoFill.Name = "radioButtonDispositivoFill"; + this.radioButtonDispositivoFill.Size = new System.Drawing.Size(57, 17); + this.radioButtonDispositivoFill.TabIndex = 10; + this.radioButtonDispositivoFill.Text = "Riempi"; + this.radioButtonDispositivoFill.UseVisualStyleBackColor = true; + // + // buttonDispositivoStart + // + this.buttonDispositivoStart.Location = new System.Drawing.Point(175, 33); + this.buttonDispositivoStart.Name = "buttonDispositivoStart"; + this.buttonDispositivoStart.Size = new System.Drawing.Size(467, 23); + this.buttonDispositivoStart.TabIndex = 13; + this.buttonDispositivoStart.Text = "Avvia"; + this.buttonDispositivoStart.UseVisualStyleBackColor = true; + this.buttonDispositivoStart.Click += new System.EventHandler(this.buttonDispositivoStart_ClickAsync); + // + // textBoxDispositivoLog + // + this.textBoxDispositivoLog.BackColor = System.Drawing.SystemColors.MenuText; + this.textBoxDispositivoLog.ForeColor = System.Drawing.SystemColors.Menu; + this.textBoxDispositivoLog.Location = new System.Drawing.Point(9, 120); + this.textBoxDispositivoLog.Multiline = true; + this.textBoxDispositivoLog.Name = "textBoxDispositivoLog"; + this.textBoxDispositivoLog.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal; + this.textBoxDispositivoLog.Size = new System.Drawing.Size(633, 166); + this.textBoxDispositivoLog.TabIndex = 8; + // + // progressBarDispositivo + // + this.progressBarDispositivo.Location = new System.Drawing.Point(175, 91); + this.progressBarDispositivo.Name = "progressBarDispositivo"; + this.progressBarDispositivo.Size = new System.Drawing.Size(467, 23); + this.progressBarDispositivo.TabIndex = 6; + // + // buttonDispositivoStop + // + this.buttonDispositivoStop.Enabled = false; + this.buttonDispositivoStop.Location = new System.Drawing.Point(175, 62); + this.buttonDispositivoStop.Name = "buttonDispositivoStop"; + this.buttonDispositivoStop.Size = new System.Drawing.Size(467, 23); + this.buttonDispositivoStop.TabIndex = 5; + this.buttonDispositivoStop.Text = "Stop"; + this.buttonDispositivoStop.UseVisualStyleBackColor = true; + this.buttonDispositivoStop.Click += new System.EventHandler(this.buttonDispositivoStop_Click); + // + // buttonDispositivoSfoglia + // + this.buttonDispositivoSfoglia.Location = new System.Drawing.Point(567, 4); + this.buttonDispositivoSfoglia.Name = "buttonDispositivoSfoglia"; + this.buttonDispositivoSfoglia.Size = new System.Drawing.Size(75, 23); + this.buttonDispositivoSfoglia.TabIndex = 2; + this.buttonDispositivoSfoglia.Text = "Sfoglia"; + this.buttonDispositivoSfoglia.UseVisualStyleBackColor = true; + this.buttonDispositivoSfoglia.Click += new System.EventHandler(this.buttonDispositivoSfoglia_Click); + // + // labelDispositivoPath + // + this.labelDispositivoPath.AutoSize = true; + this.labelDispositivoPath.Location = new System.Drawing.Point(6, 9); + this.labelDispositivoPath.Name = "labelDispositivoPath"; + this.labelDispositivoPath.Size = new System.Drawing.Size(49, 13); + this.labelDispositivoPath.TabIndex = 1; + this.labelDispositivoPath.Text = "Percorso"; + // + // textBoxDispositivoPath + // + this.textBoxDispositivoPath.Location = new System.Drawing.Point(61, 6); + this.textBoxDispositivoPath.Name = "textBoxDispositivoPath"; + this.textBoxDispositivoPath.ReadOnly = true; + this.textBoxDispositivoPath.Size = new System.Drawing.Size(500, 20); + this.textBoxDispositivoPath.TabIndex = 0; + // + // tabPageLog + // + this.tabPageLog.Controls.Add(this.labelLogRecordNumber); + this.tabPageLog.Controls.Add(this.labelLogRecord); + this.tabPageLog.Controls.Add(this.labelLogQuery); + this.tabPageLog.Controls.Add(this.textBoxLogQuery); + this.tabPageLog.Controls.Add(this.buttonLogQuery); + this.tabPageLog.Controls.Add(this.dataGridViewLogRows); + this.tabPageLog.ImeMode = System.Windows.Forms.ImeMode.NoControl; + this.tabPageLog.Location = new System.Drawing.Point(23, 4); + this.tabPageLog.Name = "tabPageLog"; + this.tabPageLog.Padding = new System.Windows.Forms.Padding(3); + this.tabPageLog.Size = new System.Drawing.Size(648, 292); + this.tabPageLog.TabIndex = 1; + this.tabPageLog.Text = "Log"; + this.tabPageLog.UseVisualStyleBackColor = true; + // + // labelLogRecordNumber + // + this.labelLogRecordNumber.AutoSize = true; + this.labelLogRecordNumber.Location = new System.Drawing.Point(88, 276); + this.labelLogRecordNumber.Name = "labelLogRecordNumber"; + this.labelLogRecordNumber.Size = new System.Drawing.Size(13, 13); + this.labelLogRecordNumber.TabIndex = 9; + this.labelLogRecordNumber.Text = "0"; + // + // labelLogRecord + // + this.labelLogRecord.AutoSize = true; + this.labelLogRecord.Location = new System.Drawing.Point(6, 276); + this.labelLogRecord.Name = "labelLogRecord"; + this.labelLogRecord.Size = new System.Drawing.Size(76, 13); + this.labelLogRecord.TabIndex = 8; + this.labelLogRecord.Text = "Record estratti"; + // + // labelLogQuery + // + this.labelLogQuery.AutoSize = true; + this.labelLogQuery.Location = new System.Drawing.Point(6, 13); + this.labelLogQuery.Name = "labelLogQuery"; + this.labelLogQuery.Size = new System.Drawing.Size(35, 13); + this.labelLogQuery.TabIndex = 7; + this.labelLogQuery.Text = "Query"; + // + // textBoxLogQuery + // + this.textBoxLogQuery.Enabled = false; + this.textBoxLogQuery.Location = new System.Drawing.Point(47, 10); + this.textBoxLogQuery.Name = "textBoxLogQuery"; + this.textBoxLogQuery.ReadOnly = true; + this.textBoxLogQuery.Size = new System.Drawing.Size(500, 20); + this.textBoxLogQuery.TabIndex = 6; + this.textBoxLogQuery.Text = "SELECT Date, Type, Message FROM Log ORDER BY Date DESC"; + // + // buttonLogQuery + // + this.buttonLogQuery.Location = new System.Drawing.Point(553, 8); + this.buttonLogQuery.Name = "buttonLogQuery"; + this.buttonLogQuery.Size = new System.Drawing.Size(89, 23); + this.buttonLogQuery.TabIndex = 5; + this.buttonLogQuery.Text = "Esegui"; + this.buttonLogQuery.UseVisualStyleBackColor = true; + this.buttonLogQuery.Click += new System.EventHandler(this.buttonLogQuery_Click); + // + // dataGridViewLogRows + // + this.dataGridViewLogRows.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + this.dataGridViewLogRows.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridViewLogRows.Location = new System.Drawing.Point(6, 37); + this.dataGridViewLogRows.Name = "dataGridViewLogRows"; + this.dataGridViewLogRows.ReadOnly = true; + this.dataGridViewLogRows.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.dataGridViewLogRows.Size = new System.Drawing.Size(636, 236); + this.dataGridViewLogRows.TabIndex = 0; + // + // tabPageImpostazioni + // + this.tabPageImpostazioni.Controls.Add(this.buttonImpostazioniBrowse); + this.tabPageImpostazioni.Controls.Add(this.labelImpostazioniPath); + this.tabPageImpostazioni.Controls.Add(this.textBoxImpostazioniPath); + this.tabPageImpostazioni.Controls.Add(this.buttonImpostazioniSalva); + this.tabPageImpostazioni.Controls.Add(this.textBoxImpostazioniDatabase); + this.tabPageImpostazioni.Controls.Add(this.labelImpostazioniDatabase); + this.tabPageImpostazioni.Controls.Add(this.labelImpostazioniPassword); + this.tabPageImpostazioni.Controls.Add(this.labelImpostazioniUser); + this.tabPageImpostazioni.Controls.Add(this.textBoxImpostazioniPassword); + this.tabPageImpostazioni.Controls.Add(this.textBoxImpostazioniUser); + this.tabPageImpostazioni.Controls.Add(this.labelImpostazioniServer); + this.tabPageImpostazioni.Controls.Add(this.textBoxImpostazioniServer); + this.tabPageImpostazioni.Location = new System.Drawing.Point(23, 4); + this.tabPageImpostazioni.Name = "tabPageImpostazioni"; + this.tabPageImpostazioni.Padding = new System.Windows.Forms.Padding(3); + this.tabPageImpostazioni.Size = new System.Drawing.Size(648, 292); + this.tabPageImpostazioni.TabIndex = 1; + this.tabPageImpostazioni.Text = "Impostazioni"; + this.tabPageImpostazioni.UseVisualStyleBackColor = true; + // + // buttonImpostazioniBrowse + // + this.buttonImpostazioniBrowse.Location = new System.Drawing.Point(567, 109); + this.buttonImpostazioniBrowse.Name = "buttonImpostazioniBrowse"; + this.buttonImpostazioniBrowse.Size = new System.Drawing.Size(75, 23); + this.buttonImpostazioniBrowse.TabIndex = 11; + this.buttonImpostazioniBrowse.Text = "Sfoglia"; + this.buttonImpostazioniBrowse.UseVisualStyleBackColor = true; + this.buttonImpostazioniBrowse.Click += new System.EventHandler(this.buttonImpostazioniBrowse_Click); + // + // labelImpostazioniPath + // + this.labelImpostazioniPath.AutoSize = true; + this.labelImpostazioniPath.Location = new System.Drawing.Point(6, 114); + this.labelImpostazioniPath.Name = "labelImpostazioniPath"; + this.labelImpostazioniPath.Size = new System.Drawing.Size(49, 13); + this.labelImpostazioniPath.TabIndex = 10; + this.labelImpostazioniPath.Text = "Percorso"; + // + // textBoxImpostazioniPath + // + this.textBoxImpostazioniPath.Location = new System.Drawing.Point(70, 111); + this.textBoxImpostazioniPath.Name = "textBoxImpostazioniPath"; + this.textBoxImpostazioniPath.Size = new System.Drawing.Size(491, 20); + this.textBoxImpostazioniPath.TabIndex = 9; + // + // buttonImpostazioniSalva + // + this.buttonImpostazioniSalva.Location = new System.Drawing.Point(567, 137); + this.buttonImpostazioniSalva.Name = "buttonImpostazioniSalva"; + this.buttonImpostazioniSalva.Size = new System.Drawing.Size(75, 23); + this.buttonImpostazioniSalva.TabIndex = 8; + this.buttonImpostazioniSalva.Text = "Salva"; + this.buttonImpostazioniSalva.UseVisualStyleBackColor = true; + this.buttonImpostazioniSalva.Click += new System.EventHandler(this.buttonImpostazioniSalva_Click); + // + // textBoxImpostazioniDatabase + // + this.textBoxImpostazioniDatabase.Location = new System.Drawing.Point(70, 85); + this.textBoxImpostazioniDatabase.Name = "textBoxImpostazioniDatabase"; + this.textBoxImpostazioniDatabase.Size = new System.Drawing.Size(572, 20); + this.textBoxImpostazioniDatabase.TabIndex = 7; + // + // labelImpostazioniDatabase + // + this.labelImpostazioniDatabase.AutoSize = true; + this.labelImpostazioniDatabase.Location = new System.Drawing.Point(6, 88); + this.labelImpostazioniDatabase.Name = "labelImpostazioniDatabase"; + this.labelImpostazioniDatabase.Size = new System.Drawing.Size(53, 13); + this.labelImpostazioniDatabase.TabIndex = 6; + this.labelImpostazioniDatabase.Text = "Database"; + // + // labelImpostazioniPassword + // + this.labelImpostazioniPassword.AutoSize = true; + this.labelImpostazioniPassword.Location = new System.Drawing.Point(6, 62); + this.labelImpostazioniPassword.Name = "labelImpostazioniPassword"; + this.labelImpostazioniPassword.Size = new System.Drawing.Size(53, 13); + this.labelImpostazioniPassword.TabIndex = 5; + this.labelImpostazioniPassword.Text = "Password"; + // + // labelImpostazioniUser + // + this.labelImpostazioniUser.AutoSize = true; + this.labelImpostazioniUser.Location = new System.Drawing.Point(6, 36); + this.labelImpostazioniUser.Name = "labelImpostazioniUser"; + this.labelImpostazioniUser.Size = new System.Drawing.Size(39, 13); + this.labelImpostazioniUser.TabIndex = 4; + this.labelImpostazioniUser.Text = "Utente"; + // + // textBoxImpostazioniPassword + // + this.textBoxImpostazioniPassword.Location = new System.Drawing.Point(70, 59); + this.textBoxImpostazioniPassword.Name = "textBoxImpostazioniPassword"; + this.textBoxImpostazioniPassword.Size = new System.Drawing.Size(572, 20); + this.textBoxImpostazioniPassword.TabIndex = 3; + // + // textBoxImpostazioniUser + // + this.textBoxImpostazioniUser.Location = new System.Drawing.Point(70, 33); + this.textBoxImpostazioniUser.Name = "textBoxImpostazioniUser"; + this.textBoxImpostazioniUser.Size = new System.Drawing.Size(572, 20); + this.textBoxImpostazioniUser.TabIndex = 2; + // + // labelImpostazioniServer + // + this.labelImpostazioniServer.AutoSize = true; + this.labelImpostazioniServer.Location = new System.Drawing.Point(6, 10); + this.labelImpostazioniServer.Name = "labelImpostazioniServer"; + this.labelImpostazioniServer.Size = new System.Drawing.Size(38, 13); + this.labelImpostazioniServer.TabIndex = 1; + this.labelImpostazioniServer.Text = "Server"; + // + // textBoxImpostazioniServer + // + this.textBoxImpostazioniServer.Location = new System.Drawing.Point(70, 7); + this.textBoxImpostazioniServer.Name = "textBoxImpostazioniServer"; + this.textBoxImpostazioniServer.Size = new System.Drawing.Size(572, 20); + this.textBoxImpostazioniServer.TabIndex = 0; + // + // Main + // + this.ClientSize = new System.Drawing.Size(698, 323); + this.Controls.Add(this.tabHash); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "Main"; + this.Text = "BS Hash Management"; + this.tabHash.ResumeLayout(false); + this.tabPageExecute.ResumeLayout(false); + this.tabPageExecute.PerformLayout(); + this.tabPageDispositivo.ResumeLayout(false); + this.tabPageDispositivo.PerformLayout(); + this.groupBoxDispositivoChoice.ResumeLayout(false); + this.groupBoxDispositivoChoice.PerformLayout(); + this.tabPageLog.ResumeLayout(false); + this.tabPageLog.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridViewLogRows)).EndInit(); + this.tabPageImpostazioni.ResumeLayout(false); + this.tabPageImpostazioni.PerformLayout(); + this.ResumeLayout(false); + } + } +} diff --git a/BSHash/BSHash/Main.cs b/BSHash/BSHash/Main.cs new file mode 100644 index 0000000..795a298 --- /dev/null +++ b/BSHash/BSHash/Main.cs @@ -0,0 +1,330 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Data.SqlClient; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Security.Policy; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BSHash +{ + public partial class Main : Form + { + //Grafica + public Button buttonExecuteStart; + public TextBox textBoxExecuteLog; + public Database databaseHelper; + public Calculator fileHashCalculator; + public Storage storage; + public TabControl tabHash; + public TabPage tabPageExecute; + public TabPage tabPageLog; + public TabPage tabPageDispositivo; + public TabPage tabPageImpostazioni; + public Logger logger; + public Logger loggerDispositivo; + + //cancellazione + private CancellationTokenSource _cancellationTokenSource; + // Nella classe Main.cs + + + public Main() + { + InitializeComponent(); + LoadSettings(); + + textBoxDispositivoPath.Text = Properties.Settings.Default.Path; + + databaseHelper = new Database(); + logger = new Logger(textBoxExecuteLog, databaseHelper); + loggerDispositivo = new Logger(textBoxDispositivoLog, databaseHelper); + fileHashCalculator = new Calculator(logger); + storage = new Storage(loggerDispositivo); + tabHash.SelectedIndexChanged += new EventHandler(tabControl_SelectedIndexChanged); + } + + private async void StartButton_Click(object sender, EventArgs e) + { + // Inizializza il CancellationTokenSource + _cancellationTokenSource = new CancellationTokenSource(); + CancellationToken cancellationToken = _cancellationTokenSource.Token; + + // Disabilita i controlli durante l'esecuzione + buttonExecuteStart.Enabled = false; + buttonExecuteStop.Enabled = true; + + long spazioscansionato = 0; + long scansionati = 0; + int errori = 0; + int warning = 0; + + logger.LogEsecuzioneExecute(LogStatus.PREPARAZIONE, spazioscansionato, scansionati, errori, warning); + logger.Log("Inizio procedura principale.", LogType.INFO); + + // Esegui il calcolo degli hash e l'inserimento nel database in un thread separato + await Task.Run(async () => + { + while (!cancellationToken.IsCancellationRequested) + { + logger.Log("Scansione database... ", LogType.INFO); + + DataTable hashes = databaseHelper.GetHashes(); + + int totalFiles = hashes.Rows.Count; + int processedFiles = 0; + + logger.Log("Trovati " + totalFiles.ToString() + " da scansionare.", LogType.INFO); + + foreach (DataRow row in hashes.Rows) + { + if (cancellationToken.IsCancellationRequested) + { + logger.Log("Procedura interrotta dall'utente.", LogType.WARN); + break; + } + + string filePath = row["Path"].ToString(); + string hash = row["Hash"].ToString(); + + processedFiles++; + scansionati++; + + logger.Log("Scansione file " + processedFiles.ToString() + " / " + totalFiles.ToString() + ". Percorso: " + filePath, LogType.INFO); + + if (!File.Exists(filePath)) + { + logger.Log("Il file " + filePath + " non esiste.", LogType.ERROR); + continue; + } + + FileInfo fileInfo = new FileInfo(filePath); + spazioscansionato += fileInfo.Length; + + logger.Log("Calcolo hash per il file " + filePath + ".", LogType.INFO); + + string calculatedHash = fileHashCalculator.CalculateHash(filePath); + + if (calculatedHash == null) + { + logger.Log("Non è stato possibile calcolare l'hash del file " + filePath, LogType.ERROR); + continue; + } + + if (calculatedHash != hash) + { + logger.Log("L'hash calcolato dal file (" + calculatedHash + ") è diverso da quell inserito nel database (" + hash + ")", LogType.ERROR); + continue; + } + + Network network = new Network(logger); + + var sendDataHashTask = network.SendDataHash(calculatedHash); + if (await sendDataHashTask != Network.OK) + { + logger.Log("Errore nell'invio dell'hash " + calculatedHash, LogType.INFO); + continue; + } + + var getDataHashTask = network.GetDataHash(calculatedHash); + if (await getDataHashTask != Network.OK) + { + logger.Log("Errore nella ricezione della risposta dell'hash " + calculatedHash, LogType.INFO); + continue; + } + + databaseHelper.InsertHistory(calculatedHash); + logger.LogEsecuzioneExecute(LogStatus.ELABORAZIONE, spazioscansionato, scansionati, errori, warning); + } + + logger.Log("Calcolati correttamente " + processedFiles.ToString() + " su " + totalFiles.ToString() + ".", LogType.INFO); + } + }, cancellationToken); + + logger.LogEsecuzioneExecute(LogStatus.FERMATA, spazioscansionato, scansionati, errori, warning); + logger.Log("Procedura terminata.", LogType.INFO); + + // Riabilita i controlli dopo l'esecuzione + buttonExecuteStart.Enabled = true; + buttonExecuteStop.Enabled = false; + } + + private void tabControl_SelectedIndexChanged(object sender, EventArgs e) + { + if (tabHash.SelectedTab == tabPageLog) + { + //LoadLogs(); + } + } + + private void LoadLogs() + { + DataTable logs = databaseHelper.GetLogs(textBoxLogQuery.Text); + dataGridViewLogRows.DataSource = logs; + labelLogRecordNumber.Text = dataGridViewLogRows.RowCount.ToString(); + } + + private void buttonDispositivoSfoglia_Click(object sender, EventArgs e) + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (folderBrowserDialog.ShowDialog() == DialogResult.OK) + { + textBoxDispositivoPath.Text = folderBrowserDialog.SelectedPath; + } + } + } + + private void LoadSettings() + { + textBoxImpostazioniServer.Text = Properties.Settings.Default.Server; + textBoxImpostazioniUser.Text = Properties.Settings.Default.User; + textBoxImpostazioniPassword.Text = Properties.Settings.Default.Password; + textBoxImpostazioniDatabase.Text = Properties.Settings.Default.Database; + textBoxImpostazioniPath.Text = Properties.Settings.Default.Path; + } + + private void SaveSettings() + { + Properties.Settings.Default.Server = textBoxImpostazioniServer.Text; + Properties.Settings.Default.User = textBoxImpostazioniUser.Text; + Properties.Settings.Default.Password = textBoxImpostazioniPassword.Text; + Properties.Settings.Default.Database = textBoxImpostazioniDatabase.Text; + Properties.Settings.Default.Path = textBoxImpostazioniPath.Text; + Properties.Settings.Default.Save(); + } + + protected override void OnFormClosing(FormClosingEventArgs e) + { + SaveSettings(); + base.OnFormClosing(e); + } + + private void buttonImpostazioniSalva_Click(object sender, EventArgs e) + { + SaveSettings(); + } + + private void SetControlEnabled(bool enabled) + { + if (InvokeRequired) + { + Invoke(new Action(SetControlEnabled), enabled); + } + else + { + buttonDispositivoStart.Enabled = enabled; + buttonDispositivoStop.Enabled = !enabled; + } + } + + private void buttonImpostazioniBrowse_Click(object sender, EventArgs e) + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (folderBrowserDialog.ShowDialog() == DialogResult.OK) + { + textBoxImpostazioniPath.Text = folderBrowserDialog.SelectedPath; + } + } + } + + private void buttonLogQuery_Click(object sender, EventArgs e) + { + LoadLogs(); + } + + private async void buttonDispositivoStart_ClickAsync(object sender, EventArgs e) + { + if (radioButtonDispositivoCheck.Checked) + { + // Controlla se il percorso esiste + if (!Directory.Exists(textBoxDispositivoPath.Text)) + { + loggerDispositivo.Log("Errore: Il percorso specificato non esiste.", LogType.FATAL); + return; + } + + loggerDispositivo.Log("Caricamento informazioni per esecuzione...", LogType.INFO); + + // Disabilita i controlli prima dell'esecuzione e abilita il pulsante Stop + SetControlEnabled(false); + buttonDispositivoStop.Enabled = true; + + // Esegui il riempimento del percorso in un thread separato + await Task.Run(() => + { + // Avvio il riempimento del dispositivo + storage.StartCheckFiles(textBoxDispositivoPath.Text, progressBarDispositivo, buttonDispositivoStart, buttonDispositivoStop); + }); + } + + if(radioButtonDispositivoFill.Checked) + { + // Controlla se il percorso esiste + if (!Directory.Exists(textBoxDispositivoPath.Text)) + { + loggerDispositivo.Log("Errore: Il percorso specificato non esiste.", LogType.FATAL); + return; + } + + loggerDispositivo.Log("Caricamento informazioni per esecuzione...", LogType.INFO); + + // Disabilita i controlli prima dell'esecuzione e abilita il pulsante Stop + SetControlEnabled(false); + buttonDispositivoStop.Enabled = true; + + // Esegui il riempimento del percorso in un thread separato + await Task.Run(() => + { + // Avvio il riempimento del dispositivo + storage.StartFillStorage(textBoxDispositivoPath.Text, progressBarDispositivo, buttonDispositivoStart, buttonDispositivoStop); + }); + } + + if (radioButtonDispositivoClear.Checked) + { + // Controlla se il percorso esiste + if (!Directory.Exists(textBoxDispositivoPath.Text)) + { + loggerDispositivo.Log("Errore: Il percorso specificato non esiste.", LogType.FATAL); + return; + } + + // Disabilita i controlli prima dell'esecuzione e abilita il pulsante Stop + SetControlEnabled(false); + buttonDispositivoStop.Enabled = true; + + // Esegui la pulizia del percorso in un thread separato + await Task.Run(() => + { + // Avvio la pulizia del dispositivo in un thread separato + storage.StartClearStorage(textBoxDispositivoPath.Text, progressBarDispositivo, buttonDispositivoStart, buttonDispositivoStop); + }); + } + } + + private void buttonDispositivoStop_Click(object sender, EventArgs e) + { + //Fermo l'attività avviata + storage.StopFillStorage(progressBarDispositivo, buttonDispositivoStart, buttonDispositivoStop); + //storage.StopCheckStorage(progressBarDispositivo, buttonDispositivoStart, buttonDispositivoStop); + storage.StopClearStorage(progressBarDispositivo, buttonDispositivoStart, buttonDispositivoStop); + + // Riabilita i controlli dopo l'esecuzione + SetControlEnabled(true); + } + private void buttonExecuteStop_Click(object sender, EventArgs e) + { + // Annulla l'operazione + _cancellationTokenSource?.Cancel(); + } + } +} diff --git a/BSHash/BSHash/Main.resx b/BSHash/BSHash/Main.resx new file mode 100644 index 0000000..7603038 --- /dev/null +++ b/BSHash/BSHash/Main.resx @@ -0,0 +1,203 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + Avviando questa procedura verrà ricreata la tabella Hash. Tutti gli Hash presenti verranno eliminati e inseriti quelli del nuovo percorso. Usarlo solo in caso di modifica sostanziale al percorso di scansione. + + + + + AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAMMOAADDDgAAAAAAAAAA + AAD//////////9HCr/+HWSD/gksH/4JNC/+DUA//h1MQ/4xXEf+RXBP/l2EV/59nFv+obhj/rnMa/7N4 + G/+5fR3/u38c/7t+G/+5fBr/s3ca/6huGP+haBf/mmMW/5JdFf+KVxP/hFMS/4BPEv9+TBL/g1Yi/8q4 + pf/////////////////08e3/oHM9/5ZVBf+eWwj/oF0L/6FfDv+kYhD/p2US/6xqFP+xbxb/tXIX/7h2 + GP+7eRj/vXsZ/758Gf++fBn/vnsY/7x6GP+6eBj/uHYW/7VzFf+ycBT/rWwT/6hoEv+iYxL/nF4S/5Za + Ev+QVRH/k2k3/+7q5P///////////+Tazv+aXxf/m1gH/5tZB/+gXAb/pmAE/6pkBP+rZgf/r2oI/7Ru + Cf+4cgj/u3UI/753B//BeQf/wnoH/8J6B//BeQf/v3gH/713CP+7dQj/uHMH/7VwBv+xbAb/rGkH/6Zk + Cf+fXgn/mVkK/5VWCv+NVxb/18u7////////////3s68/6BgEf+fWgj/ol4G/6VhBv+oYwX/rWcF/7Fr + B/+1bgj/unMI/753CP/Begj/xX0H/8d/B//IgAf/yIAH/8d/CP/Gfgj/xH0I/8F7CP++eAj/u3UI/7Zx + B/+xbgj/q2kJ/6VjCf+eXgr/mFkL/5BXD//NvKf////////////Yw6r/nlwL/59aB/+lXwb/qmQG/61m + Bv+zbAb/uHAH/7tzB/+/dwb/w3oH/8Z+B//KgQf/zIQG/86FBv/NhQf/zIUH/8uDB//IgQf/xn8I/8N9 + CP+/egf/u3YI/7ZyCP+wbQn/qWcJ/6JhCv+cXAr/k1cM/8eyl////////////820lv+fXAf/pF4H/6Zg + B/+uZwf/t28H/7dvBv++dQf/wXgG/8R7Bf/Hfwb/y4IG/86GBv/RiAb/0ooH/9OKB//SiQf/0IgH/86G + B//LhQf/yIEH/8R+B/+/egj/unUI/7RwCP+uawn/p2UK/59fCv+WWQr/vqWF////////////xqmE/6Fd + Bv+mYQf/qWMG/7BpB/+1bQf/vHQI/8V7Cf/Eewj/yoEH/82DBv/Qhgb/1IoH/9aMB//Xjgf/2I8G/9eO + Bv/VjAf/04sH/9GJB//Nhgf/yYIH/8R+CP++eQj/uHQI/7JuCf+qaAr/o2IJ/5laCf+1mXT///////// + ///BnnP/oV4G/6lkCP+sZQf/smsI/7ZvCP+8dAn/xHsK/82ECv/OhQn/0YgI/9WLB//Zjgf/2pEH/9qS + B//bkwf/2pIH/9mRB//YkAf/1Y0I/9GKCP/NhQf/x4EI/8J8Cf+8dgj/tXEJ/65rCf+mZAn/nF0I/7CP + ZP/9/f3//f3+/7iSYv+mYgf/qWQJ/61nCf+3bwr/vHQK/752Cf/Gfgr/0IYL/9CHC//VjQz/2ZAL/9yT + Cf/dlAj/35UI/96WCP/dlgj/3ZUJ/9uTCf/YkQn/1Y0I/9CICP/LhAj/xX4I/795Cf+4cwn/sW0J/6lm + Cf+gXwj/r4hV//r6+f/5+fj/r4VS/6lkCP+rZgn/smsL/7hwCv+/eAv/xX0M/8mBDP/Ohgz/1IwN/9aO + DP/clA//35cN/+CXCv/imQr/4poK/+KaCv/hmQn/3pcK/9uUCv/XkAn/0osI/82GCf/HgQj/wXsJ/7p1 + Cf+zbwn/q2gJ/6NiCf+qgEb/9vTx//b08f+qfkX/qmUK/65pC/+0bgz/vXcM/8F6Df/Ffg3/zYcP/9OM + D//VjhD/2JIQ/9+YEv/gmQ//450P/+WeDv/mng3/5Z4M/+ScC//hmgr/3pcK/9qTCf/Ujgn/0IkJ/8qD + Cf/DfQn/vHcJ/7VxCf+tagn/pWMJ/6R2OP/w7Of/8u7p/6x7PP+saQz/s24N/7hzDf/Aeg7/w30Q/8iD + D//RixH/1I4S/9iTFP/clxT/35kU/+KeE//npRf/56MT/+mmFf/nohD/5aAP/+SdDv/gmgv/3JUL/9eQ + C//Siwv/zIUL/8R+C/+9eAv/t3IK/65rCv+mZQr/o3Ev/+zl2//s5t7/qXY0/65rEP+2chD/vHcQ/8J9 + Ev/HgxP/zooV/9GNFf/UkRf/2ZYZ/92aGf/gnhr/5KIZ/+elGv/opxr/6qgZ/+mmFv/npBT/5qIV/+Kd + EP/emA//2ZIO/9ONDf/Nhg3/xoAN/795Df+4dAz/sG0M/6dmDP+ibif/5dvP/+Xb0P+lcSz/sG8T/7h1 + FP++exX/xoMW/8uIGP/QjRr/1JIb/9aUHP/ZmB7/354f/+KhH//lpiH/6aoj/+urIf/rqhz/6qkc/+mn + Gv/moxf/46AX/96ZFP/ZlBL/1I8S/86IEf/HghD/wHsQ/7l1D/+xbg7/qWcO/59qIP/bz7//3tHC/6Ru + Jf+ychb/unkY/8GAGv/Ihhz/zYwe/9KRIP/WliL/2psk/92eJv/goij/4qUm/+arKv/qryz/6q4o/+uu + Jf/rrCL/6akg/+elHf/kohv/3pwZ/9uYGf/Wkxn/z4sX/8qFFf/BfRT/uncS/7NwEv+raRH/oWkd/9XG + sf/Xx7L/qHEm/7h7I/++gST/xIcl/8mMJv/Pkij/05Yp/9eZK//cny3/4aUv/+GmL//mrTH/5q0x/+iu + L//qsS//7LIv/+uwLf/rryz/6Ksn/+OkI//foCD/3Jsg/9eWIf/RkB7/yogc/8OAGf+9ehf/tnMX/65s + Fv+maxz/z7uh/866of+ueS//vok3/8KLNP/HjzP/y5My/8+XMv/TmzL/2J8z/96lNf/hqDb/46s2/+Wt + N//nsDn/6bM5/+u0OP/stTn/7LY5/+qyNf/orjD/5qwv/+GlK//anSj/2Jop/9KTJf/KiSL/x4Uf/8B+ + Hv+5dx3/snEb/6puHf/Hro3/xa2O/7B9Mf/Bj0D/xpE9/8qVO//OmTr/0pw6/9WgOv/apTv/3qk9/+Kt + P//msUD/6LRA/+m1Qv/rt0P/67dD/+y5RP/rt0H/6rU+/+iyOv/mrjj/4ag1/92kMv/XnDD/0pYu/86Q + Kv/HiCb/woEl/7x7JP+0dCL/rHAg/8SmfP/Ao33/tYM3/8WUSf/Jl0X/zZpE/9GeQv/UoUL/2KVC/9up + RP/frUb/4rFH/+WzSf/ot0n/6rlK/+u5S//svE3/7LtM/+y5S//quEj/6LRE/+SwQf/irUD/3qc7/9ig + OP/VmzT/0JUw/8qNLf/Ehiz/vX8r/7Z4KP+ydib/wJxr/7uZa/+8iz//x5pR/8ucTv/PoEz/06NL/9am + Sv/aqkr/3a1M/+CxTf/jtFD/5bdS/+e5U//pu1P/671U/+y+Vv/svlj/7L5W/+u8U//ouVD/5rVO/+Ox + Sv/grEX/3KZB/9afPP/UnDr/zJI2/8aLNP/AhTL/uX0v/7Z7Kv+2jlf/s45Z/8GSSf/LoFr/zqJX/9Gl + Vf/VqVT/2atT/9yuU//fsVT/4bRW/+S4WP/mulr/6Lxb/+m9XP/rv13/7MFf/+zBX//swF//7L9d/+q8 + W//mt1b/5LNS/+GwT//cqUr/2KRH/9ahQ//QmUH/yZE8/8KKOf+7gTX/t34v/7SHSP+wiEz/xZpV/82l + Yv/QqGD/06tf/9etXf/bsFz/3bNc/+C2XP/juF7/5btg/+e9Yv/pv2P/6sBk/+vBZf/rwmb/7MJm/+zD + Z//swWX/6b5j/+i8Yv/luF7/4LJY/92tVP/bqlH/0qBL/8+aSP/JlET/yJFA/8CIO/+4gTb/sYA9/7CG + Rf/Ko2P/0Kts/9Otaf/WsGj/2bNn/9y1Zv/ft2b/4bpm/+S8Z//mvmn/6MBq/+nCa//qw2z/68Nt/+vE + bv/rw23/68Nt/+vDbf/rwm3/6L9r/+W6Z//htmP/37Nf/9mrWP/VplT/0J5P/8yYS//Gkkf/wYxC/7yG + Pf+wfjP/rYI//8+scP/TsXX/1rNy/9m1cf/bt3H/3rlw/+G8cf/ivnH/5L9y/+bCc//ow3P/6sVz/+vF + dP/rxnX/68Z1/+rFdf/qxHT/6sR0/+rEdf/nwHP/5b1x/+G5bf/ds2j/2rBj/9apXf/QoVf/zJtS/8iW + Tf/Gk0j/v4xE/698MP+ugz3/07N9/9a3f//YuHz/2rp7/928e//gvnr/4sB7/+TCe//lxHz/58V8/+nG + fP/qx3z/68h9/+vIff/qyHz/6sd8/+nGe//oxXr/6MR7/+fCe//lwHn/4rx2/9+5c//ZsWv/1atm/9Oo + Yf/OoFj/yppS/8SUTv/Aj0z/r3wy/7SJRP/Wu4r/2b2J/9u+h//dv4X/38GE/+HDhf/kxYX/5ceG/+fI + hv/oyYb/6cqF/+rLhf/ry4X/68uF/+vKhP/qyYT/6ciC/+jGgv/nxYL/5cOC/+PBgf/iv3//4b19/9u1 + df/XsHD/06pp/8+kYf/KnFr/xphW/8SWVf+ugjz/uY5L/9nAlf/awZX/3cOS/9/Ekf/hxZD/48eQ/+XJ + kP/ny5D/6MyP/+nNkP/qzY//686P/+zOjv/rzo3/682M/+rMjP/rz5T/6s+Y/+fKkv/mx47/5MWL/+PC + h//hwIX/3LqC/9azev/QrHX/zahv/8ula//IoWb/vJFT/8apf/+2jU7/2cCV/97Jo//gyqH/4syg/+TN + n//lzp//59Cf/+nRnv/q057/7NSf/+3Unv/t1J3/7tSd/+7UnP/u1J7/7tWi/+LDg//atm3/3bx8/9y9 + gf/bu4L/2biB/9a0gf/TsoL/zq6B/8qqgP/JqoD/yKmA/8enfP/Ru57/9vPu/9S+nf/AnGL/z7B9/9S1 + gf/YuIL/3L2E/+DCh//jxYj/5smJ/+nMi//pzYz/6syL/+jKif/myIn/5caJ/+C+fP/Ro07/17uE//bx + 5v/9/fz//v7+//7+/v/+/v7//v7+///+/v///v7///7+/////v///v7//////////////////v7+/8mu + hv+reS7/tII3/7yJOf/EkTz/y5k//9OhQv/cq0b/4bJM/+K0Tf/is03/3rBL/9ipSP/To0X/z6FI/8ib + Sv/v59b////////+/v///v7///7+///+/v///v7///7+///+/v///v7///7+///+/v////////////// + ////////5trH/7iNTf/Gm1z/zaJg/9KpZf/ZsWz/4btz/+nFef/vzoT/89OJ//PTiP/vzoL/6sh8/+XB + d//ctmz/0bBx//r48////v////7+///+/v///v7///7+///+/v///v7///7+///+/v///v7///7///// + ///////////////////8+/n/zbKI/7iLQ/+8kEb/wpZJ/8idTP/OpFD/2K5U/+G5Xv/jvmH/4rxf/920 + Wf/Tq1X/zqRS/8ukWP/q3cX////////+/v///v7///7+///+/v///v7///7+///+/v///v7///7+///+ + /v///v//////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + + + \ No newline at end of file diff --git a/BSHash/BSHash/Network.cs b/BSHash/BSHash/Network.cs new file mode 100644 index 0000000..c727a74 --- /dev/null +++ b/BSHash/BSHash/Network.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace BSHash +{ + public class Network + { + private readonly HttpClient _httpClient; + private Logger _logger; + private static readonly Random _random = new Random(); + + // Costanti per i possibili stati di risposta + public static string OK = "OK"; + public static string TIMEOUT = "TIMEOUT"; + public static string ERROR = "ERROR"; + + public Network(Logger logger) + { + _httpClient = new HttpClient(); + _logger = logger; + } + + public async Task SendDataHash(string hash) + { + try + { + /* + var content = new StringContent(data, Encoding.UTF8, "application/json"); + HttpResponseMessage response = await _httpClient.PostAsync(url, content); + + response.EnsureSuccessStatusCode(); + + string responseData = await response.Content.ReadAsStringAsync(); + return responseData; + */ + + _logger.Log("Invio dati...", LogType.INFO); + + //Simula l'attesa di una risposta con un tempo randomico + //int delay = _random.Next(1, 5000); // da 1ms a 5s + int delay = 0; // per testare il timeout + + _logger.Log("Dati inviati. Elaborazione... ", LogType.INFO); + + Thread.Sleep(delay); + + _logger.Log("Tempo di chiamata: " + delay.ToString(), LogType.INFO); + + return OK; + } + catch (Exception ex) + { + // Logga o gestisci l'eccezione come necessario + _logger.Log("Errore della chiamata: " + ex.Message, LogType.ERROR); + return $"Error: {ex.Message}"; + } + } + + public async Task GetDataHash(string hash) + { + try + { + /* + HttpResponseMessage response = await _httpClient.GetAsync(url); + + response.EnsureSuccessStatusCode(); + + string responseData = await response.Content.ReadAsStringAsync(); + return responseData; + */ + + _logger.Log("Ricezione risposta...", LogType.INFO); + + // Simula l'attesa di una risposta con un tempo randomico + //int delay = _random.Next(1, 5000); // da 1ms a 5s + int delay = 0; // per testare il timeout + + _logger.Log("Risposta ricevuta. Elaborazione... ", LogType.INFO); + + Thread.Sleep(delay); + + _logger.Log("Tempo di risposta: " + delay.ToString(), LogType.INFO); + + return OK; + } + catch (Exception ex) + { + // Logga o gestisci l'eccezione come necessario + _logger.Log("Errore della chiamata: " + ex.Message, LogType.ERROR); + return $"Error: {ex.Message}"; + } + } + } +} diff --git a/BSHash/BSHash/Program.cs b/BSHash/BSHash/Program.cs new file mode 100644 index 0000000..b14750b --- /dev/null +++ b/BSHash/BSHash/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BSHash +{ + internal static class Program + { + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Main()); + } + } +} diff --git a/BSHash/BSHash/Properties/AssemblyInfo.cs b/BSHash/BSHash/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c8efa95 --- /dev/null +++ b/BSHash/BSHash/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Le informazioni generali relative a un assembly sono controllate dal seguente +// set di attributi. Modificare i valori di questi attributi per modificare le informazioni +// associate a un assembly. +[assembly: AssemblyTitle("BSHash")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("BSHash")] +[assembly: AssemblyCopyright("Copyright © 2024")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili +// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da +// COM, impostare su true l'attributo ComVisible per tale tipo. +[assembly: ComVisible(false)] + +// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi +[assembly: Guid("108dfc74-04da-484e-bb6b-da1070b26c1a")] + +// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori: +// +// Versione principale +// Versione secondaria +// Numero di build +// Revisione +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/BSHash/BSHash/Properties/Resources.Designer.cs b/BSHash/BSHash/Properties/Resources.Designer.cs new file mode 100644 index 0000000..54cd6cf --- /dev/null +++ b/BSHash/BSHash/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// Codice generato da uno strumento. +// Versione runtime:4.0.30319.42000 +// +// Le modifiche apportate a questo file possono causare un comportamento non corretto e andranno perse se +// il codice viene rigenerato. +// +//------------------------------------------------------------------------------ + +namespace BSHash.Properties +{ + + + /// + /// Classe di risorse fortemente tipizzata per la ricerca di stringhe localizzate e così via. + /// + // Questa classe è stata generata automaticamente dalla classe StronglyTypedResourceBuilder + // tramite uno strumento quale ResGen o Visual Studio. + // Per aggiungere o rimuovere un membro, modificare il file .ResX, quindi eseguire di nuovo ResGen + // con l'opzione /str oppure ricompilare il progetto VS. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Restituisce l'istanza di ResourceManager memorizzata nella cache e usata da questa classe. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BSHash.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Esegue l'override della proprietà CurrentUICulture del thread corrente per tutte + /// le ricerche di risorse che utilizzano questa classe di risorse fortemente tipizzata. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/BSHash/BSHash/Properties/Resources.resx b/BSHash/BSHash/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/BSHash/BSHash/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/BSHash/BSHash/Properties/Settings.Designer.cs b/BSHash/BSHash/Properties/Settings.Designer.cs new file mode 100644 index 0000000..2c00439 --- /dev/null +++ b/BSHash/BSHash/Properties/Settings.Designer.cs @@ -0,0 +1,86 @@ +//------------------------------------------------------------------------------ +// +// Il codice è stato generato da uno strumento. +// Versione runtime:4.0.30319.42000 +// +// Le modifiche apportate a questo file possono provocare un comportamento non corretto e andranno perse se +// il codice viene rigenerato. +// +//------------------------------------------------------------------------------ + +namespace BSHash.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.11.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string Server { + get { + return ((string)(this["Server"])); + } + set { + this["Server"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string User { + get { + return ((string)(this["User"])); + } + set { + this["User"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string Password { + get { + return ((string)(this["Password"])); + } + set { + this["Password"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string Database { + get { + return ((string)(this["Database"])); + } + set { + this["Database"] = value; + } + } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string Path { + get { + return ((string)(this["Path"])); + } + set { + this["Path"] = value; + } + } + } +} diff --git a/BSHash/BSHash/Properties/Settings.settings b/BSHash/BSHash/Properties/Settings.settings new file mode 100644 index 0000000..d328b8d --- /dev/null +++ b/BSHash/BSHash/Properties/Settings.settings @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/BSHash/BSHash/Storage.cs b/BSHash/BSHash/Storage.cs new file mode 100644 index 0000000..dc5fe50 --- /dev/null +++ b/BSHash/BSHash/Storage.cs @@ -0,0 +1,408 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace BSHash +{ + public class Storage + { + private readonly Logger _logger; + private readonly Random _random = new Random(); + private CancellationTokenSource _cancellationTokenSource; + + public Storage(Logger logger) + { + _logger = logger; + } + + public void StartClearStorage(string path, System.Windows.Forms.ProgressBar progressBar, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + _cancellationTokenSource = new CancellationTokenSource(); + startButton.Enabled = false; + stopButton.Enabled = true; + Task.Run(async () => await ClearStorageAsync(path, progressBar, _cancellationTokenSource.Token, startButton, stopButton)); + } + + public void StartFillStorage(string path, System.Windows.Forms.ProgressBar progressBar, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + _cancellationTokenSource = new CancellationTokenSource(); + startButton.Enabled = false; + stopButton.Enabled = true; + Task.Run(async () => await FillStorageAsync(path, progressBar, _cancellationTokenSource.Token, startButton, stopButton)); + } + + public void StartCheckFiles(string path, System.Windows.Forms.ProgressBar progressBar, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + _cancellationTokenSource = new CancellationTokenSource(); + startButton.Enabled = false; + stopButton.Enabled = true; + Task.Run(async () => await CheckFilesAsync(path, progressBar, _cancellationTokenSource.Token, startButton, stopButton)); + } + + internal void StopFillStorage(System.Windows.Forms.ProgressBar progressBar, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + _cancellationTokenSource?.Cancel(); + startButton.Invoke((Action)(() => startButton.Enabled = true)); + stopButton.Invoke((Action)(() => stopButton.Enabled = false)); + } + + internal void StopClearStorage(System.Windows.Forms.ProgressBar progressBar, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + _cancellationTokenSource?.Cancel(); + startButton.Invoke((Action)(() => startButton.Enabled = true)); + stopButton.Invoke((Action)(() => stopButton.Enabled = false)); + } + + internal void StoptCkeckFiles(System.Windows.Forms.ProgressBar progressBar, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + _cancellationTokenSource?.Cancel(); + startButton.Invoke((Action)(() => startButton.Enabled = true)); + stopButton.Invoke((Action)(() => stopButton.Enabled = false)); + } + + private async Task ClearStorageAsync(string path, System.Windows.Forms.ProgressBar progressBar, CancellationToken cancellationToken, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + var stopwatch = Stopwatch.StartNew(); + var elapsedTimes = new Queue(); + const int maxSamples = 10; // Numero di campioni per la media mobile + + try + { + string[] files = Directory.GetFiles(path, "*"); + long totalFiles = files.Length; + long deletedFiles = 0; + + var progress = new Progress(value => progressBar.Value = value); + progressBar.Maximum = 100; + progressBar.Value = 0; + + foreach (string file in files) + { + if (cancellationToken.IsCancellationRequested) + { + _logger.Log("Cancellazione interrotta dall'utente.", LogType.ERROR); + break; + } + + try + { + File.Delete(file); + deletedFiles++; + + int progressValue = (int)(deletedFiles * 100 / totalFiles); + ((IProgress)progress).Report(Math.Min(progressValue, 100)); + + _logger.Log($"Cancellato file {file}.", LogType.INFO); + + // Calcola il tempo rimanente usando una media mobile + double elapsedSeconds = stopwatch.Elapsed.TotalSeconds; + elapsedTimes.Enqueue(elapsedSeconds / deletedFiles); + + if (elapsedTimes.Count > maxSamples) + { + elapsedTimes.Dequeue(); + } + + double averageTimePerFile = elapsedTimes.Average(); + double estimatedTotalSeconds = averageTimePerFile * totalFiles; + double remainingSeconds = estimatedTotalSeconds - elapsedSeconds; + + _logger.Log($"Tempo rimanente stimato: {TimeSpan.FromSeconds(remainingSeconds):hh\\:mm\\:ss}", LogType.INFO); + } + catch (IOException ex) + { + _logger.Log($"Errore durante la cancellazione del file {file}: {ex.Message}", LogType.ERROR); + } + } + + _logger.Log("Cancellazione completata.", LogType.INFO); + } + catch (Exception ex) + { + _logger.Log($"Errore durante la cancellazione dei file: {ex.Message}", LogType.ERROR); + } + finally + { + stopwatch.Stop(); + startButton.Invoke((Action)(() => startButton.Enabled = true)); + stopButton.Invoke((Action)(() => stopButton.Enabled = false)); + } + } + + private async Task FillStorageAsync(string path, System.Windows.Forms.ProgressBar progressBar, CancellationToken cancellationToken, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + try + { + _logger.LogDispositivoFill(LogStatus.ELABORAZIONE, 0, 0, 0, 0, 0, 0); + + string drive = Path.GetPathRoot(path); + DriveInfo driveInfo = new DriveInfo(drive); + long initialFreeSpace = driveInfo.AvailableFreeSpace; + + var progress = new Progress(value => + { + if (progressBar.InvokeRequired) + { + progressBar.Invoke((Action)(() => progressBar.Value = value)); + } + else + { + progressBar.Value = value; + } + }); + + progressBar.Maximum = 100; + progressBar.Value = 0; + + long usedSpace = 0; + int creati = 0; + int salvati = 0; + int errori = 0; + int warning = 0; + int sectorSize = GetSectorSize(drive); + + _logger.LogDispositivoFill(LogStatus.ELABORAZIONE, creati, salvati, initialFreeSpace, usedSpace, errori, warning); + + while (usedSpace < initialFreeSpace) + { + if (cancellationToken.IsCancellationRequested) + { + _logger.Log("Riempimento interrotto dall'utente.", LogType.ERROR); + break; + } + + long fileSize = await CreateRandomFileAsync(path, sectorSize); + usedSpace += fileSize; + creati++; + salvati++; + + double progressValue = (usedSpace * 100 / initialFreeSpace); + ((IProgress)progress).Report(Math.Min((int)progressValue, 100)); + + _logger.Log($"Progresso {progressValue}%. ({usedSpace}/{initialFreeSpace})", LogType.INFO); + + if (usedSpace >= initialFreeSpace) + { + _logger.Log("Il dispositivo è pieno.", LogType.WARN); + break; + } + + _logger.LogDispositivoFill(LogStatus.ELABORAZIONE, creati, salvati, initialFreeSpace, usedSpace, errori, warning); + } + + _logger.LogDispositivoFill(LogStatus.COMPLETATO, creati, salvati, initialFreeSpace, usedSpace, errori, warning); + } + catch (IOException ex) + { + string drive = Path.GetPathRoot(path); + DriveInfo driveInfo = new DriveInfo(drive); + + if (driveInfo.AvailableFreeSpace > 0) + { + _logger.Log($"Errore di I/O durante il riempimento del dispositivo: {ex.Message}", LogType.ERROR); + _logger.LogDispositivoFill(LogStatus.ERRORE, 0, 0, 0, 0, 0, 0); + } + else + { + _logger.Log("Il dispositivo è pieno.", LogType.WARN); + _logger.LogDispositivoFill(LogStatus.COMPLETATO, 0, 0, 0, 0, 0, 0); + } + } + } + + private async Task CreateRandomFileAsync(string path, int sectorSize) + { + try + { + string fileName = Path.Combine(path, Guid.NewGuid() + ".bs"); + byte[] data = new byte[sectorSize]; + _random.NextBytes(data); + + await WriteAllBytesAsync(fileName, data); + _logger.Log($"Creato file {fileName}.", LogType.INFO); + + + + return data.Length; + } + catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) + { + _logger.Log($"Errore durante la creazione del file: {ex.Message}", LogType.ERROR); + return 0; + } + } + + private async Task WriteAllBytesAsync(string path, byte[] bytes) + { + using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None, 4096, true)) + { + await fs.WriteAsync(bytes, 0, bytes.Length); + } + } + + private int GetSectorSize(string drive) + { + // Assuming a default sector size of 1024 * 1024 * 128 bytes (128 MB) + // Total 127.831.113.728 bytes + // : 128 = 998.680.576 + // : 1024 = 975.274 + // : 1024 = 952 + return 1024 * 128; + } + + public async Task CheckFilesAsync(string path, System.Windows.Forms.ProgressBar progressBar, CancellationToken cancellationToken, System.Windows.Forms.Button startButton, System.Windows.Forms.Button stopButton) + { + // Controlla se l'hash è già presente nel database + Database database = new Database(); + + _logger.Log($"Scansione percorso {path}...", LogType.INFO); + _logger.LogDispositivoCheck(LogStatus.PREPARAZIONE, 0, 0, 0, 0, 0, 0); + + // Pulisci il database + database.ClearHash(); + + try + { + _logger.Log("Ricavando la lista dei files supportati...", LogType.INFO); ; + + string[] files = Directory.GetFiles(path, "*", SearchOption.AllDirectories); + var hashSet = new HashSet(); + var invalidFiles = new List(); + var duplicateFiles = new List(); + + progressBar.Invoke((Action)(() => + { + progressBar.Maximum = files.Length; + progressBar.Value = 0; + })); + + int processedFiles = 0; + int errori = 0; + int warning = 0; + int inseriti = 0; + int aggiornati = 0; + int totalFiles = files.Length; + + _logger.Log($"Inizio controllo {totalFiles} files.", LogType.INFO); + + foreach (string file in files) + { + processedFiles++; + + _logger.Log($"({processedFiles}/{totalFiles}) Verifica file {file}...", LogType.INFO); + + if (cancellationToken.IsCancellationRequested) + { + _logger.Log("Scansione interrotta dall'utente.", LogType.ERROR); + break; + } + + try + { + string hash = await ComputeFileHashAsync(file); + + if (hashSet.Contains(hash)) + { + duplicateFiles.Add(file); + } + else + { + hashSet.Add(hash); + } + + + + _logger.Log("Verificando l'esistenza dell'hash...", LogType.INFO); + + // Controlla se l'hash esiste già nel database + if (database.HashExists(hash)) + { + _logger.Log("Hash esistente. Aggiornando hash... ", LogType.INFO); + + // L'hash esiste già nel database, aggiorna il percorso del file + if(database.UpdateHash(file, hash)) + { + _logger.Log("Hash aggiornato con successo.", LogType.INFO); + aggiornati++; + } + else + { + _logger.Log("Errore durante l'aggiornamento dell'hash.", LogType.ERROR); + errori++; + } + } + else + { + _logger.Log("Hash non presente. Inserendo hash... ", LogType.INFO); + + // L'hash non esiste nel database, inseriscilo + if (database.InsertHash(file, hash)) + { + _logger.Log("Hash inserito con successo.", LogType.INFO); + inseriti++; + } + else + { + _logger.Log("Errore durante l'inserimento dell'hash.", LogType.ERROR); + errori++; + } + } + + _logger.LogDispositivoCheck(LogStatus.ELABORAZIONE, totalFiles, processedFiles, inseriti, aggiornati, errori, warning); + } + catch (Exception ex) + { + invalidFiles.Add(file); + _logger.Log($"Errore durante la verifica del file {file}: {ex.Message}", LogType.ERROR); + + errori++; + } + + progressBar.Invoke((Action)(() => progressBar.Value = processedFiles)); + } + + if (invalidFiles.Count > 0) + { + _logger.Log($"Trovati {invalidFiles.Count} file non validi.", LogType.WARN); + } + + if (duplicateFiles.Count > 0) + { + _logger.Log($"Trovati {duplicateFiles.Count} file duplicati.", LogType.WARN); + } + + _logger.LogDispositivoCheck(LogStatus.COMPLETATO, totalFiles, processedFiles, inseriti, aggiornati, errori, warning); + + _logger.Log("Verifica completata.", LogType.INFO); + } + catch (Exception ex) + { + _logger.Log($"Errore durante la verifica dei file: {ex.Message}", LogType.ERROR); + } + finally + { + startButton.Invoke((Action)(() => startButton.Enabled = true)); + stopButton.Invoke((Action)(() => stopButton.Enabled = false)); + } + } + + private async Task ComputeFileHashAsync(string filePath) + { + using (var sha256 = SHA256.Create()) + using (var stream = File.OpenRead(filePath)) + { + byte[] hashBytes = await Task.Run(() => sha256.ComputeHash(stream)); + return BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); + } + } + } +}