Skip to content

Commit

Permalink
recreate function, move from newtonsoft, add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
eoinobrien committed Jun 30, 2024
1 parent 8614683 commit c8f3a9a
Show file tree
Hide file tree
Showing 27 changed files with 276 additions and 128 deletions.
2 changes: 1 addition & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ dotnet_style_prefer_simplified_interpolation = true:warning
# Implicit and explicit types
# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#implicit-and-explicit-types
csharp_style_var_for_built_in_types = true:warning
csharp_style_var_when_type_is_apparent = false:warning
csharp_style_var_when_type_is_apparent = true:warning
csharp_style_var_elsewhere = false:warning
# Expression-bodied members
# https://docs.microsoft.com/visualstudio/ide/editorconfig-language-conventions#expression-bodied-members
Expand Down
21 changes: 14 additions & 7 deletions LuasAPI.AzureFunction/LuasAPI.AzureFunction.csproj
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<IsPackable>false</IsPackable>
<OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.4.0" />
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.21.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http" Version="3.1.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore" Version="1.2.1" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.17.0" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.22.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.ApplicationInsights" Version="1.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\LuasAPI.NET\LuasAPI.NET.csproj" />
Expand All @@ -23,4 +27,7 @@
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Using Include="System.Threading.ExecutionContext" Alias="ExecutionContext" />
</ItemGroup>
</Project>
64 changes: 31 additions & 33 deletions LuasAPI.AzureFunction/LuasApiFunction.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,37 @@
namespace LuasAPI.AzureFunction
namespace LuasApi.AzureFunction
{
using System;
using System.Linq;
using System.Threading.Tasks;
using LuasAPI.NET;
using LuasAPI.NET.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;

public static class LuasApiFunction
public class LuasApiFunction
{
[FunctionName("GetAllStations")]
public static async Task<IActionResult> GetAllStations(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "stations")] HttpRequest req,
ILogger log)
private readonly ILogger<LuasApiFunction> _logger;

public LuasApiFunction(ILogger<LuasApiFunction> logger)
{
_logger = logger;
}

[Function("GetAllStations")]
public IActionResult GetAllStations([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "stations")] HttpRequest req)
{
log.LogInformation("Get all stations");
this._logger.LogInformation("Get all stations");

Check warning on line 22 in LuasAPI.AzureFunction/LuasApiFunction.cs

View workflow job for this annotation

GitHub Actions / build-and-deploy

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

LuasApi api = new LuasApi();

return new OkObjectResult(api.GetAllStations());
}

[FunctionName("GetStation")]
public static async Task<IActionResult> GetStation(
[Function("GetStation")]
public IActionResult GetStation(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "stations/{stationAbbreviation}")] HttpRequest req,
string stationAbbreviation,
ILogger log)
string stationAbbreviation)
{
log.LogInformation($"Get station for '{stationAbbreviation}'");
this._logger.LogInformation($"Get station for '{stationAbbreviation}'");

Check warning on line 34 in LuasAPI.AzureFunction/LuasApiFunction.cs

View workflow job for this annotation

GitHub Actions / build-and-deploy

For improved performance, use the LoggerMessage delegates instead of calling 'LoggerExtensions.LogInformation(ILogger, string?, params object?[])' (https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1848)

LuasApi api = new LuasApi();

Expand All @@ -42,23 +42,22 @@ public static async Task<IActionResult> GetStation(
}
catch (StationNotFoundException ex)
{
log.LogWarning($"StationNotFoundException for '{stationAbbreviation}'. Exception: {ex}");
this._logger.LogWarning($"StationNotFoundException for '{stationAbbreviation}'. Exception: {ex}");
return new NotFoundObjectResult($"Unable to find station for: '{stationAbbreviation}'");
}
catch (Exception ex)
{
log.LogError($"Unexpected code path '{stationAbbreviation}'. Exception: {ex}");
this._logger.LogError($"Unexpected code path '{stationAbbreviation}'. Exception: {ex}");
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}

[FunctionName("GetStationForecast")]
public static async Task<IActionResult> GetStationForecast(
[Function("GetStationForecast")]
public async Task<IActionResult> GetStationForecast(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "stations/{stationAbbreviation}/forecast")] HttpRequest req,
string stationAbbreviation,
ILogger log)
string stationAbbreviation)
{
log.LogInformation($"Get station forecast for {stationAbbreviation}");
this._logger.LogInformation($"Get station forecast for {stationAbbreviation}");

LuasApi api = new LuasApi();

Expand All @@ -69,22 +68,21 @@ public static async Task<IActionResult> GetStationForecast(
}
catch (StationNotFoundException ex)
{
log.LogWarning($"StationNotFoundException for '{stationAbbreviation}'. Exception: {ex}");
this._logger.LogWarning($"StationNotFoundException for '{stationAbbreviation}'. Exception: {ex}");
return new NotFoundObjectResult($"Unable to find forecast for: '{stationAbbreviation}'");
}
catch (Exception ex)
{
log.LogError($"Exception thrown in GetStationForecast. Exception: {ex}");
this._logger.LogError($"Exception thrown in GetStationForecast. Exception: {ex}");
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}

[FunctionName("GetAllStationsForecast")]
public static async Task<IActionResult> GetAllStationsForecast(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "stations/all/forecast")] HttpRequest req,
ILogger log)
[Function("GetAllStationsForecast")]
public async Task<IActionResult> GetAllStationsForecast(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "stations/all/forecast")] HttpRequest req)
{
log.LogInformation($"Get station forecast for all stations");
this._logger.LogInformation($"Get station forecast for all stations");

LuasApi api = new LuasApi();

Expand All @@ -105,12 +103,12 @@ await Task.WhenAll(
}
catch (StationNotFoundException ex)
{
log.LogWarning($"StationNotFoundException for '{ex.StationThatWasNotFound}'. Exception: {ex}");
this._logger.LogWarning($"StationNotFoundException for '{ex.StationThatWasNotFound}'. Exception: {ex}");
return new NotFoundObjectResult($"Unable to find forecast for: '{ex.StationThatWasNotFound}'");
}
catch (Exception ex)
{
log.LogError($"Exception thrown in GetStationForecast. Exception: {ex}");
this._logger.LogError($"Exception thrown in GetStationForecast. Exception: {ex}");
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
}
Expand Down
14 changes: 14 additions & 0 deletions LuasAPI.AzureFunction/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
.ConfigureFunctionsWebApplication()
.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
})
.Build();

host.Run();

This file was deleted.

11 changes: 11 additions & 0 deletions LuasAPI.AzureFunction/Properties/serviceDependencies.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"dependencies": {
"appInsights1": {
"type": "appInsights"
},
"storage1": {
"type": "storage",
"connectionId": "AzureWebJobsStorage"
}
}
}
11 changes: 11 additions & 0 deletions LuasAPI.AzureFunction/Properties/serviceDependencies.local.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"dependencies": {
"appInsights1": {
"type": "appInsights.sdk"
},
"storage1": {
"type": "storage.emulator",
"connectionId": "AzureWebJobsStorage"
}
}
}
13 changes: 11 additions & 2 deletions LuasAPI.AzureFunction/host.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
{
"version": "2.0"
}
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
},
"enableLiveMetricsFilters": true
}
}
}
6 changes: 3 additions & 3 deletions LuasAPI.NET.Example/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace LuasAPI.NET.Example
{
using System;
using Newtonsoft.Json;
using System.Text.Json;

class Program
{
Expand All @@ -10,10 +10,10 @@ static void Main()
LuasApi api = new LuasApi();
var s = api.GetStation("ABB");

//Console.WriteLine(JsonConvert.SerializeObject(api.GetAllStations()));
//Console.WriteLine(JsonSerializer.Serialize(api.GetAllStations()));
//Console.WriteLine();

Console.WriteLine(JsonConvert.SerializeObject(api.GetForecast(s)));
Console.WriteLine(JsonSerializer.Serialize(api.GetForecast(s)));
}
}
}
2 changes: 0 additions & 2 deletions LuasAPI.NET.Tests/Infrastructure/UnitTestForcastClient.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
namespace LuasAPI.NET.Tests.Infrastructure
{
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using LuasAPI.NET.Infrastructure;
using LuasAPI.NET.Models;
Expand Down
4 changes: 2 additions & 2 deletions LuasAPI.NET.Tests/LuasAPI.NET.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netcoreapp3.1;net5.0;net6.0;net8.0</TargetFrameworks>

<TargetFrameworks>net8.0</TargetFrameworks>
<nullable>enable</nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>

Expand Down
74 changes: 74 additions & 0 deletions LuasAPI.NET.Tests/Models/JsonConverterTestExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Code below from https://khalidabuhakmeh.com/systemtextjson-jsonconverter-test-helpers. Thanks!

namespace LuasAPI.NET.Tests
{
using System.IO;
using System;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;

public static class JsonConverterTestExtensions
{
public static TResult? Read<TResult>(
this JsonConverter<TResult> converter,
string token,
JsonSerializerOptions? options = null)
{
options ??= JsonSerializerOptions.Default;
var bytes = Encoding.UTF8.GetBytes(token);
var reader = new Utf8JsonReader(bytes);
// advance to token
reader.Read();
var result = converter.Read(ref reader, typeof(TResult), options);
// did we get the result?
return result;
}

public static (bool IsSuccessful, TResult? Result) TryRead<TResult>(
this JsonConverter<TResult> converter,
string token,
JsonSerializerOptions? options = null)
{
try
{
var result = Read(converter, token, options);
return (true, result);
}
catch (Exception)
{
return (IsSuccessful: false, Result: default);
}
}

public static string Write<T>(
this JsonConverter<T> converter,
T value,
JsonSerializerOptions? options = null)
{
options ??= JsonSerializerOptions.Default;
using var ms = new MemoryStream();
using var writer = new Utf8JsonWriter(ms);
converter.Write(writer, value, options);
writer.Flush();
var result = Encoding.UTF8.GetString(ms.ToArray());
return result;
}

public static (bool IsSuccessful, string? Result) TryWrite<T>(
this JsonConverter<T> converter,
T value,
JsonSerializerOptions? options = null)
{
try
{
var result = Write(converter, value, options);
return (true, result);
}
catch
{
return (false, null);
}
}
}
}
3 changes: 0 additions & 3 deletions LuasAPI.NET.Tests/Models/StationForcastTests.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
namespace LuasAPI.NET.Tests.Models
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using LuasAPI.NET.Models;
using LuasAPI.NET.Models.RpaApiXml;
using LuasAPI.NET.Tests.StationInformation;
using Newtonsoft.Json;
using Xunit;

public class StationForecastTests
Expand Down
Loading

0 comments on commit c8f3a9a

Please sign in to comment.