🚧 Core API and abstractions extending

This commit is contained in:
2020-03-02 00:00:44 +04:00
parent ed255e2506
commit e86049f4fd
7 changed files with 198 additions and 0 deletions
+16
View File
@@ -66,6 +66,7 @@ namespace Kruzya.TelegramBot.Core
{ {
_configuration = configuration; _configuration = configuration;
HookAppDomain();
Start(); Start();
} }
@@ -156,5 +157,20 @@ namespace Kruzya.TelegramBot.Core
return module; return module;
} }
private void HookAppDomain()
{
AppDomain.CurrentDomain.AssemblyResolve += delegate(object? sender, ResolveEventArgs args)
{
var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string assemblyPath = Path.Combine(basePath, new AssemblyName(args.Name).Name + ".dll");
if (!File.Exists(assemblyPath))
{
return null;
}
return Assembly.LoadFrom(assemblyPath);
};
}
} }
} }
+4
View File
@@ -8,6 +8,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="AleXr64.BotFramework" Version="0.0.17" /> <PackageReference Include="AleXr64.BotFramework" Version="0.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="3.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Hosting.Systemd" Version="3.1.2" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+41
View File
@@ -0,0 +1,41 @@
using System;
using BotFramework;
using Microsoft.EntityFrameworkCore;
namespace Kruzya.TelegramBot.Core
{
/// <summary>
/// Resolves the GUIDs from database to entities.
/// </summary>
/// <typeparam name="TResolvedEntity">Entity type</typeparam>
/// <typeparam name="TAppContext">Database context where entity should be finded</typeparam>
public class DbResolverParameter<TResolvedEntity, TAppContext> : IParameterParser<TResolvedEntity>
where TAppContext : DbContext
where TResolvedEntity : class
{
private TAppContext _dbContext;
public DbResolverParameter(TAppContext dbContext)
{
_dbContext = dbContext;
}
public TResolvedEntity DefaultInstance()
{
return default(TResolvedEntity);
}
public bool TryGetValue(string text, out TResolvedEntity result)
{
result = null;
Guid id;
if (Guid.TryParse(text, out id))
{
result = _dbContext.Find<TResolvedEntity>(id);
return (result != null);
}
return false;
}
}
}
+47
View File
@@ -0,0 +1,47 @@
using Microsoft.EntityFrameworkCore;
namespace Kruzya.TelegramBot.Core.Extensions
{
public static class RepositoryExtension
{
#region DbContext
/// <summary>
/// Marks the entity as created.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as created.</param>
public static void MarkAsCreated(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Added;
/// <summary>
/// Marks the entity as deleted.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as deleted.</param>
public static void MarkAsDeleted(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Deleted;
/// <summary>
/// Marks the entity as modified.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="entity">Entity for marking as modified.</param>
public static void MarkAsModified(this DbContext dbContext, object entity) =>
dbContext.Entry(entity).State = EntityState.Modified;
#endregion
#region Repository
public static TEntity Create<TEntity>(this DbSet<TEntity> repository) where TEntity : class, new()
{
var entity = new TEntity();
repository.Add(entity);
return entity;
}
#endregion
}
}
+13
View File
@@ -0,0 +1,13 @@
using System.Collections.Concurrent;
using Microsoft.Extensions.DependencyInjection;
namespace Kruzya.TelegramBot.Core.Extensions
{
public static class StartupExtension
{
public static IServiceCollection AddQueue<T>(this IServiceCollection collection)
{
return collection.AddSingleton<ConcurrentQueue<T>>();
}
}
}
+1
View File
@@ -12,6 +12,7 @@ namespace Kruzya.TelegramBot.Core
public static IHostBuilder CreateHostBuilder(string[] args) => public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args) Host.CreateDefaultBuilder(args)
.UseSystemd()
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
} }
} }
@@ -0,0 +1,76 @@
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BotFramework;
using Microsoft.Extensions.Logging;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
namespace Kruzya.TelegramBot.Core.Service
{
public abstract class AbstractTimedHostedService
{
private Timer _timer;
protected readonly ILogger _logger;
protected readonly ITelegramBot _bot;
protected virtual TimeSpan TimerPeriod => TimeSpan.FromSeconds(45);
protected AbstractTimedHostedService(ILogger logger, ITelegramBot bot)
{
_bot = bot;
_logger = logger;
}
#region IHostedService
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Message sender service is starting.");
_timer = new Timer(Run, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Message sender service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
#endregion
#region IDisposable
/// <summary>
/// Disposes the timer.
/// </summary>
public void Dispose()
{
_timer?.Dispose();
}
#endregion
private async void Run(object state)
{
_timer?.Change(Timeout.Infinite, 0);
try
{
await OnRun();
}
finally
{
var timerPeriod = this.TimerPeriod;
_timer?.Change(timerPeriod, timerPeriod);
}
}
protected virtual async Task OnRun()
{
await Task.Delay(500);
}
}
}