Skip to content

Commit

Permalink
Update to .net version 7
Browse files Browse the repository at this point in the history
  • Loading branch information
Christdej committed Sep 26, 2023
1 parent 9feb218 commit 8922c38
Show file tree
Hide file tree
Showing 17 changed files with 95 additions and 124 deletions.
20 changes: 10 additions & 10 deletions .github/workflows/backend_lint_and_test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,25 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3

- name: Set up .NET
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v3
with:
dotnet-version: "6.0.x"
dotnet-version: "7.0.x"
- name: Build project and dependencies
run: dotnet build

test_backend:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2.1.0
uses: actions/checkout@v3

- name: Set up .NET
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v3
with:
dotnet-version: "6.0.x"
dotnet-version: "7.0.x"

- name: Build project and dependencies
run: dotnet build -warnaserror
Expand All @@ -46,14 +46,14 @@ jobs:
check_formatting:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3

- name: Setup .NET Core
uses: actions/setup-dotnet@v1
uses: actions/setup-dotnet@v3
with:
dotnet-version: "6.0.x"
dotnet-version: "7.0.x"

# Dotnet format is included in the .NET6 SDK
# Dotnet format is included in the .NET7 SDK
# By default, the task ensures the exit code is 0
# If a file needs to be edited by dotnet format, the exit code will be a non-zero value
# We are using severity level 'info' here.
Expand Down
2 changes: 1 addition & 1 deletion backend/api.test/EndpointTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ public async Task GetMissionsInAreaTest()
Assert.True(areaMissionsResponse.IsSuccessStatusCode);
var missions = await areaMissionsResponse.Content.ReadFromJsonAsync<IList<MissionRun>>(_serializerOptions);
Assert.NotNull(missions);
Assert.Equal(1, missions.Count);
Assert.Single(missions);
Assert.Equal(missions[0].Id, mission.MissionId);
}

Expand Down
7 changes: 3 additions & 4 deletions backend/api.test/EventHandlers/TestMissionEventHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ public async void NoMissionIsStartedIfQueueIsEmptyWhenRobotBecomesAvailable()
_mqttService.RaiseEvent(nameof(MqttService.MqttIsarRobotStatusReceived), mqttEventArgs);

// Assert
bool ongoingMission = _missionRunService.ReadAll(
var ongoingMission = await _missionRunService.ReadAll(
new MissionRunQueryStringParameters
{
Statuses = new List<MissionStatus>
Expand All @@ -276,9 +276,8 @@ public async void NoMissionIsStartedIfQueueIsEmptyWhenRobotBecomesAvailable()
},
OrderBy = "DesiredStartTime",
PageSize = 100
}).Result.Any();

Assert.False(ongoingMission);
});
Assert.False(ongoingMission.Any());
}

[Fact]
Expand Down
7 changes: 3 additions & 4 deletions backend/api.test/Mocks/CustomMissionServiceMock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ public string UploadSource(List<MissionTask> tasks)

public async Task<List<MissionTask>?> GetMissionTasksFromSourceId(string id)
{
if (mockBlobStore.ContainsKey(id))
if (mockBlobStore.TryGetValue(id, out var value))
{
var content = mockBlobStore[id];
var content = value;
foreach (var task in content)
{
task.Id = Guid.NewGuid().ToString(); // This is needed as tasks are owned by mission runs
Expand All @@ -44,8 +44,7 @@ public string CalculateHashFromTasks(IList<MissionTask> tasks)
}

string json = JsonSerializer.Serialize(genericTasks);
var hasher = SHA256.Create();
byte[] hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(json));
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(json));
return BitConverter.ToString(hash).Replace("-", "", StringComparison.CurrentCulture).ToUpperInvariant();
}
}
Expand Down
12 changes: 4 additions & 8 deletions backend/api.test/Services/MissionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,8 @@ public async Task ReadIdDoesNotExist()
public async Task Create()
{
var robot = _context.Robots.First();
int nReportsBefore = _missionRunService
.ReadAll(new MissionRunQueryStringParameters())
.Result.Count;

var reportsBefore = await _missionRunService.ReadAll(new MissionRunQueryStringParameters());
int nReportsBefore = reportsBefore.Count;
var testInstallation = new Installation
{
InstallationCode = "test",
Expand Down Expand Up @@ -86,10 +84,8 @@ public async Task Create()
};

await _missionRunService.Create(missionRun);
int nReportsAfter = _missionRunService
.ReadAll(new MissionRunQueryStringParameters())
.Result.Count;

var reportsAfter = await _missionRunService.ReadAll(new MissionRunQueryStringParameters());
int nReportsAfter = reportsAfter.Count;
Assert.Equal(nReportsBefore + 1, nReportsAfter);
}
}
Expand Down
6 changes: 4 additions & 2 deletions backend/api.test/Services/RobotService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ public async Task ReadIdDoesNotExist()
public async Task Create()
{
var robotService = new RobotService(_context);
int nRobotsBefore = robotService.ReadAll().Result.Count();
var robotsBefore = await robotService.ReadAll();
int nRobotsBefore = robotsBefore.Count();
var videoStreamQuery = new CreateVideoStreamQuery()
{
Name = "Front Camera",
Expand All @@ -84,7 +85,8 @@ public async Task Create()
robot.Model = robotModel;

await robotService.Create(robot);
int nRobotsAfter = robotService.ReadAll().Result.Count();
var robotsAfter = await robotService.ReadAll();
int nRobotsAfter = robotsAfter.Count();

Assert.Equal(nRobotsBefore + 1, nRobotsAfter);
}
Expand Down
14 changes: 7 additions & 7 deletions backend/api.test/api.test.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
Expand All @@ -10,15 +10,15 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0"/>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.13"/>
<PackageReference Include="Moq" Version="4.18.4"/>
<PackageReference Include="xunit" Version="2.4.2"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2"/>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="7.0.11"/>
<PackageReference Include="Moq" Version="4.20.69"/>
<PackageReference Include="xunit" Version="2.5.1"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="3.1.0">
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
26 changes: 13 additions & 13 deletions backend/api/MQTT/MqttService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,24 @@ public MqttService(ILogger<MqttService> logger, IConfiguration config)
).Equals("Production", StringComparison.OrdinalIgnoreCase);*/

var mqttConfig = config.GetSection("Mqtt");
string password = mqttConfig.GetValue<string>("Password");
string username = mqttConfig.GetValue<string>("Username");
_serverHost = mqttConfig.GetValue<string>("Host");
string password = mqttConfig.GetValue<string>("Password") ?? "";
string username = mqttConfig.GetValue<string>("Username") ?? "";
_serverHost = mqttConfig.GetValue<string>("Host") ?? "";
_serverPort = mqttConfig.GetValue<int>("Port");
_maxRetryAttempts = mqttConfig.GetValue<int>("MaxRetryAttempts");
_shouldFailOnMaxRetries = mqttConfig.GetValue<bool>("ShouldFailOnMaxRetries");


var tlsOptions = new MqttClientTlsOptions
{
UseTls = true,
/* Currently disabled to use self-signed certificate in the internal broker communication */
//if (_notProduction)
IgnoreCertificateChainErrors = true
};
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(_serverHost, _serverPort)
.WithTls(
o =>
{
o.UseTls = true;
/* Currently disabled to use self-signed certificate in the internal broker communication */
//if (_notProduction)
o.IgnoreCertificateChainErrors = true;
}
)
.WithTlsOptions(tlsOptions)
.WithCredentials(username, password);

_options = new ManagedMqttClientOptionsBuilder()
Expand All @@ -70,7 +70,7 @@ public MqttService(ILogger<MqttService> logger, IConfiguration config)

RegisterCallbacks();

var topics = mqttConfig.GetSection("Topics").Get<List<string>>();
var topics = mqttConfig.GetSection("Topics").Get<List<string>>() ?? new List<string>();
SubscribeToTopics(topics);
}
public static event EventHandler<MqttReceivedArgs>? MqttIsarRobotStatusReceived;
Expand Down
14 changes: 7 additions & 7 deletions backend/api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches()
.AddDownstreamWebApi(EchoService.ServiceName, builder.Configuration.GetSection("Echo"))
.AddDownstreamWebApi(StidService.ServiceName, builder.Configuration.GetSection("Stid"))
.AddDownstreamWebApi(IsarService.ServiceName, builder.Configuration.GetSection("Isar"));
.AddDownstreamApi(EchoService.ServiceName, builder.Configuration.GetSection("Echo"))
.AddDownstreamApi(StidService.ServiceName, builder.Configuration.GetSection("Stid"))
.AddDownstreamApi(IsarService.ServiceName, builder.Configuration.GetSection("Isar"));

builder.Services.AddAuthorization(
options =>
Expand All @@ -106,8 +106,7 @@
);

var app = builder.Build();

string basePath = builder.Configuration["BackendBaseRoute"];
string basePath = builder.Configuration["BackendBaseRoute"] ?? "";
app.UseSwagger(
c =>
{
Expand Down Expand Up @@ -138,7 +137,7 @@
new Dictionary<string, string>
{
{
"Resource", builder.Configuration["AzureAd:ClientId"]
"Resource", builder.Configuration["AzureAd:ClientId"] ?? throw new ArgumentException("No Azure Ad ClientId")
}
}
);
Expand All @@ -150,10 +149,11 @@
option.AddRedirect("^$", "swagger");
app.UseRewriter(option);

string[] allowedOrigins = builder.Configuration.GetSection("AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
app.UseCors(
corsBuilder =>
corsBuilder
.WithOrigins(builder.Configuration.GetSection("AllowedOrigins").Get<string[]>())
.WithOrigins(allowedOrigins)
.SetIsOriginAllowedToAllowWildcardSubdomains()
.WithExposedHeaders(QueryStringParameters.PaginationHeader)
.AllowAnyHeader()
Expand Down
3 changes: 1 addition & 2 deletions backend/api/Services/CustomMissionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ public string CalculateHashFromTasks(IList<MissionTask> tasks)
}

string json = JsonSerializer.Serialize(genericTasks);
var hasher = SHA256.Create();
byte[] hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(json));
byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes(json));
return BitConverter.ToString(hash).Replace("-", "", StringComparison.CurrentCulture).ToUpperInvariant();
}
}
Expand Down
48 changes: 12 additions & 36 deletions backend/api/Services/EchoService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
using Api.Database.Models;
using Api.Services.Models;
using Api.Utilities;
using Microsoft.Identity.Web;
using Microsoft.Identity.Abstractions;
using Microsoft.IdentityModel.Tokens;
namespace Api.Services
{
Expand All @@ -20,10 +20,10 @@ public interface IEchoService
public class EchoService : IEchoService
{
public const string ServiceName = "EchoApi";
private readonly IDownstreamWebApi _echoApi;
private readonly IDownstreamApi _echoApi;
private readonly ILogger<EchoService> _logger;

public EchoService(IDownstreamWebApi downstreamWebApi, ILogger<EchoService> logger)
public EchoService(IDownstreamApi downstreamWebApi, ILogger<EchoService> logger)
{
_echoApi = downstreamWebApi;
_logger = logger;
Expand All @@ -35,7 +35,7 @@ public async Task<IList<CondensedMissionDefinition>> GetAvailableMissions(string
? "robots/robot-plan?Status=Ready"
: $"robots/robot-plan?InstallationCode={installationCode}&&Status=Ready";

var response = await _echoApi.CallWebApiForUserAsync(
var response = await _echoApi.CallApiForUserAsync(
ServiceName,
options =>
{
Expand All @@ -48,12 +48,7 @@ public async Task<IList<CondensedMissionDefinition>> GetAvailableMissions(string

var echoMissions = await response.Content.ReadFromJsonAsync<
List<EchoMissionResponse>
>();
if (echoMissions is null)
{
throw new JsonException("Failed to deserialize missions from Echo");
}

>() ?? throw new JsonException("Failed to deserialize missions from Echo");
var availableMissions = ProcessAvailableEchoMission(echoMissions);

return availableMissions;
Expand All @@ -63,7 +58,7 @@ public async Task<EchoMission> GetMissionById(int missionId)
{
string relativePath = $"robots/robot-plan/{missionId}";

var response = await _echoApi.CallWebApiForUserAsync(
var response = await _echoApi.CallApiForUserAsync(
ServiceName,
options =>
{
Expand All @@ -74,26 +69,15 @@ public async Task<EchoMission> GetMissionById(int missionId)

response.EnsureSuccessStatusCode();

var echoMission = await response.Content.ReadFromJsonAsync<EchoMissionResponse>();

if (echoMission is null)
{
throw new JsonException("Failed to deserialize mission from Echo");
}

var processedEchoMission = ProcessEchoMission(echoMission);
if (processedEchoMission == null)
{
throw new InvalidDataException($"EchoMission with id: {missionId} is invalid.");
}

var echoMission = await response.Content.ReadFromJsonAsync<EchoMissionResponse>() ?? throw new JsonException("Failed to deserialize mission from Echo");
var processedEchoMission = ProcessEchoMission(echoMission) ?? throw new InvalidDataException($"EchoMission with id: {missionId} is invalid.");
return processedEchoMission;
}

public async Task<IList<EchoPlantInfo>> GetEchoPlantInfos()
{
string relativePath = "plantinfo";
var response = await _echoApi.CallWebApiForUserAsync(
var response = await _echoApi.CallApiForUserAsync(
ServiceName,
options =>
{
Expand All @@ -105,19 +89,15 @@ public async Task<IList<EchoPlantInfo>> GetEchoPlantInfos()
response.EnsureSuccessStatusCode();
var echoPlantInfoResponse = await response.Content.ReadFromJsonAsync<
List<EchoPlantInfoResponse>
>();
if (echoPlantInfoResponse is null)
{
throw new JsonException("Failed to deserialize plant information from Echo");
}
>() ?? throw new JsonException("Failed to deserialize plant information from Echo");
var installations = ProcessEchoPlantInfos(echoPlantInfoResponse);
return installations;
}

public async Task<EchoPoseResponse> GetRobotPoseFromPoseId(int poseId)
{
string relativePath = $"/robots/pose/{poseId}";
var response = await _echoApi.CallWebApiForUserAsync(
var response = await _echoApi.CallApiForUserAsync(
ServiceName,
options =>
{
Expand All @@ -126,11 +106,7 @@ public async Task<EchoPoseResponse> GetRobotPoseFromPoseId(int poseId)
}
);
response.EnsureSuccessStatusCode();
var echoPoseResponse = await response.Content.ReadFromJsonAsync<EchoPoseResponse>();
if (echoPoseResponse is null)
{
throw new JsonException("Failed to deserialize robot pose from Echo");
}
var echoPoseResponse = await response.Content.ReadFromJsonAsync<EchoPoseResponse>() ?? throw new JsonException("Failed to deserialize robot pose from Echo");
return echoPoseResponse;
}

Expand Down
Loading

0 comments on commit 8922c38

Please sign in to comment.