Skip to content

Commit

Permalink
chore: add Roslyn analyzers and fix issues
Browse files Browse the repository at this point in the history
  • Loading branch information
mu88 committed Jul 19, 2024
1 parent aebdb75 commit 82d91bf
Show file tree
Hide file tree
Showing 10 changed files with 105 additions and 25 deletions.
21 changes: 21 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[*]
indent_size = 2

[*.cs]
indent_size = 4
dotnet_diagnostic.MA0004.severity = none
dotnet_diagnostic.MA0048.severity = none
dotnet_diagnostic.SA0001.severity = none
dotnet_diagnostic.SA1000.severity = none
dotnet_diagnostic.SA1009.severity = none
dotnet_diagnostic.SA1101.severity = none
dotnet_diagnostic.SA1116.severity = none
dotnet_diagnostic.SA1200.severity = none
dotnet_diagnostic.SA1309.severity = none
dotnet_diagnostic.SA1313.severity = none
dotnet_diagnostic.SA1413.severity = none
dotnet_diagnostic.SA1516.severity = none
dotnet_diagnostic.SA1600.severity = none
dotnet_diagnostic.SA1601.severity = none
dotnet_diagnostic.SA1602.severity = none
dotnet_diagnostic.SA1633.severity = none
29 changes: 22 additions & 7 deletions Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
<Project>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Version>2.5.2</Version>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Version>2.5.2</Version>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<ImplicitUsings>true</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup Condition="!$(MSBuildProjectName.Contains('Test'))">
<PackageReference Include="AspNetCoreAnalyzers"/>
<PackageReference Include="IDisposableAnalyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Meziantou.Analyzer">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="StyleCop.Analyzers">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
6 changes: 5 additions & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="AspNetCoreAnalyzers" Version="0.3.0" />
<PackageVersion Include="BenchmarkDotNet" Version="0.13.12" />
<PackageVersion Include="coverlet.msbuild" Version="6.0.2" />
<PackageVersion Include="FluentAssertions" Version="6.12.0" />
<PackageVersion Include="IDisposableAnalyzers" Version="4.0.8" />
<PackageVersion Include="Magick.NET-Q16-AnyCPU" Version="13.9.1" />
<PackageVersion Include="Meziantou.Analyzer" Version="2.0.161" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.7" />
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="8.0.7" />
<PackageVersion Include="Microsoft.Bcl.TimeProvider" Version="8.0.1" />
Expand All @@ -24,7 +27,8 @@
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<PackageVersion Include="StyleCop.Analyzers" Version="1.1.118" />
<PackageVersion Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageVersion Include="Testcontainers" Version="3.9.0" />
</ItemGroup>
</Project>
</Project>
15 changes: 11 additions & 4 deletions src/ScreenshotCreator.Api/BackgroundScreenshotCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ internal class BackgroundScreenshotCreator : BackgroundService
private readonly ILogger<BackgroundScreenshotCreator> _logger;
private readonly ScreenshotOptions _screenshotOptions;

/// <inheritdoc />
public BackgroundScreenshotCreator(IScreenshotCreator screenshotCreator, IOptions<ScreenshotOptions> options, ILogger<BackgroundScreenshotCreator> logger)
{
_screenshotCreator = screenshotCreator;
Expand All @@ -26,7 +25,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
return;
}

PeriodicTimer timer = new(TimeSpan.FromSeconds(_screenshotOptions.RefreshIntervalInSeconds));
using PeriodicTimer timer = new(TimeSpan.FromSeconds(_screenshotOptions.RefreshIntervalInSeconds));

// There should always be at least one image present in case the background processor is enabled
await _screenshotCreator.CreateScreenshotAsync(_screenshotOptions.Width, _screenshotOptions.Height);
Expand All @@ -38,11 +37,19 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (_screenshotOptions.BackgroundProcessingWithTryCatch)
{
try { await _screenshotCreator.CreateScreenshotAsync(_screenshotOptions.Width, _screenshotOptions.Height); }
catch (Exception e) { _logger.LogError(e, "Background processing failed"); }
try
{
await _screenshotCreator.CreateScreenshotAsync(_screenshotOptions.Width, _screenshotOptions.Height);
}
catch (Exception e)
{
_logger.LogError(e, "Background processing failed");
}
}
else
{
await _screenshotCreator.CreateScreenshotAsync(_screenshotOptions.Width, _screenshotOptions.Height);
}
}
}
}
Expand Down
20 changes: 16 additions & 4 deletions src/ScreenshotCreator.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,21 @@ async Task<IResult> ReturnImageOrNotFoundAsync(HttpContext httpContext,
bool asWaveshareBytes = false,
bool addWaveshareInstructions = false)
{
if (!File.Exists(options.Value.ScreenshotFile)) return Results.NotFound();
if (!File.Exists(options.Value.ScreenshotFile))
{
return Results.NotFound();
}

var processingResult = await imageProcessor.ProcessAsync(options.Value.ScreenshotFile, blackAndWhite, asWaveshareBytes);

var result = asWaveshareBytes
? Results.Bytes(processingResult.Data, processingResult.MediaType)
: Results.File(processingResult.Data, processingResult.MediaType);

if (addWaveshareInstructions) httpContext.Response.Headers.AddWaveshareInstructions(options.Value, options.Value.ScreenshotFile);
if (addWaveshareInstructions)
{
httpContext.Response.Headers.AddWaveshareInstructions(options.Value, options.Value.ScreenshotFile);
}

return result;
}
Expand All @@ -95,8 +101,14 @@ static void ConfigureOpenTelemetry(IHostApplicationBuilder builder)
.AddAspNetCoreInstrumentation()
.AddRuntimeInstrumentation();
})
.WithTracing(tracing => { tracing.AddAspNetCoreInstrumentation(); });
.WithTracing(tracing =>
{
tracing.AddAspNetCoreInstrumentation();
});

var useOtlpExporter = !string.IsNullOrWhiteSpace(builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]);
if (useOtlpExporter) builder.Services.AddOpenTelemetry().UseOtlpExporter();
if (useOtlpExporter)
{
builder.Services.AddOpenTelemetry().UseOtlpExporter();
}
}
5 changes: 4 additions & 1 deletion src/ScreenshotCreator.Logic/ActivityExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ public static class ActivityExtensions
{
public static bool DisplayShouldBeActive([NotNullWhen(false)] this Activity? activity, TimeProvider? timeProvider = null)
{
if (activity is null) return true;
if (activity is null)
{
return true;
}

var currentLocalTime = GetCurrentLocalTime(timeProvider ?? TimeProvider.System);
return activity.ActiveFrom <= currentLocalTime && currentLocalTime <= activity.ActiveTo;
Expand Down
3 changes: 2 additions & 1 deletion src/ScreenshotCreator.Logic/ImageProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ private byte[] ToWaveshareBytes(MagickImage image)

var newWidth = image.Width / 8;
var waveshareBytes = new byte[newWidth * image.Height];
var pixelByteSpan = image.GetPixelsUnsafe().ToByteArray("R").AsSpan();
using var unsafePixelCollection = image.GetPixelsUnsafe();
var pixelByteSpan = unsafePixelCollection.ToByteArray("R").AsSpan();
var array = new BitArray(8);
for (var finalBytePosition = 0; finalBytePosition < pixelByteSpan.Length / 8; finalBytePosition++)
{
Expand Down
14 changes: 11 additions & 3 deletions src/ScreenshotCreator.Logic/PlaywrightFacade.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace ScreenshotCreator.Logic;

internal class PlaywrightFacade : IPlaywrightFacade
internal sealed class PlaywrightFacade : IPlaywrightFacade
{
private IBrowser? _browser;
private bool _disposed;
Expand All @@ -11,16 +11,24 @@ internal class PlaywrightFacade : IPlaywrightFacade

public async ValueTask DisposeAsync()
{
if (_disposed) return;
if (_disposed)
{
return;
}

if (_browser != null)
{
await _browser.DisposeAsync();
}

if (_browser != null) await _browser.DisposeAsync();
_playwright?.Dispose();

_disposed = true;
}

public async ValueTask<IPage> GetPlaywrightPageAsync()
{
_playwright?.Dispose();
_playwright = await Playwright.CreateAsync();
_browser = await _playwright.Chromium.LaunchAsync();
_page = await _browser.NewPageAsync(new BrowserNewPageOptions { TimezoneId = Environment.GetEnvironmentVariable("TZ") });
Expand Down
15 changes: 12 additions & 3 deletions src/ScreenshotCreator.Logic/ScreenshotCreator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ public async Task CreateScreenshotAsync(uint width, uint height)
var page = await playwrightFacade.GetPlaywrightPageAsync();

await page.SetViewportSizeAsync((int)width, (int)height);
if (await NeedsLoginAsync(page)) { await LoginAsync(page); }
if (await NeedsLoginAsync(page))
{
await LoginAsync(page);
}

if (await PageIsAvailableAsync(page))
{
Expand All @@ -27,7 +30,10 @@ public async Task CreateScreenshotAsync(uint width, uint height)
private async Task<bool> PageIsAvailableAsync(IPage page)
{
await NavigateToUrlAsync(page);
if (string.IsNullOrWhiteSpace(_screenshotOptions.AvailabilityIndicator)) return true;
if (string.IsNullOrWhiteSpace(_screenshotOptions.AvailabilityIndicator))
{
return true;
}

return await page.GetByText(_screenshotOptions.AvailabilityIndicator).CountAsync() > 0;
}
Expand All @@ -49,7 +55,10 @@ private async Task LoginAsync(IPage page)
if (!await usernameTextfield.IsVisibleAsync())
{
var loginButton = page.GetByText("lock_shield_fill");
if (!await loginButton.IsVisibleAsync()) await page.GetByText("menu").ClickAsync();
if (!await loginButton.IsVisibleAsync())
{
await page.GetByText("menu").ClickAsync();
}

await loginButton.ClickAsync();
}
Expand Down
2 changes: 1 addition & 1 deletion src/ScreenshotCreator.Logic/ScreenshotOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ public class ScreenshotOptions
public string ScreenshotFile { get; set; } = "/home/app/Screenshot.png";

public string? AvailabilityIndicator { get; set; } = string.Empty;
// Stryker restore all

// Stryker restore all
[Range(1, uint.MaxValue)]
public uint Width { get; set; }

Expand Down

0 comments on commit 82d91bf

Please sign in to comment.