Commit fb665064 authored by Jason Ouellet's avatar Jason Ouellet

Conversion à .NET Core 2.2 (afin de pouvoir compiler avec OpenShift)

Correction problèmes de conversions et communications entre le service Here et l'API
parent 129b535c
Pipeline #11148 failed with stages
<?xml version="1.0"?>
<doc>
<assembly>
<name>Here</name>
</assembly>
<members>
</members>
</doc>
using Here.Api.Properties;
using Here.Geocoder;
using Here.Geocoder;
using Here.Models;
using Here.Options.Geocoder;
using Here.Options.Route;
using Here.Route;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
......@@ -17,27 +15,24 @@ namespace Here.Api.Controllers
/// <summary>
///
/// </summary>
[Route("api/[controller]")]
[ApiController]
[FormatFilter]
[Route("api/[controller]")]
public class HereController : ControllerBase
{
private readonly ILogger<HereController> _logger;
private readonly IConfiguration _config;
private readonly IHereRouteTruckService _routeSrv;
private readonly IHereGeocodeService _geoSrv;
public HereController(ILogger<HereController> logger, IConfiguration config, IHereRouteTruckService routeSrv, IHereGeocodeService geoSrv)
public HereController(IConfiguration config, IHereRouteTruckService routeSrv, IHereGeocodeService geoSrv)
{
_config = config;
_logger = logger;
_routeSrv = routeSrv;
_geoSrv = geoSrv;
}
// GET: api/Here
[HttpGet("{format?}")]
[HttpGet]
[Produces("application/json")]
public async Task<IActionResult> GetAsync()
{
HttpClient client = new HttpClient();
......@@ -81,6 +76,5 @@ namespace Here.Api.Controllers
client.Dispose();
return retour;
}
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
<UserSecretsId>db90d3fd-c30e-4a8f-be61-382200637cac</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<AssemblyName>Here</AssemblyName>
......@@ -17,18 +17,21 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.5-beta1.final">
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.ViewFeatures" Version="2.2.0" />
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.5" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.4" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0-rc3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0-rc3" />
</ItemGroup>
......
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace Here
{
public static class Program
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
CreateWebHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
\ No newline at end of file
......@@ -4,10 +4,11 @@ using Here.Route;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
using System;
namespace Here
......@@ -16,68 +17,62 @@ namespace Here
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration env)
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
public static void ConfigureServices(IServiceCollection services, IWebHostEnvironment env)
public void ConfigureServices(IServiceCollection services)//, IHostingEnvironment env)
{
services.AddControllers(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
})
.AddXmlSerializerFormatters()
.AddJsonOptions(options =>
{
// Use the default property (Pascal) casing.
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.WriteIndented = true;
});
//.AddNewtonsoftJson(options =>
// {
// // Use the default property (Pascal) casing
// //options.SerializerSettings.ContractResolver = new DefautlContractResolver();
// options.UseCamelCasing(true);
// options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
// });
services.AddMvcCore(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
}
)
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddApiExplorer()
.AddXmlSerializerFormatters()
.AddJsonFormatters();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Here Middleware", Version = "v1" });
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Here API Middleware", Version = "v1" });
});
services.AddScoped<IHereConfig, HereConfig>();
services.AddScoped<IHereRouteTruckService, HereRouteTruckService>();
services.AddScoped<IHereGeocodeService, HereGeocodeService>();
if (!env.IsDevelopment())
{
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
options.HttpsPort = 443;
});
//if (!env.IsDevelopment())
//{
// services.AddHttpsRedirection(options =>
// {
// options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
// options.HttpsPort = 443;
// });
//}
//else
//{
services.AddHsts(options =>
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(60);
options.ExcludedHosts.Add("example.com");
options.ExcludedHosts.Add("www.example.com");
});
}
{
options.Preload = true;
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromDays(60);
});
//}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
......@@ -86,21 +81,23 @@ namespace Here
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Here API Middleware");
c.RoutePrefix = string.Empty;
});
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseHsts();
app.UseMvc();
app.UseRouting();
//app.UseRouting();
app.UseAuthorization();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//app.UseEndpointRouting(endpoints =>
//{
// endpoints.MapControllers();
//});
}
}
}
\ No newline at end of file
......@@ -11,7 +11,7 @@ namespace Here.Geocoder
{
public class HereGeocodeService : HereService, IHereGeocodeService
{
public HereGeocodeService(IConfiguration config) : base(config, "GeoSrv")
public HereGeocodeService(IConfiguration config) : base(config, "GeocoderSvc")
{
}
......@@ -44,7 +44,7 @@ namespace Here.Geocoder
{
//TODO: Doit être traité et retourné dans un RouteCamionModel
//Newtonsoft.Json.JO
JObject retourJson = (JObject)JToken.Parse(response.Content.ReadAsStringAsync().Result).SelectToken("Response.View[*].Result[*].Location.NavigationPosition[*]");
JObject retourJson = (JObject)JToken.Parse(response.Content.ReadAsStringAsync().Result).SelectToken("Response.View[*].Result[0].Location.NavigationPosition[*]");
retour = new Localisation(retourJson.SelectToken("Latitude").Value<decimal>(),
retourJson.SelectToken("Longitude").Value<decimal>()
);
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
<RootNamespace>Here</RootNamespace>
</PropertyGroup>
......@@ -10,10 +10,10 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3-beta2" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.2.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup>
</Project>
......@@ -22,9 +22,9 @@ namespace Here
throw new ArgumentException(string.Format("Le service Here à utiliser doit être spécifié {0} correctement dans la configuration", service), nameof(service));
}
AppId = config.GetSection("HereConfig:HereAppId").Value;
AppCode = config.GetSection("HereConfig:HereAppCode").Value;
Uri = config.GetSection(string.Format("HereConfig:HereServices:{0}", service)).Value;
AppId = config.GetSection("HereConfig:AppId").Value;
AppCode = config.GetSection("HereConfig:AppCode").Value;
Uri = config.GetSection(string.Format("HereConfig:UriServices:{0}", service)).Value;
Valider();
}
......
......@@ -12,5 +12,10 @@ namespace Here
Latitude = latitude;
Longitude = longitude;
}
public override string ToString()
{
return this.GetPointString();
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Text;
namespace Here.Models
{
public class CalculDistanceRetourModel
{
public int Distance { get; set; }
public TimeSpan Delais { get; set; }
public void SetDelais(int Delaissecondes)
{
Delais = TimeSpan.FromSeconds(Delaissecondes);
}
public string DelaisStr()
{
return string.Format("{0:D2}h{1:D2}",
Delais.Hours,
Delais.Minutes);
}
public string Notes { get; set; }
}
}
......@@ -13,7 +13,7 @@
{
Depart = new AdresseModel() { NoCivique = 337, Rue = "Morreault", Ville = "Rimouski", Pays = "CAN" };
Destination = new AdresseModel() { NoCivique = 150, Rue = "René-Lévesque", Ville = "Québec", Pays = "CAN" };
Poids = 50000;
Poids = 1000;
Longueur = 14;
Largeur = 2;
}
......
......@@ -21,12 +21,12 @@ namespace Here.Params
public T[] Valeurs { get; set; }
public string ValeurStr
public string ValeurStr => string.Join(";", Valeurs.Select(v => v.ToString()).ToArray());
public override string ToString()
{
get
{
return string.Join(" ", Valeurs.Select(v => v.ToString()).ToArray());
}
return string.Format("{0}={1}", Nom, ValeurStr);
}
}
}
\ No newline at end of file
......@@ -18,7 +18,7 @@ namespace Here.Params
public T Valeur { get; set; }
public string Nom { get; private set; }
public string ValeurStr { get { return string.Format("{0}", Valeur); } }
public virtual string ValeurStr => string.Format("{0}", Valeur);
public override string ToString()
{
......
......@@ -6,9 +6,7 @@
{
}
public override string ToString()
{
return base.ToString().ToLower();
}
public override string ValeurStr => string.Format("{0}", Valeur.ToString().ToLower());
}
}
\ No newline at end of file
......@@ -4,7 +4,7 @@ namespace Here.Services
{
public class HereRouteService : HereService
{
public HereRouteService(IConfiguration config) : base(config, "RouteSrv")
public HereRouteService(IConfiguration config) : base(config, "RouteSvc")
{
}
......
using Here.Options.Route;
using Here.Models;
using Here.Options.Route;
using Here.Services;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
......@@ -24,24 +26,28 @@ namespace Here.Route
//TODO: À changer pour un string builder
UriBuilder uri = new UriBuilder(Uri);
uri.Query = string.Format("app_id={0}&app_code={1}{2}", AppId, AppCode, options.ToString());
uri.Query = string.Format("app_id={0}&app_code={1}&{2}", AppId, AppCode, options.ToString());
return uri.Uri;
}
public async Task<string> ObtenirDistanceAsync(RouteOptions options)
public async Task<CalculDistanceRetourModel> ObtenirDistanceAsync(RouteOptions options)
{
HttpClient client = new HttpClient();
//Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
string retour;
CalculDistanceRetourModel retour;
var response = await client.GetAsync(ObtenirUri(options)).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
//TODO: Doit être traité et retourné dans un RouteCamionModel
retour = response.Content.ReadAsStringAsync().Result.ToString();
JObject retourJson = (JObject)JToken.Parse(response.Content.ReadAsStringAsync().Result);
retour = new CalculDistanceRetourModel();
retour.Distance = retourJson.SelectToken("response.route[0].summary.distance").Value<int>();
retour.SetDelais(retourJson.SelectToken("response.route[0].summary.baseTime").Value<int>());
retour.Notes = retourJson.ToString();
}
else
{
......
using Here.Options.Route;
using Here.Models;
using Here.Options.Route;
using System.Threading.Tasks;
namespace Here.Route
{
public interface IHereRouteTruckService
{
Task<string> ObtenirDistanceAsync(RouteOptions options);
Task<CalculDistanceRetourModel> ObtenirDistanceAsync(RouteOptions options);
}
}
\ No newline at end of file
......@@ -4,7 +4,7 @@ namespace Here.Options.Route
{
public static class ModeExtensions
{
public static string ToString(this Mode mode)
public static string ToValueString(this Mode mode)
{
switch (mode)
{
......
using Here.Params;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Here.Options.Route
{
......@@ -44,7 +45,7 @@ namespace Here.Options.Route
if (valeurs == null || valeurs.Length <= 0) throw new ArgumentNullException(nameof(valeurs));
string nom = "mode";
var param = new ParamsArray<Mode>(nom, valeurs);
var param = new ParamsArray<string>(nom, valeurs.Select(v => v.ToValueString()).ToArray());
if (!tpParams.Parametres.TryAdd(nom, param))
{
......
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netcoreapp2.2</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment