Browse Source

Fix review changes

pull/2134/head
Duke 3 years ago
parent
commit
acd62f8447
8 changed files with 109 additions and 115 deletions
  1. +4
    -55
      docs/guides/other_libs/efcore.md
  2. +36
    -0
      docs/guides/other_libs/samples/ConfiguringSerilog.cs
  3. +9
    -0
      docs/guides/other_libs/samples/DbContextDepInjection.cs
  4. +19
    -0
      docs/guides/other_libs/samples/DbContextSample.cs
  5. +20
    -0
      docs/guides/other_libs/samples/InteractionModuleDISample.cs
  6. +1
    -0
      docs/guides/other_libs/samples/LogDebugSample.cs
  7. +15
    -0
      docs/guides/other_libs/samples/ModifyLogMethod.cs
  8. +5
    -60
      docs/guides/other_libs/serilog.md

+ 4
- 55
docs/guides/other_libs/efcore.md View File

@@ -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<ApplicationDbContext> options) : base(options)
{

}

public DbSet<UserEntity> 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<ApplicationDbContext>(
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<SocketInteractionContext>
{
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 |


+ 36
- 0
docs/guides/other_libs/samples/ConfiguringSerilog.cs View File

@@ -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<AConfigurationClass>(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);
}
}

+ 9
- 0
docs/guides/other_libs/samples/DbContextDepInjection.cs View File

@@ -0,0 +1,9 @@
private static ServiceProvider ConfigureServices()
{
return new ServiceCollection()
.AddDbContext<ApplicationDbContext>(
options => options.UseNpgsql("Your connection string")
)
[...]
.BuildServiceProvider();
}

+ 19
- 0
docs/guides/other_libs/samples/DbContextSample.cs View File

@@ -0,0 +1,19 @@
// ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{

}

public DbSet<UserEntity> Users { get; set; } = null!;
}

// UserEntity.cs
public class UserEntity
{
public ulong Id { get; set; }
public string Name { get; set; }
}

+ 20
- 0
docs/guides/other_libs/samples/InteractionModuleDISample.cs View File

@@ -0,0 +1,20 @@
using Discord;

public class SampleModule : InteractionModuleBase<SocketInteractionContext>
{
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);

...
}
}

+ 1
- 0
docs/guides/other_libs/samples/LogDebugSample.cs View File

@@ -0,0 +1 @@
Log.Debug("Your log message, with {Variables}!", 10); // This will output "[21:51:00 DBG] Your log message, with 10!"

+ 15
- 0
docs/guides/other_libs/samples/ModifyLogMethod.cs View File

@@ -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;
}

+ 5
- 60
docs/guides/other_libs/serilog.md View File

@@ -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<AConfigurationClass>(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.

Loading…
Cancel
Save