├── thumbnail.png ├── appsettings.json ├── aps-simple-viewer-dotnet.csproj ├── Models ├── APS.cs ├── APS.Auth.cs ├── APS.Oss.cs └── APS.Deriv.cs ├── Program.cs ├── Controllers ├── AuthController.cs └── ModelsController.cs ├── Properties └── launchSettings.json ├── wwwroot ├── main.css ├── index.html ├── viewer.js └── main.js ├── LICENSE ├── .vscode ├── launch.json └── tasks.json ├── aps-simple-viewer-dotnet.sln ├── Startup.cs ├── README.md └── .gitignore /thumbnail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/autodesk-platform-services/aps-simple-viewer-dotnet/HEAD/thumbnail.png -------------------------------------------------------------------------------- /appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /aps-simple-viewer-dotnet.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net8.0 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Models/APS.cs: -------------------------------------------------------------------------------- 1 | public partial class APS 2 | { 3 | private readonly string _clientId; 4 | private readonly string _clientSecret; 5 | private readonly string _bucket; 6 | 7 | public APS(string clientId, string clientSecret, string bucket = null) 8 | { 9 | _clientId = clientId; 10 | _clientSecret = clientSecret; 11 | _bucket = string.IsNullOrEmpty(bucket) ? string.Format("{0}-basic-app", _clientId.ToLower()) : bucket; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | public class Program 5 | { 6 | public static void Main(string[] args) 7 | { 8 | CreateHostBuilder(args).Build().Run(); 9 | } 10 | 11 | public static IHostBuilder CreateHostBuilder(string[] args) => 12 | Host.CreateDefaultBuilder(args) 13 | .ConfigureWebHostDefaults(webBuilder => 14 | { 15 | webBuilder.UseStartup(); 16 | }); 17 | } 18 | -------------------------------------------------------------------------------- /Controllers/AuthController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Microsoft.AspNetCore.Mvc; 4 | 5 | [ApiController] 6 | [Route("api/[controller]")] 7 | public class AuthController : ControllerBase 8 | { 9 | private readonly APS _aps; 10 | 11 | public AuthController(APS aps) 12 | { 13 | _aps = aps; 14 | } 15 | 16 | [HttpGet("token")] 17 | public async Task GetAccessToken() 18 | { 19 | var token = await _aps.GetPublicToken(); 20 | return Ok(new 21 | { 22 | access_token = token.AccessToken, 23 | expires_in = (long)Math.Round((token.ExpiresAt - DateTime.UtcNow).TotalSeconds) 24 | }); 25 | } 26 | } -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:2543", 8 | "sslPort": 44318 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "aps_simple_viewer_dotnet": { 20 | "commandName": "Project", 21 | "dotnetRunMessages": "true", 22 | "launchBrowser": true, 23 | "hotReloadProfile": "aspnetcore", 24 | "applicationUrl": "http://localhost:8080", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /wwwroot/main.css: -------------------------------------------------------------------------------- 1 | body, html { 2 | margin: 0; 3 | padding: 0; 4 | height: 100vh; 5 | font-family: ArtifaktElement; 6 | } 7 | 8 | #header, #preview, #overlay { 9 | position: absolute; 10 | width: 100%; 11 | } 12 | 13 | #header { 14 | height: 3em; 15 | display: flex; 16 | flex-flow: row nowrap; 17 | justify-content: space-between; 18 | align-items: center; 19 | } 20 | 21 | #preview, #overlay { 22 | top: 3em; 23 | bottom: 0; 24 | } 25 | 26 | #overlay { 27 | z-index: 1; 28 | background-color: rgba(0, 0, 0, 0.5); 29 | padding: 1em; 30 | display: none; 31 | } 32 | 33 | #overlay > .notification { 34 | margin: auto; 35 | padding: 1em; 36 | max-width: 50%; 37 | background: white; 38 | } 39 | 40 | #header > * { 41 | height: 2em; 42 | margin: 0 0.5em; 43 | font-size: 1em; 44 | font-family: ArtifaktElement; 45 | } 46 | 47 | #header .title { 48 | flex: 1 0 auto; 49 | height: auto; 50 | } 51 | 52 | #models { 53 | flex: 0 1 auto; 54 | min-width: 2em; 55 | } 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2024 Autodesk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (web)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/bin/Debug/net8.0/aps-simple-viewer-dotnet.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}", 15 | "stopAtEntry": false, 16 | "serverReadyAction": { 17 | "action": "openExternally", 18 | "pattern": "\\bNow listening on:\\s+(https?://\\S+)" 19 | }, 20 | "env": { 21 | "ASPNETCORE_ENVIRONMENT": "Development" 22 | }, 23 | "sourceFileMap": { 24 | "/Views": "${workspaceFolder}/Views" 25 | } 26 | }, 27 | { 28 | "name": ".NET Core Attach", 29 | "type": "coreclr", 30 | "request": "attach" 31 | } 32 | ] 33 | } -------------------------------------------------------------------------------- /aps-simple-viewer-dotnet.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.002.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "aps-simple-viewer-dotnet", "aps-simple-viewer-dotnet.csproj", "{B3D377FC-2DAD-4545-9186-D330E1278A0A}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {B3D377FC-2DAD-4545-9186-D330E1278A0A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {B3D377FC-2DAD-4545-9186-D330E1278A0A}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {B3D377FC-2DAD-4545-9186-D330E1278A0A}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {B3D377FC-2DAD-4545-9186-D330E1278A0A}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {32E9E2F4-A253-4434-BEA2-D7171148B922} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | Autodesk Platform Services: Simple Viewer 12 | 13 | 14 | 15 | 22 |
23 |
24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Models/APS.Auth.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | using Autodesk.Authentication; 5 | using Autodesk.Authentication.Model; 6 | 7 | public record Token(string AccessToken, DateTime ExpiresAt); 8 | 9 | public partial class APS 10 | { 11 | private Token _internalTokenCache; 12 | private Token _publicTokenCache; 13 | 14 | private async Task GetToken(List scopes) 15 | { 16 | var authenticationClient = new AuthenticationClient(); 17 | var auth = await authenticationClient.GetTwoLeggedTokenAsync(_clientId, _clientSecret, scopes); 18 | return new Token(auth.AccessToken, DateTime.UtcNow.AddSeconds((double)auth.ExpiresIn)); 19 | } 20 | 21 | public async Task GetPublicToken() 22 | { 23 | if (_publicTokenCache == null || _publicTokenCache.ExpiresAt < DateTime.UtcNow) 24 | _publicTokenCache = await GetToken([Scopes.ViewablesRead]); 25 | return _publicTokenCache; 26 | } 27 | 28 | private async Task GetInternalToken() 29 | { 30 | if (_internalTokenCache == null || _internalTokenCache.ExpiresAt < DateTime.UtcNow) 31 | _internalTokenCache = await GetToken([Scopes.BucketCreate, Scopes.BucketRead, Scopes.DataRead, Scopes.DataWrite, Scopes.DataCreate]); 32 | return _internalTokenCache; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/aps-simple-viewer-dotnet.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/aps-simple-viewer-dotnet.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/aps-simple-viewer-dotnet.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /wwwroot/viewer.js: -------------------------------------------------------------------------------- 1 | async function getAccessToken(callback) { 2 | try { 3 | const resp = await fetch('/api/auth/token'); 4 | if (!resp.ok) { 5 | throw new Error(await resp.text()); 6 | } 7 | const { access_token, expires_in } = await resp.json(); 8 | callback(access_token, expires_in); 9 | } catch (err) { 10 | alert('Could not obtain access token. See the console for more details.'); 11 | console.error(err); 12 | } 13 | } 14 | 15 | export function initViewer(container) { 16 | return new Promise(function (resolve, reject) { 17 | Autodesk.Viewing.Initializer({ env: 'AutodeskProduction', getAccessToken }, function () { 18 | const config = { 19 | extensions: ['Autodesk.DocumentBrowser'] 20 | }; 21 | const viewer = new Autodesk.Viewing.GuiViewer3D(container, config); 22 | viewer.start(); 23 | viewer.setTheme('light-theme'); 24 | resolve(viewer); 25 | }); 26 | }); 27 | } 28 | 29 | export function loadModel(viewer, urn) { 30 | return new Promise(function (resolve, reject) { 31 | function onDocumentLoadSuccess(doc) { 32 | resolve(viewer.loadDocumentNode(doc, doc.getRoot().getDefaultGeometry())); 33 | } 34 | function onDocumentLoadFailure(code, message, errors) { 35 | reject({ code, message, errors }); 36 | } 37 | viewer.setLightPreset(0); 38 | Autodesk.Viewing.Document.load('urn:' + urn, onDocumentLoadSuccess, onDocumentLoadFailure); 39 | }); 40 | } 41 | -------------------------------------------------------------------------------- /Controllers/ModelsController.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | 8 | [ApiController] 9 | [Route("api/[controller]")] 10 | public class ModelsController : ControllerBase 11 | { 12 | public record BucketObject(string name, string urn); 13 | 14 | private readonly APS _aps; 15 | 16 | public ModelsController(APS aps) 17 | { 18 | _aps = aps; 19 | } 20 | 21 | [HttpGet()] 22 | public async Task> GetModels() 23 | { 24 | var objects = await _aps.GetObjects(); 25 | return from o in objects 26 | select new BucketObject(o.ObjectKey, APS.Base64Encode(o.ObjectId)); 27 | } 28 | 29 | [HttpGet("{urn}/status")] 30 | public async Task GetModelStatus(string urn) 31 | { 32 | var status = await _aps.GetTranslationStatus(urn); 33 | return status; 34 | } 35 | 36 | public class UploadModelForm 37 | { 38 | [FromForm(Name = "model-zip-entrypoint")] 39 | public string Entrypoint { get; set; } 40 | 41 | [FromForm(Name = "model-file")] 42 | public IFormFile File { get; set; } 43 | } 44 | 45 | [HttpPost(), DisableRequestSizeLimit] 46 | public async Task UploadAndTranslateModel([FromForm] UploadModelForm form) 47 | { 48 | using var stream = form.File.OpenReadStream(); 49 | var obj = await _aps.UploadModel(form.File.FileName, stream); 50 | var job = await _aps.TranslateModel(obj.ObjectId, form.Entrypoint); 51 | return new BucketObject(obj.ObjectKey, job.Urn); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | 8 | public class Startup 9 | { 10 | public Startup(IConfiguration configuration) 11 | { 12 | Configuration = configuration; 13 | } 14 | 15 | public IConfiguration Configuration { get; } 16 | 17 | // This method gets called by the runtime. Use this method to add services to the container. 18 | public void ConfigureServices(IServiceCollection services) 19 | { 20 | services.AddControllers(); 21 | var clientID = Configuration["APS_CLIENT_ID"]; 22 | var clientSecret = Configuration["APS_CLIENT_SECRET"]; 23 | var bucket = Configuration["APS_BUCKET"]; // Optional 24 | if (string.IsNullOrEmpty(clientID) || string.IsNullOrEmpty(clientSecret)) 25 | { 26 | throw new ApplicationException("Missing required environment variables APS_CLIENT_ID or APS_CLIENT_SECRET."); 27 | } 28 | services.AddSingleton(new APS(clientID, clientSecret, bucket)); 29 | } 30 | 31 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 32 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 33 | { 34 | if (env.IsDevelopment()) 35 | { 36 | app.UseDeveloperExceptionPage(); 37 | } 38 | app.UseDefaultFiles(); 39 | app.UseStaticFiles(); 40 | app.UseRouting(); 41 | app.UseEndpoints(endpoints => 42 | { 43 | endpoints.MapControllers(); 44 | }); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /Models/APS.Oss.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Threading.Tasks; 5 | using Autodesk.Oss; 6 | using Autodesk.Oss.Model; 7 | 8 | public partial class APS 9 | { 10 | private async Task EnsureBucketExists(string bucketKey) 11 | { 12 | var auth = await GetInternalToken(); 13 | var ossClient = new OssClient(); 14 | try 15 | { 16 | await ossClient.GetBucketDetailsAsync(bucketKey, accessToken: auth.AccessToken); 17 | } 18 | catch (OssApiException ex) 19 | { 20 | if (ex.HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.NotFound) 21 | { 22 | var payload = new CreateBucketsPayload 23 | { 24 | BucketKey = bucketKey, 25 | PolicyKey = PolicyKey.Persistent 26 | }; 27 | await ossClient.CreateBucketAsync(Region.US, payload, auth.AccessToken); 28 | } 29 | else 30 | { 31 | throw; 32 | } 33 | } 34 | } 35 | 36 | public async Task UploadModel(string objectName, Stream stream) 37 | { 38 | await EnsureBucketExists(_bucket); 39 | var auth = await GetInternalToken(); 40 | var ossClient = new OssClient(); 41 | var objectDetails = await ossClient.UploadObjectAsync(_bucket, objectName, stream, accessToken: auth.AccessToken); 42 | return objectDetails; 43 | } 44 | 45 | public async Task> GetObjects() 46 | { 47 | await EnsureBucketExists(_bucket); 48 | var auth = await GetInternalToken(); 49 | var ossClient = new OssClient(); 50 | const int PageSize = 64; 51 | var results = new List(); 52 | var response = await ossClient.GetObjectsAsync(_bucket, PageSize, accessToken: auth.AccessToken); 53 | results.AddRange(response.Items); 54 | while (!string.IsNullOrEmpty(response.Next)) 55 | { 56 | var queryParams = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(new Uri(response.Next).Query); 57 | response = await ossClient.GetObjectsAsync(_bucket, PageSize, startAt: queryParams["startAt"], accessToken: auth.AccessToken); 58 | results.AddRange(response.Items); 59 | } 60 | return results; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /Models/APS.Deriv.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Autodesk.ModelDerivative; 4 | using Autodesk.ModelDerivative.Model; 5 | 6 | public record TranslationStatus(string Status, string Progress, IEnumerable Messages); 7 | 8 | public partial class APS 9 | { 10 | public static string Base64Encode(string plainText) 11 | { 12 | var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText); 13 | return System.Convert.ToBase64String(plainTextBytes).TrimEnd('='); 14 | } 15 | 16 | public async Task TranslateModel(string objectId, string rootFilename) 17 | { 18 | var auth = await GetInternalToken(); 19 | var modelDerivativeClient = new ModelDerivativeClient(); 20 | var payload = new JobPayload 21 | { 22 | Input = new JobPayloadInput 23 | { 24 | Urn = Base64Encode(objectId) 25 | }, 26 | Output = new JobPayloadOutput 27 | { 28 | Formats = 29 | [ 30 | new JobPayloadFormatSVF2 31 | { 32 | Views = [View._2d, View._3d] 33 | } 34 | ] 35 | } 36 | }; 37 | if (!string.IsNullOrEmpty(rootFilename)) 38 | { 39 | payload.Input.RootFilename = rootFilename; 40 | payload.Input.CompressedUrn = true; 41 | } 42 | var job = await modelDerivativeClient.StartJobAsync(jobPayload: payload, region: Region.US, accessToken: auth.AccessToken); 43 | return job; 44 | } 45 | 46 | public async Task GetTranslationStatus(string urn) 47 | { 48 | var auth = await GetInternalToken(); 49 | var modelDerivativeClient = new ModelDerivativeClient(); 50 | try 51 | { 52 | var manifest = await modelDerivativeClient.GetManifestAsync(urn, accessToken: auth.AccessToken); 53 | return new TranslationStatus(manifest.Status, manifest.Progress, []); 54 | } 55 | catch (ModelDerivativeApiException ex) 56 | { 57 | if (ex.HttpResponseMessage.StatusCode == System.Net.HttpStatusCode.NotFound) 58 | { 59 | return new TranslationStatus("n/a", "", null); 60 | } 61 | else 62 | { 63 | throw; 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple Viewer (.NET) 2 | 3 | ![platforms](https://img.shields.io/badge/platform-windows%20%7C%20osx%20%7C%20linux-lightgray.svg) 4 | [![.net](https://img.shields.io/badge/net-6.0-blue.svg)](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) 5 | [![license](https://img.shields.io/:license-mit-green.svg)](https://opensource.org/licenses/MIT) 6 | 7 | [Autodesk Platform Services](https://forge.autodesk.com) application built by following 8 | the [Simple Viewer](https://tutorials.autodesk.io/tutorials/simple-viewer/) tutorial 9 | from https://tutorials.autodesk.io. 10 | 11 | ![thumbnail](thumbnail.png) 12 | 13 | ## Development 14 | 15 | ### Prerequisites 16 | 17 | - [APS credentials](https://forge.autodesk.com/en/docs/oauth/v2/tutorials/create-app) 18 | - [.NET 8](https://dotnet.microsoft.com/en-us/download/dotnet/8.0) 19 | - Command-line terminal such as [PowerShell](https://learn.microsoft.com/en-us/powershell/scripting/overview) 20 | or [bash](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) (should already be available on your system) 21 | 22 | > We recommend using [Visual Studio Code](https://code.visualstudio.com) which, among other benefits, 23 | > provides an [integrated terminal](https://code.visualstudio.com/docs/terminal/basics) as well. 24 | 25 | ### Setup & Run 26 | 27 | - Clone this repository: `git clone https://github.com/autodesk-platform-services/aps-simple-viewer-dotnet` 28 | - Go to the project folder: `cd aps-simple-viewer-dotnet` 29 | - Install .NET dependencies: `dotnet restore` 30 | - Open the project folder in a code editor of your choice 31 | - Create an _appsettings.Development.json_ file in the project folder (if it does not exist already), 32 | and populate it with the JSON snippet below, replacing `` and `` 33 | with your APS Client ID and Client Secret: 34 | 35 | ```json 36 | { 37 | "Logging": { 38 | "LogLevel": { 39 | "Default": "Information", 40 | "Microsoft.AspNetCore": "Warning" 41 | } 42 | }, 43 | "APS_CLIENT_ID": "", 44 | "APS_CLIENT_SECRET": "" 45 | } 46 | ``` 47 | 48 | - Run the application, either from your code editor, or by running `dotnet run` in terminal 49 | - Open http://localhost:8080 50 | 51 | > When using [Visual Studio Code](https://code.visualstudio.com), you can run & debug 52 | > the application by pressing `F5`. 53 | 54 | ## Troubleshooting 55 | 56 | ### Invalid active developer path 57 | 58 | If you're getting `invalid active developer path` errors, please follow the steps 59 | explained in https://apple.stackexchange.com/questions/254380/why-am-i-getting-an-invalid-active-developer-path-when-attempting-to-use-git-a. 60 | 61 | ### Dev-certs errors 62 | 63 | If you're seeing errors related to `dev-certs`, try cleaning any existing certificates 64 | as explained in https://docs.microsoft.com/en-us/dotnet/core/additional-tools/self-signed-certificates-guide, 65 | and on macOS and Windows systems, do not forget to use the `--trust` switch. 66 | 67 | If you have any other question, please contact us via https://forge.autodesk.com/en/support/get-help. 68 | 69 | ## License 70 | 71 | This sample is licensed under the terms of the [MIT License](http://opensource.org/licenses/MIT). 72 | Please see the [LICENSE](LICENSE) file for more details. 73 | -------------------------------------------------------------------------------- /wwwroot/main.js: -------------------------------------------------------------------------------- 1 | import { initViewer, loadModel } from './viewer.js'; 2 | 3 | initViewer(document.getElementById('preview')).then(viewer => { 4 | const urn = window.location.hash?.substring(1); 5 | setupModelSelection(viewer, urn); 6 | setupModelUpload(viewer); 7 | }); 8 | 9 | async function setupModelSelection(viewer, selectedUrn) { 10 | const dropdown = document.getElementById('models'); 11 | dropdown.innerHTML = ''; 12 | try { 13 | const resp = await fetch('/api/models'); 14 | if (!resp.ok) { 15 | throw new Error(await resp.text()); 16 | } 17 | const models = await resp.json(); 18 | dropdown.innerHTML = models.map(model => ``).join('\n'); 19 | dropdown.onchange = () => onModelSelected(viewer, dropdown.value); 20 | if (dropdown.value) { 21 | onModelSelected(viewer, dropdown.value); 22 | } 23 | } catch (err) { 24 | alert('Could not list models. See the console for more details.'); 25 | console.error(err); 26 | } 27 | } 28 | 29 | async function setupModelUpload(viewer) { 30 | const upload = document.getElementById('upload'); 31 | const input = document.getElementById('input'); 32 | const models = document.getElementById('models'); 33 | upload.onclick = () => input.click(); 34 | input.onchange = async () => { 35 | const file = input.files[0]; 36 | let data = new FormData(); 37 | data.append('model-file', file); 38 | if (file.name.endsWith('.zip')) { // When uploading a zip file, ask for the main design file in the archive 39 | const entrypoint = window.prompt('Please enter the filename of the main design inside the archive.'); 40 | data.append('model-zip-entrypoint', entrypoint); 41 | } 42 | upload.setAttribute('disabled', 'true'); 43 | models.setAttribute('disabled', 'true'); 44 | showNotification(`Uploading model ${file.name}. Do not reload the page.`); 45 | try { 46 | const resp = await fetch('/api/models', { method: 'POST', body: data }); 47 | if (!resp.ok) { 48 | throw new Error(await resp.text()); 49 | } 50 | const model = await resp.json(); 51 | setupModelSelection(viewer, model.urn); 52 | } catch (err) { 53 | alert(`Could not upload model ${file.name}. See the console for more details.`); 54 | console.error(err); 55 | } finally { 56 | clearNotification(); 57 | upload.removeAttribute('disabled'); 58 | models.removeAttribute('disabled'); 59 | input.value = ''; 60 | } 61 | }; 62 | } 63 | 64 | async function onModelSelected(viewer, urn) { 65 | if (window.onModelSelectedTimeout) { 66 | clearTimeout(window.onModelSelectedTimeout); 67 | delete window.onModelSelectedTimeout; 68 | } 69 | window.location.hash = urn; 70 | try { 71 | const resp = await fetch(`/api/models/${urn}/status`); 72 | if (!resp.ok) { 73 | throw new Error(await resp.text()); 74 | } 75 | const status = await resp.json(); 76 | switch (status.status) { 77 | case 'n/a': 78 | showNotification(`Model has not been translated.`); 79 | break; 80 | case 'inprogress': 81 | showNotification(`Model is being translated (${status.progress})...`); 82 | window.onModelSelectedTimeout = setTimeout(onModelSelected, 5000, viewer, urn); 83 | break; 84 | case 'failed': 85 | showNotification(`Translation failed.
    ${status.messages.map(msg => `
  • ${JSON.stringify(msg)}
  • `).join('')}
`); 86 | break; 87 | default: 88 | clearNotification(); 89 | loadModel(viewer, urn); 90 | break; 91 | } 92 | } catch (err) { 93 | alert('Could not load model. See the console for more details.'); 94 | console.error(err); 95 | } 96 | } 97 | 98 | function showNotification(message) { 99 | const overlay = document.getElementById('overlay'); 100 | overlay.innerHTML = `
${message}
`; 101 | overlay.style.display = 'flex'; 102 | } 103 | 104 | function clearNotification() { 105 | const overlay = document.getElementById('overlay'); 106 | overlay.innerHTML = ''; 107 | overlay.style.display = 'none'; 108 | } 109 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | 33 | # Visual Studio 2015/2017 cache/options directory 34 | .vs/ 35 | # Uncomment if you have tasks that create the project's static files in wwwroot 36 | #wwwroot/ 37 | 38 | # Visual Studio 2017 auto generated files 39 | Generated\ Files/ 40 | 41 | # MSTest test Results 42 | [Tt]est[Rr]esult*/ 43 | [Bb]uild[Ll]og.* 44 | 45 | # NUNIT 46 | *.VisualState.xml 47 | TestResult.xml 48 | 49 | # Build Results of an ATL Project 50 | [Dd]ebugPS/ 51 | [Rr]eleasePS/ 52 | dlldata.c 53 | 54 | # Benchmark Results 55 | BenchmarkDotNet.Artifacts/ 56 | 57 | # .NET Core 58 | project.lock.json 59 | project.fragment.lock.json 60 | artifacts/ 61 | 62 | # StyleCop 63 | StyleCopReport.xml 64 | 65 | # Files built by Visual Studio 66 | *_i.c 67 | *_p.c 68 | *_h.h 69 | *.ilk 70 | *.meta 71 | *.obj 72 | *.iobj 73 | *.pch 74 | *.pdb 75 | *.ipdb 76 | *.pgc 77 | *.pgd 78 | *.rsp 79 | *.sbr 80 | *.tlb 81 | *.tli 82 | *.tlh 83 | *.tmp 84 | *.tmp_proj 85 | *_wpftmp.csproj 86 | *.log 87 | *.vspscc 88 | *.vssscc 89 | .builds 90 | *.pidb 91 | *.svclog 92 | *.scc 93 | 94 | # Chutzpah Test files 95 | _Chutzpah* 96 | 97 | # Visual C++ cache files 98 | ipch/ 99 | *.aps 100 | *.ncb 101 | *.opendb 102 | *.opensdf 103 | *.sdf 104 | *.cachefile 105 | *.VC.db 106 | *.VC.VC.opendb 107 | 108 | # Visual Studio profiler 109 | *.psess 110 | *.vsp 111 | *.vspx 112 | *.sap 113 | 114 | # Visual Studio Trace Files 115 | *.e2e 116 | 117 | # TFS 2012 Local Workspace 118 | $tf/ 119 | 120 | # Guidance Automation Toolkit 121 | *.gpState 122 | 123 | # ReSharper is a .NET coding add-in 124 | _ReSharper*/ 125 | *.[Rr]e[Ss]harper 126 | *.DotSettings.user 127 | 128 | # JustCode is a .NET coding add-in 129 | .JustCode 130 | 131 | # TeamCity is a build add-in 132 | _TeamCity* 133 | 134 | # DotCover is a Code Coverage Tool 135 | *.dotCover 136 | 137 | # AxoCover is a Code Coverage Tool 138 | .axoCover/* 139 | !.axoCover/settings.json 140 | 141 | # Visual Studio code coverage results 142 | *.coverage 143 | *.coveragexml 144 | 145 | # NCrunch 146 | _NCrunch_* 147 | .*crunch*.local.xml 148 | nCrunchTemp_* 149 | 150 | # MightyMoose 151 | *.mm.* 152 | AutoTest.Net/ 153 | 154 | # Web workbench (sass) 155 | .sass-cache/ 156 | 157 | # Installshield output folder 158 | [Ee]xpress/ 159 | 160 | # DocProject is a documentation generator add-in 161 | DocProject/buildhelp/ 162 | DocProject/Help/*.HxT 163 | DocProject/Help/*.HxC 164 | DocProject/Help/*.hhc 165 | DocProject/Help/*.hhk 166 | DocProject/Help/*.hhp 167 | DocProject/Help/Html2 168 | DocProject/Help/html 169 | 170 | # Click-Once directory 171 | publish/ 172 | 173 | # Publish Web Output 174 | *.[Pp]ublish.xml 175 | *.azurePubxml 176 | # Note: Comment the next line if you want to checkin your web deploy settings, 177 | # but database connection strings (with potential passwords) will be unencrypted 178 | *.pubxml 179 | *.publishproj 180 | 181 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 182 | # checkin your Azure Web App publish settings, but sensitive information contained 183 | # in these scripts will be unencrypted 184 | PublishScripts/ 185 | 186 | # NuGet Packages 187 | *.nupkg 188 | # The packages folder can be ignored because of Package Restore 189 | **/[Pp]ackages/* 190 | # except build/, which is used as an MSBuild target. 191 | !**/[Pp]ackages/build/ 192 | # Uncomment if necessary however generally it will be regenerated when needed 193 | #!**/[Pp]ackages/repositories.config 194 | # NuGet v3's project.json files produces more ignorable files 195 | *.nuget.props 196 | *.nuget.targets 197 | 198 | # Microsoft Azure Build Output 199 | csx/ 200 | *.build.csdef 201 | 202 | # Microsoft Azure Emulator 203 | ecf/ 204 | rcf/ 205 | 206 | # Windows Store app package directories and files 207 | AppPackages/ 208 | BundleArtifacts/ 209 | Package.StoreAssociation.xml 210 | _pkginfo.txt 211 | *.appx 212 | *.appxbundle 213 | *.appxupload 214 | 215 | # Visual Studio cache files 216 | # files ending in .cache can be ignored 217 | *.[Cc]ache 218 | # but keep track of directories ending in .cache 219 | !?*.[Cc]ache/ 220 | 221 | # Others 222 | ClientBin/ 223 | ~$* 224 | *~ 225 | *.dbmdl 226 | *.dbproj.schemaview 227 | *.jfm 228 | *.pfx 229 | *.publishsettings 230 | orleans.codegen.cs 231 | 232 | # Including strong name files can present a security risk 233 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 234 | #*.snk 235 | 236 | # Since there are multiple workflows, uncomment next line to ignore bower_components 237 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 238 | #bower_components/ 239 | 240 | # RIA/Silverlight projects 241 | Generated_Code/ 242 | 243 | # Backup & report files from converting an old project file 244 | # to a newer Visual Studio version. Backup files are not needed, 245 | # because we have git ;-) 246 | _UpgradeReport_Files/ 247 | Backup*/ 248 | UpgradeLog*.XML 249 | UpgradeLog*.htm 250 | ServiceFabricBackup/ 251 | *.rptproj.bak 252 | 253 | # SQL Server files 254 | *.mdf 255 | *.ldf 256 | *.ndf 257 | 258 | # Business Intelligence projects 259 | *.rdl.data 260 | *.bim.layout 261 | *.bim_*.settings 262 | *.rptproj.rsuser 263 | *- Backup*.rdl 264 | 265 | # Microsoft Fakes 266 | FakesAssemblies/ 267 | 268 | # GhostDoc plugin setting file 269 | *.GhostDoc.xml 270 | 271 | # Node.js Tools for Visual Studio 272 | .ntvs_analysis.dat 273 | node_modules/ 274 | 275 | # Visual Studio 6 build log 276 | *.plg 277 | 278 | # Visual Studio 6 workspace options file 279 | *.opt 280 | 281 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 282 | *.vbw 283 | 284 | # Visual Studio LightSwitch build output 285 | **/*.HTMLClient/GeneratedArtifacts 286 | **/*.DesktopClient/GeneratedArtifacts 287 | **/*.DesktopClient/ModelManifest.xml 288 | **/*.Server/GeneratedArtifacts 289 | **/*.Server/ModelManifest.xml 290 | _Pvt_Extensions 291 | 292 | # Paket dependency manager 293 | .paket/paket.exe 294 | paket-files/ 295 | 296 | # FAKE - F# Make 297 | .fake/ 298 | 299 | # CodeRush personal settings 300 | .cr/personal 301 | 302 | # Python Tools for Visual Studio (PTVS) 303 | __pycache__/ 304 | *.pyc 305 | 306 | # Cake - Uncomment if you are using it 307 | # tools/** 308 | # !tools/packages.config 309 | 310 | # Tabs Studio 311 | *.tss 312 | 313 | # Telerik's JustMock configuration file 314 | *.jmconfig 315 | 316 | # BizTalk build output 317 | *.btp.cs 318 | *.btm.cs 319 | *.odx.cs 320 | *.xsd.cs 321 | 322 | # OpenCover UI analysis results 323 | OpenCover/ 324 | 325 | # Azure Stream Analytics local run output 326 | ASALocalRun/ 327 | 328 | # MSBuild Binary and Structured Log 329 | *.binlog 330 | 331 | # NVidia Nsight GPU debugger configuration file 332 | *.nvuser 333 | 334 | # MFractors (Xamarin productivity tool) working folder 335 | .mfractor/ 336 | 337 | # Local History for Visual Studio 338 | .localhistory/ 339 | 340 | # BeatPulse healthcheck temp database 341 | healthchecksdb 342 | 343 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 344 | MigrationBackup/ 345 | 346 | ## 347 | ## Visual studio for Mac 348 | ## 349 | 350 | 351 | # globs 352 | Makefile.in 353 | *.userprefs 354 | *.usertasks 355 | config.make 356 | config.status 357 | aclocal.m4 358 | install-sh 359 | autom4te.cache/ 360 | *.tar.gz 361 | tarballs/ 362 | test-results/ 363 | 364 | # Mac bundle stuff 365 | *.dmg 366 | *.app 367 | 368 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 369 | # General 370 | .DS_Store 371 | .AppleDouble 372 | .LSOverride 373 | 374 | # Icon must end with two \r 375 | Icon 376 | 377 | 378 | # Thumbnails 379 | ._* 380 | 381 | # Files that might appear in the root of a volume 382 | .DocumentRevisions-V100 383 | .fseventsd 384 | .Spotlight-V100 385 | .TemporaryItems 386 | .Trashes 387 | .VolumeIcon.icns 388 | .com.apple.timemachine.donotpresent 389 | 390 | # Directories potentially created on remote AFP share 391 | .AppleDB 392 | .AppleDesktop 393 | Network Trash Folder 394 | Temporary Items 395 | .apdisk 396 | 397 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 398 | # Windows thumbnail cache files 399 | Thumbs.db 400 | ehthumbs.db 401 | ehthumbs_vista.db 402 | 403 | # Dump file 404 | *.stackdump 405 | 406 | # Folder config file 407 | [Dd]esktop.ini 408 | 409 | # Recycle Bin used on file shares 410 | $RECYCLE.BIN/ 411 | 412 | # Windows Installer files 413 | *.cab 414 | *.msi 415 | *.msix 416 | *.msm 417 | *.msp 418 | 419 | # Windows shortcuts 420 | *.lnk 421 | 422 | # JetBrains Rider 423 | .idea/ 424 | *.sln.iml 425 | 426 | ## 427 | ## Visual Studio Code 428 | ## 429 | .vscode/* 430 | !.vscode/settings.json 431 | !.vscode/tasks.json 432 | !.vscode/launch.json 433 | !.vscode/extensions.json 434 | 435 | ## Custom 436 | .env 437 | appsettings.Development.json --------------------------------------------------------------------------------