« Application console » : différence entre les versions
De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 201 : | Ligne 201 : | ||
Configuration = builder.Build(); | Configuration = builder.Build(); | ||
</filebox> | |||
<filebox fn='MyProject.csproj'> | |||
<!-- copy the appsettings.json file in the output folder --> | |||
<ItemGroup> | |||
<None Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" /> | |||
</ItemGroup> | |||
</filebox> | </filebox> | ||
Version du 20 août 2023 à 11:40
Liens
Code
using System; namespace MonNS { class MaClasse { public static void Main(string[] args) { Console.WriteLine(""); } } } |
Read input
ConsoleKeyInfo keyInfo = Console.ReadKey(true); if (keyInfo.Key == ConsoleKey.Escape) { } |
Masquer la saisie d'un mot de passe
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
[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
Console.BackgroundColor = ConsoleColor.DarkRed; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("..."); Console.ResetColor(); |
Dependency injection
dotnet add package Microsoft.Extensions.DependencyInjection |
Program.cs |
static void Main(string[] args) { ServiceProvider serviceProvider = ConfigureServices(services); IServiceScope scope = serviceProvider.CreateScope(); scope.ServiceProvider.GetRequiredService<ConsoleApplication>().Run(); serviceProvider.GetRequiredService<ConsoleApplication>().Run(); } private static ServiceProvider ConfigureServices(IServiceCollection services) => new ServiceCollection() .AddSingleton<IConfiguration>( _ => new ConfigurationBuilder() .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false); .AddUserSecrets<Program>() .Build()) .AddSingleton<IMyService, MyService>() .BuildServiceProvider(); |
ConsoleApplication.cs |
class ConsoleApplication { private readonly IConfiguration configuration; private readonly IMyService myService; public ConsoleApplication(IConfiguration configuration, IMyService myService) { this.configuration = configuration; this.myService = myService; } public void Run() { var serviceProvider = ConfigureServices(); using var dbContext = serviceProvider.GetService<AppDbContext>(); myService.DoSomething(); } private ServiceProvider ConfigureServices() => new ServiceCollection() .AddDbContext<AppDbContext>( 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; } } |
Logging in .Net Core Console Apps
dotnet add package Microsoft.Extensions.Logging dotnet add package Microsoft.Extensions.Logging.Console |
Program.cs |
static void Main(string[] args) { var services = new ServiceCollection(); ConfigureServices(services); // log var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetService<ILoggerFactory>() .CreateLogger<Program>(); logger.LogDebug("Starting application"); } private static void ConfigureServices(IServiceCollection services) { services.AddLogging(configure => configure.AddConsole()); } |
Configuration
dotnet add package Microsoft.Extensions.Configuration.Json |
Program.cs |
private static IConfiguration Configuration; static void Main(string[] args) { var builder = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json"); Configuration = builder.Build(); |
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(); |