Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
TimHess committed Nov 6, 2024
1 parent 5dc2e45 commit 8969b48
Show file tree
Hide file tree
Showing 20 changed files with 94 additions and 114 deletions.
16 changes: 8 additions & 8 deletions Management/src/ActuatorApi/AdminTasks/ForecastTask.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
using Steeltoe.Common;
using System.Globalization;
using Steeltoe.Common;
using Steeltoe.Samples.ActuatorApi.Data;
using System.Globalization;

namespace Steeltoe.Samples.ActuatorApi.AdminTasks;

internal class ForecastTask(WeatherDbContext weatherContext, ILogger<ForecastTask> logger) : IApplicationTask
{
public async Task RunAsync(CancellationToken cancellationToken)
{
var args = Environment.GetCommandLineArgs();
var fromDateString = args.FirstOrDefault(text => text.StartsWith("--fromDate", StringComparison.OrdinalIgnoreCase))?.Split("=")[1];
var fromDate = DateOnly.FromDateTime(fromDateString == null ? DateTime.Now : DateTime.Parse(fromDateString, CultureInfo.InvariantCulture));
var days = int.Parse(args.FirstOrDefault(text => text.StartsWith("--days", StringComparison.OrdinalIgnoreCase))?.Split("=")[1] ?? "7");
string[] args = Environment.GetCommandLineArgs();
string? fromDateString = args.FirstOrDefault(text => text.StartsWith("--fromDate", StringComparison.OrdinalIgnoreCase))?.Split("=")[1];
DateOnly fromDate = DateOnly.FromDateTime(fromDateString == null ? DateTime.Now : DateTime.Parse(fromDateString, CultureInfo.InvariantCulture));
int days = int.Parse(args.FirstOrDefault(text => text.StartsWith("--days", StringComparison.OrdinalIgnoreCase))?.Split("=")[1] ?? "7");

for (var index = 0; index < days; index++)
for (int index = 0; index < days; index++)
{
var dateToForecast = fromDate.AddDays(index);
DateOnly dateToForecast = fromDate.AddDays(index);

if (!weatherContext.Forecasts.Any(weather => weather.Date == dateToForecast))
{
Expand Down
5 changes: 3 additions & 2 deletions Management/src/ActuatorApi/BasicAuthExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using idunno.Authentication.Basic;
using System.Security.Claims;
using idunno.Authentication.Basic;
using Microsoft.AspNetCore.Authentication;

namespace Steeltoe.Samples.ActuatorApi;

internal static class BasicAuthExtensions
{
public static void ConfigureActuatorAuth(this IServiceCollection services)
{
var builder = services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme);
AuthenticationBuilder builder = services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme);

builder.AddBasic(BasicAuthenticationDefaults.AuthenticationScheme, options =>
{
Expand Down
2 changes: 1 addition & 1 deletion Management/src/ActuatorApi/Data/WeatherDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ namespace Steeltoe.Samples.ActuatorApi.Data;
public sealed class WeatherDbContext(DbContextOptions<WeatherDbContext> options)
: DbContext(options)
{
public DbSet<WeatherForecast> Forecasts { get; init; }
public DbSet<WeatherForecast> Forecasts { get; set; }
}
8 changes: 4 additions & 4 deletions Management/src/ActuatorApi/MySqlSeeder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ internal static class MySqlSeeder

public static async Task CreateSampleDataAsync(IServiceProvider serviceProvider)
{
await using var scope = serviceProvider.CreateAsyncScope();
await using AsyncServiceScope scope = serviceProvider.CreateAsyncScope();
await using var appDbContext = scope.ServiceProvider.GetRequiredService<WeatherDbContext>();

await ForecastTheNextWeekAsync(appDbContext);
Expand All @@ -32,7 +32,7 @@ public static async Task CreateSampleDataAsync(IServiceProvider serviceProvider)
/// </summary>
private static async Task ForecastTheNextWeekAsync(WeatherDbContext dbContext)
{
var firstNewForecastDate = DateOnly.FromDateTime(DateTime.Now);
DateOnly firstNewForecastDate = DateOnly.FromDateTime(DateTime.Now);

try
{
Expand All @@ -43,9 +43,9 @@ private static async Task ForecastTheNextWeekAsync(WeatherDbContext dbContext)
// 'Sequence contains no elements.' is expected when there is no existing forecast data.
}

for (var index = 0; index < 7; index++)
for (int index = 0; index < 7; index++)
{
var dateToForecast = firstNewForecastDate.AddDays(index);
DateOnly dateToForecast = firstNewForecastDate.AddDays(index);
dbContext.Forecasts.Add(MakeForecast(dateToForecast));
}

Expand Down
4 changes: 2 additions & 2 deletions Management/src/ActuatorApi/OpenTelemetryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ public static void ConfigureOpenTelemetry(this IServiceCollection services, ICon
{
tracerProviderBuilder.AddAspNetCoreInstrumentation();

var otlpExporterAddress = configuration.GetValue<string>("OpenTelemetry:OTLPExporterAddress");
string? otlpExporterAddress = configuration.GetValue<string>("OpenTelemetry:OTLPExporterAddress");

if (!string.IsNullOrEmpty(otlpExporterAddress))
{
tracerProviderBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpExporterAddress));
}

var zipkinExporterAddress = configuration.GetValue<string>("OpenTelemetry:ZipkinExporterAddress");
string? zipkinExporterAddress = configuration.GetValue<string>("OpenTelemetry:ZipkinExporterAddress");

if (!string.IsNullOrEmpty(zipkinExporterAddress))
{
Expand Down
4 changes: 2 additions & 2 deletions Management/src/ActuatorApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
using Steeltoe.Samples.ActuatorApi.AdminTasks;
using Steeltoe.Samples.ActuatorApi.Data;

var builder = WebApplication.CreateBuilder(args);
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
Expand Down Expand Up @@ -54,7 +54,7 @@
builder.Services.AddTask<ForecastTask>("ForecastWeather");
builder.Services.AddTask<ResetTask>("ResetWeather");

var app = builder.Build();
WebApplication app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
Expand Down
2 changes: 1 addition & 1 deletion Management/src/ActuatorApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
// Wildcard used instead of "localhost" here in order to support connections from local containers
// Steeltoe: Wildcard used instead of "localhost" here in order to support connections from local containers.
"applicationUrl": "http://+:5140"
},
"https": {
Expand Down
67 changes: 32 additions & 35 deletions Management/src/ActuatorApi/WeatherEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,49 +9,46 @@ internal static class WeatherEndpoints
{
public static void Map(WebApplication app)
{
app.MapGet("/WeatherForecast",
async (WeatherDbContext context, ILoggerFactory loggerFactory, [FromQuery] string? fromDate, [FromQuery] int days = 5) =>
{
// Steeltoe: Log messages at various levels for loggers actuator demonstration.
var logger = loggerFactory.CreateLogger<WeatherForecast>();
logger.LogCritical("Test Critical message");
logger.LogError("Test Error message");
logger.LogWarning("Test Warning message");
logger.LogInformation("Test Informational message");
logger.LogDebug("Test Debug message");
logger.LogTrace("Test Trace message");
app.MapGet("/WeatherForecast", async (WeatherDbContext context, ILoggerFactory loggerFactory, [FromQuery] string? fromDate, [FromQuery] int days = 5) =>
{
// Steeltoe: Log messages at various levels for loggers actuator demonstration.
ILogger<WeatherForecast> logger = loggerFactory.CreateLogger<WeatherForecast>();
logger.LogCritical("Test Critical message");
logger.LogError("Test Error message");
logger.LogWarning("Test Warning message");
logger.LogInformation("Test Informational message");
logger.LogDebug("Test Debug message");
logger.LogTrace("Test Trace message");

DateTime queryDate = string.IsNullOrEmpty(fromDate) ? DateTime.Now : DateTime.Parse(fromDate);

var queryDate = string.IsNullOrEmpty(fromDate) ? DateTime.Now : DateTime.Parse(fromDate);
logger.LogInformation("Determining the {DayCount}-day forecast starting from {ForecastQueryDate}.", days, DateOnly.FromDateTime(queryDate));

logger.LogInformation("Determining the {DayCount}-day forecast starting from {ForecastQueryDate}.", days,
DateOnly.FromDateTime(queryDate));
IQueryable<WeatherForecast> forecast = context.Forecasts.Where(f =>
f.Date >= DateOnly.FromDateTime(queryDate) && f.Date < DateOnly.FromDateTime(queryDate.AddDays(days)));

var forecast = context.Forecasts.Where(f =>
f.Date >= DateOnly.FromDateTime(queryDate) && f.Date < DateOnly.FromDateTime(queryDate.AddDays(days)));
if (forecast.Count() < days)
{
logger.LogError("Relevant forecast data was found for only {DayCount} day(s). Use the forecast task to generate the missing data.",
forecast.Count());

if (forecast.Count() < days)
if (Platform.IsCloudFoundry)
{
logger.LogInformation(
"cf run-task actuator-api-management-sample --command \"./Steeltoe.Samples.ActuatorApi runtask=Forecast --fromDate={FromDate} --days={DayCount}\"",
queryDate.ToString("yyyy-MM-dd"), days);
}
else
{
logger.LogError(
"Relevant forecast data was found for only {DayCount} day(s). Use the forecast task to generate the missing data.",
forecast.Count());

if (Platform.IsCloudFoundry)
{
logger.LogInformation(
"cf run-task actuator-api-management-sample --command \"./Steeltoe.Samples.ActuatorApi runtask=Forecast --fromDate={FromDate} --days={DayCount}\"",
queryDate.ToString("yyyy-MM-dd"), days);
}
else
{
logger.LogInformation("dotnet run --runtask=Forecast --fromDate={FromDate} --days={DayCount}", queryDate.ToString("yyyy-MM-dd"), days);
}
logger.LogInformation("dotnet run --runtask=Forecast --fromDate={FromDate} --days={DayCount}", queryDate.ToString("yyyy-MM-dd"), days);
}
}

// Steeltoe: Sleep a random amount of milliseconds for variance in trace data.
await Task.Delay(Random.Shared.Next(10, 3000));
// Steeltoe: Sleep a random amount of milliseconds for variance in trace data.
await Task.Delay(Random.Shared.Next(10, 3000));

return forecast;
}).WithName("GetWeatherForecast").WithOpenApi().AllowAnonymous();
return forecast;
}).WithName("GetWeatherForecast").WithOpenApi().AllowAnonymous();

app.MapGet("/AllForecastData", (WeatherDbContext context) => context.Forecasts).WithName("GetAllForecastData").WithOpenApi().AllowAnonymous();
}
Expand Down
16 changes: 7 additions & 9 deletions Management/src/ActuatorApi/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"Microsoft.AspNetCore": "Warning"
}
},
// Steeltoe: configure exposure of all actuators.
// Steeltoe: Configure exposure of all actuators.
"Management": {
"Endpoints": {
"Actuator": {
Expand All @@ -23,25 +23,23 @@
"OTLPExporterAddress": "",
"ZipkinExporterAddress": "http://localhost:9411/api/v2/spans"
},
// Steeltoe: configure client for Spring Boot Admin.
// Steeltoe: Configure client for Spring Boot Admin.
"Spring": {
"Boot": {
"Admin": {
"Client": {
//"BasePath": "http://host.docker.internal:5140",
// For podman compatibility, change host.docker.internal to host.containers.internal
"BasePath": "http://host.docker.internal:9999",
// Use this hostname when SBA is running in podman instead of docker.
//"BasePath": "http://host.containers.internal:9999",
"Url": "http://localhost:9090",
"Metadata": {
"user.name": "actuatorUser",
"user.password": "actuatorPassword"
}
},
"Url": "http://localhost:9090"
}
}
}
},
// Steeltoe: Set MySQL connection string for non-cloud local development.
// Steeltoe: Set MySQL connection string for non-cloud, local development.
"Steeltoe": {
"Client": {
"MySql": {
Expand All @@ -51,6 +49,6 @@
}
}
},
// Steeltoe sample code: register this application with a Spring Boot Admin server.
// Steeltoe: Register this application with a Spring Boot Admin server.
"UseSpringBootAdmin": true
}
5 changes: 3 additions & 2 deletions Management/src/ActuatorWeb/BasicAuthExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using idunno.Authentication.Basic;
using System.Security.Claims;
using idunno.Authentication.Basic;
using Microsoft.AspNetCore.Authentication;

namespace Steeltoe.Samples.ActuatorWeb;

internal static class BasicAuthExtensions
{
public static void ConfigureActuatorAuth(this IServiceCollection services)
{
var builder = services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme);
AuthenticationBuilder builder = services.AddAuthentication(BasicAuthenticationDefaults.AuthenticationScheme);

builder.AddBasic(BasicAuthenticationDefaults.AuthenticationScheme, options =>
{
Expand Down
4 changes: 2 additions & 2 deletions Management/src/ActuatorWeb/OpenTelemetryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ public static void ConfigureOpenTelemetry(this IServiceCollection services, ICon
{
tracerProviderBuilder.AddAspNetCoreInstrumentation();

var otlpExporterAddress = configuration.GetValue<string>("OpenTelemetry:OTLPExporterAddress");
string? otlpExporterAddress = configuration.GetValue<string>("OpenTelemetry:OTLPExporterAddress");

if (!string.IsNullOrEmpty(otlpExporterAddress))
{
tracerProviderBuilder.AddOtlpExporter(otlpExporterOptions => otlpExporterOptions.Endpoint = new Uri(otlpExporterAddress));
}

var zipkinExporterAddress = configuration.GetValue<string>("OpenTelemetry:ZipkinExporterAddress");
string? zipkinExporterAddress = configuration.GetValue<string>("OpenTelemetry:ZipkinExporterAddress");

if (!string.IsNullOrEmpty(zipkinExporterAddress))
{
Expand Down
8 changes: 1 addition & 7 deletions Management/src/ActuatorWeb/Pages/Error.cshtml.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,17 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Diagnostics;

namespace Steeltoe.Samples.ActuatorWeb.Pages;

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
[IgnoreAntiforgeryToken]
public class ErrorModel : PageModel
{
private readonly ILogger<ErrorModel> _logger;
public string? RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

public ErrorModel(ILogger<ErrorModel> logger)
{
_logger = logger;
}

public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
Expand Down
7 changes: 0 additions & 7 deletions Management/src/ActuatorWeb/Pages/Index.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@ namespace Steeltoe.Samples.ActuatorWeb.Pages;

public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;

public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}

public void OnGet()
{
}
Expand Down
7 changes: 0 additions & 7 deletions Management/src/ActuatorWeb/Pages/Privacy.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,6 @@ namespace Steeltoe.Samples.ActuatorWeb.Pages;

public class PrivacyModel : PageModel
{
private readonly ILogger<PrivacyModel> _logger;

public PrivacyModel(ILogger<PrivacyModel> logger)
{
_logger = logger;
}

public void OnGet()
{
}
Expand Down
6 changes: 3 additions & 3 deletions Management/src/ActuatorWeb/Pages/Weather.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@ public async Task OnGet(string? fromDate, int? days)
logger.LogDebug("Test Debug message");
logger.LogTrace("Test Trace message");

using var httpClient = httpClientFactory.CreateClient(nameof(WeatherModel));
using HttpClient httpClient = httpClientFactory.CreateClient(nameof(WeatherModel));

try
{
var requestUri = BuildRequestUri(fromDate, days);
string requestUri = BuildRequestUri(fromDate, days);

var response = await httpClient.GetAsync(requestUri);
HttpResponseMessage response = await httpClient.GetAsync(requestUri);

Forecasts = await response.Content.ReadFromJsonAsync<WeatherForecast[]>() ?? [];
}
Expand Down
10 changes: 5 additions & 5 deletions Management/src/ActuatorWeb/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
using Steeltoe.Samples.ActuatorWeb;
using Steeltoe.Samples.ActuatorWeb.Pages;

var builder = WebApplication.CreateBuilder(args);
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
Expand Down Expand Up @@ -39,7 +39,7 @@
// Steeltoe: Register HttpClients for communicating with a backend service.
builder.Services.AddHttpClient<WeatherModel>(SetBaseAddress);

var app = builder.Build();
WebApplication app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
Expand Down Expand Up @@ -73,8 +73,8 @@ static void SetBaseAddress(IServiceProvider serviceProvider, HttpClient client)

if (instanceInfo is CloudFoundryApplicationOptions { Uris.Count: > 0 } options)
{
var address = options.Uris.First();
var baseAddress = address.Replace("actuator-web", "actuator-api");
string address = options.Uris.First();
string baseAddress = address.Replace("actuator-web", "actuator-api");
client.BaseAddress = new Uri($"https://{baseAddress}");
}
else
Expand All @@ -83,7 +83,7 @@ static void SetBaseAddress(IServiceProvider serviceProvider, HttpClient client)
}

var loggerFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<Program>();
ILogger<Program> logger = loggerFactory.CreateLogger<Program>();

logger.LogInformation("HttpClient BaseAddress set to {BaseAddress}", client.BaseAddress);
}
Loading

0 comments on commit 8969b48

Please sign in to comment.