mixels
mixels
CC#
Created by mixels on 10/2/2024 in #help
✅ Why is this try/catch block preventing lines after it from firing when an exception is caught?
I have this foreach block with a try/catch inside it. Can someone please help me understand why the logger line for initialization completing isn't executing when an exception occurs inside the foreach try/catch? I know it's bad form to control flow with exceptions. This is a call to a dependency service which unfortunately doesn't give me a good way to tell if the ConnectAsync method succeeds or fails, so I don't really have a choice. (Also I'd want to catch exceptions regardless.)
c#
_logger.LogInformation("Beginning initialization of ClusterChat");

foreach (var client in _clients)
{
bool authenticated = false;
try
{
await client.Item2.ConnectAsync();
authenticated = await client.Item2.AuthenticateAsync(client.Item1.RconPassword);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Initialization of ClusterChat server {client.Item1.Name} with key {client.Item1.Key} failed.");
continue;
}
if (authenticated)
{
_logger.LogInformation($"ClusterChat successfully initialized for server {client.Item1.Name}.");
}
else
{
_logger.LogError($"Initialization of ClusterChat server {client.Item1.Key} failed.");
_clients.Remove(client);
continue;
}
}

// This logger line isn't executing when an exception is caught above...?
_logger.LogInformation("Initialization of ClusterChat complete.");
c#
_logger.LogInformation("Beginning initialization of ClusterChat");

foreach (var client in _clients)
{
bool authenticated = false;
try
{
await client.Item2.ConnectAsync();
authenticated = await client.Item2.AuthenticateAsync(client.Item1.RconPassword);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Initialization of ClusterChat server {client.Item1.Name} with key {client.Item1.Key} failed.");
continue;
}
if (authenticated)
{
_logger.LogInformation($"ClusterChat successfully initialized for server {client.Item1.Name}.");
}
else
{
_logger.LogError($"Initialization of ClusterChat server {client.Item1.Key} failed.");
_clients.Remove(client);
continue;
}
}

// This logger line isn't executing when an exception is caught above...?
_logger.LogInformation("Initialization of ClusterChat complete.");
7 replies
CC#
Created by mixels on 9/18/2024 in #help
Accessing configuration inside CreateDefaultBuilder chain
I'm trying to override the configuration implementation of IHostBuilder via the CreateDefaultBuilder method with my own using the below. Then, later in the IHostBuilder chain, I'm trying to read a value from configuration, like shown. My appsettings.json file clearly contains WebService.BindUrls, and I can see when debugging at runtime that configRoot contains WebService:BindUrls. Now I'm really confused. Can anyone shed some light on why bindUrls is coming back null? appsettings.json
{
"WebService": {
"BindUrls": "http://0.0.0.0:8180"
}
}
{
"WebService": {
"BindUrls": "http://0.0.0.0:8180"
}
}
Program.cs
c#
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddCommandLine(args);

if (Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") != null && Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT").Equals("Development"))
{
configuration.AddJsonFile("appsettings.Development.json");
}
else
{
configuration.AddJsonFile("appsettings.json");
}

var configRoot = configuration.Build();

IHostBuilder builder = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config =>
{
config.Sources.Clear();
config.AddConfiguration(configRoot);
})
.ConfigureWebHost((config) =>
{
# PROBLEM HERE -> bindUrls is null
string[] bindUrls = configRoot.GetSection("WebService").GetValue<string[]>("BindUrls");
config.UseUrls(bindUrls)
.UseKestrel()
.Configure((configure) =>
{
configure.UseMiddleware(typeof(WebHostMiddleware));
});
});
c#
var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables()
.AddCommandLine(args);

if (Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") != null && Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT").Equals("Development"))
{
configuration.AddJsonFile("appsettings.Development.json");
}
else
{
configuration.AddJsonFile("appsettings.json");
}

var configRoot = configuration.Build();

IHostBuilder builder = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config =>
{
config.Sources.Clear();
config.AddConfiguration(configRoot);
})
.ConfigureWebHost((config) =>
{
# PROBLEM HERE -> bindUrls is null
string[] bindUrls = configRoot.GetSection("WebService").GetValue<string[]>("BindUrls");
config.UseUrls(bindUrls)
.UseKestrel()
.Configure((configure) =>
{
configure.UseMiddleware(typeof(WebHostMiddleware));
});
});
8 replies
CC#
Created by mixels on 7/5/2023 in #help
❔ Specify timezone of DateTime converted from localized timestamp without changing the time?
I'm working with an API that returns timestamps localized to Eastern Standard Time. These are encoded as Unix timestamps (seconds since 1970-01-01 00:00:00). I need to convert the timestamp to a DateTime object and then specify that the DateTime is reflecting a specific time zone. I do not want to convert the value as I don't want to add or subtract hours; I just want to specify that the value is already GMT -6. I need this because I need to compare the time against real Eastern Standard Time, which is at different times of the year either Eastern Standard Time or Eastern Daylight Time. So how can I specify the time zone of a DateTime sourced from a localized timestamp?
10 replies
CC#
Created by mixels on 6/13/2023 in #help
❔ Serilog.Settings.Configuration file sink not writing to file?
I'm using the below configuration for Serilog trying to get it to write to both console and file, but it's only writing to console. Does anyone see what's wrong? Been looking at this for awhile now and would appreciate a second set of eyes. JSON:
{
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/logs/TestWorker.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] | {Message}{NewLine}{Exception}"
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] | {Message}{NewLine}{Exception}"
}
}
],
"Application": "The7LegionsVoteHelper"
}
}
{
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Console" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information"
}
},
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "/logs/TestWorker.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] | {Message}{NewLine}{Exception}"
}
},
{
"Name": "Console",
"Args": {
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] | {Message}{NewLine}{Exception}"
}
}
],
"Application": "The7LegionsVoteHelper"
}
}
Code (Program class):
private static async Task Main(string[] args)
{
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, builder) =>
{
builder.ClearProviders();
builder.AddSerilog();
})
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();

IConfiguration configuration = host.Services.GetRequiredService<IConfiguration>();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

await host.RunAsync();
}
private static async Task Main(string[] args)
{
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, builder) =>
{
builder.ClearProviders();
builder.AddSerilog();
})
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
})
.Build();

IConfiguration configuration = host.Services.GetRequiredService<IConfiguration>();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();

await host.RunAsync();
}
3 replies
CC#
Created by mixels on 6/5/2023 in #help
Properties of IConfigurationSection.Get are null?
I have a very simple test case set up using Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Binder. The config (aopsettings.json):
{
"Foo": "bar"
}
{
"Foo": "bar"
}
And the class:
public class Configuration
{
public string Foo;
}
public class Configuration
{
public string Foo;
}
The configuration builds correctly. I can see it contains the Foo property when debugging. However, when I try to use var test = _configuration.Get<Configuration>(), the Foo property of test is null. I'm confused what is going wrong here. Can anyone spot the mistake?
7 replies
CC#
Created by mixels on 5/28/2023 in #help
❔ Create console app with runtime option to run headless or with console in .NET 6 or later?
I want to build an application that gives the user running it the option to display the console or to not display the console (headless console). I know that InteropServices is capable of hiding the window. This is a mostly satisfactory solution, except it's kind of ugly because running the application does briefly display the console. I'm wondering, is there a way in .NET 6 or later to specify when running a console application to hide or show the console?
14 replies