From cefa63b78b109f99cd27378d5a6b0f6285194d52 Mon Sep 17 00:00:00 2001 From: Kelly Nelson <31662976+knelson-farmbeltnorth@users.noreply.github.com> Date: Thu, 13 Jan 2022 13:17:37 -0600 Subject: [PATCH] Adding prototype converter --- .gitignore | 136 ++++------------------ Converter.cs | 122 +++++++++++++++++++ Properties/serviceDependencies.json | 11 ++ Properties/serviceDependencies.local.json | 11 ++ ShippedItemInstanceConverter.csproj | 23 ++++ ShippedItemInstanceConverter.sln | 25 ++++ host.json | 11 ++ 7 files changed, 228 insertions(+), 111 deletions(-) create mode 100644 Converter.cs create mode 100644 Properties/serviceDependencies.json create mode 100644 Properties/serviceDependencies.local.json create mode 100644 ShippedItemInstanceConverter.csproj create mode 100644 ShippedItemInstanceConverter.sln create mode 100644 host.json diff --git a/.gitignore b/.gitignore index dfcfd56..ff5b00c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,10 @@ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# Azure Functions localsettings file +local.settings.json # User-specific files -*.rsuser *.suo *.user *.userosscache @@ -13,9 +13,6 @@ # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs -# Mono auto generated files -mono_crash.* - # Build results [Dd]ebug/ [Dd]ebugPublic/ @@ -23,58 +20,42 @@ mono_crash.* [Rr]eleases/ x64/ x86/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ -[Ll]ogs/ -# Visual Studio 2015/2017 cache/options directory +# Visual Studio 2015 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ -# Visual Studio 2017 auto generated files -Generated\ Files/ - # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* -# NUnit +# NUNIT *.VisualState.xml TestResult.xml -nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core +# DNX project.lock.json project.fragment.lock.json artifacts/ -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio *_i.c *_p.c -*_h.h +*_i.h *.ilk *.meta *.obj -*.iobj *.pch *.pdb -*.ipdb *.pgc *.pgd *.rsp @@ -84,7 +65,6 @@ StyleCopReport.xml *.tlh *.tmp *.tmp_proj -*_wpftmp.csproj *.log *.vspscc *.vssscc @@ -113,9 +93,6 @@ ipch/ *.vspx *.sap -# Visual Studio Trace Files -*.e2e - # TFS 2012 Local Workspace $tf/ @@ -127,20 +104,15 @@ _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user +# JustCode is a .NET coding add-in +.JustCode + # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - # NCrunch _NCrunch_* .*crunch*.local.xml @@ -172,9 +144,9 @@ publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, +# TODO: Comment the next line if you want to checkin your web deploy settings # but database connection strings (with potential passwords) will be unencrypted -*.pubxml +#*.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to @@ -184,15 +156,13 @@ PublishScripts/ # NuGet Packages *.nupkg -# NuGet Symbol Packages -*.snupkg # The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* +**/packages/* # except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ +!**/packages/build/ # Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files *.nuget.props *.nuget.targets @@ -209,15 +179,12 @@ AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt -*.appx -*.appxbundle -*.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache -!?*.[Cc]ache/ +!*.[Cc]ache/ # Others ClientBin/ @@ -228,12 +195,9 @@ ClientBin/ *.jfm *.pfx *.publishsettings +node_modules/ orleans.codegen.cs -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ @@ -248,22 +212,15 @@ _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak # SQL Server files *.mdf *.ldf -*.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ @@ -273,7 +230,6 @@ FakesAssemblies/ # Node.js Tools for Visual Studio .ntvs_analysis.dat -node_modules/ # Visual Studio 6 build log *.plg @@ -281,9 +237,6 @@ node_modules/ # Visual Studio 6 workspace options file *.opt -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts @@ -299,52 +252,13 @@ paket-files/ # FAKE - F# Make .fake/ -# CodeRush personal settings -.cr/personal +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ +*.pyc \ No newline at end of file diff --git a/Converter.cs b/Converter.cs new file mode 100644 index 0000000..c78221c --- /dev/null +++ b/Converter.cs @@ -0,0 +1,122 @@ +using System; +using System.IO; +using System.Net; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Enums; +using Microsoft.Extensions.Logging; +using Microsoft.OpenApi.Models; +using Newtonsoft.Json; + +namespace ShippedItemInstanceConverter +{ + public class Converter + { + private readonly ILogger _logger; + + public Converter(ILogger log) + { + _logger = log; + } + + [FunctionName("Converter")] + [OpenApiOperation(operationId: "Run", tags: new[] { "name" })] + [OpenApiSecurity("function_key", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)] + [OpenApiResponseWithBody(statusCode: HttpStatusCode.OK, contentType: "text/plain", bodyType: typeof(string), Description = "The OK response")] + public async Task Run( + [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ExecutionContext executionContext) + { + _logger.LogInformation("C# HTTP trigger function processed a request."); + + bool nativeOut = false; + bool isoOut = false; + bool admOut = false; + if (req.Headers.TryGetValue("content-type", out Microsoft.Extensions.Primitives.StringValues contentHeaders)) + { + //Determine output type from header + if (contentHeaders.Contains("application/vnd.aggateway.adapt.iso+zip")) + { + isoOut = true; + } + else if (contentHeaders.Contains("application/vnd.aggateway.adapt.adm+zip")) + { + admOut = true; + } + else + { + nativeOut = true; + } + + //Read the input shipped item instance input from the request body + string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); + string input = JsonConvert.DeserializeObject(requestBody).ToString(); + input = input.Replace("\r\n", string.Empty).Replace("\t", string.Empty).Replace(" ", string.Empty); //Remove whitespace in the request as desired + + //Override the default location of the ADAPT resource files to accomodate placement within Azure function + AgGateway.ADAPT.Representation.UnitSystem.UnitSystemManager.UnitSystemDataLocation = System.IO.Path.Combine(executionContext.FunctionDirectory, "../Resources", "UnitSystem.xml"); + AgGateway.ADAPT.Representation.RepresentationSystem.RepresentationManager.RepresentationSystemDataLocation = System.IO.Path.Combine(executionContext.FunctionDirectory, "../Resources", "RepresentationSystem.xml"); + AgGateway.ADAPT.ISOv4Plugin.Representation.DdiLoader.DDIDataFile = System.IO.Path.Combine(executionContext.FunctionDirectory, "../Resources", "ddiExport.txt"); + AgGateway.ADAPT.ISOv4Plugin.Representation.IsoUnitOfMeasureList.ISOUOMDataFile = System.IO.Path.Combine(executionContext.FunctionDirectory, "../Resources", "IsoUnitOfMeasure.xml"); + + //Write the input to a file so that the ShippedItemInstance plugin can read it + string folder = System.IO.Path.GetTempPath(); + string tempPath = Path.Combine(folder, "input.json"); + File.WriteAllText(tempPath, input); + + //Read the input data + AgGateway.ADAPT.ShippedItemInstancePlugin.Plugin p = new AgGateway.ADAPT.ShippedItemInstancePlugin.Plugin(); + var admList = p.Import(folder); + + if (admList.Count == 1) //We assume the caller is requesting one document at a time + { + var inputData = admList[0]; + + string outputPath = Path.Combine(folder, "output"); + if (Directory.Exists(outputPath)) + { + Directory.Delete(outputPath, true); + } + Directory.CreateDirectory(outputPath); + + string outputZip = Path.Combine(folder, "output.zip"); + if (File.Exists(outputZip)) + { + File.Delete(outputZip); + } + + if (nativeOut) + { + return new OkObjectResult(input); //Just returning the json in the body + } + else + { + if (isoOut) + { + AgGateway.ADAPT.ISOv4Plugin.Plugin isoPlugin = new AgGateway.ADAPT.ISOv4Plugin.Plugin(); + isoPlugin.Export(inputData, outputPath, new AgGateway.ADAPT.ApplicationDataModel.ADM.Properties()); + } + else if (admOut) + { + AgGateway.ADAPT.ADMPlugin.Plugin admPlugin = new AgGateway.ADAPT.ADMPlugin.Plugin(); + admPlugin.Export(inputData, outputPath); + } + + System.IO.Compression.ZipFile.CreateFromDirectory(outputPath, outputZip); + return new FileContentResult(File.ReadAllBytes(outputZip), "application/octet-stream"); + } + } + else //Multiple documents not supported at this time. Otherwise input not valid. + { + return new BadRequestResult(); + } + } + return new BadRequestResult(); //Likely no valid content header or malformed request body + } + } +} + diff --git a/Properties/serviceDependencies.json b/Properties/serviceDependencies.json new file mode 100644 index 0000000..df4dcc9 --- /dev/null +++ b/Properties/serviceDependencies.json @@ -0,0 +1,11 @@ +{ + "dependencies": { + "appInsights1": { + "type": "appInsights" + }, + "storage1": { + "type": "storage", + "connectionId": "AzureWebJobsStorage" + } + } +} \ No newline at end of file diff --git a/Properties/serviceDependencies.local.json b/Properties/serviceDependencies.local.json new file mode 100644 index 0000000..b804a28 --- /dev/null +++ b/Properties/serviceDependencies.local.json @@ -0,0 +1,11 @@ +{ + "dependencies": { + "appInsights1": { + "type": "appInsights.sdk" + }, + "storage1": { + "type": "storage.emulator", + "connectionId": "AzureWebJobsStorage" + } + } +} \ No newline at end of file diff --git a/ShippedItemInstanceConverter.csproj b/ShippedItemInstanceConverter.csproj new file mode 100644 index 0000000..9ad12b4 --- /dev/null +++ b/ShippedItemInstanceConverter.csproj @@ -0,0 +1,23 @@ + + + net6.0 + v4 + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + Never + + + diff --git a/ShippedItemInstanceConverter.sln b/ShippedItemInstanceConverter.sln new file mode 100644 index 0000000..faabd0b --- /dev/null +++ b/ShippedItemInstanceConverter.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31919.166 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShippedItemInstanceConverter", "ShippedItemInstanceConverter.csproj", "{A91BCF27-B192-415A-9932-71ABA02C1526}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A91BCF27-B192-415A-9932-71ABA02C1526}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A91BCF27-B192-415A-9932-71ABA02C1526}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A91BCF27-B192-415A-9932-71ABA02C1526}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A91BCF27-B192-415A-9932-71ABA02C1526}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EEEDCA61-C747-4A6A-A03D-2785443F2A9B} + EndGlobalSection +EndGlobal diff --git a/host.json b/host.json new file mode 100644 index 0000000..beb2e40 --- /dev/null +++ b/host.json @@ -0,0 +1,11 @@ +{ + "version": "2.0", + "logging": { + "applicationInsights": { + "samplingSettings": { + "isEnabled": true, + "excludedTypes": "Request" + } + } + } +} \ No newline at end of file