示例#1
0
        private async Task <IList <jsTreeNode> > GetFolderContents(string href)
        {
            IList <jsTreeNode> nodes = new List <jsTreeNode>();

            // the API SDK
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = Credentials.TokenInternal;

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

            var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId);

            foreach (KeyValuePair <string, dynamic> folderContentItem in new DynamicDictionaryItems(folderContents.data))
            {
                string     displayName = folderContentItem.Value.attributes.displayName;
                jsTreeNode itemNode    = new jsTreeNode(folderContentItem.Value.links.self.href, displayName, (string)folderContentItem.Value.type, true);
                nodes.Add(itemNode);
            }

            return(nodes);
        }
        private async Task <IList <TreeNode> > GetFolderContents(string href)
        {
            IList <TreeNode> nodes = new List <TreeNode>();

            string[] idParams  = href.Split('/');
            string   folderId  = idParams[idParams.Length - 1];
            string   projectId = idParams[idParams.Length - 3];

            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = AccessToken;
            var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId);

            foreach (KeyValuePair <string, dynamic> folderContentItem in new DynamicDictionaryItems(folderContents.data))
            {
                string displayName = folderContentItem.Value.attributes.displayName;
                if (string.IsNullOrWhiteSpace(displayName))
                {
                    // BIM 360 related documents don't have displayName
                    // need to ask each one for a name
                    ItemsApi itemsApi = new ItemsApi();
                    itemsApi.Configuration.AccessToken = AccessToken;
                    dynamic item = await itemsApi.GetItemAsync(projectId, folderContentItem.Value.id);

                    displayName = item.included[0].attributes.displayName;
                }

                TreeNode itemNode = new TreeNode(folderContentItem.Value.links.self.href, displayName, (string)folderContentItem.Value.type, true);

                nodes.Add(itemNode);
            }

            return(nodes);
        }
        private async Task CreateItemVersion(string projectId, string folderId, string fileName, string storageId)
        {
            FoldersApi foldersApi     = new FoldersApi();
            var        folderContents = await foldersApi.GetFolderContentsAsync(projectId, folderId);

            var folderData = new DynamicDictionaryItems(folderContents.data);

            string itemId = string.Empty;

            foreach (KeyValuePair <string, dynamic> item in folderData)
            {
                if (item.Value.attributes.displayName == fileName)
                {
                    itemId = item.Value.id; // this means a file with same name is already there, so we'll create a new version
                }
            }
            if (string.IsNullOrWhiteSpace(itemId))
            {
                // create a new item
                BaseAttributesExtensionObject        baseAttribute                   = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "items:autodesk.core:File" : "items:autodesk.bim360:File", "1.0");
                CreateItemDataAttributes             createItemAttributes            = new CreateItemDataAttributes(fileName, baseAttribute);
                CreateItemDataRelationshipsTipData   createItemRelationshipsTipData  = new CreateItemDataRelationshipsTipData(CreateItemDataRelationshipsTipData.TypeEnum.Versions, CreateItemDataRelationshipsTipData.IdEnum._1);
                CreateItemDataRelationshipsTip       createItemRelationshipsTip      = new CreateItemDataRelationshipsTip(createItemRelationshipsTipData);
                StorageRelationshipsTargetData       storageTargetData               = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
                CreateStorageDataRelationshipsTarget createStorageRelationshipTarget = new CreateStorageDataRelationshipsTarget(storageTargetData);
                CreateItemDataRelationships          createItemDataRelationhips      = new CreateItemDataRelationships(createItemRelationshipsTip, createStorageRelationshipTarget);
                CreateItemData createItemData = new CreateItemData(CreateItemData.TypeEnum.Items, createItemAttributes, createItemDataRelationhips);
                BaseAttributesExtensionObject      baseAttExtensionObj = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes        storageDataAtt      = new CreateStorageDataAttributes(fileName, baseAttExtensionObj);
                CreateItemRelationshipsStorageData createItemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageId);
                CreateItemRelationshipsStorage     createItemRelationshipsStorage     = new CreateItemRelationshipsStorage(createItemRelationshipsStorageData);
                CreateItemRelationships            createItemRelationship             = new CreateItemRelationships(createItemRelationshipsStorage);
                CreateItemIncluded includedVersion = new CreateItemIncluded(CreateItemIncluded.TypeEnum.Versions, CreateItemIncluded.IdEnum._1, storageDataAtt, createItemRelationship);
                CreateItem         createItem      = new CreateItem(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), createItemData, new List <CreateItemIncluded>()
                {
                    includedVersion
                });

                ItemsApi itemsApi = new ItemsApi();
                var      newItem  = await itemsApi.PostItemAsync(projectId, createItem);
            }
            else
            {
                // create a new version
                BaseAttributesExtensionObject          attExtensionObj              = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes            storageDataAtt               = new CreateStorageDataAttributes(fileName, attExtensionObj);
                CreateVersionDataRelationshipsItemData dataRelationshipsItemData    = new CreateVersionDataRelationshipsItemData(CreateVersionDataRelationshipsItemData.TypeEnum.Items, itemId);
                CreateVersionDataRelationshipsItem     dataRelationshipsItem        = new CreateVersionDataRelationshipsItem(dataRelationshipsItemData);
                CreateItemRelationshipsStorageData     itemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageId);
                CreateItemRelationshipsStorage         itemRelationshipsStorage     = new CreateItemRelationshipsStorage(itemRelationshipsStorageData);
                CreateVersionDataRelationships         dataRelationships            = new CreateVersionDataRelationships(dataRelationshipsItem, itemRelationshipsStorage);
                CreateVersionData versionData    = new CreateVersionData(CreateVersionData.TypeEnum.Versions, storageDataAtt, dataRelationships);
                CreateVersion     newVersionData = new CreateVersion(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), versionData);

                VersionsApi versionsApis = new VersionsApi();
                dynamic     newVersion   = await versionsApis.PostVersionAsync(projectId, newVersionData);
            }
        }
示例#4
0
        public async Task GetFolderContentsAsync(string userId, string hubId, string folderHref, int page, PerformContext context)
        {
            Credentials credentials = await Credentials.FromDatabaseAsync(userId);

            // the API SDK
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = credentials.TokenInternal;

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

            BackgroundJobClient indexQueue = new BackgroundJobClient();
            IState state = new EnqueuedState("index");

            try
            {
                var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderUrn, null, null, null, page, 100);

                if (folderContents.links.ToString().IndexOf("next") > 0)
                {
                    indexQueue.Create(() => GetFolderContentsAsync(credentials.UserId, hubId, folderHref, page + 1, null), state);
                }
                var folderData = new DynamicDictionaryItems(folderContents.data);

                // let's start iterating the FOLDER DATA
                foreach (KeyValuePair <string, dynamic> folderContentItem in folderData)
                {
                    if ((string)folderContentItem.Value.type == "folders")
                    {
                        // get subfolder...
                        string subFolderHref = folderContentItem.Value.links.self.href;
                        indexQueue.Create(() => GetFolderContentsAsync(credentials.UserId, hubId, subFolderHref, page, null), state);
                    }
                    else
                    {
                        // found an item!
                        await GetItemVersionsAsync(credentials, hubId, folderUrn, folderContentItem.Value.links.self.href, context);
                    }
                }
            }
            catch (Exception e)
            {
            }
        }
示例#5
0
        public async Task <IList <Item> > GetFolderContentsAsync(string projectId, string folderId)
        {
            string sessionId, localId;

            if (!HeaderUtils.GetSessionLocalIDs(out sessionId, out localId))
            {
                return(null);
            }
            if (!await OAuthDB.IsSessionIdValid(sessionId, localId))
            {
                return(null);
            }
            string userAccessToken = await OAuthDB.GetAccessToken(sessionId, localId);

            IList <Item> folderItems = new List <Item>();

            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = userAccessToken;
            var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId);

            foreach (KeyValuePair <string, dynamic> folderContentItem in new DynamicDictionaryItems(folderContents.data))
            {
                string displayName = folderContentItem.Value.attributes.displayName;
                if (string.IsNullOrWhiteSpace(displayName))
                {
                    continue;
                }

                Item itemNode = new Item(folderContentItem.Value.links.self.href, displayName, (string)folderContentItem.Value.type);

                folderItems.Add(itemNode);
            }

            return(folderItems);
        }
        public async Task <IActionResult> OnCallbackUpdategp([FromBody] dynamic body)
        {
            try
            {
                dynamic oauth = await OAuthController.GetInternalAsync();

                JObject bodyJson     = JObject.Parse((string)body.ToString());
                var     parentFolder = (string)body.payload.parentFolderUrn;
                var     status       = (string)body.payload.state;
                var     user         = (string)body.payload.context.lineage.createUserName;
                var     project      = (string)body.hook.hookAttribute.projectName;
                var     projectId    = (string)body.hook.hookAttribute.projectId;
                var     fileName     = (string)body.payload.name;
                var     hub          = (string)body.hook.hookAttribute.hubId;
                var     version      = (int)body.payload.version;
                var     rvt          = (string)body.payload.name;
                var     urn          = (string)body.payload.lineageUrn;
                urn = urn.Split(":").Last();
                var folderApi = new FoldersApi();
                folderApi.Configuration.AccessToken = oauth.access_token;
                var content = await folderApi.GetFolderContentsAsync(projectId, parentFolder);

                var included  = new DynamicDictionaryItems(content.included);
                var _included = included.FirstOrDefault(x => (new KeyValuePair <string, dynamic>(x.Key, x.Value).Value.id as string).Contains(urn));
                var guid      = ((string)((dynamic)_included.Value).relationships.storage.data.id).Split("/").Last();

                //var texto = bodyJson.ToString();
                var gp = await PostGoodPractices(project, version, hub, rvt, guid);

                // TODO: Enviar email si la respuesta es correcta.
                await SendEmail(user, fileName, project, version);
            }
            catch { }

            return(Ok());
        }
        private async Task <IList <jsTreeNode> > GetFolderContents(string href)
        {
            IList <jsTreeNode> nodes = new List <jsTreeNode>();

            // the API SDK
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = Credentials.TokenInternal;

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

            // check if folder specifies visible types
            JArray  visibleTypes = null;
            dynamic folder       = (await folderApi.GetFolderAsync(projectId, folderId)).ToJson();

            if (folder.data.attributes != null && folder.data.attributes.extension != null && folder.data.attributes.extension.data != null && !(folder.data.attributes.extension.data is JArray) && folder.data.attributes.extension.data.visibleTypes != null)
            {
                visibleTypes = folder.data.attributes.extension.data.visibleTypes;
            }

            var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId);

            // the GET Folder Contents has 2 main properties: data & included (not always available)
            var folderData     = new DynamicDictionaryItems(folderContents.data);
            var folderIncluded = (folderContents.Dictionary.ContainsKey("included") ? new DynamicDictionaryItems(folderContents.included) : null);

            // let's start iterating the FOLDER DATA
            foreach (KeyValuePair <string, dynamic> folderContentItem in folderData)
            {
                // do we need to skip some items? based on the visibleTypes of this folder
                string extension = folderContentItem.Value.attributes.extension.type;
                if (extension.IndexOf("Folder") /*any folder*/ == -1 && visibleTypes != null && !visibleTypes.ToString().Contains(extension))
                {
                    continue;
                }

                // if the type is items:autodesk.bim360:Document we need some manipulation...
                if (extension.Equals("items:autodesk.bim360:Document"))
                {
                    // as this is a DOCUMENT, lets interate the FOLDER INCLUDED to get the name (known issue)
                    foreach (KeyValuePair <string, dynamic> includedItem in folderIncluded)
                    {
                        // check if the id match...
                        if (includedItem.Value.relationships.item.data.id.IndexOf(folderContentItem.Value.id) != -1)
                        {
                            // found it! now we need to go back on the FOLDER DATA to get the respective FILE for this DOCUMENT
                            foreach (KeyValuePair <string, dynamic> folderContentItem1 in folderData)
                            {
                                if (folderContentItem1.Value.attributes.extension.type.IndexOf("File") == -1)
                                {
                                    continue;                                                                           // skip if type is NOT File
                                }
                                // check if the sourceFileName match...
                                if (folderContentItem1.Value.attributes.extension.data.sourceFileName == includedItem.Value.attributes.extension.data.sourceFileName)
                                {
                                    // ready!

                                    // let's return for the jsTree with a special id:
                                    // itemUrn|versionUrn|viewableId
                                    // itemUrn: used as target_urn to get document issues
                                    // versionUrn: used to launch the Viewer
                                    // viewableId: which viewable should be loaded on the Viewer
                                    // this information will be extracted when the user click on the tree node, see ForgeTree.js:136 (activate_node.jstree event handler)
                                    string treeId = string.Format("{0}|{1}|{2}",
                                                                  folderContentItem.Value.id,                                       // item urn
                                                                  Base64Encode(folderContentItem1.Value.relationships.tip.data.id), // version urn
                                                                  includedItem.Value.attributes.extension.data.viewableId           // viewableID
                                                                  );
                                    nodes.Add(new jsTreeNode(treeId, WebUtility.UrlDecode(includedItem.Value.attributes.name), "bim360documents", false));
                                }
                            }
                        }
                    }
                }
                else
                {
                    // non-Plans folder items
                    nodes.Add(new jsTreeNode(folderContentItem.Value.links.self.href, folderContentItem.Value.attributes.displayName, (string)folderContentItem.Value.type, true));
                }
            }

            return(nodes);
        }
        //public async Task<dynamic> UploadObject([FromForm]UploadFile input)
        public async Task <dynamic> UploadObject(Stream input)//mb
        {
            // get the uploaded file and save on the server

            /*mb var fileSavePath = Path.Combine(_env.ContentRootPath, input.fileToUpload.FileName);
             * using (var stream = new FileStream(fileSavePath, FileMode.Create))
             *  await input.fileToUpload.CopyToAsync(stream); mb*/

            // user credentials
            Credentials = await Credentials.FromSessionAsync(base.Request.Cookies, Response.Cookies);

            // extract projectId and folderId from folderHref

            /*mb string[] hrefParams = input.folderHref.Split("/");
             * string projectId = hrefParams[hrefParams.Length - 3];
             * string folderId = hrefParams[hrefParams.Length - 1]; mb*/
            string projectId = "3be23c1c-1383-440a-b395-ac5933f797a1";
            string folderId  = "urn:adsk.wipprod:fs.folder:co.-w2D5-voTQiB-6-aowONzg";
            string fileName  = "result.ifc";

            // prepare storage
            ProjectsApi projectApi = new ProjectsApi();

            projectApi.Configuration.AccessToken = Credentials.TokenInternal;
            StorageRelationshipsTargetData       storageRelData = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
            CreateStorageDataRelationshipsTarget storageTarget  = new CreateStorageDataRelationshipsTarget(storageRelData);
            CreateStorageDataRelationships       storageRel     = new CreateStorageDataRelationships(storageTarget);
            BaseAttributesExtensionObject        attributes     = new BaseAttributesExtensionObject(string.Empty, string.Empty, new JsonApiLink(string.Empty), null);
            //mb CreateStorageDataAttributes storageAtt = new CreateStorageDataAttributes(input.fileToUpload.FileName, attributes);
            CreateStorageDataAttributes storageAtt  = new CreateStorageDataAttributes(fileName, attributes);
            CreateStorageData           storageData = new CreateStorageData(CreateStorageData.TypeEnum.Objects, storageAtt, storageRel);
            CreateStorage storage        = new CreateStorage(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), storageData);
            dynamic       storageCreated = await projectApi.PostStorageAsync(projectId, storage);

            string[] storageIdParams = ((string)storageCreated.data.id).Split('/');
            string[] bucketKeyParams = storageIdParams[storageIdParams.Length - 2].Split(':');
            string   bucketKey       = bucketKeyParams[bucketKeyParams.Length - 1];
            string   objectName      = storageIdParams[storageIdParams.Length - 1];

            // upload the file/object, which will create a new object
            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = Credentials.TokenInternal;

            // get file size
            //mb long fileSize = (new FileInfo(fileSavePath)).Length;
            long fileSize = 10;

            // decide if upload direct or resumable (by chunks)
            if (fileSize > UPLOAD_CHUNK_SIZE * 1024 * 1024) // upload in chunks
            {
                /*mb long chunkSize = 2 * 1024 * 1024; // 2 Mb
                 * long numberOfChunks = (long)Math.Round((double)(fileSize / chunkSize)) + 1;
                 *
                 * long start = 0;
                 * chunkSize = (numberOfChunks > 1 ? chunkSize : fileSize);
                 * long end = chunkSize;
                 * string sessionId = Guid.NewGuid().ToString();
                 *
                 * // upload one chunk at a time
                 * using (BinaryReader reader = new BinaryReader(new FileStream(fileSavePath, FileMode.Open)))
                 * {
                 *  for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
                 *  {
                 *      string range = string.Format("bytes {0}-{1}/{2}", start, end, fileSize);
                 *
                 *      long numberOfBytes = chunkSize + 1;
                 *      byte[] fileBytes = new byte[numberOfBytes];
                 *      MemoryStream memoryStream = new MemoryStream(fileBytes);
                 *      reader.BaseStream.Seek((int)start, SeekOrigin.Begin);
                 *      int count = reader.Read(fileBytes, 0, (int)numberOfBytes);
                 *      memoryStream.Write(fileBytes, 0, (int)numberOfBytes);
                 *      memoryStream.Position = 0;
                 *
                 *      await objects.UploadChunkAsync(bucketKey, objectName, (int)numberOfBytes, range, sessionId, memoryStream);
                 *
                 *      start = end + 1;
                 *      chunkSize = ((start + chunkSize > fileSize) ? fileSize - start - 1 : chunkSize);
                 *      end = start + chunkSize;
                 *  }
                 * } mb*/
            }
            else // upload in a single call
            {
                /*mb using (StreamReader streamReader = new StreamReader(fileSavePath))
                 * {
                 *   await objects.UploadObjectAsync(bucketKey, objectName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
                 * } mb*/
                await objects.UploadObjectAsync(bucketKey, objectName, (int)input.Length, input, "application/octet-stream");
            }

            // cleanup

            /*mb string fileName = input.fileToUpload.FileName;
             * System.IO.File.Delete(fileSavePath); mb*/

            // check if file already exists...
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = Credentials.TokenInternal;
            var filesInFolder = await folderApi.GetFolderContentsAsync(projectId, folderId);

            string itemId = string.Empty;

            foreach (KeyValuePair <string, dynamic> item in new DynamicDictionaryItems(filesInFolder.data))
            {
                if (item.Value.attributes.displayName == fileName)
                {
                    itemId = item.Value.id; // this means a file with same name is already there, so we'll create a new version
                }
            }
            // now decide whether create a new item or new version
            if (string.IsNullOrWhiteSpace(itemId))
            {
                // create a new item
                BaseAttributesExtensionObject        baseAttribute                   = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "items:autodesk.core:File" : "items:autodesk.bim360:File", "1.0");
                CreateItemDataAttributes             createItemAttributes            = new CreateItemDataAttributes(fileName, baseAttribute);
                CreateItemDataRelationshipsTipData   createItemRelationshipsTipData  = new CreateItemDataRelationshipsTipData(CreateItemDataRelationshipsTipData.TypeEnum.Versions, CreateItemDataRelationshipsTipData.IdEnum._1);
                CreateItemDataRelationshipsTip       createItemRelationshipsTip      = new CreateItemDataRelationshipsTip(createItemRelationshipsTipData);
                StorageRelationshipsTargetData       storageTargetData               = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
                CreateStorageDataRelationshipsTarget createStorageRelationshipTarget = new CreateStorageDataRelationshipsTarget(storageTargetData);
                CreateItemDataRelationships          createItemDataRelationhips      = new CreateItemDataRelationships(createItemRelationshipsTip, createStorageRelationshipTarget);
                CreateItemData createItemData = new CreateItemData(CreateItemData.TypeEnum.Items, createItemAttributes, createItemDataRelationhips);
                BaseAttributesExtensionObject      baseAttExtensionObj = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes        storageDataAtt      = new CreateStorageDataAttributes(fileName, baseAttExtensionObj);
                CreateItemRelationshipsStorageData createItemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                CreateItemRelationshipsStorage     createItemRelationshipsStorage     = new CreateItemRelationshipsStorage(createItemRelationshipsStorageData);
                CreateItemRelationships            createItemRelationship             = new CreateItemRelationships(createItemRelationshipsStorage);
                CreateItemIncluded includedVersion = new CreateItemIncluded(CreateItemIncluded.TypeEnum.Versions, CreateItemIncluded.IdEnum._1, storageDataAtt, createItemRelationship);
                CreateItem         createItem      = new CreateItem(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), createItemData, new List <CreateItemIncluded>()
                {
                    includedVersion
                });

                ItemsApi itemsApi = new ItemsApi();
                itemsApi.Configuration.AccessToken = Credentials.TokenInternal;
                var newItem = await itemsApi.PostItemAsync(projectId, createItem);

                return(newItem);
            }
            else
            {
                // create a new version
                BaseAttributesExtensionObject          attExtensionObj              = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes            storageDataAtt               = new CreateStorageDataAttributes(fileName, attExtensionObj);
                CreateVersionDataRelationshipsItemData dataRelationshipsItemData    = new CreateVersionDataRelationshipsItemData(CreateVersionDataRelationshipsItemData.TypeEnum.Items, itemId);
                CreateVersionDataRelationshipsItem     dataRelationshipsItem        = new CreateVersionDataRelationshipsItem(dataRelationshipsItemData);
                CreateItemRelationshipsStorageData     itemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                CreateItemRelationshipsStorage         itemRelationshipsStorage     = new CreateItemRelationshipsStorage(itemRelationshipsStorageData);
                CreateVersionDataRelationships         dataRelationships            = new CreateVersionDataRelationships(dataRelationshipsItem, itemRelationshipsStorage);
                CreateVersionData versionData    = new CreateVersionData(CreateVersionData.TypeEnum.Versions, storageDataAtt, dataRelationships);
                CreateVersion     newVersionData = new CreateVersion(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), versionData);

                VersionsApi versionsApis = new VersionsApi();
                versionsApis.Configuration.AccessToken = Credentials.TokenInternal;
                dynamic newVersion = await versionsApis.PostVersionAsync(projectId, newVersionData);

                return(newVersion);
            }
        }
        private async Task <IList <jsTreeNode> > GetFolderContents(string href, string qtype, string qtext)
        {
            IList <jsTreeNode> nodes = new List <jsTreeNode>();

            // the API SDK
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = Credentials.TokenInternal;

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

            // check if folder specifies visible types
            JArray  visibleTypes = null;
            dynamic folder       = (await folderApi.GetFolderAsync(projectId, folderId)).ToJson();

            if (folder.data.attributes != null && folder.data.attributes.extension != null && folder.data.attributes.extension.data != null && !(folder.data.attributes.extension.data is JArray) && folder.data.attributes.extension.data.visibleTypes != null)
            {
                visibleTypes = folder.data.attributes.extension.data.visibleTypes;
            }

            var folderContents = await folderApi.GetFolderContentsAsync(projectId, folderId);

            // the GET Folder Contents has 2 main properties: data & included (not always available)
            var folderData     = new DynamicDictionaryItems(folderContents.data);
            var folderIncluded = (folderContents.Dictionary.ContainsKey("included") ? new DynamicDictionaryItems(folderContents.included) : null);

            // let's start iterating the FOLDER DATA
            foreach (KeyValuePair <string, dynamic> folderContentItem in folderData)
            {
                // do we need to skip some items? based on the visibleTypes of this folder
                string extension = folderContentItem.Value.attributes.extension.type;
                if (extension.IndexOf("Folder") /*any folder*/ == -1 && visibleTypes != null && !visibleTypes.ToString().Contains(extension))
                {
                    continue;
                }

                // if the type is items:autodesk.bim360:Document we need some manipulation...
                if (extension.Equals("items:autodesk.bim360:Document"))
                {
                    //mb
                    continue;
                    // as this is a DOCUMENT, lets interate the FOLDER INCLUDED to get the name (known issue)
                    foreach (KeyValuePair <string, dynamic> includedItem in folderIncluded)
                    {
                        // check if the id match...
                        if (includedItem.Value.relationships.item.data.id.IndexOf(folderContentItem.Value.id) != -1)
                        {
                            // found it! now we need to go back on the FOLDER DATA to get the respective FILE for this DOCUMENT
                            foreach (KeyValuePair <string, dynamic> folderContentItem1 in folderData)
                            {
                                if (folderContentItem1.Value.attributes.extension.type.IndexOf("File") == -1)
                                {
                                    continue;                                                                           // skip if type is NOT File
                                }
                                // check if the sourceFileName match...
                                if (folderContentItem1.Value.attributes.extension.data.sourceFileName == includedItem.Value.attributes.extension.data.sourceFileName)
                                {
                                    // ready!

                                    // let's return for the jsTree with a special id:
                                    // itemUrn|versionUrn|viewableId
                                    // itemUrn: used as target_urn to get document issues
                                    // versionUrn: used to launch the Viewer
                                    // viewableId: which viewable should be loaded on the Viewer
                                    // this information will be extracted when the user click on the tree node, see ForgeTree.js:136 (activate_node.jstree event handler)
                                    string treeId = string.Format("{0}|{1}|{2}",
                                                                  folderContentItem.Value.id,                                       // item urn
                                                                  Base64Encode(folderContentItem1.Value.relationships.tip.data.id), // version urn
                                                                  includedItem.Value.attributes.extension.data.viewableId           // viewableID
                                                                  );
                                    nodes.Add(new jsTreeNode(treeId, WebUtility.UrlDecode(includedItem.Value.attributes.name), "bim360documents", false));
                                }
                            }
                        }
                    }
                }
                else if (extension.Equals("folders:autodesk.bim360:Folder"))
                {
                    //mb: , string qtype, string qtext
                    string   legend      = "";
                    string   permissions = "";
                    string   userId      = "";
                    string[] useremails  = null;
                    string[] companies   = null;
                    string[] roles       = null;

                    if (qtype.Equals("userId"))
                    {
                        //get user company and roles
                        userId = qtext.Trim();
                        string utoken  = Credentials.TokenInternal;
                        var    uclient = new RestClient("https://developer.api.autodesk.com/bim360/admin/v1/projects/" + projectId.Substring(2) + "/users/" + userId);
                        uclient.Timeout = -1;
                        var urequest = new RestRequest(Method.GET);
                        urequest.AddHeader("Content-Type", "application/json");
                        urequest.AddHeader("Accept", "application/json");
                        urequest.AddHeader("Authorization", "Bearer " + utoken);
                        IRestResponse uresponse = uclient.Execute(urequest);
                        JObject       ures      = JObject.Parse(uresponse.Content);
                        useremails = new string[] { ures["email"].ToString() };
                        companies  = new string[] { ures["companyId"].ToString() };
                        List <string> lroles = new List <string>();
                        foreach (var item in ures["roleIds"].Children())
                        {
                            lroles.Add(item.ToString());
                        }
                        roles = lroles.ToArray();
                    }
                    else if (qtype.Equals("by_emails_only"))
                    {
                        useremails = qtext.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    else if (qtype.Equals("companies"))
                    {
                        companies = qtext.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    else if (qtype.Equals("roles"))
                    {
                        roles = qtext.Split(new Char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }

                    string token     = Credentials.TokenInternal;
                    string folderUrn = folderContentItem.Value.links.self.href.ToString();
                    folderUrn = folderUrn.Split("/folders/")[1].Split("/contents?")[0].Replace(":", "%3A");
                    var client = new RestClient("https://developer.api.autodesk.com/bim360/docs/v1/projects/" + projectId.Substring(2) + "/folders/" + folderUrn + "/permissions");
                    client.Timeout = -1;
                    var request = new RestRequest(Method.GET);
                    request.AddHeader("Content-Type", "application/vnd.api+json");
                    request.AddHeader("Accept", "application/vnd.api+json");
                    request.AddHeader("Authorization", "Bearer " + token);

                    try
                    {
                        bool   validresponse = false;
                        int    countvr       = 0;
                        int    maxvr         = 3;
                        JArray res           = null;
                        while (!validresponse)
                        {
                            ++countvr;
                            IRestResponse response = client.Execute(request);
                            //Console.WriteLine(response.Content);
                            try
                            {
                                res           = JArray.Parse(response.Content);
                                validresponse = true;
                            }
                            catch
                            {
                                if (countvr >= maxvr)
                                {
                                    break;
                                }
                                System.Threading.Thread.Sleep(25000);
                            }
                        }



                        foreach (var item in res.Children())
                        {
                            dynamic data = JObject.Parse(item.ToString());
                            if (data["subjectType"].ToString().Equals("USER") && useremails != null)
                            {
                                int count = 0;
                                foreach (string useremail in useremails)
                                {
                                    ++count;
                                    if (data["email"].ToString().Equals(useremail.Trim()))
                                    {
                                        permissions += " " + GetPermissionString(data, count, useremail);
                                    }
                                }
                            }
                            else if (data["subjectType"].ToString().Equals("COMPANY") && companies != null)
                            {
                                int count = 3;
                                foreach (string company in companies)
                                {
                                    ++count;
                                    if (data["name"].ToString().Equals(company.Trim()) || data["subjectId"].ToString().Equals(company.Trim()))
                                    {
                                        permissions += " " + GetPermissionString(data, count, "C:" + data["name"].ToString());
                                    }
                                }
                            }
                            else if (data["subjectType"].ToString().Equals("ROLE") && roles != null)
                            {
                                int count = 6;
                                foreach (string role in roles)
                                {
                                    ++count;
                                    if (data["name"].ToString().Equals(role.Trim()) || data["subjectId"].ToString().Equals(role.Trim()))
                                    {
                                        permissions += " " + GetPermissionString(data, count, "R:" + data["name"].ToString());
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception e) { permissions = e.Message + "###" + e.StackTrace; }


                    // non-Plans folder items
                    //if (folderContentItem.Value.attributes.hidden == true) continue;
                    nodes.Add(new jsTreeNode(folderContentItem.Value.links.self.href, folderContentItem.Value.attributes.displayName + permissions, (string)folderContentItem.Value.type, true));
                }
            }
            //nodes.Add(new jsTreeNode("", "long long text", "folders", false));
            return(nodes);
        }
示例#10
0
        public async Task <IActionResult> SubmitProject([FromForm] InputSubmit input)
        {
            string projectId = "b.014c6054-6da1-4ed8-b199-1975c07f608a";
            string folderId  = "urn:adsk.wipprod:fs.folder:co.1X3m8NAlRL-xNDQsXk_bxQ";

            Credentials credentials = await Credentials.FromDatabaseAsync(Utils.GetAppSetting("USERID"));

            dynamic token2lo = await OAuthController2L.GetInternalAsync();

            var fileSavePath = Path.Combine(_env.ContentRootPath, input.fileToUpload.FileName);

            using (var stream = new FileStream(fileSavePath, FileMode.Create))
                await input.fileToUpload.CopyToAsync(stream);

            // prepare storage
            ProjectsApi projectApi = new ProjectsApi();

            projectApi.Configuration.AccessToken = credentials.TokenInternal;
            StorageRelationshipsTargetData       storageRelData = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
            CreateStorageDataRelationshipsTarget storageTarget  = new CreateStorageDataRelationshipsTarget(storageRelData);
            CreateStorageDataRelationships       storageRel     = new CreateStorageDataRelationships(storageTarget);
            BaseAttributesExtensionObject        attributes     = new BaseAttributesExtensionObject(string.Empty, string.Empty, new JsonApiLink(string.Empty), null);
            CreateStorageDataAttributes          storageAtt     = new CreateStorageDataAttributes(input.fileToUpload.FileName, attributes);
            CreateStorageData storageData    = new CreateStorageData(CreateStorageData.TypeEnum.Objects, storageAtt, storageRel);
            CreateStorage     storage        = new CreateStorage(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), storageData);
            dynamic           storageCreated = await projectApi.PostStorageAsync(projectId, storage);

            string[] storageIdParams = ((string)storageCreated.data.id).Split('/');
            string[] bucketKeyParams = storageIdParams[storageIdParams.Length - 2].Split(':');
            string   bucketKey       = bucketKeyParams[bucketKeyParams.Length - 1];
            string   objectName      = storageIdParams[storageIdParams.Length - 1];

            // upload the file/object, which will create a new object
            ObjectsApi objects = new ObjectsApi();

            objects.Configuration.AccessToken = credentials.TokenInternal;

            // get file size
            long fileSize = (new FileInfo(fileSavePath)).Length;

            // decide if upload direct or resumable (by chunks)
            if (fileSize > UPLOAD_CHUNK_SIZE * 1024 * 1024) // upload in chunks
            {
                long chunkSize      = 2 * 1024 * 1024;      // 2 Mb
                long numberOfChunks = (long)Math.Round((double)(fileSize / chunkSize)) + 1;

                long start = 0;
                chunkSize = (numberOfChunks > 1 ? chunkSize : fileSize);
                long   end       = chunkSize;
                string sessionId = Guid.NewGuid().ToString();

                // upload one chunk at a time
                using (BinaryReader reader = new BinaryReader(new FileStream(fileSavePath, FileMode.Open)))
                {
                    for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
                    {
                        string range = string.Format("bytes {0}-{1}/{2}", start, end, fileSize);

                        long         numberOfBytes = chunkSize + 1;
                        byte[]       fileBytes     = new byte[numberOfBytes];
                        MemoryStream memoryStream  = new MemoryStream(fileBytes);
                        reader.BaseStream.Seek((int)start, SeekOrigin.Begin);
                        int count = reader.Read(fileBytes, 0, (int)numberOfBytes);
                        memoryStream.Write(fileBytes, 0, (int)numberOfBytes);
                        memoryStream.Position = 0;

                        await objects.UploadChunkAsync(bucketKey, objectName, (int)numberOfBytes, range, sessionId, memoryStream);

                        start     = end + 1;
                        chunkSize = ((start + chunkSize > fileSize) ? fileSize - start - 1 : chunkSize);
                        end       = start + chunkSize;
                    }
                }
            }
            else // upload in a single call
            {
                using (StreamReader streamReader = new StreamReader(fileSavePath))
                {
                    await objects.UploadObjectAsync(bucketKey, objectName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
                }
            }

            // cleanup
            string fileName = input.fileToUpload.FileName;

            System.IO.File.Delete(fileSavePath);

            // check if file already exists...
            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = credentials.TokenInternal;
            var filesInFolder = await folderApi.GetFolderContentsAsync(projectId, folderId);

            string itemId = string.Empty;

            foreach (KeyValuePair <string, dynamic> item in new DynamicDictionaryItems(filesInFolder.data))
            {
                if (item.Value.attributes.displayName == fileName)
                {
                    itemId = item.Value.id; // this means a file with same name is already there, so we'll create a new version
                }
            }
            // now decide whether create a new item or new version
            if (string.IsNullOrWhiteSpace(itemId))
            {
                // create a new item
                BaseAttributesExtensionObject        baseAttribute                   = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "items:autodesk.core:File" : "items:autodesk.bim360:File", "1.0");
                CreateItemDataAttributes             createItemAttributes            = new CreateItemDataAttributes(fileName, baseAttribute);
                CreateItemDataRelationshipsTipData   createItemRelationshipsTipData  = new CreateItemDataRelationshipsTipData(CreateItemDataRelationshipsTipData.TypeEnum.Versions, CreateItemDataRelationshipsTipData.IdEnum._1);
                CreateItemDataRelationshipsTip       createItemRelationshipsTip      = new CreateItemDataRelationshipsTip(createItemRelationshipsTipData);
                StorageRelationshipsTargetData       storageTargetData               = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, folderId);
                CreateStorageDataRelationshipsTarget createStorageRelationshipTarget = new CreateStorageDataRelationshipsTarget(storageTargetData);
                CreateItemDataRelationships          createItemDataRelationhips      = new CreateItemDataRelationships(createItemRelationshipsTip, createStorageRelationshipTarget);
                CreateItemData createItemData = new CreateItemData(CreateItemData.TypeEnum.Items, createItemAttributes, createItemDataRelationhips);
                BaseAttributesExtensionObject      baseAttExtensionObj = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes        storageDataAtt      = new CreateStorageDataAttributes(fileName, baseAttExtensionObj);
                CreateItemRelationshipsStorageData createItemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                CreateItemRelationshipsStorage     createItemRelationshipsStorage     = new CreateItemRelationshipsStorage(createItemRelationshipsStorageData);
                CreateItemRelationships            createItemRelationship             = new CreateItemRelationships(createItemRelationshipsStorage);
                CreateItemIncluded includedVersion = new CreateItemIncluded(CreateItemIncluded.TypeEnum.Versions, CreateItemIncluded.IdEnum._1, storageDataAtt, createItemRelationship);
                CreateItem         createItem      = new CreateItem(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), createItemData, new List <CreateItemIncluded>()
                {
                    includedVersion
                });

                ItemsApi itemsApi = new ItemsApi();
                itemsApi.Configuration.AccessToken = credentials.TokenInternal;
                var newItem = await itemsApi.PostItemAsync(projectId, createItem);

                itemId = newItem.data.id;
            }
            else
            {
                // create a new version
                BaseAttributesExtensionObject          attExtensionObj              = new BaseAttributesExtensionObject(projectId.StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                CreateStorageDataAttributes            storageDataAtt               = new CreateStorageDataAttributes(fileName, attExtensionObj);
                CreateVersionDataRelationshipsItemData dataRelationshipsItemData    = new CreateVersionDataRelationshipsItemData(CreateVersionDataRelationshipsItemData.TypeEnum.Items, itemId);
                CreateVersionDataRelationshipsItem     dataRelationshipsItem        = new CreateVersionDataRelationshipsItem(dataRelationshipsItemData);
                CreateItemRelationshipsStorageData     itemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                CreateItemRelationshipsStorage         itemRelationshipsStorage     = new CreateItemRelationshipsStorage(itemRelationshipsStorageData);
                CreateVersionDataRelationships         dataRelationships            = new CreateVersionDataRelationships(dataRelationshipsItem, itemRelationshipsStorage);
                CreateVersionData versionData    = new CreateVersionData(CreateVersionData.TypeEnum.Versions, storageDataAtt, dataRelationships);
                CreateVersion     newVersionData = new CreateVersion(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), versionData);

                VersionsApi versionsApis = new VersionsApi();
                versionsApis.Configuration.AccessToken = credentials.TokenInternal;
                dynamic newVersion = await versionsApis.PostVersionAsync(projectId, newVersionData);
            }

            await NotificationDB.Register(itemId, input.phoneNumber);

            return(Ok());
        }
        private async void listFolderContents(MyTreeNode folderNode, bool isForDownload, bool isRecursive)
        {
            if (folderNode.nodeState == DownloadState.Downloaded ||
                folderNode.nodeState == DownloadState.Downloading)
            {
                if (isRecursive)
                {
                    foreach (MyTreeNode node in folderNode.Nodes)
                    {
                        if (node.nodeType == NodeType.Folder)
                        {
                            listFolderContents(node, isForDownload, isRecursive);
                        }
                        else if (node.nodeType == NodeType.Item)
                        {
                            listItemVersions(node, isForDownload);
                        }
                    }
                }
            }
            else
            {
                var foldersApi = new FoldersApi();
                foldersApi.Configuration.AccessToken = logInInfo.accessToken;

                string[] idParams  = folderNode.id.Split('/');
                string   folderId  = idParams[idParams.Length - 1];
                string   projectId = idParams[idParams.Length - 3];

                setNodeState(folderNode, true);

                dynamic contents = null;
                while (contents == null)
                {
                    try
                    {
                        contents = await foldersApi.GetFolderContentsAsync(projectId, folderId);
                    }
                    catch (Exception ex)
                    {
                        Debug.Print("startDownload >> catch1 : " + ex.Message);
                        await Task.Delay(kTimeOutDelay);
                    }
                }

                foreach (KeyValuePair <string, dynamic> contentInfo in new DynamicDictionaryItems(contents.data))
                {
                    NodeType   nodeType    = contentInfo.Value.attributes.extension.type.EndsWith(":Folder") ? NodeType.Folder : NodeType.Item;
                    MyTreeNode contentNode = new MyTreeNode(
                        contentInfo.Value.links.self.href,
                        contentInfo.Value.attributes.displayName,
                        contentInfo.Value.attributes.extension.type,
                        "",
                        nodeType
                        );
                    addToTreeView(folderNode, contentNode);
                    if (isRecursive)
                    {
                        if (contentNode.nodeType == NodeType.Folder)
                        {
                            listFolderContents(contentNode, isForDownload, isRecursive);
                        }
                        else if (contentNode.nodeType == NodeType.Item)
                        {
                            listItemVersions(contentNode, isForDownload);
                        }
                    }
                }
                setNodeState(folderNode, false);
            }
        }
示例#12
0
            public static async Task UploadAsync()
            {
                ProjectsApi projectsApi = new ProjectsApi();

                StorageRelationshipsTargetData       storageRelData = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, "urn:adsk.wipprod:fs.folder:co.OoAFTIjQTdCEF2HJUjee0g");
                CreateStorageDataRelationshipsTarget storageTarget  = new CreateStorageDataRelationshipsTarget(storageRelData);
                CreateStorageDataRelationships       storageRel     = new CreateStorageDataRelationships(storageTarget);
                BaseAttributesExtensionObject        attributes     = new BaseAttributesExtensionObject(string.Empty, string.Empty, new JsonApiLink(string.Empty), null);
                CreateStorageDataAttributes          storageAtt     = new CreateStorageDataAttributes("test", attributes);
                CreateStorageData storageData    = new CreateStorageData(CreateStorageData.TypeEnum.Objects, storageAtt, storageRel);
                CreateStorage     storage        = new CreateStorage(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), storageData);
                dynamic           storageCreated = await projectsApi.PostStorageAsync("3b5c6352-cf34-41fd-a0e9-a5246d93bf55", storage);

                string[] storageIdParams = ((string)storageCreated.data.id).Split('/');
                string[] bucketKeyParams = storageIdParams[storageIdParams.Length - 2].Split(':');
                string   bucketKey       = bucketKeyParams[bucketKeyParams.Length - 1];
                string   objectName      = storageIdParams[storageIdParams.Length - 1];

                ObjectsApi objects = new ObjectsApi();

                objects.Configuration.AccessToken = token;

                long fileSize = (new FileInfo(@"C:\Users\joao.martins\Desktop\ESGOTO_R2.rvt")).Length;

                if (fileSize > 5 * 1024 * 1024)            // upload in chunks if > 5Mb
                {
                    long chunkSize      = 2 * 1024 * 1024; // 2 Mb
                    long numberOfChunks = (long)Math.Round((double)(fileSize / chunkSize)) + 1;

                    long start = 0;
                    chunkSize = (numberOfChunks > 1 ? chunkSize : fileSize);
                    long   end       = chunkSize;
                    string sessionId = Guid.NewGuid().ToString();

                    // upload one chunk at a time
                    using (BinaryReader reader = new BinaryReader(new FileStream(@"C:\Users\joao.martins\Desktop\ESGOTO_R2.rvt", FileMode.Open)))
                    {
                        for (int chunkIndex = 0; chunkIndex < numberOfChunks; chunkIndex++)
                        {
                            string range = string.Format("bytes {0}-{1}/{2}", start, end, fileSize);

                            long         numberOfBytes = chunkSize + 1;
                            byte[]       fileBytes     = new byte[numberOfBytes];
                            MemoryStream memoryStream  = new MemoryStream(fileBytes);
                            reader.BaseStream.Seek((int)start, SeekOrigin.Begin);
                            int count = reader.Read(fileBytes, 0, (int)numberOfBytes);
                            memoryStream.Write(fileBytes, 0, (int)numberOfBytes);
                            memoryStream.Position = 0;

                            await objects.UploadChunkAsync(bucketKey, objectName, (int)numberOfBytes, range, sessionId, memoryStream);

                            start     = end + 1;
                            chunkSize = ((start + chunkSize > fileSize) ? fileSize - start - 1 : chunkSize);
                            end       = start + chunkSize;
                        }
                    }
                }
                else // upload in a single call
                {
                    using (StreamReader streamReader = new StreamReader(@"C:\Users\joao.martins\Desktop\ESGOTO_R2.rvt"))
                    {
                        await objects.UploadObjectAsync(bucketKey, objectName, (int)streamReader.BaseStream.Length, streamReader.BaseStream, "application/octet-stream");
                    }
                }

                // check if file already exists...
                FoldersApi folderApi = new FoldersApi();

                folderApi.Configuration.AccessToken = token;
                var filesInFolder = await folderApi.GetFolderContentsAsync("3b5c6352-cf34-41fd-a0e9-a5246d93bf55", "urn:adsk.wipprod:fs.folder:co.OoAFTIjQTdCEF2HJUjee0g");

                string itemId = string.Empty;

                foreach (KeyValuePair <string, dynamic> item in new DynamicDictionaryItems(filesInFolder.data))
                {
                    if (item.Value.attributes.displayName == "test")
                    {
                        itemId = item.Value.id; // this means a file with same name is already there, so we'll create a new version
                    }
                }
                // now decide whether create a new item or new version
                if (string.IsNullOrWhiteSpace(itemId))
                {
                    // create a new item
                    BaseAttributesExtensionObject        baseAttribute                   = new BaseAttributesExtensionObject("3b5c6352-cf34-41fd-a0e9-a5246d93bf55".StartsWith("a.") ? "items:autodesk.core:File" : "items:autodesk.bim360:File", "1.0");
                    CreateItemDataAttributes             createItemAttributes            = new CreateItemDataAttributes("test", baseAttribute);
                    CreateItemDataRelationshipsTipData   createItemRelationshipsTipData  = new CreateItemDataRelationshipsTipData(CreateItemDataRelationshipsTipData.TypeEnum.Versions, CreateItemDataRelationshipsTipData.IdEnum._1);
                    CreateItemDataRelationshipsTip       createItemRelationshipsTip      = new CreateItemDataRelationshipsTip(createItemRelationshipsTipData);
                    StorageRelationshipsTargetData       storageTargetData               = new StorageRelationshipsTargetData(StorageRelationshipsTargetData.TypeEnum.Folders, "urn:adsk.wipprod:fs.folder:co.OoAFTIjQTdCEF2HJUjee0g");
                    CreateStorageDataRelationshipsTarget createStorageRelationshipTarget = new CreateStorageDataRelationshipsTarget(storageTargetData);
                    CreateItemDataRelationships          createItemDataRelationhips      = new CreateItemDataRelationships(createItemRelationshipsTip, createStorageRelationshipTarget);
                    CreateItemData createItemData = new CreateItemData(CreateItemData.TypeEnum.Items, createItemAttributes, createItemDataRelationhips);
                    BaseAttributesExtensionObject      baseAttExtensionObj = new BaseAttributesExtensionObject("3b5c6352-cf34-41fd-a0e9-a5246d93bf55".StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                    CreateStorageDataAttributes        storageDataAtt      = new CreateStorageDataAttributes("test", baseAttExtensionObj);
                    CreateItemRelationshipsStorageData createItemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                    CreateItemRelationshipsStorage     createItemRelationshipsStorage     = new CreateItemRelationshipsStorage(createItemRelationshipsStorageData);
                    CreateItemRelationships            createItemRelationship             = new CreateItemRelationships(createItemRelationshipsStorage);
                    CreateItemIncluded includedVersion = new CreateItemIncluded(CreateItemIncluded.TypeEnum.Versions, CreateItemIncluded.IdEnum._1, storageDataAtt, createItemRelationship);
                    CreateItem         createItem      = new CreateItem(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), createItemData, new List <CreateItemIncluded>()
                    {
                        includedVersion
                    });

                    ItemsApi itemsApi = new ItemsApi();
                    itemsApi.Configuration.AccessToken = token;
                    var newItem = await itemsApi.PostItemAsync("3b5c6352-cf34-41fd-a0e9-a5246d93bf55", createItem);
                }
                else
                {
                    // create a new version
                    BaseAttributesExtensionObject          attExtensionObj              = new BaseAttributesExtensionObject("3b5c6352-cf34-41fd-a0e9-a5246d93bf55".StartsWith("a.") ? "versions:autodesk.core:File" : "versions:autodesk.bim360:File", "1.0");
                    CreateStorageDataAttributes            storageDataAtt               = new CreateStorageDataAttributes("test", attExtensionObj);
                    CreateVersionDataRelationshipsItemData dataRelationshipsItemData    = new CreateVersionDataRelationshipsItemData(CreateVersionDataRelationshipsItemData.TypeEnum.Items, itemId);
                    CreateVersionDataRelationshipsItem     dataRelationshipsItem        = new CreateVersionDataRelationshipsItem(dataRelationshipsItemData);
                    CreateItemRelationshipsStorageData     itemRelationshipsStorageData = new CreateItemRelationshipsStorageData(CreateItemRelationshipsStorageData.TypeEnum.Objects, storageCreated.data.id);
                    CreateItemRelationshipsStorage         itemRelationshipsStorage     = new CreateItemRelationshipsStorage(itemRelationshipsStorageData);
                    CreateVersionDataRelationships         dataRelationships            = new CreateVersionDataRelationships(dataRelationshipsItem, itemRelationshipsStorage);
                    CreateVersionData versionData    = new CreateVersionData(CreateVersionData.TypeEnum.Versions, storageDataAtt, dataRelationships);
                    CreateVersion     newVersionData = new CreateVersion(new JsonApiVersionJsonapi(JsonApiVersionJsonapi.VersionEnum._0), versionData);

                    VersionsApi versionsApis = new VersionsApi();
                    versionsApis.Configuration.AccessToken = token;
                    dynamic newVersion = await versionsApis.PostVersionAsync("3b5c6352-cf34-41fd-a0e9-a5246d93bf55", newVersionData);
                }
            }