public async Task StartDesignCheck(string userId, string hubId, string projectId, string versionId, string contentRootPath) { // uncomment these lines to clear all appbundles & activities under your account //await _designAutomation.DeleteForgeAppAsync("me"); Credentials credentials = await Credentials.FromDatabaseAsync(userId); await EnsureAppBundle(contentRootPath); await EnsureActivity(); string resultFilename = versionId.Base64Encode() + ".txt"; string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/{1}/{2}/{3}/{4}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), userId, hubId, projectId, versionId.Base64Encode()); WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityFullName, Arguments = new Dictionary <string, IArgument>() { { "rvtFile", await BuildDownloadURL(credentials.TokenInternal, projectId, versionId) }, { "result", await BuildUploadURL(resultFilename) }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); }
protected async Task <WorkItemStatus> SubmitWorkitem(Credentials credentials, string projectId, string versionId, string resultFilename, string callbackUrl) { WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityFullName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", await BuildDownloadURL(credentials.TokenInternal, projectId, versionId) }, { "result", await BuildUploadURL(resultFilename) }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; return(await _designAutomation.CreateWorkItemAsync(workItemSpec)); }
public async Task StartUploadFamily(string userId, string projectId, string versionId, string contentRootPath) { // uncomment these lines to clear all appbundles & activities under your account //await _designAutomation.DeleteForgeAppAsync("me"); Credentials credentials = await Credentials.FromDatabaseAsync(userId); // find Revit files on the folder where the IPT is List <string> rvtFilesOnFolder = await GetRevitFileVersionId(projectId, Utils.Base64Decode(versionId), credentials.TokenInternal); // check Design Automation for Revit setup await EnsureAppBundle(contentRootPath); await EnsureActivity(); await EnsureTemplateExists(contentRootPath); // at this point we're triggering one Design Automation workItem for each RVT file on the folder, // which can be expensive, so better to filter out... for this sample, let's just do it foreach (string fileInFolder in rvtFilesOnFolder) { StorageInfo info = await PreWorkNewVersion(credentials.TokenInternal, projectId, fileInFolder); string satFileName = versionId + ".sat"; string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/revit/{1}/{2}/{3}/{4}/{5}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), userId, projectId, info.itemId.Base64Encode(), info.storageId.Base64Encode(), info.fileName.Base64Encode()); WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityFullName, Arguments = new Dictionary <string, IArgument>() { { "rvtFile", await BuildBIM360DownloadURL(credentials.TokenInternal, projectId, fileInFolder) }, { "inputGeometry", await BuildS3DownloadURL(satFileName) }, { "familyTemplate", await BuildS3DownloadURL(RFA_TEMPLATE) }, { "result", await BuildBIM360UploadURL(credentials.TokenInternal, info) }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); } }
public async Task RunWorkItemAsync() { dynamic oauth = await OAuthController.GetInternalAsync(); var nickname = await GetNicknameAsync(); string bucketKey = nickname.ToLower() + BucketKey; // create work item var wi = new WorkItem { ActivityId = await GetFullActivityId(), Arguments = GetWorkItemArgs(bucketKey, ObjectName, ParamFile, ResultFile, oauth.access_token) }; // run WI and wait for completion var status = await Client.CreateWorkItemAsync(wi); Console.WriteLine($"Created WI {status.Id}"); while (status.Status == Status.Pending || status.Status == Status.Inprogress) { Console.Write("."); Thread.Sleep(2000); status = await Client.GetWorkitemStatusAsync(status.Id); } Console.WriteLine(); Console.WriteLine($"WI {status.Id} completed with {status.Status}"); Console.WriteLine(); // dump report var client = new HttpClient(); var report = await client.GetStringAsync(status.ReportUrl); var oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write(report); Console.ForegroundColor = oldColor; Console.WriteLine(); }
private async Task <dynamic> GetWorkItemId(XrefTreeArgument inputFileArgument, XrefTreeArgument outputFileArgument, XrefTreeArgument inputJsonArgument, string callbackUrl, string ActivityId) { WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityId, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _repository.CreateWorkItem(workItemSpec); return(new { WorkItemId = workItemStatus.Id }); }
public async Task StartDWGValidation(string bucketKey, string objectName, string contentRootPath, string connectionId) { // check Design Automation for Revit setup await EnsureAppBundle(contentRootPath); await EnsureActivity(); string resultJson = objectName.Replace(".dwg", ".json"); string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/autocad/{1}/{2}", Utils.GetAppSetting("FORGE_WEBHOOK_URL"), connectionId, resultJson); WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityFullName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", BuildDownloadURL((await OAuthController2L.GetInternalAsync()).access_token, bucketKey, objectName) }, { "results", await BuildUploadURL(resultJson) }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); }
private async Task <string> CreateWorkItem(JObject input, Dictionary <string, string> headers, string browerConnectionId, string outputName, string fileName, string url) { input["output"] = outputName; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json," + input.ToString(Formatting.None) }; XrefTreeArgument outputArgument = new XrefTreeArgument() { Url = url, Verb = Verb.Put, Headers = headers }; string callbackComplete = string.Format( "{0}/api/forge/callback/oncomplete?id={1}&outputFile={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, fileName); WorkItem workItemSpec = new WorkItem() { ActivityId = QualifiedBundleActivityName, Arguments = new Dictionary <string, IArgument>() { { "inputJson", inputJsonArgument }, { outputName, outputArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackComplete } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(workItemStatus.Id); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { // basic input validation WorkItemStatus workItemStatus = null; JObject workItemData = JObject.Parse(input.data); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); string fileType = workItemData["fileType"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>()); List <string> activityList = await GetDefinedActivities(); if (!activityList.Contains(workItemData["activityName"].Value <string>())) { await CreateAppBundle(); await CreateActivity(fileType); } if (fileType == "assembly") { string path = _env.ContentRootPath; Trace.TraceInformation("Zipping started"); string fileSavePath = await CreateZipFileStreamAsync(input.inputFile, input.inputFiles, path); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "-designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(fileSavePath)); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), PathInZip = input.inputFile.FileName, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. output file //string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding //string outputFileNameOSS = string.Format("{0}_output_{1}.zip", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding string outputFileNameOSS = string.Format("{0}_output_{1}.zip", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}&name={3}&type={4}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS, Path.GetFileNameWithoutExtension(input.inputFile.FileName), fileType); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); } else if (fileType == "part") { // save the file on the server var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName)); using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "-designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. output file //string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding string outputFileNameOSS = string.Format("{0}_output_{1}.ipt", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}&name={3}&type={4}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS, "", fileType); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); } return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> ExtractParams([FromBody] JObject workItemsSpecs) { // basic input validation string documentPath = workItemsSpecs["documentPath"].Value <string>(); string projectPath = workItemsSpecs["projectPath"].Value <string>(); string inputFile = workItemsSpecs["inputFile"].Value <string>(); string outputFile = inputFile + ".json"; string browerConnectionId = workItemsSpecs["browerConnectionId"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, "ExtractParams+prod"); string bucketKey = NickName.ToLower() + "_designautomation"; // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFile), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json dynamic inputJson = new JObject(); inputJson.documentPath = documentPath; if (projectPath != "") { inputJson.projectPath = projectPath; } XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFile), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/extractparams?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, HttpUtility.UrlEncode(outputFile)); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputParams", inputJsonArgument }, { "documentParams", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; try { WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { try { DataSetBuilder dataSetBuilder = new DataSetBuilder(LocalDataSetFolder, "DataSet"); dataSetBuilder.SaveJsonData(input.shelfData, "params.json"); dataSetBuilder.ZipFolder("MyWallShelf.zip"); } catch (Exception ex) { return(Ok(new { WorkItemId = ex.Message }));; } JObject connItemData = JObject.Parse(input.forgeData); string uniqueActivityName = string.Format("{0}.{1}+{2}", NickName, ActivityName, Alias); string browerConnectionId = connItemData["browerConnectionId"].Value <string>(); // TODO - this piece of cod will be used for sending picture in Visualization module // save the file on the server var fileSavePath = Path.Combine(LocalDataSetFolder, "MyWallShelf.zip"); //using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, bucketRegion); //TODO - use EMEA buckets also } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "MyShelf.zip"); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); //System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Verb = Verb.Get, LocalName = "Wall_shelf", PathInZip = "MyWallShelf.iam", Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json /*dynamic inputJson = new JObject(); * inputJson.Width = widthParam; * inputJson.Height = heigthParam; * XrefTreeArgument inputJsonArgument = new XrefTreeArgument() * { * Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") * };*/ // 3. output file // TODO - output file name should be passed from client string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "Result.zip"); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 3a. output pdf fajl out of zipping string outputPDFFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "Result.pdf"); // avoid overriding XrefTreeArgument outputPDFFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputPDFFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format( "{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", //OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), "https://webwallshelfbuilder.herokuapp.com", browerConnectionId, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = uniqueActivityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, //{ "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "outputPDFFile", outputPDFFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; try { WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); } catch (Exception e) { return(Ok(new { WorkItemId = e.Message })); } }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "workitem")] HttpRequest req, [Table("token", "token", "token", Connection = "StorageConnectionString")] Token token, [Table("workItems", Connection = "StorageConnectionString")] IAsyncCollector <WorkItemStatusEntity> workItemsTable, ILogger log) { log.LogInformation("C# HTTP trigger function processed CreateWorkItem."); try { Autodesk.Forge.Client.Configuration.Default.AccessToken = token.ForgeToken.access_token; // Parse the body of the request string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); WorkItemDescription workItemDescription = JsonConvert.DeserializeObject <WorkItemDescription>(requestBody); int existingCredits = await _utilities.GetConversionCredits(workItemDescription.userId); if (existingCredits > 0) { // Create two signed URLs to upload the file to the activity and download the result ObjectsApi apiInstance = new ObjectsApi(); string rvtBucketKey = Environment.GetEnvironmentVariable("rvtStorageKey"); // string | URL-encoded bucket key string ifcBucketKey = Environment.GetEnvironmentVariable("ifcStorageKey"); // string | URL-encoded bucket key string inputObjectName = workItemDescription.inputObjectName; // string | URL-encoded object name string outputObjectName = workItemDescription.outputObjectName; string onCompleteCallbackUrl = Environment.GetEnvironmentVariable("api_uri") + "/api/onworkitemcomplete"; PostBucketsSigned postBucketsSigned = new PostBucketsSigned(60 * 24 * 30); DynamicJsonResponse dynamicJsonResponseDownload = await apiInstance.CreateSignedResourceAsync(rvtBucketKey, inputObjectName, postBucketsSigned, "read"); PostObjectSigned downloadSigned = dynamicJsonResponseDownload.ToObject <PostObjectSigned>(); DynamicJsonResponse dynamicJsonResponseUpload = await apiInstance.CreateSignedResourceAsync(ifcBucketKey, outputObjectName, postBucketsSigned, "readwrite"); PostObjectSigned uploadSigned = dynamicJsonResponseUpload.ToObject <PostObjectSigned>(); Autodesk.Forge.DesignAutomation.Model.WorkItem workItem = new Autodesk.Forge.DesignAutomation.Model.WorkItem() { ActivityId = workItemDescription.activityId, Arguments = new Dictionary <string, IArgument> { { "rvtFile", new XrefTreeArgument() { Url = downloadSigned.SignedUrl } }, { "result", new XrefTreeArgument { Verb = Verb.Put, Url = uploadSigned.SignedUrl } }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = onCompleteCallbackUrl } } } }; Autodesk.Forge.Core.ApiResponse <WorkItemStatus> workItemResponse = await _workItemApi.CreateWorkItemAsync(workItem); // ApiResponse<Page<string>> page = await _engineApi.GetEnginesAsync(); WorkItemStatus workItemStatusCreationResponse = workItemResponse.Content; WorkItemStatusEntity WorkItemStatusObject = Mappings.ToWorkItemStatusEntity( workItemStatusCreationResponse, workItemDescription.userId, workItemDescription.fileSize, workItemDescription.version, workItemDescription.fileName, uploadSigned.SignedUrl, downloadSigned.SignedUrl); await workItemsTable.AddAsync(WorkItemStatusObject); WorkItemStatusResponse workItemStatusResponse = new WorkItemStatusResponse() { WorkItemId = workItemResponse.Content.Id, OutputUrl = uploadSigned.SignedUrl, WorkItemCreationStatus = WorkItemCreationStatus.Created }; return(new OkObjectResult(workItemStatusResponse)); } else { WorkItemStatusResponse workItemStatusResponse = new WorkItemStatusResponse() { WorkItemId = null, OutputUrl = null, WorkItemCreationStatus = WorkItemCreationStatus.NotEnoughCredit }; return(new OkObjectResult(workItemStatusResponse)); } } catch (Exception ex) { return(new BadRequestObjectResult(ex)); } }
public async Task <IActionResult> UpdateModel([FromBody] JObject workItemsSpecs) { // basic input validation string widthParam = workItemsSpecs["width"].Value <string>(); string heigthParam = workItemsSpecs["height"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, "UpdateModel"); string browerConnectionId = workItemsSpecs["browerConnectionId"].Value <string>(); string inputFileNameOSS = ""; string outputFileNameOSS = ""; // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "_designautomation"; // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json dynamic inputJson = new JObject(); inputJson.Width = widthParam; inputJson.Height = heigthParam; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); if (Credentials == null) { return(null); } // basic input validation JObject workItemData = JObject.Parse(input.data); string inputRvtFileName = workItemData["inputRvtFileName"].Value <string>(); string inputRvtFileUrl = workItemData["inputRvtFileUrl"].Value <string>(); string inputFamilyFileName = workItemData["inputFamilyFileName"].Value <string>(); string inputFamilyFileUrl = workItemData["inputFamilyFileUrl"].Value <string>(); string outputFolderUrl = workItemData["outputFolderUrl"].Value <string>(); string roomUniquId = workItemData["roomUniquId"].Value <string>(); string gridTypeId = workItemData["gridTypeId"].Value <string>(); string distanceXMinParam = workItemData["distanceXMinParam"].Value <string>(); string distanceXMaxParam = workItemData["distanceXMaxParam"].Value <string>(); string distanceYMinParam = workItemData["distanceYMinParam"].Value <string>(); string distanceYMaxParam = workItemData["distanceYMaxParam"].Value <string>(); string distanceWallMinParam = workItemData["distanceWallMinParam"].Value <string>(); string distanceWallMaxParam = workItemData["distanceWallMaxParam"].Value <string>(); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>()); // OAuth token dynamic da4rToken = Credentials.DA4RTokenInternal; dynamic userToken = Credentials.TokenInternal; VersionsApi versionApi = new VersionsApi(); versionApi.Configuration.AccessToken = Credentials.TokenInternal; // Revit file download URL string[] revitFileParams = inputRvtFileUrl.Split('/'); string revitFileProjectIdParam = revitFileParams[1]; string revitFileVersionIdParam = revitFileParams[2]; dynamic revitFileVersion = await versionApi.GetVersionAsync(revitFileProjectIdParam, revitFileVersionIdParam); string[] revitFileVersionStorageParams = ((string)revitFileVersion.data.relationships.storage.data.id).Split('/'); string[] revitFileBucketKeyParams = revitFileVersionStorageParams[revitFileVersionStorageParams.Length - 2].Split(':'); string revitFileBucketKey = revitFileBucketKeyParams[revitFileBucketKeyParams.Length - 1]; string revitFileObjectName = revitFileVersionStorageParams[revitFileVersionStorageParams.Length - 1]; string revitFileDownloadUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", revitFileBucketKey, revitFileObjectName); // Family file download URL string[] familyFileParams = inputFamilyFileUrl.Split('/'); string familyFileProjectIdParam = familyFileParams[1]; string familyFileVersionIdParam = familyFileParams[2]; dynamic familyFileVersion = await versionApi.GetVersionAsync(familyFileProjectIdParam, familyFileVersionIdParam); string[] familyFileVersionStorageParams = ((string)familyFileVersion.data.relationships.storage.data.id).Split('/'); string[] familyFileBucketKeyParams = familyFileVersionStorageParams[familyFileVersionStorageParams.Length - 2].Split(':'); string familyFileBucketKey = familyFileBucketKeyParams[familyFileBucketKeyParams.Length - 1]; string familyFileObjectName = familyFileVersionStorageParams[familyFileVersionStorageParams.Length - 1]; string familyFileDownloadUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", familyFileBucketKey, familyFileObjectName); // prepare workitem arguments // 1. input file XrefTreeArgument inputRevitFileArgument = new XrefTreeArgument() { Url = string.Format(revitFileDownloadUrl), Verb = Verb.Get, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + userToken } } }; XrefTreeArgument inputFamilyFileArgument = new XrefTreeArgument() { Url = string.Format(familyFileDownloadUrl), Verb = Verb.Get, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + userToken } } }; // 2. input json dynamic inputJson = new JObject(); inputJson.RoomUniqueId = roomUniquId; inputJson.GridTypeId = gridTypeId; inputJson.FamilyFileName = inputFamilyFileName; inputJson.OutputZipFileName = "exportedDwgs"; inputJson.DistanceXMinParam = distanceXMinParam; inputJson.DistanceXMaxParam = distanceXMaxParam; inputJson.DistanceYMinParam = distanceYMinParam; inputJson.DistanceYMaxParam = distanceYMaxParam; inputJson.DistanceWallMinParam = distanceWallMinParam; inputJson.DistanceWallMaxParam = distanceWallMaxParam; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file string[] folderParams = outputFolderUrl.Split('/'); string outputFolderId = folderParams[folderParams.Length - 1]; string outputProjectId = folderParams[folderParams.Length - 3]; dynamic storageCreatedZip = await this.CreateStorage(outputFolderId, outputProjectId, "exportedDwgs" + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"); string[] zipFileStorageIdParams = ((string)storageCreatedZip.data.id).Split('/'); string[] zipFileBucketKeyParams = zipFileStorageIdParams[zipFileStorageIdParams.Length - 2].Split(':'); string zipFileBucketKey = zipFileBucketKeyParams[zipFileBucketKeyParams.Length - 1]; string zipFileObjectName = zipFileStorageIdParams[zipFileStorageIdParams.Length - 1]; string uploadZipFileUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", zipFileBucketKey, zipFileObjectName); XrefTreeArgument outputZipFileArgument = new XrefTreeArgument() { Url = uploadZipFileUrl, Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + userToken } } }; // prepare & submit workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/grid_object_placement?id={1}&zipFileName={2}&zipFileBucketKey={3}&zipFileObjectName={4}&zipStorageId={5}&projectId={6}&folderId={7}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, "exportedDwgs.zip", zipFileBucketKey, zipFileObjectName, (string)storageCreatedZip.data.id, outputProjectId, outputFolderId); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputRvtFile", inputRevitFileArgument }, { "inputFamilyFile", inputFamilyFileArgument }, { "inputJsonFile", inputJsonArgument }, { "resultZipFile", outputZipFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = null; try { workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); } catch (Exception e) { string message = e.Message; } return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> StartWorkItem([FromForm] StartWorkitemInput input) //public async Task<IActionResult> StartWorkItem(string id) { // OAuth token // Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); string id = $"https://developer.api.autodesk.com/data/v1/projects/b.9f77180c-7cd1-40d8-9d70-d80608dfdfd9/items/urn:adsk.wipprod:dm.lineage:SXwSwlsTT_GkrOQ3GXtDUA"; // extract the projectId & itemId from the href ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; string[] idParams = id.Split('/'); string itemId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; dynamic item = await itemApi.GetItemAsync(projectId, itemId); List <int?> filterVersionNumber = new List <int?>() { 1 }; var versions = await itemApi.GetItemVersionsAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id; string displayFileName = item.data.attributes.displayName; string versionId = null; foreach (KeyValuePair <string, dynamic> version in new DynamicDictionaryItems(versions.data)) { DateTime versionDate = version.Value.attributes.lastModifiedTime; string verNum = version.Value.id.Split("=")[1]; string userName = version.Value.attributes.lastModifiedUserName; versionId = version.Value.id; string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { } } // // basic input validation JObject workItemData = JObject.Parse(input.data); string widthParam = workItemData["width"].Value <string>(); string heigthParam = workItemData["height"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>()); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); // save the file on the server var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName)); using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "_designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = credentials.TokenInternal; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = credentials.TokenInternal; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + credentials.TokenInternal } } }; //XrefTreeArgument inputFileArgument = BuildBIM360DownloadURL(oauth.access_token, projectId, versionId); // 2. input json dynamic inputJson = new JObject(); inputJson.Width = widthParam; inputJson.Height = heigthParam; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + credentials.TokenInternal } } }; // prepare & submit workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> StartWorkItem([FromForm] StartWorkitemInput input) { // basic input validation string activityName = string.Format("{0}.{1}", NickName, input.activityId); string browerConnectionId = input.browerConnectionId; string bucketKey = input.bucketId; string inputFileNameOSS = input.objectId; bool isCount = input.activityId.ToLower() == "countitactivity+dev"; // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + (input.data.Replace("\"", "'")) }; // 3. output file string outputFileNameOSS = null; if (isCount) { outputFileNameOSS = string.Format("{0}_{1}.txt", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileNameWithoutExtension(inputFileNameOSS)); // avoid overriding } else { outputFileNameOSS = string.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(inputFileNameOSS)); // avoid overriding } XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&bucketKey={2}&outputFileName={3}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, bucketKey, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { isCount? "outputTxt": "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
//public async Task<IActionResult> Testing(string id) public async Task <IList <jsTreeNode> > Testing(string id) { IList <jsTreeNode> nodes = new List <jsTreeNode>(); // the API SDK Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies); ItemsApi itemApi = new ItemsApi(); itemApi.Configuration.AccessToken = credentials.TokenInternal; // extract the projectId & itemId from the href string[] idParams = id.Split('/'); string itemId = idParams[idParams.Length - 1]; string projectId = idParams[idParams.Length - 3]; var versions = await itemApi.GetItemVersionsAsync(projectId, itemId); dynamic item = await itemApi.GetItemAsync(projectId, itemId); string folderId = item.data.relationships.parent.data.id; string displayFileName = item.data.attributes.displayName; string versionId = null; foreach (KeyValuePair <string, dynamic> version in new DynamicDictionaryItems(versions.data)) { DateTime versionDate = version.Value.attributes.lastModifiedTime; string verNum = version.Value.id.Split("=")[1]; string userName = version.Value.attributes.lastModifiedUserName; versionId = version.Value.id; if (verNum == "1") { break; } string urn = string.Empty; try { urn = (string)version.Value.relationships.derivatives.data.id; } catch { } } //get user id UserController user = new UserController(); user.Credentials = credentials; dynamic userProfile = await user.GetUserProfileAsync(); string userId = userProfile.id; //// Prepare the DA input from BIM 360 //var input = await BuildBIM360DownloadURL(credentials.TokenInternal, projectId, versionId); //// Prepare the DA output to BIM 360 //var storageInfo = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); //string storageId = storageInfo.storageId; //string fileName = storageInfo.fileName; //try //{ // BackgroundJob.Schedule(() => PostProcessFile(credentials.TokenInternal, userId, projectId, itemId, storageId, fileName), TimeSpan.FromSeconds(1)); //} //catch (Exception e) { } // StorageInfo info = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); string callbackUrl = string.Format("{0}/api/forge/callback/designautomation/revit/{1}/{2}/{3}/{4}/{5}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), userId, projectId, info.itemId.Base64Encode(), info.storageId.Base64Encode(), info.fileName.Base64Encode()); WorkItem workItemSpec = new WorkItem() { ActivityId = ActivityFullName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", await BuildBIM360DownloadURL(credentials.TokenInternal, projectId, versionId) }, { "outputFile", await BuildBIM360UploadURL(credentials.TokenInternal, info) }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemsAsync(workItemSpec); try { var storageInfo = await PreWorkNewVersion(credentials.TokenInternal, projectId, versionId); string storageId = storageInfo.storageId; string fileName = storageInfo.fileName; BackgroundJob.Schedule(() => PostProcessFile(credentials.TokenInternal, userId, projectId, itemId, storageId, fileName), TimeSpan.FromSeconds(1)); } catch (Exception e) { } // return(nodes); }
private async Task <IActionResult> PostGoodPractices(string projectId, int version, string hubId, string rvt, string guid) { // basic input validation string activityName = "cyBnhhxpfsbhGC1jv4CdyDSLwj912JA4.UpdateRVTParamActivity+dev"; //var projectId = (string)rvt.projectId; //var version = (int)rvt.version; // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "-designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // prepare workitem arguments // 1. input file //var guid = (string)rvt.guid; var rvtName = rvt;//(string)rvt.rvtName; XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = $"https://developer.api.autodesk.com/oss/v2/buckets/wip.dm.prod/objects/{guid}", LocalName = "myzip", PathInZip = rvtName, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json dynamic inputJson = new JObject(); inputJson.HubId = hubId; inputJson.ProjectId = projectId; inputJson.Version = version; var inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName("OutputFile.json")); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format("{0}/api/forge/callback/mongo?id={1}&outputFileName={2}", Credentials.GetAppSetting("FORGE_WEBHOOK_URL"), "", outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { // basic input validation JObject workItemData = JObject.Parse(input.data); string widthParam = workItemData["width"].Value <string>(); string heigthParam = workItemData["height"].Value <string>(); string activityName = string.Format("{0}.{1}", NickName, workItemData["activityName"].Value <string>()); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); // save the file on the server var fileSavePath = Path.Combine(_env.ContentRootPath, Path.GetFileName(input.inputFile.FileName)); using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); // upload file to OSS Bucket // 1. ensure bucket existis string bucketKey = NickName.ToLower() + "-designautomation"; BucketsApi buckets = new BucketsApi(); buckets.Configuration.AccessToken = oauth.access_token; try { PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient); await buckets.CreateBucketAsync(bucketPayload, "US"); } catch { }; // in case bucket already exists // 2. upload inputFile string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2. input json dynamic inputJson = new JObject(); inputJson.Width = widthParam; inputJson.Height = heigthParam; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // 3. output file string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), Path.GetFileName(input.inputFile.FileName)); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputFileNameOSS); WorkItem workItemSpec = new WorkItem() { ActivityId = activityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
private async Task <string> CreateWorkItem(JToken input, Dictionary <string, string> headers, string browerConnectionId, string inputBucket, string inputName, string outputName, string outputRfaName) { input["output"] = outputName; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json," + input.ToString(Formatting.None) }; string inputUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", inputBucket, inputName); string outputUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", TransientBucketKey, outputName); string outputRfaUrl = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", TransientBucketKey, outputRfaName); XrefTreeArgument inputArgument = new XrefTreeArgument() { Url = inputUrl, Verb = Verb.Get, Headers = headers }; XrefTreeArgument outputArgument = new XrefTreeArgument() { Url = outputUrl, Verb = Verb.Put, Headers = headers }; XrefTreeArgument outputRfaArgument = new XrefTreeArgument() { Url = outputRfaUrl, Verb = Verb.Put, Headers = headers }; string callbackComplete = string.Format( "{0}/api/forge/callback/oncomplete?id={1}&outputFile={2}&outputRfaFile={3}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), browerConnectionId, outputName, outputRfaName); XrefTreeArgument callbackArgument = new XrefTreeArgument { Verb = Verb.Post, Url = callbackComplete }; WorkItem workItemSpec = new WorkItem() { ActivityId = QualifiedBundleActivityName, Arguments = new Dictionary <string, IArgument>() { { "inputZip", inputArgument }, { "inputJson", inputJsonArgument }, { "outputZip", outputArgument }, { "onComplete", callbackArgument } } }; if (outputRfaName != null) { workItemSpec.Arguments.Add("outputRfa", outputRfaArgument); } WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(workItemStatus.Id); }
// <summary> // Creates WorkItem // </summary> private async Task <IActionResult> CreateWorkItem(ModelAttributes param) { // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); string bucketkey = "inventorilogicda" + nickName.ToLower(); string qualifiedActivityId = string.Format("{0}.{1}+{2}", nickName, ACTIVITY_NAME, ALIAS); // input json dynamic inputJson = new JObject(); inputJson.Material = param.color; inputJson.Diameter = param.diameter; inputJson.Spoke_Design = param.rim; inputJson.Width = param.width; inputJson.InputIPT = "RIM.ipt"; inputJson.InputIDW = "RIM.idw"; XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'") }; // output IPT file XrefTreeArgument outputIPTFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketkey, outputIPTFile), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // output IDW file XrefTreeArgument outputIDWFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketkey, outputIDWFile), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // output PDF file XrefTreeArgument outputPDFFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketkey, outputPDFile), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}", OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"), param.browserconnectionId); WorkItem workItemSpec = new WorkItem() { ActivityId = qualifiedActivityId, Arguments = new Dictionary <string, IArgument>() { { "inputJson", inputJsonArgument }, { "ResultIPT", outputIPTFileArgument }, { "ResultIDW", outputIDWFileArgument }, { "ResultPDF", outputPDFFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { WorkItemId = workItemStatus.Id })); }
public async Task <IActionResult> StartWorkitem([FromForm] StartWorkitemInput input) { // basic input validation JObject workItemData = JObject.Parse(input.data); string uniqueActivityName = string.Format("{0}.{1}+{2}", NickName, ActivityName, Alias); string browerConnectionId = workItemData["browerConnectionId"].Value <string>(); // save the file on the server var fileSavePath = Path.Combine(LocalDataSetFolder, "Kitchen.zip"); //using (var stream = new FileStream(fileSavePath, FileMode.Create)) await input.inputFile.CopyToAsync(stream); // OAuth token dynamic oauth = await OAuthController.GetInternalAsync(); string inputFileNameOSS = string.Format("{0}_input_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "Kitchen.zip"); // avoid overriding ObjectsApi objects = new ObjectsApi(); objects.Configuration.AccessToken = oauth.access_token; using (StreamReader streamReader = new StreamReader(fileSavePath)) await objects.UploadObjectAsync(bucketKey, inputFileNameOSS, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream"); //System.IO.File.Delete(fileSavePath);// delete server copy // prepare workitem arguments // 1. input file XrefTreeArgument inputFileArgument = new XrefTreeArgument() { Verb = Verb.Get, LocalName = "Kitchen", PathInZip = "CleanSlate.iam", Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, inputFileNameOSS), Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // 2b. input json from viewer string inputJsonStr = workItemData.ToString(Newtonsoft.Json.Formatting.None).Replace("\"", "'"); XrefTreeArgument inputJsonArgument = new XrefTreeArgument() { Verb = Verb.Get, Url = "data:application/json, " + inputJsonStr }; // 3. output file string outputFileNameOSS = string.Format("{0}_output_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), "Kitchen.zip"); // avoid overriding XrefTreeArgument outputFileArgument = new XrefTreeArgument() { Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS), Verb = Verb.Put, Headers = new Dictionary <string, string>() { { "Authorization", "Bearer " + oauth.access_token } } }; // prepare & submit workitem // the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem string callbackUrl = string.Format( "{0}/api/forge/callback/designautomation?id={1}&outputFileName={2}", /* OAuthController.GetAppSetting("FORGE_WEBHOOK_URL"),*/ "https://webkitchenbuilder.herokuapp.com", browerConnectionId, outputFileNameOSS ); WorkItem workItemSpec = new WorkItem() { ActivityId = uniqueActivityName, Arguments = new Dictionary <string, IArgument>() { { "inputFile", inputFileArgument }, { "inputJson", inputJsonArgument }, { "outputFile", outputFileArgument }, { "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } } } }; try { WorkItemStatus workItemStatus = await _designAutomation.CreateWorkItemAsync(workItemSpec); return(Ok(new { workItemId = workItemStatus.Id })); } catch (Exception ex) { return(Ok(new { workItemId = ex.Message })); } }