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 sql lite #39

Merged
merged 2 commits into from
Apr 9, 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
32 changes: 14 additions & 18 deletions source/Kangaroo.UI/App.axaml.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
using System;
using System.Linq;
using AsyncAwaitBestPractices;
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;

using Kangaroo.UI.Services;
using Kangaroo.UI.Services.Database;
using Kangaroo.UI.ViewModels;
using Kangaroo.UI.Views;
using LiveChartsCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Kangaroo.UI;

Expand All @@ -24,26 +28,18 @@ public override void Initialize()
public override void OnFrameworkInitializationCompleted()
{
var builder = Host.CreateApplicationBuilder();
builder.AddKangaroo();
builder.Services.AddSingleton(TimeProvider.System);

builder.Services.AddTransient<MainWindow>();
builder.Services.AddTransient<MainView>();
builder.Services.AddTransient<MainViewModel>();

builder.Services.AddTransient<HomePageView>();
builder.Services.AddTransient<HomePageViewModel>();

builder.Services.AddTransient<IpScannerView>();
builder.Services.AddSingleton<IpScannerViewModel>();

builder.Services.AddTransient<PortScannerView>();
builder.Services.AddTransient<PortScannerViewModel>();

builder.Services.AddTransient<ConfigurationView>();
builder.Services.AddTransient<ConfigurationViewModel>();
var app = builder.Build();

builder.Services.AddTransient<IScannerBuilder, ScannerBuilder>();
var dbInitializer = app.Services.GetRequiredService<IDbInitializer>();
dbInitializer.InitializeAsync().SafeFireAndForget(ex =>
{
Console.WriteLine(ex);
// app.Services.GetRequiredService<ILogger>().LogError(ex, "Failed to initialize the database");
});

var app = builder.Build();
Services = app.Services;

this.Resources[typeof(IHost)] = app;
Expand Down
Binary file added source/Kangaroo.UI/Assets/kangaroo-header.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added source/Kangaroo.UI/Assets/kangaroo-logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added source/Kangaroo.UI/Assets/kangaroo.ico
Binary file not shown.
6 changes: 6 additions & 0 deletions source/Kangaroo.UI/Kangaroo.UI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,23 @@

<ItemGroup>
<None Remove="Assets\circle-loader.gif" />
<None Remove="Assets\kangaroo-header.png" />
<None Remove="Assets\kangaroo-logo.png" />
<None Remove="Assets\kangaroo.ico" />
<None Remove="Assets\wave-loader.gif" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="AnimatedImage.Avalonia" Version="1.0.7" />
<PackageReference Include="AsyncAwaitBestPractices" Version="7.0.0" />
<PackageReference Include="Avalonia" Version="11.0.10" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.0.10" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />

<!--Condition below is needed to remove Avalonia.Diagnostics package from build output in Release configuration.-->
<PackageReference Condition="'$(Configuration)' == 'Debug'" Include="Avalonia.Diagnostics" Version="11.0.10" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.3" />
<PackageReference Include="FluentAvaloniaUI" Version="2.0.5" />
<PackageReference Include="LiveChartsCore.SkiaSharpView.Avalonia" Version="2.0.0-rc2" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
Expand Down
2 changes: 2 additions & 0 deletions source/Kangaroo.UI/Kangaroo.UI.csproj.DotSettings
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=services_005Cdatabase_005Crecentscans/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
10 changes: 10 additions & 0 deletions source/Kangaroo.UI/Models/ScanMode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace Kangaroo.UI.Models;

public enum ScanMode
{
AddressRange,
NetworkSubnet,
NetworkAdapter,
SingleAddress,
SpecifiedAddresses
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using System;
using Dapper;

namespace Kangaroo.UI.Services.Database;

public sealed class BaseTypesRepositoryConfiguration : IConfigureRepository
{
public bool Configure()
{
try
{
SqlMapper.AddTypeHandler(new GuidTypeHandler());
SqlMapper.AddTypeHandler(new DateTimeTypeHandler());
SqlMapper.AddTypeHandler(new TimeSpanTypeHandler());


return true;
}
catch (Exception )
{
return false;
}
}
}
18 changes: 18 additions & 0 deletions source/Kangaroo.UI/Services/Database/DateTimeTypeHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Data;
using Dapper;

namespace Kangaroo.UI.Services.Database;

public class DateTimeTypeHandler : SqlMapper.TypeHandler<DateTime>
{
public override void SetValue(IDbDataParameter parameter, DateTime dateTime)
{
parameter.Value = dateTime;
}

public override DateTime Parse(object value)
{
return DateTime.Parse(value.ToString());
}
}
21 changes: 21 additions & 0 deletions source/Kangaroo.UI/Services/Database/GuidTypeHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System;
using System.Data;
using Dapper;

namespace Kangaroo.UI.Services.Database;

/// <summary>
/// Facilitates the conversion from the GUID to a string and back.
/// </summary>
public class GuidTypeHandler : SqlMapper.TypeHandler<Guid>
{
public override void SetValue(IDbDataParameter parameter, Guid guid)
{
parameter.Value = guid;
}

public override Guid Parse(object value)
{
return new Guid((string)value);
}
}
15 changes: 15 additions & 0 deletions source/Kangaroo.UI/Services/Database/IConfigureRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Kangaroo.UI.Services.Database;

/// <summary>
/// Used to configure repositories.
/// All repositories requiring configuration or executions can implement this interfaces
/// and the configure method will be automatically executed by the framework.
/// </summary>
public interface IConfigureRepository
{
/// <summary>
/// Configures the data type mapping required for the repository.
/// </summary>
/// <returns>Results of the Configuration execution</returns>
bool Configure();
}
18 changes: 18 additions & 0 deletions source/Kangaroo.UI/Services/Database/IDbConnectionFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using static SkiaSharp.HarfBuzz.SKShaper;

namespace Kangaroo.UI.Services.Database;

/// <summary>
/// Creates a new connection to a database
/// </summary>
public interface IDbConnectionFactory
{
/// <summary>
/// Creates an asynchronous connection to a provided database
/// </summary>
/// <returns>Database Connection</returns>
Task<IDbConnection> CreateConnectionAsync(CancellationToken token = default);
}
15 changes: 15 additions & 0 deletions source/Kangaroo.UI/Services/Database/IDbInitializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.Threading.Tasks;

namespace Kangaroo.UI.Services.Database;

/// <summary>
/// Initialized the DB scheme and ensures all tables are created when the system starts.
/// </summary>
public interface IDbInitializer
{
/// <summary>
/// Adds and removes all tables from the database required for the application to initialize correctly.
/// </summary>
/// <returns>awaitable task</returns>
Task InitializeAsync();
}
64 changes: 64 additions & 0 deletions source/Kangaroo.UI/Services/Database/IEntityRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Kangaroo.UI.Services.Database;

/// <summary>
/// Reads and writes entities in a database
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TUniqueId"></typeparam>
public interface IEntityRepository<TEntity, in TUniqueId>
where TEntity : notnull
where TUniqueId: notnull
{
/// <summary>
/// Returns all the entities in the repository
/// <param name="token">cancellation token with default assignment</param>
/// </summary>
/// <returns>User accounts</returns>
Task<IEnumerable<TEntity>> GetAsync(CancellationToken token = default);

/// <summary>
/// Returns the entity with the specified ID
/// </summary>
/// <param name="id">ID</param>
/// <param name="token">cancellation token with default assignment</param>
/// <returns>the nullable entity</returns>
Task<TEntity?> GetByIdAsync(TUniqueId id, CancellationToken token = default);

/// <summary>
/// Creates a new entity in the repository.
/// <remarks>Will return false if the ID or account name already exists</remarks>
/// </summary>
/// <param name="entity">New User Account to Add</param>
/// <param name="token">cancellation token with default assignment</param>
/// <returns>Results</returns>
Task<bool> CreateAsync(TEntity entity, CancellationToken token = default);

/// <summary>
/// Updates the entity in the repository.
/// <remarks>Will return false if the ID or entity exists</remarks>
/// </summary>
/// <param name="entity">New User Account to Add</param>
/// <param name="token">cancellation token with default assignment</param>
/// <returns>Results</returns>
Task<bool> UpdateAsync(TEntity entity, CancellationToken token = default);

/// <summary>
/// Deletes the specified entity with the ID
/// </summary>
/// <param name="id">ID</param>
/// <param name="token"></param>
/// <returns>Result</returns>
Task<bool> DeleteByIdAsync(TUniqueId id, CancellationToken token = default);

/// <summary>
/// Determines if the Entity exists in the repository.
/// </summary>
/// <param name="id">ID</param>
/// <param name="token"></param>
/// <returns>True if account is valid</returns>
Task<bool> ExistsById(TUniqueId id, CancellationToken token = default);
}
62 changes: 62 additions & 0 deletions source/Kangaroo.UI/Services/Database/RecentScans/RecentScan.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
using System;
using System.Net;
using Kangaroo.UI.Models;

namespace Kangaroo.UI.Services.Database;

public sealed class RecentScan
{
public Guid Id { get; set; }
public ScanMode ScanMode { get; set; }
public string? StartAddress { get; set; }
public string? EndAddress { get; set; }
public string? SubnetMask { get; set; }
public string? SpecifiedAddresses { get; set; }
public string? Adapter { get; set; }
public DateTime CreatedDateTime { get; set; }
public TimeSpan ElapsedTime { get; set; }
public int OnlineDevices { get; set; }


public static RecentScan FromRange(string start, string end, TimeProvider time, TimeSpan elapsedTime, int onlineDevices)
{
return new RecentScan
{
Id = Guid.NewGuid(),
ScanMode = ScanMode.AddressRange,
StartAddress = start,
EndAddress = end,
CreatedDateTime = time.GetLocalNow().DateTime,
ElapsedTime = elapsedTime,
OnlineDevices = onlineDevices
};
}
public static RecentScan FromAdapter(string adapter, IPAddress address, IPAddress subnet, TimeProvider time, TimeSpan elapsedTime, int onlineDevices)
{
return new RecentScan
{
Id = Guid.NewGuid(),
ScanMode = ScanMode.NetworkAdapter,
StartAddress = address.ToString(),
SubnetMask = subnet.ToString(),
CreatedDateTime = time.GetLocalNow().DateTime,
ElapsedTime = elapsedTime,
OnlineDevices = onlineDevices
};
}

public static RecentScan FromSubnet(IPAddress address, IPAddress subnet, TimeProvider time, TimeSpan elapsedTime, int onlineDevices)
{
return new RecentScan
{
Id = Guid.NewGuid(),
ScanMode = ScanMode.NetworkSubnet,
StartAddress = address.ToString(),
SubnetMask = subnet.ToString(),
CreatedDateTime = time.GetLocalNow().DateTime,
ElapsedTime = elapsedTime,
OnlineDevices = onlineDevices
};
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;

namespace Kangaroo.UI.Services.Database;

internal class RecentScansConfiguration : IConfigureRepository
{
public bool Configure()
{
try
{
return true;

}
catch (Exception)
{
return false;
}
}

public static object CreateRecentScansParameters(RecentScan recentScan, TimeProvider timeProvider)
{
var parameters = new
{
recentScan.Id,
recentScan.ScanMode,
recentScan.StartAddress,
recentScan.EndAddress,
recentScan.SubnetMask,
recentScan.SpecifiedAddresses,
recentScan.Adapter,
CreatedDateTime = timeProvider.GetLocalNow().DateTime,
recentScan.ElapsedTime,
recentScan.OnlineDevices
};
return parameters;
}
}
Loading