Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixed code smells from sonarcloud #GCPActive #370

Merged
merged 3 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build-and-analyze.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
run: |
dotnet-sonarscanner begin /k:"Altinn_altinn-notifications" /o:"altinn" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" /d:sonar.cpd.exclusions="src/Altinn.Notifications.Persistence/Migration/**/*.sql" /d:sonar.coverage.exclusions="src/Altinn.Notifications.Persistence/Migration/"
dotnet-sonarscanner begin /k:"Altinn_altinn-notifications" /o:"altinn" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" /d:sonar.exclusions="src/Altinn.Notifications.Persistence/Migration/**/*"

dotnet build Altinn.Notifications.sln -v q

Expand Down
21 changes: 21 additions & 0 deletions src/Altinn.Notifications.Core/JsonSerializerOptionsProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Altinn.Notifications.Core
{
/// <summary>
/// Provider class for JsonSerializerOptions
/// </summary>
public static class JsonSerializerOptionsProvider
{
/// <summary>
/// Standard serializer options
/// </summary>
public static JsonSerializerOptions Options { get; } = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
};
}
}
10 changes: 1 addition & 9 deletions src/Altinn.Notifications.Core/Models/Email.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Text.Json;
using System.Text.Json.Serialization;

using Altinn.Notifications.Core.Enums;

Expand Down Expand Up @@ -58,13 +57,6 @@ public Email(Guid notificationId, string subject, string body, string fromAddres
/// </summary>
public string Serialize()
{
return JsonSerializer.Serialize(
this,
new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
});
return JsonSerializer.Serialize(this, JsonSerializerOptionsProvider.Options);
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using System.Text.Json;
using System.Text.Json.Serialization;

using Altinn.Notifications.Core.Enums;
using Altinn.Notifications.Core.Models.Orders;

namespace Altinn.Notifications.Core.Models.Notification;

/// <summary>
/// A class representing a send operation update object
/// </summary>
/// </summary>
public class SendOperationResult
{
/// <summary>
Expand All @@ -30,14 +29,7 @@ public class SendOperationResult
/// </summary>
public string Serialize()
{
return JsonSerializer.Serialize(
this,
new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
});
return JsonSerializer.Serialize(this, JsonSerializerOptionsProvider.Options);
}

/// <summary>
Expand All @@ -46,12 +38,7 @@ public string Serialize()
public static SendOperationResult? Deserialize(string serializedString)
{
return JsonSerializer.Deserialize<SendOperationResult>(
serializedString,
new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
});
serializedString, JsonSerializerOptionsProvider.Options);
}

/// <summary>
Expand Down
18 changes: 2 additions & 16 deletions src/Altinn.Notifications.Core/Models/Orders/NotificationOrder.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Text.Json;
using System.Text.Json.Serialization;

using Altinn.Notifications.Core.Enums;
using Altinn.Notifications.Core.Models.NotificationTemplate;
Expand Down Expand Up @@ -42,7 +41,7 @@
/// <summary>
/// Initializes a new instance of the <see cref="NotificationOrder"/> class.
/// </summary>
public NotificationOrder(Guid id, string? sendersReference, List<INotificationTemplate> templates, DateTime requestedSendTime, NotificationChannel notificationChannel, Creator creator, DateTime created, List<Recipient> recipients)

Check warning on line 44 in src/Altinn.Notifications.Core/Models/Orders/NotificationOrder.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Constructor has 8 parameters, which is greater than the 7 authorized. (https://rules.sonarsource.com/csharp/RSPEC-107)

Check warning on line 44 in src/Altinn.Notifications.Core/Models/Orders/NotificationOrder.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Constructor has 8 parameters, which is greater than the 7 authorized. (https://rules.sonarsource.com/csharp/RSPEC-107)
{
Id = id;
SendersReference = sendersReference;
Expand All @@ -67,28 +66,15 @@
/// </summary>
public string Serialize()
{
return JsonSerializer.Serialize(
this,
new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
});
return JsonSerializer.Serialize(this, JsonSerializerOptionsProvider.Options);
}

/// <summary>
/// Deserialize a json string into the <see cref="NotificationOrder"/>
/// </summary>
public static NotificationOrder? Deserialize(string serializedString)
{
return JsonSerializer.Deserialize<NotificationOrder>(
serializedString,
new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
});
return JsonSerializer.Deserialize<NotificationOrder>(serializedString, JsonSerializerOptionsProvider.Options);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public NotificationSummaryService(INotificationSummaryRepository summaryReposito
return (null, new ServiceError(404));
}

if (summary.Notifications.Any())
if (summary.Notifications.Count != 0)
{
ProcessNotificationResults(summary);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Altinn.Notifications/Mappers/OrderMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public static NotificationOrderWithStatusExt MapToNotificationOrderWithStatusExt
StatusDescription = order.ProcessingStatus.StatusDescription
};

if (order.NotificationStatuses.Any())
if (order.NotificationStatuses.Count != 0)
{
orderExt.NotificationsStatusSummary = new();
foreach (var entry in order.NotificationStatuses)
Expand Down
6 changes: 2 additions & 4 deletions src/Altinn.Notifications/Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#nullable disable

Check warning on line 1 in src/Altinn.Notifications/Program.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Refactor this top-level file to reduce its Cognitive Complexity from 17 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand Down Expand Up @@ -80,7 +80,7 @@
{
var logFactory = LoggerFactory.Create(builder =>
{
builder

Check warning on line 83 in src/Altinn.Notifications/Program.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Make sure that this logger's configuration is safe. (https://rules.sonarsource.com/csharp/RSPEC-4792)
.AddFilter("Altinn.Platform.Notifications.Program", LogLevel.Debug)
.AddConsole();
});
Expand Down Expand Up @@ -119,7 +119,7 @@
// If not application insight is available log to console
logging.AddFilter("Microsoft", LogLevel.Warning);
logging.AddFilter("System", LogLevel.Warning);
logging.AddConsole();

Check warning on line 122 in src/Altinn.Notifications/Program.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Make sure that this logger's configuration is safe. (https://rules.sonarsource.com/csharp/RSPEC-4792)
}
}

Expand All @@ -140,7 +140,7 @@
services.AddSingleton(config);
if (!string.IsNullOrEmpty(applicationInsightsConnectionString))
{
services.AddSingleton(typeof(ITelemetryChannel), new ServerTelemetryChannel() { StorageFolder = "/tmp/logtelemetry" });

Check warning on line 143 in src/Altinn.Notifications/Program.cs

View workflow job for this annotation

GitHub Actions / Build, test & analyze

Make sure publicly writable directories are used safely here. (https://rules.sonarsource.com/csharp/RSPEC-5443)

services.AddApplicationInsightsTelemetry(new ApplicationInsightsServiceOptions
{
Expand Down Expand Up @@ -187,13 +187,11 @@

void AddAuthorizationRulesAndHandlers(IServiceCollection services, IConfiguration config)
{
services.AddAuthorization(options =>
{
options.AddPolicy(AuthorizationConstants.POLICY_CREATE_SCOPE_OR_PLATFORM_ACCESS, policy =>
services.AddAuthorizationBuilder()
.AddPolicy(AuthorizationConstants.POLICY_CREATE_SCOPE_OR_PLATFORM_ACCESS, policy =>
{
policy.Requirements.Add(new CreateScopeOrAccessTokenRequirement(AuthorizationConstants.SCOPE_NOTIFICATIONS_CREATE));
});
});

services.AddTransient<IAuthorizationHandler, ScopeAccessHandler>();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;

using Altinn.Common.AccessToken.Services;
using Altinn.Notifications.Core;
using Altinn.Notifications.Core.Models.Orders;
using Altinn.Notifications.IntegrationTests.Utils;
using Altinn.Notifications.Mappers;
Expand Down Expand Up @@ -93,7 +93,7 @@ public async Task GetById_SingleMatchInDb_ReturnsOk()
// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
string resString = await response.Content.ReadAsStringAsync();
NotificationOrderExt? actual = JsonSerializer.Deserialize<NotificationOrderExt>(resString, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } });
NotificationOrderExt? actual = JsonSerializer.Deserialize<NotificationOrderExt>(resString, JsonSerializerOptionsProvider.Options);

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;

using Altinn.Common.AccessToken.Services;
using Altinn.Notifications.Core;
using Altinn.Notifications.Core.Models.Orders;
using Altinn.Notifications.IntegrationTests.Utils;
using Altinn.Notifications.Models;
Expand Down Expand Up @@ -49,7 +49,7 @@ public async Task GetBySendersRef_NoMatchInDb_ReturnsOK_EmptyList()
// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
string resString = await response.Content.ReadAsStringAsync();
NotificationOrderListExt actual = JsonSerializer.Deserialize<NotificationOrderListExt>(resString, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } })!;
NotificationOrderListExt actual = JsonSerializer.Deserialize<NotificationOrderListExt>(resString, JsonSerializerOptionsProvider.Options)!;

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Expand All @@ -73,7 +73,7 @@ public async Task GetBySendersRef_SingleMatchInDb_ReturnsOk_SingleElementInlList
// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
string resString = await response.Content.ReadAsStringAsync();
NotificationOrderListExt actual = JsonSerializer.Deserialize<NotificationOrderListExt>(resString, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } })!;
NotificationOrderListExt actual = JsonSerializer.Deserialize<NotificationOrderListExt>(resString, JsonSerializerOptionsProvider.Options)!;

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Expand All @@ -100,7 +100,7 @@ public async Task GetBySendersRef_MultipleMatchInDb_ReturnsOk_MultipleElementInl
// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
string resString = await response.Content.ReadAsStringAsync();
NotificationOrderListExt actual = JsonSerializer.Deserialize<NotificationOrderListExt>(resString, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } })!;
NotificationOrderListExt actual = JsonSerializer.Deserialize<NotificationOrderListExt>(resString, JsonSerializerOptionsProvider.Options)!;

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;

using Altinn.Common.AccessToken.Services;
using Altinn.Notifications.Core;
using Altinn.Notifications.Core.Models.Orders;
using Altinn.Notifications.IntegrationTests.Utils;
using Altinn.Notifications.Models;
Expand Down Expand Up @@ -98,7 +98,7 @@ public async Task GetWithStatusById_SingleMatchInDbAndOneEmail_ReturnsOk()
// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
string resString = await response.Content.ReadAsStringAsync();
NotificationOrderWithStatusExt? actual = JsonSerializer.Deserialize<NotificationOrderWithStatusExt>(resString, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } });
NotificationOrderWithStatusExt? actual = JsonSerializer.Deserialize<NotificationOrderWithStatusExt>(resString, JsonSerializerOptionsProvider.Options);

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Expand Down Expand Up @@ -137,7 +137,7 @@ public async Task GetWithStatusById_SingleMatchInDb_ReturnsOk()
// Act
HttpResponseMessage response = await client.SendAsync(httpRequestMessage);
string resString = await response.Content.ReadAsStringAsync();
NotificationOrderWithStatusExt? actual = JsonSerializer.Deserialize<NotificationOrderWithStatusExt>(resString, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() } });
NotificationOrderWithStatusExt? actual = JsonSerializer.Deserialize<NotificationOrderWithStatusExt>(resString, JsonSerializerOptionsProvider.Options);

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System;

using AltinnCore.Authentication.JwtCookie;

using Microsoft.AspNetCore.Authentication.Cookies;
Expand All @@ -22,7 +20,7 @@ public void PostConfigure(string? name, JwtCookieOptions options)

options.CookieManager ??= new ChunkingCookieManager();

if (!string.IsNullOrEmpty(options.MetadataAddress) && !options.MetadataAddress.EndsWith("/", StringComparison.Ordinal))
if (!string.IsNullOrEmpty(options.MetadataAddress) && !options.MetadataAddress.EndsWith('/'))
{
options.MetadataAddress += "/";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static string GenerateToken(ClaimsPrincipal principal, TimeSpan tokenExip
return tokenstring;
}

private static SigningCredentials GetSigningCredentials(string issuer)
private static X509SigningCredentials GetSigningCredentials(string issuer)
{
string certPath = "jwtselfsignedcert.pfx";
if (!issuer.Equals("UnitTest"))
Expand Down
Loading