From acd62f84473ed93be931414b781f793b3f236628 Mon Sep 17 00:00:00 2001 From: Duke <40759437+dukesteen@users.noreply.github.com> Date: Fri, 25 Feb 2022 00:08:24 +0100 Subject: [PATCH] Fix review changes --- docs/guides/other_libs/efcore.md | 59 ++--------------- .../other_libs/samples/ConfiguringSerilog.cs | 36 ++++++++++ .../samples/DbContextDepInjection.cs | 9 +++ .../other_libs/samples/DbContextSample.cs | 19 ++++++ .../samples/InteractionModuleDISample.cs | 20 ++++++ .../other_libs/samples/LogDebugSample.cs | 1 + .../other_libs/samples/ModifyLogMethod.cs | 15 +++++ docs/guides/other_libs/serilog.md | 65 ++----------------- 8 files changed, 109 insertions(+), 115 deletions(-) create mode 100644 docs/guides/other_libs/samples/ConfiguringSerilog.cs create mode 100644 docs/guides/other_libs/samples/DbContextDepInjection.cs create mode 100644 docs/guides/other_libs/samples/DbContextSample.cs create mode 100644 docs/guides/other_libs/samples/InteractionModuleDISample.cs create mode 100644 docs/guides/other_libs/samples/LogDebugSample.cs create mode 100644 docs/guides/other_libs/samples/ModifyLogMethod.cs diff --git a/docs/guides/other_libs/efcore.md b/docs/guides/other_libs/efcore.md index e39efbfc7..ffdea42aa 100644 --- a/docs/guides/other_libs/efcore.md +++ b/docs/guides/other_libs/efcore.md @@ -26,28 +26,7 @@ You can install the following packages through your IDE or go to the nuget link To use EFCore, you need a DbContext to access everything in your database. The DbContext will look like this. Here is an example entity to show you how you can add more entities yourself later on. -```cs -// ApplicationDbContext.cs -using Microsoft.EntityFrameworkCore; - -public class ApplicationDbContext : DbContext -{ - public ApplicationDbContext(DbContextOptions options) : base(options) - { - - } - - public DbSet Users { get; set; } = null!; -} - -// UserEntity.cs - -public class UserEntity -{ - public ulong Id { get; set; } - public string Name { get; set; } -} -``` +[!code-csharp[DBContext Sample](samples/DbContextSample.cs)] > [!NOTE] > To learn more about creating the EFCore model, visit the following [link](https://docs.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli#create-the-model) @@ -56,17 +35,7 @@ public class UserEntity To add your newly created DbContext to your Dependency Injection container, simply use the extension method provided by EFCore to add the context to your container. It should look something like this -```cs -private static ServiceProvider ConfigureServices() -{ - return new ServiceCollection() - .AddDbContext( - options => options.UseNpgsql("Your connection string") - ) - [...] - .BuildServiceProvider(); -} -``` +[!code-csharp[DBContext Dependency Injection](samples/DbContextDepInjection.cs)] > [!NOTE] > You can find out how to get your connection string [here](https://www.connectionstrings.com/npgsql/standard/) @@ -80,30 +49,10 @@ To learn more about migrations, visit the official Microsoft documentation [here You can now use the DbContext wherever you can inject it. Here's an example on injecting it into an interaction command module. -```cs -using Discord; - -public class SampleModule : InteractionModuleBase -{ - private readonly ApplicationDbContext _db; - - public SampleModule(ApplicationDbContext db) - { - _db = db; - } - - [SlashCommand("sample", "sample")] - public async Task Sample() - { - // Do stuff with your injected DbContext - var user = _db.Users.FirstOrDefault(x => x.Id == Context.User.Id); - - ... - } -} -``` +[!code-csharp[DBContext injected into interaction module](samples/InteractionModuleDISample.cs)] ## Using a different database provider + Here's a couple of popular database providers for EFCore and links to tutorials on how to set them up. The only thing that usually changes is the provider inside of your `DbContextOptions` | Provider | Link | diff --git a/docs/guides/other_libs/samples/ConfiguringSerilog.cs b/docs/guides/other_libs/samples/ConfiguringSerilog.cs new file mode 100644 index 000000000..f60b8aab1 --- /dev/null +++ b/docs/guides/other_libs/samples/ConfiguringSerilog.cs @@ -0,0 +1,36 @@ +using Discord; +using Serilog; +using Serilog.Events; + +public class Program +{ + static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult(); + + public async Task MainAsync() + { + Log.Logger = new LoggerConfiguration() + .MinimumLevel.Verbose() + .Enrich.FromLogContext() + .WriteTo.Console() + .CreateLogger(); + + _client = new DiscordSocketClient(); + + _client.Log += LogAsync; + + // You can assign your bot token to a string, and pass that in to connect. + // This is, however, insecure, particularly if you plan to have your code hosted in a public repository. + var token = "token"; + + // Some alternative options would be to keep your token in an Environment Variable or a standalone file. + // var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable"); + // var token = File.ReadAllText("token.txt")[0]; + // var token = JsonConvert.DeserializeObject(File.ReadAllText("config.json")).Token; + + await _client.LoginAsync(TokenType.Bot, token); + await _client.StartAsync(); + + // Block this task until the program is closed. + await Task.Delay(Timeout.Infinite); + } +} diff --git a/docs/guides/other_libs/samples/DbContextDepInjection.cs b/docs/guides/other_libs/samples/DbContextDepInjection.cs new file mode 100644 index 000000000..5d989995b --- /dev/null +++ b/docs/guides/other_libs/samples/DbContextDepInjection.cs @@ -0,0 +1,9 @@ +private static ServiceProvider ConfigureServices() +{ + return new ServiceCollection() + .AddDbContext( + options => options.UseNpgsql("Your connection string") + ) + [...] + .BuildServiceProvider(); +} diff --git a/docs/guides/other_libs/samples/DbContextSample.cs b/docs/guides/other_libs/samples/DbContextSample.cs new file mode 100644 index 000000000..96104ae53 --- /dev/null +++ b/docs/guides/other_libs/samples/DbContextSample.cs @@ -0,0 +1,19 @@ +// ApplicationDbContext.cs +using Microsoft.EntityFrameworkCore; + +public class ApplicationDbContext : DbContext +{ + public ApplicationDbContext(DbContextOptions options) : base(options) + { + + } + + public DbSet Users { get; set; } = null!; +} + +// UserEntity.cs +public class UserEntity +{ + public ulong Id { get; set; } + public string Name { get; set; } +} diff --git a/docs/guides/other_libs/samples/InteractionModuleDISample.cs b/docs/guides/other_libs/samples/InteractionModuleDISample.cs new file mode 100644 index 000000000..777d6aef0 --- /dev/null +++ b/docs/guides/other_libs/samples/InteractionModuleDISample.cs @@ -0,0 +1,20 @@ +using Discord; + +public class SampleModule : InteractionModuleBase +{ + private readonly ApplicationDbContext _db; + + public SampleModule(ApplicationDbContext db) + { + _db = db; + } + + [SlashCommand("sample", "sample")] + public async Task Sample() + { + // Do stuff with your injected DbContext + var user = _db.Users.FirstOrDefault(x => x.Id == Context.User.Id); + + ... + } +} diff --git a/docs/guides/other_libs/samples/LogDebugSample.cs b/docs/guides/other_libs/samples/LogDebugSample.cs new file mode 100644 index 000000000..e796e207a --- /dev/null +++ b/docs/guides/other_libs/samples/LogDebugSample.cs @@ -0,0 +1 @@ +Log.Debug("Your log message, with {Variables}!", 10); // This will output "[21:51:00 DBG] Your log message, with 10!" diff --git a/docs/guides/other_libs/samples/ModifyLogMethod.cs b/docs/guides/other_libs/samples/ModifyLogMethod.cs new file mode 100644 index 000000000..0f7c11daf --- /dev/null +++ b/docs/guides/other_libs/samples/ModifyLogMethod.cs @@ -0,0 +1,15 @@ +private static async Task LogAsync(LogMessage message) +{ + var severity = message.Severity switch + { + LogSeverity.Critical => LogEventLevel.Fatal, + LogSeverity.Error => LogEventLevel.Error, + LogSeverity.Warning => LogEventLevel.Warning, + LogSeverity.Info => LogEventLevel.Information, + LogSeverity.Verbose => LogEventLevel.Verbose, + LogSeverity.Debug => LogEventLevel.Debug, + _ => LogEventLevel.Information + }; + Log.Write(severity, message.Exception, "[{Source}] {Message}", message.Source, message.Message); + await Task.CompletedTask; +} diff --git a/docs/guides/other_libs/serilog.md b/docs/guides/other_libs/serilog.md index 3f2a993de..7fe5b037c 100644 --- a/docs/guides/other_libs/serilog.md +++ b/docs/guides/other_libs/serilog.md @@ -22,66 +22,13 @@ You can install the following packages through your IDE or go to the nuget link Serilog will be configured at the top of your async Main method, it looks like this -```cs -using Discord; -using Serilog; -using Serilog.Events; - -public class Program -{ - public static Task Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult(); - - public async Task MainAsync() - { - Log.Logger = new LoggerConfiguration() - .MinimumLevel.Verbose() - .Enrich.FromLogContext() - .WriteTo.Console() - .CreateLogger(); - - _client = new DiscordSocketClient(); - - _client.Log += LogAsync; - - // You can assign your bot token to a string, and pass that in to connect. - // This is, however, insecure, particularly if you plan to have your code hosted in a public repository. - var token = "token"; - - // Some alternative options would be to keep your token in an Environment Variable or a standalone file. - // var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable"); - // var token = File.ReadAllText("token.txt")[0]; - // var token = JsonConvert.DeserializeObject(File.ReadAllText("config.json")).Token; - - await _client.LoginAsync(TokenType.Bot, token); - await _client.StartAsync(); - - // Block this task until the program is closed. - await Task.Delay(Timeout.Infinite); - } -} -``` +[!code-csharp[Configuring serilog](samples/ConfiguringSerilog.cs)] ## Modifying your logging method -For serilog to log discord events correctly, we have to map the discord `LogSeverity` to the serilog `LogEventLevel`. You can modify your log method to look like this. - -```cs -private static async Task LogAsync(LogMessage message) -{ - var severity = message.Severity switch - { - LogSeverity.Critical => LogEventLevel.Fatal, - LogSeverity.Error => LogEventLevel.Error, - LogSeverity.Warning => LogEventLevel.Warning, - LogSeverity.Info => LogEventLevel.Information, - LogSeverity.Verbose => LogEventLevel.Verbose, - LogSeverity.Debug => LogEventLevel.Debug, - _ => LogEventLevel.Information - }; - Log.Write(severity, message.Exception, "[{Source}] {Message}", message.Source, message.Message); - await Task.CompletedTask; -} -``` +For serilog to log Discord events correctly, we have to map the discord `LogSeverity` to the serilog `LogEventLevel`. You can modify your log method to look like this. + +[!code-csharp[Modifying your log method](samples/ModifyLogMethod.cs)] ## Testing @@ -92,9 +39,7 @@ If you run your application now, you should see something similar to this Now that you have set up Serilog, you can use it everywhere in your application by simply calling -```cs -Log.Debug("Your log message, with {Variables}!", 10) // This will output "[21:51:00 DBG] Your log message, with 10!" -``` +[!code-csharp[Log debug sample](samples/LogDebugSample.cs)] > [!NOTE] > Depending on your configured log level, the log messages may or may not show up in your console. Refer to [Serilog's github page](https://github.com/serilog/serilog/wiki/Configuration-Basics#minimum-level) for more information about log levels.