Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add recent connections functionality and bugfixes. #20

Merged
merged 1 commit into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="SixLabors.Fonts" Version="1.0.0-beta19" />
<PackageReference Include="SixLabors.Fonts" Version="2.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
47 changes: 47 additions & 0 deletions src/LightQueryProfiler.Shared/Data/SqliteContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using LightQueryProfiler.Shared.Models;
using Microsoft.Data.Sqlite;
using System.Data;

namespace LightQueryProfiler.Shared.Data
{
public class SqliteContext : IDatabaseContext
{
const string dataBaseName = "localStorage.db";

public IDbConnection GetConnection()
{
string dbPath = Path.Combine(AppContext.BaseDirectory, dataBaseName);
return new SqliteConnection($"Filename={dbPath}");
}


public async static void InitializeDatabase()
{
string dbPath = Path.Combine(AppContext.BaseDirectory, dataBaseName);
if (!File.Exists(dbPath))
{
await using FileStream fs = File.Create(dbPath);
}

await using SqliteConnection db = new($"Filename={dbPath}");
db.Open();

const string tableCommand = @"
CREATE TABLE IF NOT
EXISTS Connections
(
Id INTEGER PRIMARY KEY,
DataSource NVARCHAR(1000) NULL,
InitialCatalog NVARCHAR(100) NULL,
UserId NVARCHAR(100) NULL,
Password NVARCHAR(100) NULL,
IntegratedSecurity INTEGER NULL,
CreationDate Date
)";

SqliteCommand createTable = new(tableCommand, db);

await createTable.ExecuteReaderAsync();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.3" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
</ItemGroup>

</Project>
30 changes: 30 additions & 0 deletions src/LightQueryProfiler.Shared/Models/Connection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace LightQueryProfiler.Shared.Models
{
public class Connection
{
public Connection(int id, string initialCatalog, DateTime creationDate, string dataSource, bool integratedSecurity, string? password, string? userId)
{
Id = id;
InitialCatalog = initialCatalog;
CreationDate = creationDate;
DataSource = dataSource;
IntegratedSecurity = integratedSecurity;
Password = password;
UserId = userId;
}

public int Id { get; }

public string InitialCatalog { get; }

public DateTime CreationDate { get; }

public string DataSource { get; }

public bool IntegratedSecurity { get; }

public string? Password { get; }

public string? UserId { get; }
}
}
9 changes: 9 additions & 0 deletions src/LightQueryProfiler.Shared/Models/IDatabaseContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Data;

namespace LightQueryProfiler.Shared.Models
{
public interface IDatabaseContext
{
IDbConnection GetConnection();
}
}
134 changes: 134 additions & 0 deletions src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using LightQueryProfiler.Shared.Models;
using LightQueryProfiler.Shared.Repositories.Interfaces;
using Microsoft.Data.Sqlite;

namespace LightQueryProfiler.Shared.Repositories
{
public class ConnectionRepository : IRepository<Connection>
{
private readonly IDatabaseContext _context;

public ConnectionRepository(IDatabaseContext context)
{
_context = context;
}

public async Task AddAsync(Connection entity)
{
const string sql = @"INSERT INTO Connections (DataSource, InitialCatalog, UserId, Password, IntegratedSecurity, CreationDate)
VALUES (@DataSource, @InitialCatalog, @UserId, @Password, @IntegratedSecurity, @CreationDate)";

await using var db = _context.GetConnection() as SqliteConnection;
await using SqliteCommand sqliteCommand = new SqliteCommand(sql, db);
sqliteCommand.Parameters.AddWithValue("@DataSource", entity.DataSource);
sqliteCommand.Parameters.AddWithValue("@InitialCatalog", entity.InitialCatalog);
sqliteCommand.Parameters.AddWithValue("@UserId", entity.UserId);
sqliteCommand.Parameters.AddWithValue("@Password", entity.Password);
sqliteCommand.Parameters.AddWithValue("@IntegratedSecurity", entity.IntegratedSecurity);
sqliteCommand.Parameters.AddWithValue("@CreationDate", entity.CreationDate);

await db.OpenAsync();

Check warning on line 30 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 30 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
await sqliteCommand.ExecuteNonQueryAsync();
}

public async Task<Connection?> Find(Func<Connection, bool> predicate)
{
var all = await GetAllAsync();
if (all?.Count > 0 && predicate != null)
{
return all.FirstOrDefault(predicate);
}

return null;
}

public async Task Delete(int id)
{
const string sql = "DELETE FROM Connections WHERE Id = @Id";
await using var db = _context.GetConnection() as SqliteConnection;
await using SqliteCommand sqliteCommand = new SqliteCommand(sql, db);
sqliteCommand.Parameters.AddWithValue("@Id", id);

await db.OpenAsync();

Check warning on line 52 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 52 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
await sqliteCommand.ExecuteNonQueryAsync();
}

public async Task<IList<Connection>> GetAllAsync()
{
const string sql = "SELECT Id, InitialCatalog, CreationDate, DataSource, IntegratedSecurity, Password, UserId FROM Connections";
List<Connection> connections = new List<Connection>();
await using var db = _context.GetConnection() as SqliteConnection;
await using SqliteCommand sqliteCommand = new SqliteCommand(sql, db);

await db.OpenAsync();

Check warning on line 63 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 63 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
await using var query = await sqliteCommand.ExecuteReaderAsync();

int index;
while (query.Read())
{
index = 0;
connections.Add(new Connection(
query.GetInt32(index++),
query.GetString(index++),
query.GetDateTime(index++),
query.GetString(index++),
query.GetBoolean(index++),
query.GetString(index++),
query.GetString(index++)
)
);
}

return connections;
}

public async Task<Connection> GetByIdAsync(int id)
{
const string sql = "SELECT Id, InitialCatalog, CreationDate, DataSource, IntegratedSecurity, Password, UserId FROM Connections WHERE Id = @Id";
Connection? connection = null;
await using var db = _context.GetConnection() as SqliteConnection;
await using SqliteCommand sqliteCommand = new SqliteCommand(sql, db);
sqliteCommand.Parameters.AddWithValue("@Id", id);

await db.OpenAsync();

Check warning on line 93 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.

Check warning on line 93 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
await using var query = await sqliteCommand.ExecuteReaderAsync();

int index;
while (query.Read())
{
index = 0;
connection = new Connection(query.GetInt32(index++),
query.GetString(index++),
query.GetDateTime(index++),
query.GetString(index++),
query.GetBoolean(index++),
query.GetString(index++),
query.GetString(index++));
}

if (connection == null)
{
throw new Exception("Connection cannot be null.");
}

return connection;
}

public async Task UpdateAsync(Connection entity)
{
const string sql = "UPDATE Connections SET DataSource=@DataSource, InitialCatalog=@InitialCatalog, UserId=@UserId, Password=@Password, IntegratedSecurity=@IntegratedSecurity WHERE Id = @Id";
await using var db = _context.GetConnection() as SqliteConnection;
await using SqliteCommand sqliteCommand = new SqliteCommand(sql, db);
sqliteCommand.Parameters.AddWithValue("@Id", entity);
sqliteCommand.Parameters.AddWithValue("@DataSource", entity.DataSource);
sqliteCommand.Parameters.AddWithValue("@InitialCatalog", entity.InitialCatalog);
sqliteCommand.Parameters.AddWithValue("@UserId", entity.UserId);
sqliteCommand.Parameters.AddWithValue("@Password", entity.Password);
sqliteCommand.Parameters.AddWithValue("@IntegratedSecurity", entity.IntegratedSecurity);
sqliteCommand.Parameters.AddWithValue("@CreationDate", entity.CreationDate);

await db.OpenAsync();

Check warning on line 130 in src/LightQueryProfiler.Shared/Repositories/ConnectionRepository.cs

View workflow job for this annotation

GitHub Actions / build

Dereference of a possibly null reference.
await sqliteCommand.ExecuteNonQueryAsync();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using System.Linq.Expressions;

namespace LightQueryProfiler.Shared.Repositories.Interfaces
{
public interface IRepository<T>
{
Task<T> GetByIdAsync(int id);

Task<IList<T>> GetAllAsync();

Task AddAsync(T entity);

Task UpdateAsync(T entity);

Task Delete(int id);

Task<T?> Find(Func<T, bool> predicate);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Blazored.Modal" Version="7.1.0" />
<PackageReference Include="Blazored.Modal" Version="7.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.Web" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebView" Version="7.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebView" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
51 changes: 49 additions & 2 deletions src/LightQueryProfiler.WinFormsApp/Presenters/MainPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public class MainPresenter
private readonly IMainView view;
private IApplicationDbContext? _applicationDbContext;

private IRepository<Connection>? _connectionRepository;
private IProfilerService? _profilerService;
private bool _shouldStop = true;
private SqlHighlightService? _sqlHighlightService;
Expand All @@ -40,7 +41,6 @@ public class MainPresenter
private IXEventService? _xEventService;
private Dictionary<string, ProfilerEvent> CurrentRows = new();
private Dictionary<string, object>? Filters;

public MainPresenter(IMainView mainView)
{
view = mainView;
Expand All @@ -56,6 +56,8 @@ public MainPresenter(IMainView mainView)
view.OnFiltersClick += OnFiltersClick;
view.OnClearFiltersClick += OnClearFiltersClick;
view.OnSearch += OnSearch;
view.OnRecentConnectionsClick += OnRecentConnectionsClick;
_connectionRepository = new ConnectionRepository(new SqliteContext());
view.Show();
}

Expand Down Expand Up @@ -369,6 +371,36 @@ private void OnPause(object? sender, EventArgs e)
HandleCancellationRequest();
}

private void OnRecentConnectionsClick(object? sender, EventArgs e)
{
using (var form = new RecentConnectionsView())
{
var presenter = new RecentConnectionsPresenter(form, _connectionRepository);
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
var connection = presenter.GetConnection();
if (connection != null)
{
view.Server = connection.DataSource;
if (connection.IntegratedSecurity)
{
view.User = string.Empty;
view.Password = string.Empty;
view.SelectedAuthenticationMode = Shared.Enums.AuthenticationMode.WindowsAuth;
view.AuthenticationComboBox.SelectedIndex = 0;
}
else
{
view.User = connection.UserId;
view.Password = connection.Password;
view.SelectedAuthenticationMode = Shared.Enums.AuthenticationMode.SQLServerAuth;
view.AuthenticationComboBox.SelectedIndex = 1;
}
}
}
}
}
private void OnResume(object? sender, EventArgs e)
{
_shouldStop = false;
Expand Down Expand Up @@ -402,7 +434,7 @@ private void OnStart(object? sender, EventArgs e)
}
}

private void OnStop(object? sender, EventArgs e)
private async void OnStop(object? sender, EventArgs e)
{
_shouldStop = true;
ShowButtonsByAction("stop");
Expand All @@ -411,6 +443,7 @@ private void OnStop(object? sender, EventArgs e)
try
{
StopProfiling();
await SaveRecentConnection();
}
catch (Exception ex)
{
Expand All @@ -433,6 +466,20 @@ private void RowEnter(object? sender, EventArgs e)
}
}

private async Task SaveRecentConnection()
{
if (_connectionRepository != null && view.Server != null)
{
var newConnection = new Connection(0, "master", DateTime.UtcNow, view.Server, view.User?.Length == 0, view.Password, view.User);
var existingConnection = await _connectionRepository.Find(f => string.Equals(f.DataSource, newConnection.DataSource, StringComparison.InvariantCultureIgnoreCase)
&& string.Equals(f.UserId, newConnection.UserId, StringComparison.InvariantCultureIgnoreCase));
if (existingConnection == null)
{
await _connectionRepository.AddAsync(newConnection);
}
}
}

private void SearchGridValue(string searchValue)
{
if (view.ProfilerGridView.Rows.Count > 0)
Expand Down
Loading
Loading