Skip to content

Commit

Permalink
Fix code smells
Browse files Browse the repository at this point in the history
- use file scoped namespace
- use `{}` for single line
- use custom Exception thrown
- use local variables when they are only in one method
-
  • Loading branch information
merca committed Oct 13, 2023
1 parent 600a6f8 commit 01dc48b
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 47 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace stargripcorp.dataplatform.infra.azure.Exceptions
{
internal class ApiResponseExceptions(string message) : Exception(message)

Check warning on line 9 in src/stargripcorp.dataplatform.infra.azure/Exceptions/ApiResponseExceptions.cs

View workflow job for this annotation

GitHub Actions / Build and analyze

Make this exception 'public'. (https://rules.sonarsource.com/csharp/RSPEC-3871)

Check warning on line 9 in src/stargripcorp.dataplatform.infra.azure/Exceptions/ApiResponseExceptions.cs

View workflow job for this annotation

GitHub Actions / Build and analyze

Make this class name end with 'Exception'. (https://rules.sonarsource.com/csharp/RSPEC-3376)

Check warning on line 9 in src/stargripcorp.dataplatform.infra.azure/Exceptions/ApiResponseExceptions.cs

View workflow job for this annotation

GitHub Actions / Build and analyze

Make this exception 'public'. (https://rules.sonarsource.com/csharp/RSPEC-3871)

Check warning on line 9 in src/stargripcorp.dataplatform.infra.azure/Exceptions/ApiResponseExceptions.cs

View workflow job for this annotation

GitHub Actions / Build and analyze

Make this class name end with 'Exception'. (https://rules.sonarsource.com/csharp/RSPEC-3376)
{
}
}
43 changes: 22 additions & 21 deletions src/stargripcorp.dataplatform.infra.azure/Helpers/Utils.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
using Pulumi.AzureNative.Authorization;
using stargripcorp.dataplatform.infra.azure.Exceptions;
using System.Net.Http.Headers;
using System.Text.Json;

namespace stargripcorp.dataplatform.infra.azure.Helpers
namespace stargripcorp.dataplatform.infra.azure.Helpers;

internal static class Utils
{
internal class Utils
public static async Task<string> GetRoleIdByNameAsync(string roleName)
{
public static async Task<string> GetRoleIdByNameAsync(string roleName)
{
var config = await GetClientConfig.InvokeAsync();
var token = await GetClientToken.InvokeAsync();
var config = await GetClientConfig.InvokeAsync();
var token = await GetClientToken.InvokeAsync();

// Unfortunately, Microsoft hasn't shipped an .NET5-compatible SDK at the time of writing this.
// So, we have to hand-craft an HTTP request to retrieve a role definition.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
var response = await httpClient.GetAsync($"https://management.azure.com/subscriptions/{config.SubscriptionId}/providers/Microsoft.Authorization/roleDefinitions?api-version=2018-01-01-preview&$filter=roleName%20eq%20'{roleName}'");
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Request failed with {response.StatusCode}");
}
var body = await response.Content.ReadAsStringAsync();
var definition = JsonSerializer.Deserialize<RoleDefinition>(body);
return definition!.value[0].id;
// Unfortunately, Microsoft hasn't shipped an .NET5-compatible SDK at the time of writing this.
// So, we have to hand-craft an HTTP request to retrieve a role definition.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
var response = await httpClient.GetAsync($"https://management.azure.com/subscriptions/{config.SubscriptionId}/providers/Microsoft.Authorization/roleDefinitions?api-version=2018-01-01-preview&$filter=roleName%20eq%20'{roleName}'");
if (!response.IsSuccessStatusCode)
{
throw new ApiResponseExceptions($"Request failed with {response.StatusCode}");
}
var body = await response.Content.ReadAsStringAsync();
var definition = JsonSerializer.Deserialize<RoleDefinition>(body);
return definition!.value[0].id;
}
}
#pragma warning disable IDE1006 // Naming Styles
public record RoleDefinition(List<RoleDefinitionValue> value);
public record RoleDefinitionValue(string id, string type, string name);
public record RoleDefinition(List<RoleDefinitionValue> value);
public record RoleDefinitionValue(string id, string type, string name);
#pragma warning restore IDE1006 // Naming Styles
}

Check notice on line 33 in src/stargripcorp.dataplatform.infra.azure/Helpers/Utils.cs

View check run for this annotation

codefactor.io / CodeFactor

src/stargripcorp.dataplatform.infra.azure/Helpers/Utils.cs#L33

The code must not contain multiple blank lines in a row. (SA1507)
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ namespace stargripcorp.dataplatform.infra.azure.Infrastructure;

internal class CoreComponents(NamingConvention naming, Dictionary<string, string> tags)
{
private readonly string shortName = "core";

public void Run()
{
var shortName = "core";

var rg = new AzResourceGroup($"{shortName}-rg", naming, tags).WithBudget(20, ["merca@cetera.desunt.com"]);

var admins = new Dictionary<string, bool>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ namespace stargripcorp.dataplatform.infra.azure.Infrastructure;

internal class DataPlatform(NamingConvention naming, Dictionary<string, string> tags)
{
private readonly string shortName = "data";

public void Run()
{
var shortName = "data";
var rg = new AzResourceGroup($"{shortName}-rg", naming, tags).WithBudget(20, ["merca.ovnerud@pulumi.me"]);
_ = new AzStorage($"{shortName}-sa", naming, rg.ResourceGroupName).AsDataLake();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,16 +64,16 @@ public AzKeyVault WithSecretsReader(string[] readerIds)
}
public AzKeyVault WithKeyVaultSecretsAdmins(Output<Dictionary<string, bool>> contributors)
{
object value = contributors.Apply(x =>
_ = contributors.Apply(x =>
{
List<RoleAssignment> roleAssignments = [];
foreach (var key in x.Keys)
{
x.TryGetValue(key, out bool user);
if (user)
roleAssignments.Add(ForUser(key, $"{_naming.GenerateResourceId("azure-native:authorization:RoleAssignment")}-{key}"));
else
roleAssignments.Add(ForSp(key, $"{_naming.GenerateResourceId("azure-native:authorization:RoleAssignment")}-{key}"));
if (user) { roleAssignments.Add(ForUser(key, $"{_naming.GenerateResourceId("azure-native:authorization:RoleAssignment")}-{key}")); }

else { roleAssignments.Add(ForSp(key, $"{_naming.GenerateResourceId("azure-native:authorization:RoleAssignment")}-{key}")); }

}
return roleAssignments;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public AzResourceGroup WithBudget(double budgetAmount, string[] notificationEmai
Scope = Output.Format($"/subscriptions/{subscriptionId}"),
TimePeriod = new Azure.Consumption.Inputs.BudgetTimePeriodArgs
{
StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ"),
EndDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddYears(1).ToString("yyyy-MM-ddTHH:mm:ssZ")
StartDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1, 0, 0, 0, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ"),
EndDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1, 0, 0, 0, DateTimeKind.Utc).AddYears(1).ToString("yyyy-MM-ddTHH:mm:ssZ")
},
BudgetName = _naming.GetResourceName("azure-native:resources:Budget"),
Filter = new Azure.Consumption.Inputs.BudgetFilterArgs
Expand All @@ -45,11 +45,10 @@ public AzResourceGroup WithBudget(double budgetAmount, string[] notificationEmai
Name = "ResourceGroupName",
Operator = "In",
Values = new()
{
$"/subscriptions/{ClientConfig.Apply(o=>o.SubscriptionId)}/resourceGroups/{ResourceGroup!.Name}"
}
{
$"/subscriptions/{ClientConfig.Apply(o=>o.SubscriptionId)}/resourceGroups/{ResourceGroup!.Name}"
}
},

},
Notifications =
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ namespace stargripcorp.dataplatform.infra.azure.Resources;

internal class AzStorage(string id, NamingConvention naming, Output<string> resourceGroupName) : ComponentResource("pkg:azure:storage", id)
{
private readonly NamingConvention _naming = naming;

public void GenerateStorageAccount(bool isHnsEnabled)
{
_ = new Azure.Storage.StorageAccount(_naming.GenerateResourceId("azure-native:storage:StorageAccount"), new()
_ = new Azure.Storage.StorageAccount(naming.GenerateResourceId("azure-native:storage:StorageAccount"), new()
{
AccountName = _naming.GetResourceName("azure-native:storage:StorageAccount"),
AccountName = naming.GetResourceName("azure-native:storage:StorageAccount"),
ResourceGroupName = resourceGroupName,
Sku = new Azure.Storage.Inputs.SkuArgs
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,7 @@ public string GetResourceName(string resourceType)

public string GenerateResourceId(string resourceType)
{
if (!resourceTypeGenerators.ContainsKey(resourceType))
{
throw new ArgumentException($"Unknown resource type: {resourceType}");
}

var resourceTypeAbbreviation = resourceTypeAbbreviations.GetAbbreviation(resourceType);
var resourceName = $"{owner}-{shortName}-{environment}-{resourceTypeAbbreviation}";
return $"{resourceName}";
return GenerateResourceName(resourceType);
}
public string GenerateResourceName(string resourceType)
{
Expand Down

0 comments on commit 01dc48b

Please sign in to comment.