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

Implementation of #47, #48, #49 for Feature #46 #50

Merged
merged 2 commits into from
May 18, 2021
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
Binary file modified .vs/amos-ss2021-carbon-footprint/v16/.suo
Binary file not shown.
Binary file modified .vs/slnx.sqlite
Binary file not shown.
1 change: 1 addition & 0 deletions backend/Backend/Backend.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="AspNetCore.Proxy" Version="4.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>
Expand Down
54 changes: 17 additions & 37 deletions backend/Backend/Controllers/SimaProController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,56 +5,36 @@
using System.Linq;
using System.Threading.Tasks;

using Backend.Services;
using System.Net.Http;
using Microsoft.Extensions.Primitives;
using AspNetCore.Proxy;
using AspNetCore.Proxy.Options;

namespace Backend.Controllers
{
[Route("api/[controller]")]
[Route("[controller]/api")]
[ApiController]
public class SimaProController : ControllerBase
{
SimaProQueryService _simaProQueryService;
//Use the SimaPro client that has been registered at startup.
//using the login from the SimaProLoginDelegatingHandler in Starup.cs
private HttpProxyOptions httpProxyOptions = HttpProxyOptionsBuilder.Instance
.WithHttpClientName("SimaProClient")
.Build();

public SimaProController(SimaProQueryService simaProQueryService)
public SimaProController()
{
_simaProQueryService = simaProQueryService;
}

[HttpGet]
public async Task<IActionResult> GetTest()
/* Http proxy request controller.
to process all the http requests using one connection.
Takes every request in the route so that we can avoid additional endpoints.
*/
[Route("{**rest}")]
public Task ProxyCatchAll(string rest)
{
var response = await _simaProQueryService.TestAsync();
this.HttpContext.Response.RegisterForDispose(response);
return new HttpResponseMessageResult(response);
var queryString = this.Request.QueryString.Value;
return this.HttpProxyAsync($"{rest}{queryString}", httpProxyOptions);
}

//copy paste from stackoverflow to build the new response from the response the backend got from the api
public class HttpResponseMessageResult : IActionResult
{
private readonly HttpResponseMessage _responseMessage;

public HttpResponseMessageResult(HttpResponseMessage responseMessage)
{
_responseMessage = responseMessage; // could add throw if null
}

public async Task ExecuteResultAsync(ActionContext context)
{
context.HttpContext.Response.StatusCode = (int)_responseMessage.StatusCode;

foreach (var header in _responseMessage.Headers)
{
context.HttpContext.Response.Headers.TryAdd(header.Key, new StringValues(header.Value.ToArray()));
}

using (var stream = await _responseMessage.Content.ReadAsStreamAsync())
{
await stream.CopyToAsync(context.HttpContext.Response.Body);
await context.HttpContext.Response.Body.FlushAsync();
}
}
}
}
}
4 changes: 2 additions & 2 deletions backend/Backend/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchBrowser": false,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
Expand All @@ -20,7 +20,7 @@
"Backend": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launchBrowser": false,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
Expand Down
6 changes: 4 additions & 2 deletions backend/Backend/Security/SimaProLoginDelegatingHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,19 @@ public class SimaProLoginDelegatingHandler : DelegatingHandler
private readonly string simaProPassword;

private string accessToken = "";

//Gets the credentials from Environment variables.
public SimaProLoginDelegatingHandler(IConfiguration configuration)
{
baseUrl = Environment.GetEnvironmentVariable("BaseUrl") ?? configuration["BaseUrl"];
simaProUser = Environment.GetEnvironmentVariable("User") ?? configuration["User"];
simaProPassword = Environment.GetEnvironmentVariable("Password") ?? configuration["Password"];
}

//This will be called everytime a http request comes through HttpClient.
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
//Get a new access token if the access token expires/not available.
if (accessToken != "")
{
//use token if we already have one
Expand Down Expand Up @@ -57,7 +59,7 @@ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage
}), Encoding.UTF8, "application/json")
};
var loginResponse = await base.SendAsync(loginRequest, cancellationToken);

if (loginResponse.IsSuccessStatusCode)
{

Expand Down
23 changes: 0 additions & 23 deletions backend/Backend/Services/SimaProQueryService.cs

This file was deleted.

23 changes: 13 additions & 10 deletions backend/Backend/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
using AspNetCore.Proxy;
using Backend.Security;
using Backend.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -35,14 +36,15 @@ public void ConfigureServices(IServiceCollection services)
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Backend", Version = "v1" });
});

services.AddProxies();
//Used to get the authenticate/process the Http requests.
services.AddTransient<SimaProLoginDelegatingHandler>();
services.AddHttpClient<SimaProQueryService>(
client =>
{
var baseUrl = Environment.GetEnvironmentVariable("BaseUrl") ?? Configuration["BaseUrl"];
client.BaseAddress = new Uri(baseUrl);
//client.Timeout = TimeSpan.FromSeconds(30);
})
services.AddHttpClient("SimaProClient",
client => {
var baseUrl = Environment.GetEnvironmentVariable("BaseUrl") ?? Configuration["BaseUrl"];
client.BaseAddress = new Uri(baseUrl);
//client.Timeout = TimeSpan.FromSeconds(30);
})
.AddHttpMessageHandler<SimaProLoginDelegatingHandler>();
}

Expand All @@ -52,8 +54,8 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Backend v1"));
//app.UseSwagger();
//app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Backend v1"));
}

app.UseHttpsRedirection();
Expand All @@ -67,5 +69,6 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
endpoints.MapControllers();
});
}

}
}