Exemplo n.º 1
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);
        }
Exemplo n.º 2
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);
        }
        public async Task <int> TranslationProgress([FromBody] RequestModel request)
        {
            Guid testOutput;

            if (string.IsNullOrWhiteSpace(request.guid) || !Guid.TryParse(request.guid.TrimStart('t'), out testOutput))
            {
                throw new System.Exception("Invalid GUID");
            }

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

            // get object on the bucket, should be just 1
            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;
            dynamic objectsInBucket = await objects.GetObjectsAsync(request.guid);

            string objectId = string.Empty;

            foreach (KeyValuePair <string, dynamic> objInfo in new DynamicDictionaryItems(objectsInBucket.items))
            {
                objectId = objInfo.Value.objectId;
            }

            // get the manifest, that includes the status of the translation
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic manifest = await derivative.GetManifestAsync(objectId.Base64Encode());

            return(string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value));
        }
        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());
        }
Exemplo n.º 5
0
        protected async Task <ProgressInfo> JobProgressRequest(ForgeObjectInfo item)
        {
            try {
                DerivativesApi md = new DerivativesApi();
                md.Configuration.AccessToken = _accessToken;
                string urn = MainWindow.URN(item.Properties.bucketKey, item);
                ApiResponse <dynamic> response = await md.GetManifestAsyncWithHttpInfo(urn);

                MainWindow.httpErrorHandler(response, "Initializing...");
                item.Manifest = response.Data;
                int pct = 100;
                if (response.Data.progress != "complete")
                {
                    try {
                        string st  = response.Data.progress;
                        Regex  rgx = new Regex("[^0-9]*");
                        st  = rgx.Replace(st, "");
                        pct = int.Parse(st);
                    } catch (Exception) {
                        pct = 0;
                    }
                }
                string msg = response.Data.status;
                return(new ProgressInfo(pct, msg));
            } catch (Exception /*ex*/) {
                return(new ProgressInfo(0, "Initializing..."));
            }
        }
Exemplo n.º 6
0
        private async Task <bool> AutoLog()
        {
            // We should prefer getting a new token

            // Verify we got a client_id and a client_secret
            if (!string.IsNullOrEmpty(FORGE_CLIENT_ID) &&
                !string.IsNullOrEmpty(FORGE_CLIENT_SECRET)
                )
            {
                /*dynamic bearer =*/ await oauthExecAsync();

                if (!string.IsNullOrEmpty(_2LEGGED))
                {
                    return(true);
                }
            }

            // Verify this token is still valid
            if (!string.IsNullOrEmpty(_2LEGGED))
            {
                try {
                    DerivativesApi md = new DerivativesApi();
                    md.Configuration.AccessToken = accessToken;
                    dynamic response = await md.GetFormatsAsync();

                    return(true);
                } catch (Exception ex) {
                    _2LEGGED = "";
                }
            }

            //MessageBox.Show ("No auto-log...", APP_NAME, MessageBoxButton.OK, MessageBoxImage.Information) ;
            return(false);
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
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);
        }
        public async static Task ExtractMetadata(string userId, string projectId, string versionId)
        {
            // this operation may take a moment
            Credentials credentials = await Credentials.FromDatabaseAsync(userId);

            // at this point we have:
            // projectId & versionId
            // valid access token

            // ready to access the files! let's do a quick test
            // as we're tracking the modified event, the manifest should be there...
            try
            {
                DerivativesApi derivativeApi = new DerivativesApi();
                derivativeApi.Configuration.AccessToken = credentials.TokenInternal;
                dynamic manifest = await derivativeApi.GetManifestAsync(Base64Encode(versionId));

                if (manifest.status == "inprogress")
                {
                    throw new Exception("Translating...");                                  // force run it again
                }
                // now we have the metadata, can do something, like send email or generate a report...
                // for this sample, just a simple console write line
                Console.WriteLine(manifest);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw; // this should force Hangfire to try again
            }
        }
        async Task <bool> IsTranslationComplete(string urn)
        {
            if (urn == null)
            {
                throw new ArgumentNullException("urn");
            }

            var isAuthorized = await IsAuthorized();

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

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

            // get the translation manifest
            dynamic manifest;

            try
            {
                manifest = await derivative.GetManifestAsync(urn);
            }
            catch (Exception e)
            {
                _logger.Log(LogType.Error, "Exception while for checking translation complete: " + e);
                return(false);
            }

            return(manifest.status == "success");
        }
        public async Task <IActionResult> GetManifest([FromQuery] string urn)
        {
            DerivativesApi derivative = new DerivativesApi();
            dynamic        result     = await derivative.GetManifestAsyncWithHttpInfo(urn);

            return(Ok(new { Status = (string)result.Data.status, Progress = (string)result.Data.progress }));
        }
Exemplo n.º 12
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);
        }
        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);
        }
        public async Task <IActionResult> DeleteObjectAsync([FromBody] ObjectModel objectModel)
        {
            dynamic token = await OAuthController.GetInternalAsync();

            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = token.access_token;
            await derivative.DeleteManifestAsync(objectModel.objectName);

            return(Ok());
        }
        public async Task <dynamic> GetManifestStatus([FromUri] string urn)
        {
            dynamic oauth = await OAuth2Controller.GetInternalAsync();

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

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic manifest = await derivative.GetManifestAsync(Base64Encode(urn));

            return(manifest);
        }
        public async Task <dynamic> GetManifestStatus([FromBody] TranslateObjectModel objModel)
        {
            dynamic oauth = await OAuth2Controller.GetInternalAsync();

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

            derivative.Configuration.AccessToken = oauth.access_token;
            dynamic manifest = await derivative.GetManifestAsync(objModel.objectName);

            return(manifest);
        }
Exemplo n.º 17
0
        public static async Task <dynamic> CheckTranslationStatus(string urn)
        {
            dynamic oauth = await OAuth.GetInternalAsync();

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

            derivative.Configuration.AccessToken = oauth.access_token;
            var manifest = await derivative.GetManifestAsync(urn);

            return(manifest);
        }
Exemplo n.º 18
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;
        }
Exemplo n.º 19
0
        public async Task <IActionResult> DownloadDerivative(string urn, string outputType)
        {
            Credentials credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);

            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = credentials.TokenInternal;

            var manifest = await derivative.GetManifestAsync(urn);

            foreach (KeyValuePair <string, dynamic> output in new DynamicDictionaryItems(manifest.derivatives))
            {
                if (output.Value.outputType == outputType)
                {
                    // already translated!

                    if (_httpClient == null)
                    {
                        _httpClient = new HttpClient(
                            // this should avoid HttpClient seaching for proxy settings
                            new HttpClientHandler()
                        {
                            UseProxy = false,
                            Proxy    = null
                        }, true);
                        _httpClient.BaseAddress = new Uri(FORGE_BASE_URL);
                        ServicePointManager.DefaultConnectionLimit = int.MaxValue;
                    }

                    // request to download file
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, string.Format("{0}/modelderivative/v2/designdata/{1}/manifest/{2}", FORGE_BASE_URL, urn, output.Value.children[0].urn));
                    request.Headers.Add("Authorization", "Bearer " + credentials.TokenInternal); // add our Access Token
                    HttpResponseMessage response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);

                    Stream file = await response.Content.ReadAsStreamAsync();

                    // stream result to client
                    var cd = new System.Net.Mime.ContentDisposition
                    {
                        FileName = "result.ifc",
                        // always prompt the user for downloading, set to true if you want
                        // the browser to try to show the file inline
                        Inline = false,
                    };
                    Response.Headers.Add("Content-Disposition", cd.ToString());
                    return(File(file, "application/octet-stream"));
                }
            }
            return(null);
        }
Exemplo n.º 20
0
        static async Task CleanUP(string urn, DerivativesApi endpoint, Region storage = Region.US)
        {
            Console.WriteLine("Running Endpoint: " + (endpoint.RegionIsEMEA ? "EMEA" : "US") + " server - Storage: " + storage.ToString());
            region         = storage;
            DerivativesAPI = endpoint;

            dynamic response = await oauthExecAsync();

            if (response == null)
            {
                return;
            }

            DeleteManifest(urn);
            DeleteBucket();              // This deletes the file(s) as well
        }
Exemplo n.º 21
0
        private async Task RequestManifest(ForgeObjectInfo item)
        {
            try {
                item.ManifestRequested = StateEnum.Busy;
                DerivativesApi md = new DerivativesApi();
                md.Configuration.AccessToken = accessToken;
                string urn = URN((string)BucketsInRegion.SelectedItem, item);
                ApiResponse <dynamic> response = await md.GetManifestAsyncWithHttpInfo(urn);

                httpErrorHandler(response, "Failed to get manifest");
                item.Manifest = response.Data;
            } catch (Exception /*ex*/) {
                item.Manifest = null;
            } finally {
                item.ManifestRequested = StateEnum.Idle;
            }
        }
        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);
        }
Exemplo n.º 23
0
        /// <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";
        }
Exemplo n.º 24
0
        public async Task <IActionResult> UploadOssFiles([FromBody] JObject appBundleSpecs)
        {
            if (OAuthController.GetAppSetting("DISABLE_SETUP") == "true")
            {
                return(Unauthorized());
            }

            System.Diagnostics.Debug.WriteLine("UploadOssFiles");
            // OAuth token
            dynamic oauth = await OAuthController.GetInternalAsync();

            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = oauth.access_token;

            DerivativesApi derivatives = new DerivativesApi();

            derivatives.Configuration.AccessToken = oauth.access_token;

            // 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, "US");
            }
            catch { }; // in case bucket already exists

            string [] filePaths = System.IO.Directory.GetFiles(LocalFilesFolder);
            foreach (string filePath in filePaths)
            {
                string fileName = System.IO.Path.GetFileName(filePath);
                using (StreamReader streamReader = new StreamReader(filePath))
                {
                    dynamic res = await objects.UploadObjectAsync(BucketKey, fileName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");

                    TranslateFile(res.objectId, null);
                }
            }

            return(Ok());
        }
Exemplo n.º 25
0
        private async Task <bool> DeleteManifestOnServer(ForgeObjectInfo item)
        {
            try {
                DerivativesApi md = new DerivativesApi();
                md.Configuration.AccessToken = accessToken;
                string urn = URN((string)BucketsInRegion.SelectedItem, item);
                ApiResponse <dynamic> response = await md.DeleteManifestAsyncWithHttpInfo(urn);

                httpErrorHandler(response, "Failed to delete manifest");
                item.Manifest             = null;
                item.TranslationRequested = StateEnum.Idle;
            } catch (Exception ex) {
                item.TranslationRequested = StateEnum.Idle;
                Debug.WriteLine(ex.Message);
                return(false);
            }
            return(true);
        }
Exemplo n.º 26
0
        private async Task <bool> TranslateObject(ObservableCollection <ForgeObjectInfo> items, ForgeObjectInfo item)
        {
            try {
                string          urn      = URN((string)BucketsInRegion.SelectedItem, item, false);
                JobPayloadInput jobInput = new JobPayloadInput(
                    urn,
                    System.IO.Path.GetExtension(item.Name).ToLower() == ".zip",
                    item.Name
                    );
                JobPayloadOutput jobOutput = new JobPayloadOutput(
                    new List <JobPayloadItem> (
                        new JobPayloadItem [] {
                    new JobPayloadItem(
                        JobPayloadItem.TypeEnum.Svf,
                        new List <JobPayloadItem.ViewsEnum> (
                            new JobPayloadItem.ViewsEnum [] {
                        JobPayloadItem.ViewsEnum._2d, JobPayloadItem.ViewsEnum._3d
                    }
                            ),
                        null
                        )
                }
                        )
                    );
                JobPayload     job    = new JobPayload(jobInput, jobOutput);
                bool           bForce = true;
                DerivativesApi md     = new DerivativesApi();
                md.Configuration.AccessToken = accessToken;
                ApiResponse <dynamic> response = await md.TranslateAsyncWithHttpInfo(job, bForce);

                httpErrorHandler(response, "Failed to register file for translation");
                item.TranslationRequested = StateEnum.Busy;
                item.Manifest             = response.Data;

                JobProgress jobWnd = new JobProgress(item, accessToken);
                jobWnd._callback = new JobCompletedDelegate(this.TranslationCompleted);
                jobWnd.Owner     = this;
                jobWnd.Show();
            } catch (Exception /*ex*/) {
                item.TranslationRequested = StateEnum.Idle;
                return(false);
            }
            return(true);
        }
        public async Task <dynamic> GetModelDetailPropertiesAsync(ModelDetails modelDetails)
        {
            List <dynamic> results = new List <dynamic>();

            string key = "properties";

            if (_cacheManager.IsAdd(key))
            {
                return(_cacheManager.Get <dynamic>(key));
            }



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

                dynamic detail = await GetModelDetailGuid(derivativesApi, modelDetails.urn);

                dynamic metadata = detail.data.metadata;



                foreach (KeyValuePair <string, dynamic> m in new DynamicDictionaryItems(metadata))
                {
                    dynamic list = await derivativesApi.GetModelviewPropertiesAsync(modelDetails.urn, m.Value.guid);

                    dynamic collection = list.data.collection;

                    DynamicDictionaryItems items = new DynamicDictionaryItems(collection);

                    foreach (dynamic c in items)
                    {
                        results.Add(c.Value);
                    }
                }

                _cacheManager.Add(key, results, 60);

                return(results);
            }
        }
        /// <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);
        }
Exemplo n.º 29
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);
        }
Exemplo n.º 30
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);
        }