« Application console » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
 
(8 versions intermédiaires par le même utilisateur non affichées)
Ligne 2 : Ligne 2 :
[[Category:VisualStudio]]
[[Category:VisualStudio]]
= Liens =
= Liens =
* [[Spectre.Console]]
* [[Command_Line_Parser_Library|Command Line Parser Library]]
* [[Command_Line_Parser_Library|Command Line Parser Library]]
* [[CSharp_7.1#Async_Main|Async Main]]
* [[CSharp_7.1#Async_Main|Async Main]]
Ligne 95 : Ligne 96 :


= [https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/ Dependency injection] =
= [https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/ Dependency injection] =
* [https://pradeeploganathan.com/dotnet/dependency-injection-in-net-core-console-application/ Dependency injection in .net core console application]
<kode lang='bash'>
<kode lang='bash'>
dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package Microsoft.Extensions.Hosting
</kode>
</kode>


<filebox fn='Program.cs'>
<filebox fn='Program.cs'>
static void Main(string[] args)
var appBuilder = Host.CreateApplicationBuilder(args);
{
appBuilder.Services.AddSingleton<MyService>();
    ServiceProvider serviceProvider = ConfigureServices(services);
var host = appBuilder.Build();
 
    IServiceScope scope = serviceProvider.CreateScope();
    scope.ServiceProvider.GetRequiredService<ConsoleApplication>().Run();
 
    serviceProvider.GetRequiredService<ConsoleApplication>().Run();
}


private static ServiceProvider ConfigureServices(IServiceCollection services) =>
var myService = host.Services.GetService<MyService>() ?? throw new NullReferenceException("MyService service");
    new ServiceCollection()
        .AddSingleton<IConfiguration>(
            _ => new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
                .AddUserSecrets<Program>()
                .Build())
        .AddSingleton<IMyService, MyService>()
        .BuildServiceProvider();
</filebox>
</filebox>


<filebox fn='ConsoleApplication.cs'>
== [[Asp.net_core_7#Log|Logging in .Net Core Console Apps]] ==
class ConsoleApplication
* [[Serilog]]
{
<kode lang='bash'>
    private readonly IConfiguration configuration;
dotnet add package Microsoft.Extensions.Logging.Console
    private readonly IMyService myService;
</kode>


     public ConsoleApplication(IConfiguration configuration, IMyService myService)
<filebox fn='Program.cs'>
     {
var appBuilder =  Host.CreateApplicationBuilder(args);
        this.configuration = configuration;
appBuilder.Logging
        this.myService = myService;
     .ClearProviders()
    }
     .AddConsole();
var host = hostBuilder.Build();


    public void Run()
var logger = host.Services.GetService<ILoggerFactory>()?.CreateLogger<Program>() ?? throw new NullReferenceException("ILoggerFactory service");
    {
logger.LogDebug("Starting application");
        var serviceProvider = ConfigureServices();
</filebox>
        using var dbContext = serviceProvider.GetService<AppDbContext>();


        myService.DoSomething();
<filebox fn='MyService.cs'>
    }
private readonly ILogger logger;


    private ServiceProvider ConfigureServices()
public MyService(ILogger logger)
        => new ServiceCollection()
{
            .AddDbContext<AppDbContext>(
     this.logger = logger;
                x => x.UseMySql(BuildConnectionString(),
                    mySqlOptions => mySqlOptions.ServerVersion("10.5.8-mariadb")))
            .BuildServiceProvider();
 
     private string BuildConnectionString()
    {
        var connectionStringBuilder = new SqlConnectionStringBuilder("server=localhost;database=test;user=test;");
        connectionStringBuilder.Password = configuration["DbPassword"];
 
        return connectionStringBuilder.ConnectionString;
    }
}
}
</filebox>
</filebox>


== [https://www.blinkingcaret.com/2018/02/14/net-core-console-logging/ Logging in .Net Core Console Apps] ==
== Configuration ==
* [[Serilog]]
<filebox fn='Program.cs'>
<kode lang='bash'>
var appBuilder =  Host.CreateApplicationBuilder(args);
dotnet add package Microsoft.Extensions.Logging.Console
// by default the app load appsettings.json from Directory.GetCurrentDirectory()
</kode>
 
// change to load from the directory where the binary is located
var appBuilder = new HostApplicationBuilder(
    new HostApplicationBuilderSettings { ContentRootPath = AppContext.BaseDirectory });


<filebox fn='Program.cs'>
var host = hostBuilder.Build();
var hostBuilder =  Host.CreateDefaultBuilder(args)
</filebox>
    .ConfigureLogging(x =>
    {
        x.ClearProviders();
        x.AddConsole();
    })
    .ConfigureServices(x =>
    {
        x.AddSingleton<MyClass>();
    });
using var host = hostBuilder.Build();


var logger = host.Services.GetService<ILoggerFactory>()?.CreateLogger<Program>() ?? throw new NullReferenceException("ILoggerFactory service");
<filebox fn='MyService.cs'>
logger.LogDebug("Starting application");
private readonly IConfiguration configuration;


var myClass = host.Services.GetService<MyClass>() ?? throw new NullReferenceException("MyClass service");
public MyService(IConfiguration configuration)
{
    this.configuration = configuration;
}


// await host.RunAsync();
var value = configuration.GetValue<string>("key");
var values = Configuration.GetSection("sectionKey").Get<string[]>();
</filebox>
</filebox>
{{warn | By default the environment is set to Production, so the user secrets storage is not loaded.}}


= [[Asp.net_core_7#Configuration|Configuration]] =
= [[Asp.net_core_7#Configuration|Configuration]] =

Dernière version du 24 mars 2024 à 15:58

Liens

Code

Csharp.svg
using System;

namespace MonNS
{
    class MaClasse
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("");
        }
    }
}

Read input

Cs.svg
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
if (keyInfo.Key == ConsoleKey.Escape) { }

Masquer la saisie d'un mot de passe

Csharp.svg
public static string ReadPassword()
{
    string password = "";
    ConsoleKeyInfo info = Console.ReadKey(true);
    while (info.Key != ConsoleKey.Enter)
    {
        if (info.Key != ConsoleKey.Backspace)
        {
            Console.Write("*");
            password += info.KeyChar;
        }
        else if (info.Key == ConsoleKey.Backspace)
        {
            if (!string.IsNullOrEmpty(password))
            {
                // remove one character from the list of password characters
                password = password.Substring(0, password.Length - 1);

                // get the location of the cursor
                int pos = Console.CursorLeft;

                // move the cursor to the left by one character
                Console.SetCursorPosition(pos - 1, Console.CursorTop);

                // replace it with space
                Console.Write(" ");

                // move the cursor to the left by one character again
                Console.SetCursorPosition(pos - 1, Console.CursorTop);
            }
        }

        info = Console.ReadKey(true);
    }

    // add a new line because user pressed enter at the end of their password
    Console.WriteLine();

    return password;
}

Masquer la fenêtre de la Console

Csharp.svg
[DllImport("kernel32.dll")]
private static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

private const int SW_HIDE = 0;
private const int SW_SHOW = 5;

var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE);

Couleurs

Cs.svg
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("...");
Console.ResetColor();

Dependency injection

Bash.svg
dotnet add package Microsoft.Extensions.Hosting
Program.cs
var appBuilder = Host.CreateApplicationBuilder(args);
appBuilder.Services.AddSingleton<MyService>();
var host = appBuilder.Build();

var myService = host.Services.GetService<MyService>() ?? throw new NullReferenceException("MyService service");

Logging in .Net Core Console Apps

Bash.svg
dotnet add package Microsoft.Extensions.Logging.Console
Program.cs
var appBuilder =  Host.CreateApplicationBuilder(args);
appBuilder.Logging
    .ClearProviders()
    .AddConsole();
var host = hostBuilder.Build();

var logger = host.Services.GetService<ILoggerFactory>()?.CreateLogger<Program>() ?? throw new NullReferenceException("ILoggerFactory service");
logger.LogDebug("Starting application");
MyService.cs
private readonly ILogger logger;

public MyService(ILogger logger)
{
    this.logger = logger;
}

Configuration

Program.cs
var appBuilder =  Host.CreateApplicationBuilder(args);
// by default the app load appsettings.json from Directory.GetCurrentDirectory()

// change to load from the directory where the binary is located
var appBuilder = new HostApplicationBuilder(
    new HostApplicationBuilderSettings { ContentRootPath = AppContext.BaseDirectory });

var host = hostBuilder.Build();
MyService.cs
private readonly IConfiguration configuration;

public MyService(IConfiguration configuration)
{
    this.configuration = configuration;
}

var value = configuration.GetValue<string>("key");
var values = Configuration.GetSection("sectionKey").Get<string[]>();
By default the environment is set to Production, so the user secrets storage is not loaded.

Configuration

Bash.svg
dotnet add package Microsoft.Extensions.Configuration.Json
dotnet add package Microsoft.Extensions.Configuration.Binder
Program.cs
private static IConfiguration Configuration;

static void Main(string[] args)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(AppContext.BaseDirectory)  // default value
        .AddJsonFile("appsettings.json");

    Configuration = builder.Build();

    var value1 = Configuration.GetValue<string>("section1");
    var value2 = Configuration.GetValue<int>("section2");
    var values = Configuration.GetSection("section3").Get<string[]>();
MyProject.csproj
<!-- copy the appsettings.json file in the output folder -->
<ItemGroup>
  <None Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>

Entity Framework Core

Program.cs
// nuget package: Microsoft.Extensions.Hosting

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);  // allow to use scaffold with a named connection string

var connectionString = builder.Configuration.GetConnectionString("DB1");
var serverVersion = new MariaDbServerVersion(new Version(11, 0, 2));

builder.Services.AddDbContext<DB1Context>(
    dbContextOptions => dbContextOptions
        .UseMySql(connectionString, serverVersion)
        // TODO The following three options help with debugging, but should be changed or removed for production.
        .LogTo(Console.WriteLine, LogLevel.Information)
        .EnableSensitiveDataLogging()
        .EnableDetailedErrors());

builder.Services.AddTransient<ItemRepository>();

using IHost host = builder.Build();

var itemRepository = host.Services.GetService<ItemRepository>();
if (itemRepository is not null)
{
    await itemRepository.GetAllItemsAsync();
}

//await host.RunAsync();