csharp Copy code
using System;
using System.Data.SQLite;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Text;
namespace TrialManagementTool
{
static class Program
{
// Main entry point of the application.
[STAThread]
static void Main()
{
// Initialize the application.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// Ensure the database and tables are created.
DatabaseHelper.InitializeDatabase();
// Show the login form.
Application.Run(new LoginForm());
}
}
// Static class for database operations.
static class DatabaseHelper
{
private static readonly string connectionString = "Data Source=trial_management.db;Version=3;";
// Initialize the database and tables.
public static void InitializeDatabase()
{
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string createUsersTable = @"CREATE TABLE IF NOT EXISTS Users (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Username TEXT NOT NULL UNIQUE,
PasswordHash TEXT NOT NULL
);";
string createTrialsTable = @"CREATE TABLE IF NOT EXISTS Trials (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
UserId INTEGER NOT NULL,
TrialName TEXT NOT NULL,
StartDate TEXT NOT NULL,
EndDate TEXT NOT NULL,
Status TEXT NOT NULL,
FOREIGN KEY(UserId) REFERENCES Users(Id)
);";
using (var command = new SQLiteCommand(createUsersTable, connection))
{
command.ExecuteNonQuery();
}
using (var command = new SQLiteCommand(createTrialsTable, connection))
{
command.ExecuteNonQuery();
}
}
}
// Register a new user.
public static bool RegisterUser(string username, string password)
{
try
{
string passwordHash = SecurityHelper.HashPassword(password);
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string insertUser = "INSERT INTO Users (Username, PasswordHash) VALUES (@Username, @PasswordHash);";
using (var command = new SQLiteCommand(insertUser, connection))
{
command.Parameters.AddWithValue("@Username", username);
command.Parameters.AddWithValue("@PasswordHash", passwordHash);
command.ExecuteNonQuery();
}
}
return true;
}
catch
{
// Handle exceptions if user already exists.
return false;
}
}
// Authenticate a user.
public static bool AuthenticateUser(string username, string password)
{
string storedHash = null;
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string selectUser = "SELECT PasswordHash FROM Users WHERE Username = @Username;";
using (var command = new SQLiteCommand(selectUser, connection))
{
command.Parameters.AddWithValue("@Username", username);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
storedHash = reader.GetString(0);
}
else
{
return false;
}
}
}
}
return SecurityHelper.VerifyPassword(password, storedHash);
}
// Get user ID by username.
public static int GetUserId(string username)
{
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string selectUserId = "SELECT Id FROM Users WHERE Username = @Username;";
using (var command = new SQLiteCommand(selectUserId, connection))
{
command.Parameters.AddWithValue("@Username", username);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
return reader.GetInt32(0);
}
else
{
return -1;
}
}
}
}
}
// Add a new trial.
public static void AddTrial(int userId, string trialName, DateTime startDate, DateTime endDate)
{
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
string insertTrial = @"INSERT INTO Trials (UserId, TrialName, StartDate, EndDate, Status)
VALUES (@UserId, @TrialName, @StartDate, @EndDate, @Status);";
using (var command = new SQLiteCommand(insertTrial, connection))
{
command.Parameters.AddWithValue("@UserId", userId);
command.Parameters.AddWithValue("@TrialName", trialName);
command.Parameters.AddWithValue("@StartDate", startDate.ToString("yyyy-MM-dd"));
command.Parameters.AddWithValue("@EndDate", endDate.ToString("yyyy-MM-dd"));
command.Parameters.AddWithValue("@Status", "Active");
command.ExecuteNonQuery();
}
}
}
// Retrieve trials for a user.
public static SQLiteDataReader GetTrials(int userId)
{
var connection = new SQLiteConnection(connectionString);
connection.Open();
string selectTrials = "SELECT TrialName, StartDate, EndDate, Status FROM Trials WHERE UserId = @UserId;";
var command = new SQLiteCommand(selectTrials, connection);
command.Parameters.AddWithValue("@UserId", userId);
return command.ExecuteReader();
}
}
// Static class for security-related functions.
static class SecurityHelper
{
// Hash a password using SHA256.
public static string HashPassword(string password)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] bytes = Encoding.UTF8.GetBytes(password);
byte[] hash = sha256.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
}
// Verify a password against a hash.
public static bool VerifyPassword(string password, string storedHash)
{
string hashOfInput = HashPassword(password);
return StringComparer.Ordinal.Compare(hashOfInput, storedHash) == 0;
}
}
// Login form for user authentication.
public class LoginForm : Form
{
private TextBox txtUsername;
private TextBox txtPassword;
private Button btnLogin;
private Button btnRegister;
public LoginForm()
{
// Initialize form components.
Text = "Login - Trial Management Tool";
Width = 300;
Height = 200;
Label lblUsername = new Label() { Text = "Username:", Left = 10, Top = 20 };
Label lblPassword = new Label() { Text = "Password:", Left = 10, Top = 60 };
txtUsername = new TextBox() { Left = 100, Top = 20, Width = 150 };
txtPassword = new TextBox() { Left = 100, Top = 60, Width = 150, PasswordChar = '*' };
btnLogin = new Button() { Text = "Login", Left = 50, Width = 80, Top = 100 };
btnRegister = new Button() { Text = "Register", Left = 150, Width = 80, Top = 100 };
btnLogin.Click += BtnLogin_Click;
btnRegister.Click += BtnRegister_Click;
Controls.Add(lblUsername);
Controls.Add(lblPassword);
Controls.Add(txtUsername);
Controls.Add(txtPassword);
Controls.Add(btnLogin);
Controls.Add(btnRegister);
}
// Event handler for login button click.
private void BtnLogin_Click(object sender, EventArgs e)
{
if (DatabaseHelper.AuthenticateUser(txtUsername.Text, txtPassword.Text))
{
int userId = DatabaseHelper.GetUserId(txtUsername.Text);
Hide();
// Open the main application form.
Application.Run(new MainForm(userId));
Close();
}
else
{
MessageBox.Show("Invalid credentials. Please try again.", "Authentication Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Event handler for register button click.
private void BtnRegister_Click(object sender, EventArgs e)
{
if (DatabaseHelper.RegisterUser(txtUsername.Text, txtPassword.Text))
{
MessageBox.Show("Registration successful. You can now log in.", "Registration Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Registration failed. Username may already exist.", "Registration Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
// Main form of the application after login.
public class MainForm : Form
{
private int userId;
private DataGridView dgvTrials;
private Button btnAddTrial;
public MainForm(int userId)
{
// Initialize form components.
this.userId = userId;
Text = "Trial Management Tool";
Width = 600;
Height = 400;
dgvTrials = new DataGridView() { Left = 10, Top = 10, Width = 560, Height = 300 };
btnAddTrial = new Button() { Text = "Add Trial", Left = 10, Top = 320, Width = 100 };
btnAddTrial.Click += BtnAddTrial_Click;
Controls.Add(dgvTrials);
Controls.Add(btnAddTrial);
LoadTrials();
}
// Load trials from the database.
private void LoadTrials()
{
dgvTrials.Rows.Clear();
dgvTrials.Columns.Clear();
dgvTrials.Columns.Add("TrialName", "Trial Name");
dgvTrials.Columns.Add("StartDate", "Start Date");
dgvTrials.Columns.Add("EndDate", "End Date");
dgvTrials.Columns.Add("Status", "Status");
using (var reader = DatabaseHelper.GetTrials(userId))
{
while (reader.Read())
{
dgvTrials.Rows.Add(
reader["TrialName"],
reader["StartDate"],
reader["EndDate"],
reader["Status"]
);
}
}
}
// Event handler for add trial button click.
private void BtnAddTrial_Click(object sender, EventArgs e)
{
var addTrialForm = new AddTrialForm(userId);
addTrialForm.FormClosed += (s, args) => LoadTrials();
addTrialForm.ShowDialog();
}
}
// Form to add a new trial.
public class AddTrialForm : Form
{
private int userId;
private TextBox txtTrialName;
private DateTimePicker dtpStartDate;
private DateTimePicker dtpEndDate;
private Button btnAdd;
public AddTrialForm(int userId)
{
// Initialize form components.
this.userId = userId;
Text = "Add New Trial";
Width = 300;
Height = 250;
Label lblTrialName = new Label() { Text = "Trial Name:", Left = 10, Top = 20 };
Label lblStartDate = new Label() { Text = "Start Date:", Left = 10, Top = 60 };
Label lblEndDate = new Label() { Text = "End Date:", Left = 10, Top = 100 };
txtTrialName = new TextBox() { Left = 100, Top = 20, Width = 150 };
dtpStartDate = new DateTimePicker() { Left = 100, Top = 60, Width = 150 };
dtpEndDate = new DateTimePicker() { Left = 100, Top = 100, Width = 150 };
btnAdd = new Button() { Text = "Add", Left = 100, Width = 80, Top = 150 };
btnAdd.Click += BtnAdd_Click;
Controls.Add(lblTrialName);
Controls.Add(lblStartDate);
Controls.Add(lblEndDate);
Controls.Add(txtTrialName);
Controls.Add(dtpStartDate);
Controls.Add(dtpEndDate);
Controls.Add(btnAdd);
}
// Event handler for add button click.
private void BtnAdd_Click(object sender, EventArgs e)
{
// Validate input.
if (string.IsNullOrWhiteSpace(txtTrialName.Text))
{
MessageBox.Show("Trial name cannot be empty.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (dtpEndDate.Value <= dtpStartDate.Value)
{
MessageBox.Show("End date must be after start date.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Add the trial to the database.
DatabaseHelper.AddTrial(userId, txtTrialName.Text, dtpStartDate.Value, dtpEndDate.Value);
MessageBox.Show("Trial added successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
}
}