Esempio n. 1
0
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await Utility.OAuth.Get2LeggedTokenAsync(new Scope[] { Scope.DataRead, Scope.DataWrite, Scope.DataCreate });

            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            if (string.IsNullOrEmpty(objModel.rootFilename))
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectKey), new JobPayloadOutput(outputs));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectKey, true, objModel.rootFilename), new JobPayloadOutput(outputs));
            }


            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
Esempio n. 2
0
        public async Task <dynamic> TranslateObject([FromBody] ObjectModel objModel)
        {
            Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);

            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = credentials.TokenInternal;

            var manifest = await derivative.GetManifestAsync(objModel.urn);

            if (manifest.status == "inprogress")
            {
                return(null);                                 // another job in progress
            }
            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(JobPayloadItem.TypeEnum.Ifc)
            };

            JobPayload job = new JobPayload(new JobPayloadInput(objModel.urn), new JobPayloadOutput(outputs));

            // start the translation
            dynamic jobPosted = await derivative.TranslateAsync(job, false /* do not force re-translate */);

            return(jobPosted);
        }
Esempio n. 3
0
        public async Task <dynamic> TranslateObject([FromBody] ObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            if (string.IsNullOrEmpty(objModel.rootFilename))
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(objModel.objectName, true, objModel.rootFilename), new JobPayloadOutput(outputs));
            }


            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true /* force re-translate if already here, required data:write*/);

            return(jobPosted);
        }
Esempio n. 4
0
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs));

            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
        public async Task <IActionResult> StartTranslation([FromBody] JObject translateSpecs)
        {
            string urn = translateSpecs["urn"].Value <string>();

            dynamic oauth = await OAuthController.GetInternalAsync();

            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs));

            // translationを開始する
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(Ok());
        }
Esempio n. 6
0
        private async Task TranslateFile(string objectId, string rootFileName)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                }
                    )
            };
            JobPayload job;
            string     urn = Base64Encode(objectId);

            if (rootFileName != null)
            {
                job = new JobPayload(new JobPayloadInput(urn, true, rootFileName), new JobPayloadOutput(outputs));
            }
            else
            {
                job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs));
            }

            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;

            await derivative.TranslateAsync(job);
        }
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the webhook callback
            DerivativeWebhooksApi webhook = new DerivativeWebhooksApi();

            webhook.Configuration.AccessToken = oauth.access_token;
            dynamic existingHooks = await webhook.GetHooksAsync(DerivativeWebhookEvent.ExtractionFinished);

            // get the callback from your settings (e.g. web.config)
            string callbackUlr = OAuthController.GetAppSetting("FORGE_WEBHOOK_URL") + "/api/forge/callback/modelderivative";

            bool createHook = true; // need to create, we don't know if our hook is already there...

            foreach (KeyValuePair <string, dynamic> hook in new DynamicDictionaryItems(existingHooks.data))
            {
                if (hook.Value.scope.workflow.Equals(objModel.connectionId))
                {
                    // ok, found one hook with the same workflow, no need to create...
                    createHook = false;
                    if (!hook.Value.callbackUrl.Equals(callbackUlr))
                    {
                        await webhook.DeleteHookAsync(DerivativeWebhookEvent.ExtractionFinished, new System.Guid(hook.Value.hookId));

                        createHook = true; // ops, the callback URL is outdated, so delete and prepare to create again
                    }
                }
            }

            // need to (re)create the hook?
            if (createHook)
            {
                await webhook.CreateHookAsync(DerivativeWebhookEvent.ExtractionFinished, callbackUlr, objModel.connectionId);
            }

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job = new JobPayload(new JobPayloadInput(objModel.objectName), new JobPayloadOutput(outputs), new JobPayloadMisc(objModel.connectionId));


            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true /* force re-translate if already here, required data:write*/);

            return(jobPosted);
        }
Esempio n. 8
0
        private async void onClickTranslate(object sender, EventArgs e)
        {
            // for now, just one translation at a time
            if (_translationTimer.Enabled)
            {
                return;
            }

            // check level 1 of objects
            if (treeBuckets.SelectedNode == null || treeBuckets.SelectedNode.Level != 1)
            {
                MessageBox.Show("Please select an object", "Objects required", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string urn = (string)treeBuckets.SelectedNode.Tag;

            // prepare a SVF translation
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            //if (string.IsNullOrEmpty(objModel.rootFilename))
            job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(outputs));
            //else
            //  job = new JobPayload(new JobPayloadInput(objModel.objectKey, true, objModel.rootFilename), new JobPayloadOutput(outputs));

            // start progress bar for translation
            progressBar.Show();
            progressBar.Value      = 0;
            progressBar.Minimum    = 0;
            progressBar.Maximum    = 100;
            progressBar.CustomText = "Starting translation job...";

            // start translation job
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = AccessToken;
            dynamic jobPosted = await derivative.TranslateAsync(job, true);

            // start a monitor job to follow the translation
            _translationTimer.Tick    += new EventHandler(isTranslationReady);
            _translationTimer.Tag      = urn;
            _translationTimer.Interval = 5000;
            _translationTimer.Enabled  = true;
        }
        /// <summary>
        /// Translate object by safe urn from object.
        /// </summary>
        /// <param name="safeUrn">Object's, that will be translated, URN</param>
        /// <returns>Nothing...</returns>
        public async Task TranslateObject(string safeUrn)
        {
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(new JobPayloadInput(safeUrn), new JobPayloadOutput(outputs));
            api = new DerivativesApi();
            api.Configuration.AccessToken = this.token.AccessToken;
            dynamic jobPosted = await api.TranslateAsync(job);

            Dictionary <string, dynamic> callBackData = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(jobPosted.ToString());

            this.URN = callBackData["urn"].ToString();
            string status = callBackData["result"];

            while (status == "inprogress" || status == "pending" || status == "created")
            {
                dynamic resp = await api.GetManifestAsyncWithHttpInfo(this.URN);

                JObject jObject = JsonConvert.DeserializeObject <JObject>(resp.Data.ToString());

                status = jObject["status"].ToString();
            }

            if (status == "success")
            {
                Completed?.Invoke(null, new EventArgs());
            }

            else if (status == "failed" || status == "timeout")
            {
                Failed?.Invoke(null, new EventArgs());
            }

            this.IsTranslated = status == "success";
        }
        public async Task <bool> TranslateFile(string urn)
        {
            if (urn == null)
            {
                throw new ArgumentNullException("urn");
            }

            var isAuthorized = await IsAuthorized();

            if (!isAuthorized)
            {
                _logger.Log(LogType.Error, "Cannot be authorized for translating file");
                return(false);
            }

            var jobPayloadItems = new List <JobPayloadItem>
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };

            var job = new JobPayload(new JobPayloadInput(urn), new JobPayloadOutput(jobPayloadItems));

            var derivative = new DerivativesApi
            {
                Configuration = { AccessToken = AuthenticationToken.AccessToken }
            };

            try
            {
                dynamic jobPosted = await derivative.TranslateAsync(job);
            }
            catch (Exception ex)
            {
                _logger.Log(LogType.Error, "Exception while translating file: " + ex);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// Translate object
        /// </summary>
        private async Task <dynamic> TranslateObject(dynamic objModel, string outputFileName)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            string objectIdBase64 = ToBase64(objModel.objectId);
            // prepare the payload
            List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayload job;

            job = new JobPayload(
                new JobPayloadInput(objectIdBase64, false, outputFileName),
                new JobPayloadOutput(postTranslationOutput)
                );

            // start the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job, true);

            // check if it is complete.
            dynamic manifest = null;

            do
            {
                System.Threading.Thread.Sleep(1000); // wait 1 second
                try
                {
                    manifest = await derivative.GetManifestAsync(objectIdBase64);
                }
                catch (Exception) { }
            } while (manifest.progress != "complete");
            return(jobPosted.urn);
        }
Esempio n. 12
0
        public async Task <dynamic> TranslateTask(TranslateObject translateObject)
        {
            string Urn          = translateObject.objectName;
            string rootFileName = translateObject.RootFileName;

            JobPayload job = BusinessLogicRunner.RunnerStatmentOptional <JobPayload>((rootFileName != null),
                                                                                     new JobPayload(new JobPayloadInput(Urn, true, rootFileName), new JobPayloadOutput(outputs)),
                                                                                     new JobPayload(new JobPayloadInput(Urn), new JobPayloadOutput(outputs)));

            DerivativesApi derivativesApi =
                GeneralTokenConfigurationSettings <IDerivativesApi> .SetToken(new DerivativesApi(),
                                                                              await _authServiceAdapter.GetSecondaryTokenTask());



            dynamic jobTranslate = await derivativesApi.TranslateAsync(job, true);

            return(jobTranslate);
        }
Esempio n. 13
0
        public async Task <Model> UploadModel(string objectKey, Stream body, string zipEntrypoint)
        {
            await EnsureBucketExists(bucketKey);

            // Upload object
            var objectsApi = new ObjectsApi();

            objectsApi.Configuration.AccessToken = (await GetAccessToken(INTERNAL_TOKEN_SCOPES)).AccessToken;
            var response = await objectsApi.UploadObjectAsync(bucketKey, objectKey, (int)body.Length, body);

            var model = new Model {
                Name = response.objectKey, URN = Base64Encode(response.objectId)
            };

            // Start object translation
            var derivativesApi = new DerivativesApi();

            derivativesApi.Configuration.AccessToken = (await GetAccessToken(INTERNAL_TOKEN_SCOPES)).AccessToken;
            var payload = new JobPayload();

            payload.Input  = new JobPayloadInput(model.URN);
            payload.Output = new JobPayloadOutput(new List <JobPayloadItem>());
            payload.Output.Formats.Add(
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum> {
                JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d
            }
                    )
                );
            if (!string.IsNullOrEmpty(zipEntrypoint))
            {
                payload.Input.CompressedUrn = true;
                payload.Input.RootFilename  = zipEntrypoint;
            }
            await derivativesApi.TranslateAsync(payload);

            return(model);
        }
Esempio n. 14
0
        /// <summary>
        /// Translate the uploaded zip file.
        /// </summary>
        private async static Task <dynamic> TranslateZipFile(dynamic newObject)
        {
            string objectIdBase64 = ToBase64(newObject.objectId);
            string rootfilename   = Path.GetFileName(fileList[0]);
            List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._3d,
                    JobPayloadItem.ViewsEnum._2d
                })
            };

            JobPayload postTranslation = new JobPayload(
                new JobPayloadInput(objectIdBase64, true, rootfilename),
                new JobPayloadOutput(postTranslationOutput));
            DerivativesApi derivativeApi = new DerivativesApi();

            derivativeApi.Configuration.AccessToken = InternalToken.access_token;
            dynamic translation = await derivativeApi.TranslateAsync(postTranslation);

            // check if it is complete.
            int progress = 0;

            do
            {
                System.Threading.Thread.Sleep(1000); // wait 1 second
                try
                {
                    dynamic manifest = await derivativeApi.GetManifestAsync(objectIdBase64);

                    progress = (string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value));
                }
                catch (Exception) { }
            } while (progress < 100);
            return(translation);
        }
        public async Task <dynamic> TranslateObject([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuthController.GetInternalAsync();

            // prepare the payload
            List <JobPayloadItem> outputs = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };
            JobPayloadInput jobPayloadInput;

            if (objModel.ObjectType == "zipfile3D")
            {
                jobPayloadInput = new JobPayloadInput(objModel.ObjectName, true, "MyWallShelf.iam");
            }
            else if (objModel.ObjectType == "zipfile2D")
            {
                jobPayloadInput = new  JobPayloadInput(objModel.ObjectName, true, "WallShelfDrawings.idw");
            }
            else
            {
                jobPayloadInput = new JobPayloadInput(objModel.ObjectName);
            }
            // start the translation
            JobPayload job = new JobPayload(jobPayloadInput, new JobPayloadOutput(outputs));

            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic jobPosted = await derivative.TranslateAsync(job);

            return(jobPosted);
        }
Esempio n. 16
0
        public async Task <IActionResult> Post(IFormFile file)
        {
            string fileName     = "Swisscom.rvt";
            string bucketKey    = "forgeapp" + Guid.NewGuid().ToString("N").ToLower();
            string tempFilePath = _env.ContentRootPath + "/wwwroot/layout/Swisscom_detached.rvt";

            //Get Token
            TwoLeggedApi oauthApi = new TwoLeggedApi();

            dynamic bearer = await oauthApi.AuthenticateAsync(
                "mUAnGJsDnZAALOTZdNGDcV68ReVuscXO",
                "coCCQ99xevcPpLjD",
                //_developer.forgeClientId,
                //_developer.forgeClientSecret,
                "client_credentials",
                new Scope[] { Scope.BucketCreate, Scope.DataCreate, Scope.DataWrite, Scope.DataRead });

            //Create Forge Bucket
            PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
            BucketsApi         bucketApi  = new BucketsApi();

            bucketApi.Configuration.AccessToken = bearer.access_token;

            dynamic newBucket = await bucketApi.CreateBucketAsync(postBucket);

            //Upload File
            ObjectsApi objectsApi = new ObjectsApi();

            oauthApi.Configuration.AccessToken = bearer.access_token;
            dynamic newObject;

            using (StreamReader fileStream = new StreamReader(tempFilePath))
            {
                newObject = await objectsApi.UploadObjectAsync(bucketKey, fileName, (int)fileStream.BaseStream.Length,
                                                               fileStream.BaseStream, "application/octet-stream"); //TODO add comment
            }

            //Translate File
            string objectIdBase64 = ToBase64(newObject.objectId);
            List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf, new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._2d,
                    JobPayloadItem.ViewsEnum._3d
                })
            };

            JobPayload postTranslation = new JobPayload(
                new JobPayloadInput(objectIdBase64),
                new JobPayloadOutput(postTranslationOutput));

            DerivativesApi derivativeApi = new DerivativesApi();

            derivativeApi.Configuration.AccessToken = bearer.access_token;
            dynamic translation = await derivativeApi.TranslateAsync(postTranslation);

            //Translation finish check
            int progress = 0;

            do
            {
                System.Threading.Thread.Sleep(1000);
                try
                {
                    dynamic manifest = await derivativeApi.GetManifestAsync(objectIdBase64);

                    progress = (string.IsNullOrEmpty(Regex.Match(manifest.progress, @"\d+").Value)
                        ? 100
                        : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value));
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Error in translation: " + ex.Message);
                }
            } while (progress < 100);

            //Delete temp file
            //System.IO.File.Delete(tempFilePath);

            return(RedirectToAction("Index", new { URN = (object)objectIdBase64 }));
        }
        public async Task <string> UploadObject()
        {
            HttpRequest req = HttpContext.Current.Request;

            // we must have 1 file on the request (multiple files not handles on this sample)
            if (req.Files.Count != 1)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Unexpected number of files"));
            }
            HttpPostedFile file = req.Files[0];

            // save the file on the server
            string bucketKey    = Utils.GenerateRandomBucketName();
            var    fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), bucketKey, file.FileName);

            if (!Directory.Exists(fileSavePath))
            {
                Directory.CreateDirectory(fileSavePath);
            }
            file.SaveAs(fileSavePath);

            try
            {
                // authenticate with Forge
                dynamic oauth = await Get2LeggedTokenAsync(new Scope[] { Scope.BucketCreate, Scope.DataRead, Scope.DataCreate, Scope.DataWrite });

                // create the bucket
                BucketsApi buckets = new BucketsApi();
                buckets.Configuration.AccessToken = oauth.access_token;
                PostBucketsPayload bucketPayload = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient);
                dynamic            bucketResult  = await buckets.CreateBucketAsync(bucketPayload);

                // upload the file/object, which will create a new object
                ObjectsApi objects = new ObjectsApi();
                objects.Configuration.AccessToken = oauth.access_token;
                dynamic uploadedObj;
                using (StreamReader streamReader = new StreamReader(fileSavePath))
                {
                    uploadedObj = await objects.UploadObjectAsync(bucketKey,
                                                                  file.FileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream,
                                                                  "application/octet-stream");
                }

                // start translating the file
                List <JobPayloadItem> outputs = new List <JobPayloadItem>()
                {
                    new JobPayloadItem(
                        JobPayloadItem.TypeEnum.Svf,
                        new List <JobPayloadItem.ViewsEnum>()
                    {
                        JobPayloadItem.ViewsEnum._2d,
                        JobPayloadItem.ViewsEnum._3d
                    })
                };
                JobPayload     job        = new JobPayload(new JobPayloadInput(Utils.Base64Encode(uploadedObj.objectId)), new JobPayloadOutput(outputs));
                DerivativesApi derivative = new DerivativesApi();
                derivative.Configuration.AccessToken = oauth.access_token;
                dynamic jobPosted = await derivative.TranslateAsync(job);
            }
            catch (System.Exception ex)
            {
                // for this testing app, let's throw a full descriptive expcetion,
                // which is not a good idea in production
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message + ex.InnerException));
            }

            // cleanup server
            File.Delete(fileSavePath);

            return(bucketKey);
        }
Esempio n. 18
0
        protected async void uploadAndTranslate(object sender, EventArgs e)
        {
            // create a randomg bucket name (fixed prefix + randomg guid)
            string bucketKey = "forgeapp" + Guid.NewGuid().ToString("N").ToLower();

            // upload the file (to your server)
            string fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), bucketKey, FileUpload1.FileName);

            Directory.CreateDirectory(Path.GetDirectoryName(fileSavePath));
            FileUpload1.SaveAs(fileSavePath);

            // get a write enabled token
            TwoLeggedApi oauthApi = new TwoLeggedApi();
            dynamic      bearer   = await oauthApi.AuthenticateAsync(
                WebConfigurationManager.AppSettings["FORGE_CLIENT_ID"],
                WebConfigurationManager.AppSettings["FORGE_CLIENT_SECRET"],
                "client_credentials",
                new Scope[] { Scope.BucketCreate, Scope.DataCreate, Scope.DataWrite, Scope.DataRead });

            // create the Forge bucket
            PostBucketsPayload postBucket = new PostBucketsPayload(bucketKey, null, PostBucketsPayload.PolicyKeyEnum.Transient /* erase after 24h*/);
            BucketsApi         bucketsApi = new BucketsApi();

            bucketsApi.Configuration.AccessToken = bearer.access_token;
            dynamic newBucket = await bucketsApi.CreateBucketAsync(postBucket);

            // upload file (a.k.a. Objects)
            ObjectsApi objectsApi = new ObjectsApi();

            oauthApi.Configuration.AccessToken = bearer.access_token;
            dynamic newObject;

            using (StreamReader fileStream = new StreamReader(fileSavePath))
            {
                newObject = await objectsApi.UploadObjectAsync(bucketKey, FileUpload1.FileName,
                                                               (int)fileStream.BaseStream.Length, fileStream.BaseStream,
                                                               "application/octet-stream");
            }

            // translate file
            string objectIdBase64 = ToBase64(newObject.objectId);
            List <JobPayloadItem> postTranslationOutput = new List <JobPayloadItem>()
            {
                new JobPayloadItem(
                    JobPayloadItem.TypeEnum.Svf /* Viewer*/,
                    new List <JobPayloadItem.ViewsEnum>()
                {
                    JobPayloadItem.ViewsEnum._3d,
                    JobPayloadItem.ViewsEnum._2d
                })
            };
            JobPayload postTranslation = new JobPayload(
                new JobPayloadInput(objectIdBase64),
                new JobPayloadOutput(postTranslationOutput));
            DerivativesApi derivativeApi = new DerivativesApi();

            derivativeApi.Configuration.AccessToken = bearer.access_token;
            dynamic translation = await derivativeApi.TranslateAsync(postTranslation);

            // check if is ready
            int progress = 0;

            do
            {
                System.Threading.Thread.Sleep(1000); // wait 1 second
                try
                {
                    dynamic manifest = await derivativeApi.GetManifestAsync(objectIdBase64);

                    progress = (string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value));
                }
                catch (Exception ex)
                {
                }
            } while (progress < 100);

            // ready!!!!

            // register a client-side script to show this model
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ShowModel", string.Format("<script>showModel('{0}');</script>", objectIdBase64));

            // clean up
            Directory.Delete(Path.GetDirectoryName(fileSavePath), true);
        }