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");
        }
Exemple #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);
        }
        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 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
            }
        }
        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);
        }
        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);
        }
Exemple #8
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);
        }
        /// <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);
        }
Exemple #10
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);
        }
Exemple #11
0
        private async void isTranslationReady(object sender, EventArgs e)
        {
            DerivativesApi derivative = new DerivativesApi();

            derivative.Configuration.AccessToken = AccessToken;

            // get the translation manifest
            dynamic manifest = await derivative.GetManifestAsync((string)_translationTimer.Tag);

            int progress = (string.IsNullOrWhiteSpace(Regex.Match(manifest.progress, @"\d+").Value) ? 100 : Int32.Parse(Regex.Match(manifest.progress, @"\d+").Value));

            // for better UX, show a small number of progress (instead zero)
            progressBar.Value      = (progress == 0 ? 10 : progress);
            progressBar.CustomText = string.Format("Translation in progress: {0}", progress);
            Debug.WriteLine(progress);

            // if ready, hide everything
            if (progress >= 100)
            {
                progressBar.Hide();
                _translationTimer.Enabled = false;
            }
        }
        public async static Task <List <Resource> > ExtractSVFAsync(string urn, string accessToken)
        {
            DerivativesApi derivativeApi = new DerivativesApi();

            derivativeApi.Configuration.AccessToken = accessToken;

            // get the manifest for the URN
            dynamic manifest = await derivativeApi.GetManifestAsync(urn);

            // list items of the manifest file
            List <ManifestItem> urns = ParseManifest(manifest.derivatives);

            // iterate on what's on the file
            foreach (ManifestItem item in urns)
            {
                switch (item.MIME)
                {
                case "application/autodesk-svf":
                    item.Path.Files = await SVFDerivates(item, accessToken);

                    break;

                case "application/autodesk-f2d":
                    item.Path.Files = await F2DDerivates(item, accessToken);

                    break;

                case "application/autodesk-db":
                    item.Path.Files = new List <string>()
                    {
                        "objects_attrs.json.gz",
                        "objects_vals.json.gz",
                        "objects_offs.json.gz",
                        "objects_ids.json.gz",
                        "objects_avs.json.gz",
                        item.Path.RootFileName
                    };
                    break;

                default:
                    item.Path.Files = new List <string>()
                    {
                        item.Path.RootFileName
                    };
                    break;
                }
            }

            // now organize the list for external usage
            List <Resource> resouces = new List <Resource>();

            foreach (ManifestItem item in urns)
            {
                foreach (string file in item.Path.Files)
                {
                    Uri myUri = new Uri(new Uri(item.Path.BasePath), file);
                    resouces.Add(new Resource()
                    {
                        FileName   = file,
                        RemotePath = DERIVATIVE_PATH + Uri.UnescapeDataString(myUri.AbsoluteUri),
                        LocalPath  = Path.Combine(item.Path.LocalPath, file)
                    });
                }
            }

            return(resouces);
        }
Exemple #13
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);
        }
        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 static async Task ProcessFileAsync(string userId, string hubId, string projectId, string folderUrn, string itemUrn, string versionUrn, string fileName, PerformContext console)
        {
            Credentials credentials = await Credentials.FromDatabaseAsync(userId);

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

            derivative.Configuration.AccessToken = credentials.TokenInternal;

            dynamic document = new JObject();

            document.hubId      = hubId.Replace("-", string.Empty); // this is breaking the search...
            document.projectId  = projectId;
            document.folderUrn  = folderUrn;
            document.itemUrn    = itemUrn;
            document.versionUrn = versionUrn;
            document.fileName   = fileName;
            document.metadata   = new JArray();

            string  versionUrn64 = Base64Encode(versionUrn);
            dynamic manifest     = await derivative.GetManifestAsync(versionUrn64);

            if (manifest.status == "inprogress")
            {
                throw new Exception("Translating...");                                  // force run it again
            }
            List <ManifestItem> manifestItems = ParseManifest(manifest.derivatives);

            List <Resource> resouces = new List <Resource>();

            foreach (ManifestItem item in manifestItems)
            {
                if (item.MIME != "application/autodesk-db")
                {
                    continue;
                }

                string file  = "objects_vals.json.gz"; // the only file we need here
                Uri    myUri = new Uri(new Uri(item.Path.BasePath), file);
                resouces.Add(new Resource()
                {
                    FileName   = file,
                    RemotePath = "derivativeservice/v2/derivatives/" + Uri.UnescapeDataString(myUri.AbsoluteUri),
                    LocalPath  = Path.Combine(item.Path.LocalPath, file)
                });
            }

            // this approach uses the Viewer propertyDatabase, which is a non-supported way of accessing the model metadata
            // it will return the non-duplicated list of attributes values (not the attribute type)
            // as we don't want to manipulate it, just search, it doesn't matter if this list changes its format
            IRestClient forgeClient = new RestClient("https://developer.api.autodesk.com/");

            if (resouces.Count != 1)
            {
                throw new Exception(resouces.Count + " objects_vals.json.gz found, will try again");
            }

            RestRequest forgeRequest = new RestRequest(resouces[0].RemotePath, Method.GET);

            forgeRequest.AddHeader("Authorization", "Bearer " + credentials.TokenInternal);
            forgeRequest.AddHeader("Accept-Encoding", "gzip, deflate");
            IRestResponse response = await forgeClient.ExecuteTaskAsync(forgeRequest);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                console.WriteLine(string.Format("Cannot download attributes ({0}), will retry", response.StatusCode));
                throw new Exception(string.Format("Cannot download attributes: {0}", response.StatusCode));
            }
            using (GZipStream gzip = new GZipStream(new MemoryStream(response.RawBytes), CompressionMode.Decompress))
                using (var fileStream = new StreamReader(gzip))
                {
                    dynamic viewProperties = new JObject();
                    viewProperties.viewId     = "viewer";
                    viewProperties.collection = System.Text.RegularExpressions.Regex.Replace(fileStream.ReadToEnd(), @"\n", string.Empty);
                    document.metadata.Add(viewProperties);
                }


            // as an alternative solution, using supported APIs, one could get the complete metadata JSON
            // but that results in more data that we don't need for search, like attribute names

            /*{
             *  dynamic metadata = await derivative.GetMetadataAsync(versionUrn64);
             *  foreach (KeyValuePair<string, dynamic> metadataItem in new DynamicDictionaryItems(metadata.data.metadata))
             *  {
             *      dynamic properties = await derivative.GetModelviewPropertiesAsync(versionUrn64, metadataItem.Value.guid);
             *      if (properties == null)
             *      {
             *          console.WriteLine("Model not ready, will retry");
             *          throw new Exception("Model not ready...");
             *      }
             *      console.WriteLine(string.Format("View: {0}", (string)metadataItem.Value.guid));
             *      JArray collection = JObject.Parse(properties.ToString()).data.collection;
             *
             *      if (collection.Count > 0)
             *      {
             *          dynamic viewProperties = new JObject();
             *          viewProperties.viewId = (string)metadataItem.Value.guid;
             *          viewProperties.collection = collection.ToString(Newtonsoft.Json.Formatting.None);
             *          document.metadata.Add(viewProperties);
             *      }
             *  }
             * }*/

            string json         = (string)document.ToString(Newtonsoft.Json.Formatting.None);
            string absolutePath = string.Format("/manifest/_doc/{0}", Base64Encode(itemUrn));

            RestClient  elasticSearchclient  = new RestClient(Config.ElasticSearchServer);
            RestRequest elasticSearchRequest = new RestRequest(absolutePath, RestSharp.Method.POST);

            elasticSearchRequest.AddHeader("Content-Type", "application/json");
            elasticSearchRequest.AddParameter("text/json", json, ParameterType.RequestBody);

            if (!string.IsNullOrEmpty(Config.AWSKey) && !string.IsNullOrEmpty(Config.AWSSecret))
            {
                SortedDictionary <string, string> headers = AWS.Signature.SignatureHeader(
                    Amazon.RegionEndpoint.GetBySystemName(Config.AWSRegion),
                    new Uri(Config.ElasticSearchServer).Host,
                    "POST", json, absolutePath);
                foreach (var entry in headers)
                {
                    elasticSearchRequest.AddHeader(entry.Key, entry.Value);
                }
            }

            IRestResponse res = await elasticSearchclient.ExecuteTaskAsync(elasticSearchRequest);

            console.WriteLine(string.Format("Submit to elasticsearch status: {0}", res.StatusCode.ToString()));
        }
Exemple #16
0
        private async Task <IList <jsTreeNode> > GetItemVersions(string href)
        {
            IList <jsTreeNode> nodes = new List <jsTreeNode>();

            // the API SDK
            ItemsApi itemApi = new ItemsApi();

            itemApi.Configuration.AccessToken = Credentials.TokenInternal;

            DerivativesApi derivativesApi = new DerivativesApi();

            derivativesApi.Configuration.AccessToken = Credentials.TokenInternal;

            // extract the projectId & itemId from the href
            string[] idParams  = href.Split('/');
            string   itemId    = idParams[idParams.Length - 1];
            string   projectId = idParams[idParams.Length - 3];

            var versions = await itemApi.GetItemVersionsAsync(projectId, itemId);

            foreach (KeyValuePair <string, dynamic> version in new DynamicDictionaryItems(versions.data))
            {
                DateTime versionDate = version.Value.attributes.lastModifiedTime;
                string   verId       = version.Value.id;
                string   verNum      = version.Value.id.Split("=")[1];
                string   userName    = version.Value.attributes.lastModifiedUserName;

                string urn = string.Empty;
                try {
                    urn = (string)version.Value.relationships.derivatives.data.id;

                    dynamic manifestData = await derivativesApi.GetManifestAsync(urn);

                    foreach (KeyValuePair <string, dynamic> manifestParam in new DynamicDictionaryItems(manifestData))
                    {
                        if (manifestParam.Key == "derivatives")
                        {
                            foreach (KeyValuePair <string, dynamic> manifestDerivativeParam in new DynamicDictionaryItems(manifestParam.Value[0]))
                            {
                                if (manifestDerivativeParam.Key == "children")
                                {
                                    foreach (KeyValuePair <string, dynamic> manifestDerivativeChildrenParam in new DynamicDictionaryItems(manifestDerivativeParam.Value))
                                    {
                                        string roomManifestStr = Convert.ToString(manifestDerivativeChildrenParam.Value);

                                        //string roomManifestStrJson = roomManifestStr.Substring(1, roomManifestStr.Length - 2);

                                        RoomManifestChildren deserializedRoomManifest = JsonConvert.DeserializeObject <RoomManifestChildren>(roomManifestStr);

                                        if (deserializedRoomManifest.Role == "3d" && deserializedRoomManifest.Status == ManifestChildren.StatusEnum.Success)
                                        {
                                            if (deserializedRoomManifest.PhaseNames != null)
                                            {
                                                jsTreeNode phaseNode = new jsTreeNode(
                                                    urn + '|' + deserializedRoomManifest.ViewableId + '/' + projectId + '/' + verId,
                                                    string.Format("v{0}: phase: {1}", verNum, deserializedRoomManifest.PhaseNames),
                                                    "versions",
                                                    false);

                                                nodes.Add(phaseNode);
                                            }
                                        }

                                        //foreach(RoomManifestChildren roomManifestChild in deserializedManifestChildren)
                                        //{
                                        //    if (roomManifestChild.Role == ManifestChildren.RoleEnum._3d && roomManifestChild.Status == ManifestChildren.StatusEnum.Success)
                                        //    {
                                        //        if (roomManifestChild.PhaseNames != null)
                                        //        {
                                        //            jsTreeNode phaseNode = new jsTreeNode(
                                        //                    urn + '|' + roomManifestChild.ViewableId + '/' + projectId + '/' + verId,
                                        //                    string.Format("v{0}: {1}", verNum, roomManifestChild.PhaseNames),
                                        //                    "versions",
                                        //                    false);

                                        //            nodes.Add(phaseNode);
                                        //        }
                                        //    }
                                        //}

                                        //if (manifestDerivativeChildParam.Key == "role" && manifestDerivativeChildParam.Value == "3d")
                                        //{
                                        //    if(manifestDerivativeChildParam.Key == "status" && manifestDerivativeChildParam.Value == "success")
                                        //    {
                                        //        if(manifestDerivativeChildParam.Key == "phaseNames")
                                        //        {
                                        //            jsTreeNode phaseNode = new jsTreeNode(
                                        //                urn + '|' + manifestDerivativeChildParam.Value.viewableID + '/' + projectId + '/' + verId,
                                        //                string.Format("v{0}: {1}", verNum, manifestDerivativeChildParam.Value),
                                        //                "versions",
                                        //                false);

                                        //            nodes.Add(phaseNode);
                                        //        }
                                        //    }
                                        //}
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    string message = ex.Message;
                    urn = Base64Encode(version.Value.id);
                } // some BIM 360 versions don't have viewable

                jsTreeNode node = new jsTreeNode(
                    urn + '/' + projectId + '/' + verId,
                    string.Format("v{0}: {1} by {2}", verNum, versionDate.ToString("dd/MM/yy HH:mm:ss"), userName),
                    "versions",
                    false);
                nodes.Add(node);
            }



            return(nodes);
        }