Skip to content
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
34 changes: 19 additions & 15 deletions NSSLServer.Core/Extension/IPlugin.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace NSSLServer.Core.Extension
{
namespace NSSLServer.Core.Extension;

/// <summary>
/// Interface for plugins
/// </summary>
/// <remarks>
/// Has to contain empty ctor, otherwise not loaded
/// </remarks>
public interface IPlugin
{
/// <summary>
/// Interface for plugins
/// The name of the plugin
/// </summary>
/// <remarks>
/// Has to contain empty ctor, otherwise not loaded
/// </remarks>
public interface IPlugin
{
public string Name { get; }
string Name { get; }

bool Initialize(NLog.LogFactory logFactory);
/// <summary>
/// Configures the plugin during application startup.
/// </summary>
public void Configure(WebApplicationBuilder builder) { }

public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { }
public virtual void ConfigureServices(IServiceCollection services) { }
}
/// <summary>
/// Configures the plugin after all services are registered.
/// </summary>
public void Configure(WebApplication app) { }
}
8 changes: 7 additions & 1 deletion NSSLServer.Core/HelperMethods/PluginCreator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Linq.Expressions;

namespace NSSLServer.Core.HelperMethods
Expand All @@ -10,5 +11,10 @@ public static T GetInstance(Type pluginType)
var body = Expression.New(pluginType);
return Expression.Lambda<Func<T>>(body).Compile().Invoke();
}

public static T GetInstance(Type pluginType, ILogger logger)
{
return (T)Activator.CreateInstance(pluginType, [logger]);
}
}
}
1 change: 0 additions & 1 deletion NSSLServer.Core/NSSLServer.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.3.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="9.0.6" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NLog" Version="6.0.0" />
</ItemGroup>

<Import Project="..\NSSLServer.Litgit.targets" Condition="Exists('..\NSSLServer.Litgit.targets') AND '$(IsDockerBuild)' != 'true'" />
Expand Down
22 changes: 10 additions & 12 deletions NSSLServer.Database/Plugin.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
using Deviax.QueryBuilder;

using NLog;
using Microsoft.AspNetCore.Builder;

using NSSLServer.Core.Extension;

namespace NSSLServer.Database
{
public class Plugin : IPlugin
{
public string Name { get; } = "Database Core Plugin";
namespace NSSLServer.Database;

public bool Initialize(LogFactory logFactory)
{
QueryExecutor.DefaultExecutor = new PostgresExecutor();
public class Plugin : IPlugin
{
/// <inheritdoc/>
public string Name { get; } = "Database Core Plugin";

return true;
}
/// <inheritdoc/>
public void Configure(WebApplication app)
{
QueryExecutor.DefaultExecutor = new PostgresExecutor();
}
}
14 changes: 6 additions & 8 deletions NSSLServer.Database/Updater/DbUpdater.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using Deviax.QueryBuilder;

using NLog;

using Microsoft.Extensions.Logging;
using NSSLServer.Database.Models;

using System;
Expand All @@ -21,13 +19,13 @@ public abstract class DbUpdater : IDbUpdater
public abstract int Priority { get; }
public bool UpToDate => CurrentVersion == DesiredVersion;

private Logger logger;
private ILogger logger;
private List<(Version version, string path)> updateScriptPathes;

public DbUpdater()
public DbUpdater(ILogger logger)
{
var type = GetType();// "MyCompany.MyProduct.MyFile.txt";
logger = LogManager.GetCurrentClassLogger();
this.logger = logger;

updateScriptPathes = new List<(Version, string)>();

Expand Down Expand Up @@ -55,7 +53,7 @@ public virtual async Task LoadCurrentVersion()
}
catch (Exception ex)
{
logger.Warn(ex, $"Error loading current db version for {Name}, setting {nameof(CurrentVersion)} to default");
logger.LogWarning(ex, "Error loading current db version for {name}, setting {currentVersion} to default", Name, nameof(CurrentVersion));
}
if (dbVersion is null)
{
Expand Down Expand Up @@ -127,7 +125,7 @@ public async Task RunUpdates()
catch (Exception ex)
{
trans.Rollback();
logger.Error(ex, $"Error in {Name} for {updateScript.version}");
logger.LogError(ex, "Error in {name} for {version}", Name, updateScript.version);
break;
}
}
Expand Down
4 changes: 2 additions & 2 deletions NSSLServer.Database/Updater/FrameworkDbUpdater.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@

using Deviax.QueryBuilder;

using Microsoft.Extensions.Logging;
using NSSLServer.Database.Models;
using NSSLServer.Models;
using NSSLServer.Models.Products;


namespace NSSLServer.Database.Updater
{
public class FrameworkDbUpdater : DbUpdater
public class FrameworkDbUpdater(ILogger logger) : DbUpdater(logger)
{
public override int Priority { get; } = 1;

Expand Down
32 changes: 20 additions & 12 deletions NSSLServer.Plugin.Example/ExamplePlugin.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
using NLog;

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NSSLServer.Core.Extension;

namespace NSSLServer.Plugin.Example
namespace NSSLServer.Plugin.Example;

public class ExamplePlugin : IPlugin
{
public class ExamplePlugin : IPlugin
{
private Logger logger;
private ILogger<ExamplePlugin> logger;

public string Name { get; }
/// <inheritdoc/>
public string Name { get; } = "Example Plugin";

public bool Initialize(LogFactory factory)
{
logger = factory.GetCurrentClassLogger();
return true;
}
/// <inheritdoc/>
public void Configure(WebApplicationBuilder builder)
{
// Register services here if needed.
}

/// <inheritdoc/>
public void Configure(WebApplication app)
{
// Get services if needed.

logger = app.Services.GetRequiredService<ILogger<ExamplePlugin>>();
logger.LogInformation("Example Plugin loaded successfully.");
}
}
172 changes: 88 additions & 84 deletions NSSLServer.Plugin.InitializationHelper/Plugin.cs
Original file line number Diff line number Diff line change
@@ -1,100 +1,104 @@
using System;
using Microsoft.AspNetCore.Builder;
using NSSLServer.Core.Extension;
using System;
using System.IO;

using NLog;
using NSSLServer.Core.Extension;
namespace NSSLServer.Plugin.InitializationHelper;

namespace NSSLServer.Plugin.InitializationHelper
public class Plugin : IPlugin
{
public class Plugin : IPlugin
public string Name { get; } = "Initialization Helper Plugin";

private void GetEmailCert()
{
public string Name { get; }
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "external", "emailcert");
if (File.Exists(filePath))
return;
File.WriteAllLines(filePath, new[] { "test", "test" });
}

public bool Initialize(LogFactory logFactory)
{
AskForPostgres();
private void CreateServiceAccountForFirebase()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "service_account.json")))
return;
Console.WriteLine("You can create a firebase account, for firebase messaging. This service is free by google and normaly required for the shoppinglist plugin.");
Console.WriteLine("To do so, you can visit the firebase url and follow the stepts there: https://firebase.google.com/products/cloud-messaging");
Console.WriteLine("After you've created everything, you should be able to download a 'service_account.json', please copy this file into the external folder, where the secretkey and connectionstring are at.");
Console.WriteLine("Path should be: " + Path.Combine(Directory.GetCurrentDirectory(), "external"));
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}

while (!GetConnectionString()) { };
private bool GetSecretKeyForJwt()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "secretkey")))
return true;

GetSecretKeyForJwt();
Console.Clear();
Console.WriteLine("Please insert a random string of letters for the jwt key, required for login token generation.");
Console.WriteLine("Can be changed afterwards in the 'secretkey' file in the external folder. After changing it, the current login tokens will be invalidated.");

CreateServiceAccountForFirebase();
var jwtSecret = Console.ReadLine();
if (string.IsNullOrWhiteSpace(jwtSecret))
return false;
Directory.CreateDirectory("external");
File.WriteAllText(Path.Combine("external", "secretkey"), jwtSecret);

GetEmailCert();
return true;
}

private bool GetConnectionString()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "connectionstring")))
return true;
}

private void GetEmailCert()
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "external", "emailcert");
if (File.Exists(filePath))
return;
File.WriteAllLines(filePath, new[] { "test", "test" });
}

private void CreateServiceAccountForFirebase()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "service_account.json")))
return;
Console.WriteLine("You can create a firebase account, for firebase messaging. This service is free by google and normaly required for the shoppinglist plugin.");
Console.WriteLine("To do so, you can visit the firebase url and follow the stepts there: https://firebase.google.com/products/cloud-messaging");
Console.WriteLine("After you've created everything, you should be able to download a 'service_account.json', please copy this file into the external folder, where the secretkey and connectionstring are at.");
Console.WriteLine("Path should be: " + Path.Combine(Directory.GetCurrentDirectory(), "external"));
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}

private bool GetSecretKeyForJwt()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "secretkey")))
return true;

Console.Clear();
Console.WriteLine("Please insert a random string of letters for the jwt key, required for login token generation.");
Console.WriteLine("Can be changed afterwards in the 'secretkey' file in the external folder. After changing it, the current login tokens will be invalidated.");

var jwtSecret = Console.ReadLine();
if (string.IsNullOrWhiteSpace(jwtSecret))
return false;
Directory.CreateDirectory("external");
File.WriteAllText(Path.Combine("external", "secretkey"), jwtSecret);
Console.Clear();
Console.WriteLine("Please insert you connection string for the database.");
Console.WriteLine("Example: User Id=postgres;Server=127.0.0.1;Port=5432;Password=password;Database=testInit;Pooling=true;Minimum Pool Size=10;Trust Server Certificate=True;");
Console.WriteLine("If you want to change the connectionstring afterwards, you have to edit the 'connectionstring' file in the external folder");

var conString = Console.ReadLine();
if (string.IsNullOrWhiteSpace(conString))
return false;
Directory.CreateDirectory("external");
File.WriteAllText(Path.Combine("external", "connectionstring"), conString);
return true;
}

private bool AskForPostgres()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "connectionstring")))
return true;
}

private bool GetConnectionString()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "connectionstring")))
return true;
Console.Clear();
Console.WriteLine("Please insert you connection string for the database.");
Console.WriteLine("Example: User Id=postgres;Server=127.0.0.1;Port=5432;Password=password;Database=testInit;Pooling=true;Minimum Pool Size=10;Trust Server Certificate=True;");
Console.WriteLine("If you want to change the connectionstring afterwards, you have to edit the 'connectionstring' file in the external folder");

var conString = Console.ReadLine();
if (string.IsNullOrWhiteSpace(conString))
return false;
Directory.CreateDirectory("external");
File.WriteAllText(Path.Combine("external", "connectionstring"), conString);

Console.WriteLine("Do you have PostgreSQL installed? ((y)es, no)");
var res = Console.ReadLine();

if (string.IsNullOrWhiteSpace(res))
return true;

var key = res.ToLowerInvariant();

if (key.StartsWith('y'))
return true;
}

private bool AskForPostgres()
{
if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "external", "connectionstring")))
return true;
Console.WriteLine("Do you have Postresql installed? ((y)es, no)");
var res = Console.ReadLine();

if (!string.IsNullOrWhiteSpace(res) || res.ToLower().StartsWith("n"))
{
Console.Clear();
Console.WriteLine("Please install Postgres first. You can download it from https://www.postgresql.org/download/");
Console.WriteLine("If you have installed it, press any key");
Console.ReadKey();
res = null;
}
return string.IsNullOrWhiteSpace(res) || res.ToLower().StartsWith("y");
}

Console.Clear();
Console.WriteLine("Please install Postgres first. You can download it from https://www.postgresql.org/download/");
Console.WriteLine("If you have installed it, press any key");
Console.ReadKey();

return true;
}

/// <inheritdoc/>
public void Configure(WebApplicationBuilder builder)
{
AskForPostgres();

while (!GetConnectionString()) { }

GetSecretKeyForJwt();

CreateServiceAccountForFirebase();

GetEmailCert();
}
}
Loading
Loading