Skip to content

Commit 5255dd9

Browse files
committed
Change all extension methods to use C# 14's new extension members
1 parent abcb2e6 commit 5255dd9

File tree

17 files changed

+860
-805
lines changed

17 files changed

+860
-805
lines changed

application/AppGateway/ApiAggregation/ApiAggregationEndpoints.cs

Lines changed: 20 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,29 @@ namespace PlatformPlatform.AppGateway.ApiAggregation;
22

33
public static class Endpoints
44
{
5-
public static WebApplication ApiAggregationEndpoints(this WebApplication app)
5+
extension(WebApplication app)
66
{
7-
app.MapGet("/swagger", context =>
8-
{
9-
context.Response.Redirect("/openapi/v1");
10-
return Task.CompletedTask;
11-
}
12-
);
7+
public WebApplication ApiAggregationEndpoints()
8+
{
9+
app.MapGet("/swagger", context =>
10+
{
11+
context.Response.Redirect("/openapi/v1");
12+
return Task.CompletedTask;
13+
}
14+
);
1315

14-
app.MapGet("/openapi", context =>
15-
{
16-
context.Response.Redirect("/openapi/v1");
17-
return Task.CompletedTask;
18-
}
19-
);
16+
app.MapGet("/openapi", context =>
17+
{
18+
context.Response.Redirect("/openapi/v1");
19+
return Task.CompletedTask;
20+
}
21+
);
2022

21-
app.MapGet("/openapi/v1.json", async (ApiAggregationService apiAggregationService)
22-
=> Results.Content(await apiAggregationService.GetAggregatedOpenApiJson(), "application/json")
23-
).CacheOutput(c => c.Expire(TimeSpan.FromMinutes(5)));
23+
app.MapGet("/openapi/v1.json", async (ApiAggregationService apiAggregationService)
24+
=> Results.Content(await apiAggregationService.GetAggregatedOpenApiJson(), "application/json")
25+
).CacheOutput(c => c.Expire(TimeSpan.FromMinutes(5)));
2426

25-
return app;
27+
return app;
28+
}
2629
}
2730
}

application/AppHost/ConfigurationExtensions.cs

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@ namespace AppHost;
22

33
public static class ConfigurationExtensions
44
{
5-
public static IResourceBuilder<TDestination> WithUrlConfiguration<TDestination>(
6-
this IResourceBuilder<TDestination> builder,
7-
string applicationBasePath) where TDestination : IResourceWithEnvironment
5+
extension<TDestination>(IResourceBuilder<TDestination> builder) where TDestination : IResourceWithEnvironment
86
{
9-
var baseUrl = Environment.GetEnvironmentVariable("PUBLIC_URL") ?? "https://localhost:9000";
10-
applicationBasePath = applicationBasePath.TrimEnd('/');
7+
public IResourceBuilder<TDestination> WithUrlConfiguration(string applicationBasePath)
8+
{
9+
var baseUrl = Environment.GetEnvironmentVariable("PUBLIC_URL") ?? "https://localhost:9000";
10+
applicationBasePath = applicationBasePath.TrimEnd('/');
1111

12-
return builder
13-
.WithEnvironment("PUBLIC_URL", baseUrl)
14-
.WithEnvironment("CDN_URL", baseUrl + applicationBasePath);
12+
return builder
13+
.WithEnvironment("PUBLIC_URL", baseUrl)
14+
.WithEnvironment("CDN_URL", baseUrl + applicationBasePath);
15+
}
1516
}
1617
}

application/AppHost/SecretManagerHelper.cs

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -12,26 +12,6 @@ public static class SecretManagerHelper
1212

1313
private static string UserSecretsId => Assembly.GetEntryAssembly()!.GetCustomAttribute<UserSecretsIdAttribute>()!.UserSecretsId;
1414

15-
public static IResourceBuilder<ParameterResource> CreateStablePassword(
16-
this IDistributedApplicationBuilder builder,
17-
string secretName
18-
)
19-
{
20-
var password = ConfigurationRoot[secretName];
21-
22-
if (string.IsNullOrEmpty(password))
23-
{
24-
var passwordGenerator = new GenerateParameterDefault
25-
{
26-
MinLower = 5, MinUpper = 5, MinNumeric = 3, MinSpecial = 3
27-
};
28-
password = passwordGenerator.GetDefaultValue();
29-
SaveSecrectToDotNetUserSecrets(secretName, password);
30-
}
31-
32-
return builder.CreateResourceBuilder(new ParameterResource(secretName, _ => password, true));
33-
}
34-
3515
public static void GenerateAuthenticationTokenSigningKey(string secretName)
3616
{
3717
if (string.IsNullOrEmpty(ConfigurationRoot[secretName]))
@@ -56,4 +36,24 @@ private static void SaveSecrectToDotNetUserSecrets(string key, string value)
5636
using var process = Process.Start(startInfo)!;
5737
process.WaitForExit();
5838
}
39+
40+
extension(IDistributedApplicationBuilder builder)
41+
{
42+
public IResourceBuilder<ParameterResource> CreateStablePassword(string secretName)
43+
{
44+
var password = ConfigurationRoot[secretName];
45+
46+
if (string.IsNullOrEmpty(password))
47+
{
48+
var passwordGenerator = new GenerateParameterDefault
49+
{
50+
MinLower = 5, MinUpper = 5, MinNumeric = 3, MinSpecial = 3
51+
};
52+
password = passwordGenerator.GetDefaultValue();
53+
SaveSecrectToDotNetUserSecrets(secretName, password);
54+
}
55+
56+
return builder.CreateResourceBuilder(new ParameterResource(secretName, _ => password, true));
57+
}
58+
}
5959
}

application/AppHost/SslCertificateManager.cs

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,33 +11,6 @@ public static class SslCertificateManager
1111
{
1212
private static string UserSecretsId => Assembly.GetEntryAssembly()!.GetCustomAttribute<UserSecretsIdAttribute>()!.UserSecretsId;
1313

14-
public static async Task<string> CreateSslCertificateIfNotExists(this IDistributedApplicationBuilder builder, CancellationToken cancellationToken = default)
15-
{
16-
var config = new ConfigurationBuilder().AddUserSecrets(UserSecretsId).Build();
17-
18-
const string certificatePasswordKey = "certificate-password";
19-
var certificatePassword = config[certificatePasswordKey]
20-
?? await builder.CreateStablePassword(certificatePasswordKey).Resource.GetValueAsync(cancellationToken)
21-
?? throw new InvalidOperationException("Failed to retrieve or create certificate password.");
22-
23-
var certificateLocation = GetCertificateLocation("localhost");
24-
try
25-
{
26-
var certificate2 = X509CertificateLoader.LoadPkcs12FromFile(certificateLocation, certificatePassword);
27-
if (certificate2.NotAfter < DateTime.UtcNow)
28-
{
29-
Console.WriteLine($"Certificate {certificateLocation} is expired. Creating a new certificate.");
30-
CreateNewSelfSignedDeveloperCertificate(certificateLocation, certificatePassword);
31-
}
32-
}
33-
catch (CryptographicException)
34-
{
35-
CreateNewSelfSignedDeveloperCertificate(certificateLocation, certificatePassword);
36-
}
37-
38-
return certificatePassword;
39-
}
40-
4114
private static string GetCertificateLocation(string domain)
4215
{
4316
var userFolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
@@ -73,4 +46,34 @@ private static void CreateNewSelfSignedDeveloperCertificate(string certificateLo
7346
}
7447
)!.WaitForExit();
7548
}
49+
50+
extension(IDistributedApplicationBuilder builder)
51+
{
52+
public async Task<string> CreateSslCertificateIfNotExists(CancellationToken cancellationToken = default)
53+
{
54+
var config = new ConfigurationBuilder().AddUserSecrets(UserSecretsId).Build();
55+
56+
const string certificatePasswordKey = "certificate-password";
57+
var certificatePassword = config[certificatePasswordKey]
58+
?? await builder.CreateStablePassword(certificatePasswordKey).Resource.GetValueAsync(cancellationToken)
59+
?? throw new InvalidOperationException("Failed to retrieve or create certificate password.");
60+
61+
var certificateLocation = GetCertificateLocation("localhost");
62+
try
63+
{
64+
var certificate2 = X509CertificateLoader.LoadPkcs12FromFile(certificateLocation, certificatePassword);
65+
if (certificate2.NotAfter < DateTime.UtcNow)
66+
{
67+
Console.WriteLine($"Certificate {certificateLocation} is expired. Creating a new certificate.");
68+
CreateNewSelfSignedDeveloperCertificate(certificateLocation, certificatePassword);
69+
}
70+
}
71+
catch (CryptographicException)
72+
{
73+
CreateNewSelfSignedDeveloperCertificate(certificateLocation, certificatePassword);
74+
}
75+
76+
return certificatePassword;
77+
}
78+
}
7679
}

application/account-management/Core/Configuration.cs

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,32 @@ public static class Configuration
1111
{
1212
public static Assembly Assembly => Assembly.GetExecutingAssembly();
1313

14-
public static IHostApplicationBuilder AddAccountManagementInfrastructure(this IHostApplicationBuilder builder)
14+
extension(IHostApplicationBuilder builder)
1515
{
16-
// Infrastructure is configured separately from other Infrastructure services to allow mocking in tests
17-
return builder
18-
.AddSharedInfrastructure<AccountManagementDbContext>("account-management-database")
19-
.AddNamedBlobStorages(("account-management-storage", "BLOB_STORAGE_URL"));
16+
public IHostApplicationBuilder AddAccountManagementInfrastructure()
17+
{
18+
// Infrastructure is configured separately from other Infrastructure services to allow mocking in tests
19+
return builder
20+
.AddSharedInfrastructure<AccountManagementDbContext>("account-management-database")
21+
.AddNamedBlobStorages(("account-management-storage", "BLOB_STORAGE_URL"));
22+
}
2023
}
2124

22-
public static IServiceCollection AddAccountManagementServices(this IServiceCollection services)
25+
extension(IServiceCollection services)
2326
{
24-
services.AddHttpClient<GravatarClient>(client =>
25-
{
26-
client.BaseAddress = new Uri("https://gravatar.com/");
27-
client.Timeout = TimeSpan.FromSeconds(5);
28-
}
29-
);
27+
public IServiceCollection AddAccountManagementServices()
28+
{
29+
services.AddHttpClient<GravatarClient>(client =>
30+
{
31+
client.BaseAddress = new Uri("https://gravatar.com/");
32+
client.Timeout = TimeSpan.FromSeconds(5);
33+
}
34+
);
3035

31-
return services
32-
.AddSharedServices<AccountManagementDbContext>(Assembly)
33-
.AddScoped<AvatarUpdater>()
34-
.AddScoped<UserInfoFactory>();
36+
return services
37+
.AddSharedServices<AccountManagementDbContext>(Assembly)
38+
.AddScoped<AvatarUpdater>()
39+
.AddScoped<UserInfoFactory>();
40+
}
3541
}
3642
}

application/account-management/Tests/FakerExtensions.cs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,24 +5,27 @@ namespace PlatformPlatform.AccountManagement.Tests;
55

66
public static class FakerExtensions
77
{
8-
public static string TenantName(this Faker faker)
8+
extension(Faker faker)
99
{
10-
return new string(faker.Company.CompanyName().Take(30).ToArray());
11-
}
10+
public string TenantName()
11+
{
12+
return new string(faker.Company.CompanyName().Take(30).ToArray());
13+
}
1214

13-
public static string PhoneNumber(this Faker faker)
14-
{
15-
var random = new Random();
16-
return $"+{random.Next(1, 9)}-{faker.Phone.PhoneNumberFormat()}";
17-
}
15+
public string PhoneNumber()
16+
{
17+
var random = new Random();
18+
return $"+{random.Next(1, 9)}-{faker.Phone.PhoneNumberFormat()}";
19+
}
1820

19-
public static string InvalidEmail(this Faker faker)
20-
{
21-
return faker.Internet.ExampleEmail(faker.Random.AlphaNumeric(100));
22-
}
21+
public string InvalidEmail()
22+
{
23+
return faker.Internet.ExampleEmail(faker.Random.AlphaNumeric(100));
24+
}
2325

24-
public static long RandomId(this Faker faker)
25-
{
26-
return IdGenerator.NewId();
26+
public long RandomId()
27+
{
28+
return IdGenerator.NewId();
29+
}
2730
}
2831
}

application/back-office/Core/Configuration.cs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,20 @@ public static class Configuration
99
{
1010
public static Assembly Assembly => Assembly.GetExecutingAssembly();
1111

12-
public static IHostApplicationBuilder AddBackOfficeInfrastructure(this IHostApplicationBuilder builder)
12+
extension(IHostApplicationBuilder builder)
1313
{
14-
// Infrastructure is configured separately from other Infrastructure services to allow mocking in tests
15-
return builder.AddSharedInfrastructure<BackOfficeDbContext>("back-office-database");
14+
public IHostApplicationBuilder AddBackOfficeInfrastructure()
15+
{
16+
// Infrastructure is configured separately from other Infrastructure services to allow mocking in tests
17+
return builder.AddSharedInfrastructure<BackOfficeDbContext>("back-office-database");
18+
}
1619
}
1720

18-
public static IServiceCollection AddBackOfficeServices(this IServiceCollection services)
21+
extension(IServiceCollection services)
1922
{
20-
return services.AddSharedServices<BackOfficeDbContext>(Assembly);
23+
public IServiceCollection AddBackOfficeServices()
24+
{
25+
return services.AddSharedServices<BackOfficeDbContext>(Assembly);
26+
}
2127
}
2228
}

application/shared-kernel/SharedKernel/ApiResults/ApiResultExtensions.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,15 @@ namespace PlatformPlatform.SharedKernel.ApiResults;
55

66
public static class ApiResultExtensions
77
{
8-
public static ApiResult AddResourceUri<T>(this Result<T> result, string routePrefix)
8+
extension(Result result)
99
{
10-
return new ApiResult<T>(result, routePrefix);
11-
}
12-
13-
public static ApiResult AddRefreshAuthenticationTokens(this Result result)
14-
{
15-
if (!result.IsSuccess) return new ApiResult(result);
10+
public ApiResult AddRefreshAuthenticationTokens()
11+
{
12+
if (!result.IsSuccess) return new ApiResult(result);
1613

17-
return new ApiResult(result, httpHeaders: new Dictionary<string, string>
18-
{ { AuthenticationTokenHttpKeys.RefreshAuthenticationTokensHeaderKey, "true" } }
19-
);
14+
return new ApiResult(result, httpHeaders: new Dictionary<string, string>
15+
{ { AuthenticationTokenHttpKeys.RefreshAuthenticationTokensHeaderKey, "true" } }
16+
);
17+
}
2018
}
2119
}

application/shared-kernel/SharedKernel/Authentication/TokenGeneration/SecurityTokenDescriptorExtensions.cs

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,18 @@ namespace PlatformPlatform.SharedKernel.Authentication.TokenGeneration;
55

66
internal static class SecurityTokenDescriptorExtensions
77
{
8-
internal static string GenerateToken(
9-
this SecurityTokenDescriptor tokenDescriptor,
10-
DateTimeOffset expires,
11-
string issuer,
12-
string audience,
13-
SigningCredentials signingCredentials
14-
)
8+
extension(SecurityTokenDescriptor tokenDescriptor)
159
{
16-
tokenDescriptor.Expires = expires.UtcDateTime;
17-
tokenDescriptor.Issuer = issuer;
18-
tokenDescriptor.Audience = audience;
19-
tokenDescriptor.SigningCredentials = signingCredentials;
10+
internal string GenerateToken(DateTimeOffset expires, string issuer, string audience, SigningCredentials signingCredentials)
11+
{
12+
tokenDescriptor.Expires = expires.UtcDateTime;
13+
tokenDescriptor.Issuer = issuer;
14+
tokenDescriptor.Audience = audience;
15+
tokenDescriptor.SigningCredentials = signingCredentials;
2016

21-
var tokenHandler = new JwtSecurityTokenHandler();
22-
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
23-
return tokenHandler.WriteToken(securityToken);
17+
var tokenHandler = new JwtSecurityTokenHandler();
18+
var securityToken = tokenHandler.CreateToken(tokenDescriptor);
19+
return tokenHandler.WriteToken(securityToken);
20+
}
2421
}
2522
}

0 commit comments

Comments
 (0)