Skip to content

Commit

Permalink
chore: migrate to .NET 8
Browse files Browse the repository at this point in the history
  • Loading branch information
hez2010 committed Nov 23, 2023
1 parent 1af9fd6 commit 8815d3f
Show file tree
Hide file tree
Showing 21 changed files with 96 additions and 98 deletions.
50 changes: 25 additions & 25 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,44 @@
<PackageVersion Include="Aigamo.ResXGenerator" Version="4.2.0" />
<PackageVersion Include="Docker.DotNet" Version="3.125.15" />
<PackageVersion Include="KubernetesClient" Version="12.1.1" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.Protocols.Json" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.AspNetCore.SpaProxy" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0-rc.2.23480.1" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0-rc.2.23480.1" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0-rc.2" />
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.Protocols.Json" Version="8.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.SpaProxy" Version="8.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageVersion Include="NPOI" Version="2.6.2" />
<PackageVersion Include="NSwag.AspNetCore" Version="13.20.0" />
<PackageVersion Include="NSwag.MSBuild" Version="13.20.0" />
<PackageVersion Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageVersion Include="Serilog.Expressions" Version="3.4.1" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="7.0.0" />
<PackageVersion Include="NSwag.AspNetCore" Version="14.0.0-preview010" />
<PackageVersion Include="NSwag.MSBuild" Version="14.0.0-preview010" />
<PackageVersion Include="Serilog.AspNetCore" Version="8.0.0" />
<PackageVersion Include="Serilog.Expressions" Version="4.0.0" />
<PackageVersion Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageVersion Include="Serilog.Sinks.AspNetCore.SignalR" Version="0.4.0" />
<PackageVersion Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageVersion Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageVersion Include="Serilog.Sinks.File.Archive" Version="1.0.3" />
<PackageVersion Include="Serilog.Sinks.PostgreSQL" Version="2.3.0" />
<PackageVersion Include="MailKit" Version="4.2.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0-rc.2.23480.1" />
<PackageVersion Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="MemoryPack" Version="1.9.16" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0-rc.2.23479.6" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="8.0.0-rc.2.23479.6" />
<PackageVersion Include="MailKit" Version="4.3.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.DataProtection.EntityFrameworkCore" Version="8.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="8.0.0" />
<PackageVersion Include="MemoryPack" Version="1.10.0" />
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="8.0.0" />
<PackageVersion Include="SixLabors.ImageSharp" Version="3.0.2" />
<PackageVersion Include="BouncyCastle.Cryptography" Version="2.2.1" />
<PackageVersion Include="PacketDotNet" Version="1.4.7" />
<PackageVersion Include="SharpPcap" Version="6.2.5" />
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="8.0.0-rc.2.23480.2" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageVersion Include="xunit" Version="2.5.3" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.3">
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="8.0.0" />
<PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="8.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageVersion Include="xunit" Version="2.6.2" />
<PackageVersion Include="xunit.runner.visualstudio" Version="2.5.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageVersion>
<PackageVersion Include="xunit.runner.console" Version="2.5.1" />
<PackageVersion Include="xunit.runner.console" Version="2.6.2" />
<PackageVersion Include="coverlet.collector" Version="6.0.0" />
<PackageVersion Include="coverlet.msbuild" Version="6.0.0" />
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/ClientApp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
"@vitejs/plugin-react": "^4.1.1",
"axios": "^1.6.0",
"babel-plugin-prismjs": "^2.1.0",
"eslint": "8.52.0",
"eslint": "^8.52.0",
"eslint-plugin-react-hooks": "^4.6.0",
"form-data": "~4.0.0",
"lodash": "^4.17.21",
Expand Down
4 changes: 2 additions & 2 deletions src/GZCTF/Extensions/OtherExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static class ArrayExtensions
public static ArrayResponse<T> ToResponse<T>(this IEnumerable<T> array, int? tot = null) where T : class =>
array switch
{
null => new(Array.Empty<T>()),
null => new([]),
T[] arr => new(arr, tot),
_ => new(array.ToArray(), tot)
};
Expand All @@ -39,5 +39,5 @@ public static class IPAddressExtensions
public static IEnumerable<IPAddress> ResolveIP(this string? host) =>
!string.IsNullOrWhiteSpace(host)
? Dns.GetHostAddresses(host)
: Array.Empty<IPAddress>();
: [];
}
13 changes: 4 additions & 9 deletions src/GZCTF/Models/AppDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,13 @@ public class AppDbContext(DbContextOptions<AppDbContext> options) :
public DbSet<ExerciseDependency> ExerciseDependencies { get; set; } = default!;
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = default!;

internal static readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = false };

static ValueConverter<T?, string> GetJsonConverter<T>() where T : class, new()
{
var options = new JsonSerializerOptions { WriteIndented = false };
return new ValueConverter<T?, string>(
v => JsonSerializer.Serialize(v ?? new(), options),
v => JsonSerializer.Deserialize<T>(v, options)
v => JsonSerializer.Serialize(v ?? new(), _jsonOptions),
v => JsonSerializer.Deserialize<T>(v, _jsonOptions)
);
}

Expand Down Expand Up @@ -82,12 +83,6 @@ protected override void OnModelCreating(ModelBuilder builder)
.Metadata
.SetValueComparer(setComparer);

entity.Property(e => e.BloodBonus)
.HasDefaultValue(BloodBonus.Default)
.HasConversion(BloodBonus.Converter)
.Metadata
.SetValueComparer(BloodBonus.Comparer);

entity.HasMany(e => e.GameEvents)
.WithOne(e => e.Game)
.HasForeignKey(e => e.GameId);
Expand Down
2 changes: 0 additions & 2 deletions src/GZCTF/Models/Data/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,4 @@ public Config(string key, string value)
public string ConfigKey { get; set; } = string.Empty;

public string? Value { get; set; }

public bool Equal(Config other) => ConfigKey == other.ConfigKey;
}
17 changes: 16 additions & 1 deletion src/GZCTF/Models/Data/Game.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,26 @@ public class Game
[JsonPropertyName("wpnote")]
public string WriteupNote { get; set; } = string.Empty;

[JsonIgnore]
[Column(nameof(BloodBonus))]
public long BloodBonusValue { get; set; } = BloodBonus.DefaultValue;

/// <summary>
/// 三血加分
/// </summary>
[NotMapped]
[Required]
public BloodBonus BloodBonus { get; set; } = BloodBonus.Default;
public BloodBonus BloodBonus
{
get
{
return BloodBonus.FromValue(BloodBonusValue);
}
set
{
BloodBonusValue = value.Val;
}
}

[NotMapped]
[JsonIgnore]
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Models/Request/Admin/ParticipationInfoModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class ParticipationInfoModel
/// <summary>
/// 注册的成员
/// </summary>
public Guid[] RegisteredMembers { get; set; } = Array.Empty<Guid>();
public Guid[] RegisteredMembers { get; set; } = [];

/// <summary>
/// 参赛所属组织
Expand Down
6 changes: 3 additions & 3 deletions src/GZCTF/Models/Request/Edit/ChallengeEditDetailModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class ChallengeEditDetailModel
/// <summary>
/// 题目提示
/// </summary>
public string[] Hints { get; set; } = Array.Empty<string>();
public string[] Hints { get; set; } = [];

/// <summary>
/// Flag 模版,用于根据 Token 和题目、比赛信息生成 Flag
Expand Down Expand Up @@ -78,7 +78,7 @@ public class ChallengeEditDetailModel
/// 题目 Flag 信息
/// </summary>
[Required]
public FlagInfoModel[] Flags { get; set; } = Array.Empty<FlagInfoModel>();
public FlagInfoModel[] Flags { get; set; } = [];

internal static ChallengeEditDetailModel FromChallenge(GameChallenge chal) =>
new()
Expand All @@ -89,7 +89,7 @@ internal static ChallengeEditDetailModel FromChallenge(GameChallenge chal) =>
Tag = chal.Tag,
Type = chal.Type,
FlagTemplate = chal.FlagTemplate,
Hints = chal.Hints?.ToArray() ?? Array.Empty<string>(),
Hints = chal.Hints?.ToArray() ?? [],
IsEnabled = chal.IsEnabled,
ContainerImage = chal.ContainerImage,
MemoryLimit = chal.MemoryLimit,
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Models/Request/Edit/PostEditModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class PostEditModel
/// <summary>
/// 文章标签
/// </summary>
public string[] Tags { get; set; } = Array.Empty<string>();
public string[] Tags { get; set; } = [];

/// <summary>
/// 是否置顶
Expand Down
15 changes: 5 additions & 10 deletions src/GZCTF/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Localization;
using NJsonSchema.Generation;
using Serilog;
using StackExchange.Redis;

Expand Down Expand Up @@ -129,10 +128,6 @@
settings.Title = "GZCTF Server API";
settings.Description = "GZCTF Server API Document";
settings.UseControllerSummaryAsTagDescription = true;
settings.SerializerSettings =
SystemTextJsonUtilities.ConvertJsonOptionsToNewtonsoftSettings(
new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
settings.DefaultReferenceTypeNullHandling = ReferenceTypeNullHandling.NotNull;
});

#endregion OpenApiDocument
Expand Down Expand Up @@ -258,7 +253,7 @@
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/json", "text/javascript", "text/html", "text/css" }
["application/json", "text/javascript", "text/html", "text/css"]
);
});

Expand All @@ -272,7 +267,7 @@
app.UseRequestLocalization(options =>
{
options.ApplyCurrentCultureToResponseHeaders = true;
options.SupportedCultures = new[] { new CultureInfo("zh-CN"), new CultureInfo("en-US"), new CultureInfo("ja-JP") };
options.SupportedCultures = [new CultureInfo("zh-CN"), new CultureInfo("en-US"), new CultureInfo("ja-JP")];
options.SupportedUICultures = options.SupportedUICultures;
});

Expand All @@ -296,7 +291,7 @@
{
app.UseDeveloperExceptionPage();
app.UseOpenApi(options => options.PostProcess += (document, _) => document.Servers.Clear());
app.UseSwaggerUi3();
app.UseSwaggerUi();
}
else
{
Expand Down Expand Up @@ -400,8 +395,8 @@ public static IActionResult InvalidModelStateHandler(ActionContext context)
};

errors = (from val in context.ModelState.Values
where val.Errors.Count > 0
select val.Errors.FirstOrDefault()?.ErrorMessage).FirstOrDefault();
where val.Errors.Count > 0
select val.Errors.FirstOrDefault()?.ErrorMessage).FirstOrDefault();

return new JsonResult(new RequestResponse(errors is [_, ..] ? errors : StaticLocalizer[nameof(Resources.Program.Model_ValidationFailed)]))
{
Expand Down
11 changes: 5 additions & 6 deletions src/GZCTF/Providers/EntityConfigurationProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class EntityConfigurationProvider(EntityConfigurationSource source) : Con
readonly CancellationTokenSource _cancellationTokenSource = new();
Task? _databaseWatcher;
bool _disposed;
byte[] _lastHash = Array.Empty<byte>();
byte[] _lastHash = [];

public void Dispose()
{
Expand Down Expand Up @@ -85,18 +85,17 @@ public override void Load()
{
if (_databaseWatcher is not null)
{
Task<IDictionary<string, string?>> task = GetDataAsync();
task.Wait();
Data = task.Result;

Data = GetDataAsync().ConfigureAwait(false).GetAwaiter().GetResult();
_lastHash = ConfigHash(Data);
return;
}

AppDbContext context = CreateAppDbContext();

if (!context.Database.IsInMemory())
if (!context.Database.IsInMemory() && context.Database.GetMigrations().Any())
{
context.Database.Migrate();
}

context.Database.EnsureCreated();

Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Repositories/ExerciseInstanceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ IStringLocalizer<Program> localizer
public async Task<ExerciseInstance[]> GetExerciseInstances(UserInfo user, CancellationToken token = default)
{
if (!await IsExerciseAvailable(token))
return Array.Empty<ExerciseInstance>();
return [];

ExerciseInstance[] exercises = await Context.ExerciseInstances
.Where(i => i.UserId == user.Id && i.Exercise.IsEnabled)
Expand Down
4 changes: 2 additions & 2 deletions src/GZCTF/Repositories/GameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,13 +353,13 @@ public class ScoreboardCacheHandler : ICacheRequestHandler
public async Task<byte[]> Handler(AsyncServiceScope scope, CacheRequest request, CancellationToken token = default)
{
if (!int.TryParse(request.Params[0], out var id))
return Array.Empty<byte>();
return [];

var gameRepository = scope.ServiceProvider.GetRequiredService<IGameRepository>();
Game? game = await gameRepository.GetGameById(id, token);

if (game is null)
return Array.Empty<byte>();
return [];

ScoreboardModel scoreboard = await gameRepository.GenScoreboard(game, token);
return MemoryPackSerializer.Serialize(scoreboard);
Expand Down
2 changes: 1 addition & 1 deletion src/GZCTF/Services/Cache/CacheMaker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ async Task Maker(CancellationToken token = default)

try
{
await cache.SetAsync(updateLock, Array.Empty<byte>(),
await cache.SetAsync(updateLock, [],
new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(60) },
token);

Expand Down
6 changes: 4 additions & 2 deletions src/GZCTF/Services/Container/Manager/DockerManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,12 @@ CreateContainerParameters GetCreateContainerParameters(ContainerConfig config) =
Image = config.Image,
Labels = new Dictionary<string, string> { ["TeamId"] = config.TeamId, ["UserId"] = config.UserId.ToString() },
Name = DockerMetadata.GetName(config),
Env = config.Flag is null ? Array.Empty<string>() : new[] { $"GZCTF_FLAG={config.Flag}" },
Env = config.Flag is null ? [] : [$"GZCTF_FLAG={config.Flag}"],
HostConfig = new()
{
Memory = config.MemoryLimit * 1024 * 1024, CPUPercent = config.CPUCount * 10, NetworkMode = _meta.Config.ChallengeNetwork
Memory = config.MemoryLimit * 1024 * 1024,
CPUPercent = config.CPUCount * 10,
NetworkMode = _meta.Config.ChallengeNetwork
}
};
}
12 changes: 6 additions & 6 deletions src/GZCTF/Services/Container/Manager/K8sManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ authSecretName is null
Nameservers = options.Dns
},
EnableServiceLinks = false,
Containers = new[]
{
Containers =
[
new V1Container
{
Name = name,
Expand All @@ -79,8 +79,8 @@ authSecretName is null
Env =
config.Flag is null
? new List<V1EnvVar>()
: new[] { new V1EnvVar("GZCTF_FLAG", config.Flag) },
Ports = new[] { new V1ContainerPort(config.ExposedPort) },
: [new V1EnvVar("GZCTF_FLAG", config.Flag)],
Ports = [new V1ContainerPort(config.ExposedPort)],
Resources = new V1ResourceRequirements
{
Limits = new Dictionary<string, ResourceQuantity>
Expand All @@ -92,7 +92,7 @@ config.Flag is null
Requests = new Dictionary<string, ResourceQuantity> { ["cpu"] = new("10m"), ["memory"] = new("32Mi") }
}
}
},
],
RestartPolicy = "Never"
}
};
Expand Down Expand Up @@ -140,7 +140,7 @@ config.Flag is null
Spec = new V1ServiceSpec
{
Type = _meta.ExposePort ? "NodePort" : "ClusterIP",
Ports = new[] { new V1ServicePort(config.ExposedPort, targetPort: config.ExposedPort) },
Ports = [new V1ServicePort(config.ExposedPort, targetPort: config.ExposedPort)],
Selector = new Dictionary<string, string> { ["ctf.gzti.me/ResourceId"] = name }
}
};
Expand Down
Loading

0 comments on commit 8815d3f

Please sign in to comment.