Example #1
0
        public TestOutcome GetFile(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderDownload";
            try
            {
                FoldersApi foldersApi    = new FoldersApi(_url);
                string     fileName      = path + @"/" + "file";
                string     localfilename = "World-" + System.DateTime.Now.ToString("G", CultureInfo.CreateSpecificCulture("en-US")).Replace('/', '-').Replace(':', '_').Replace(' ', '_') + ".png";
                localfilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), localfilename);
                Stream downloadedFile = foldersApi.FolderDownload(_session.SessionId, fileName);
                using (FileStream localFile = File.Create(localfilename))

                {
                    downloadedFile.CopyTo(localFile);
                }
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
Example #2
0
        public TestOutcome CreateNote(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderNote";
            string noteName = "Note-" + System.DateTime.Now.ToString("G", CultureInfo.CreateSpecificCulture("en-US")).Replace('/', '-').Replace(':', '_');

            try
            {
                FoldersApi     foldersApi       = new FoldersApi(_url);
                Folder         containingFolder = foldersApi.FolderFind(_session.SessionId, path);
                ProjectContent content          = new ProjectContent(@"
                                                             <h1>A note</h1>
                                                             <p>This is a new note</p>
                                                            ");
                Folder         folder           = foldersApi.FolderNote(_session.SessionId, containingFolder.Id, "ProjectContent", noteName, content);
                Console.WriteLine(folder.Description);
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
        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);
        }
Example #4
0
        private Func <VoidEnvelopeRequestModel, UpdateEnvelopeResponseModel> VoidDraftEnvelopeFunc()
        {
            return(request =>
            {
                var account = AuthenticateUser(request.ESignAccount);
                var folderApi = new FoldersApi();
                var folders = folderApi.List(account.AccountId);
                var deletedFolder = folders.Folders.FirstOrDefault(x => x.Type == "recyclebin" && x.OwnerUserId == account.UserId);

                var currentFolder = folders.Folders
                                    .FirstOrDefault(folder => folderApi.ListItems(account.AccountId, folder.FolderId).FolderItems
                                                    .Any(folderItems => folderItems.EnvelopeId == request.EnvelopeId));

                if (deletedFolder != null && currentFolder != null)
                {
                    folderApi.MoveEnvelopes(account.AccountId, deletedFolder.FolderId, new FoldersRequest
                    {
                        EnvelopeIds = new List <string> {
                            request.EnvelopeId
                        },
                        FromFolderId = currentFolder.FolderId
                    });
                }

                return null;
            });
        }
Example #5
0
        public async Task <List <string> > GetRevitFileVersionId(string projectId, string versionId, string userAccessToken)
        {
            string folderId = await GetFolderId(projectId, versionId, userAccessToken);

            FoldersApi folderApi = new FoldersApi();

            folderApi.Configuration.AccessToken = userAccessToken;
            dynamic contents = await folderApi.SearchFolderContentsAsync(
                projectId, folderId, 0,
                new List <string>(new string[] { "rvt" }));

            if (contents.Data.included.Count == 0)
            {
                throw new Exception("No Revit file found in folder!");
            }

            List <string> versionIds = new List <string>();

            foreach (KeyValuePair <string, dynamic> includedItem in new DynamicDictionaryItems(contents.Data.included))
            {
                if (includedItem.Value.attributes.hidden == false)
                {
                    if (includedItem.Value.relationships.tip.data.type == "versions")
                    {
                        versionIds.Add(includedItem.Value.relationships.tip.data.id);
                    }
                }
            }

            return(versionIds);
        }
        public static IEnumerable <KeyValueDTO> GetFolders(DocuSignApiConfiguration conf)
        {
            var api     = new FoldersApi(conf.Configuration);
            var folders = api.List(conf.AccountId);

            return(folders.Folders?.Where(a => a.Filter == null).Select(a => new KeyValueDTO(a.Name, a.FolderId)) ?? new List <KeyValueDTO>());
        }
Example #7
0
        public TestOutcome CreateFile(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderFile";
            string imageName = "World-" + System.DateTime.Now.ToString("G", CultureInfo.CreateSpecificCulture("en-US")).Replace('/', '-').Replace(':', '_');

            try
            {
                FoldersApi foldersApi = new FoldersApi(_url);
                //string systempath = Environment.CurrentDirectory;
                string systempath = Application.StartupPath;
                using (FileStream fs = new FileStream(systempath + "\\world.jpg", FileMode.Open))
                {
                    foldersApi.FolderFile(_session.SessionId, path, fs, imageName);
                }
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
Example #8
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 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);
            }
        }
Example #10
0
        private static Func <BaseRequestModel, bool> IsFileExistFunc()
        {
            return(request =>
            {
                var accountId = Authenticate(request.ESignAccount);
                var folderApi = new FoldersApi();
                var folders = folderApi.List(accountId);

                return folders.Folders
                .Select(folder => folderApi.ListItems(accountId, folder.FolderId))
                .Any(listItems => listItems.FolderItems
                     .Any(listItem => listItem.EnvelopeId == request.EnvelopeId));
            });
        }
Example #11
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)
            {
            }
        }
        public void JwtMoveEnvelopesTest()
        {
            JwtRequestSignatureOnDocumentTest("sent");

            FoldersApi foldersApi = new FoldersApi(testConfig.ApiClient.Configuration);

            FoldersRequest foldersRequest = new FoldersRequest(EnvelopeIds: new List <string> {
                testConfig.EnvelopeId
            }, FromFolderId: "sentitems");

            string          ToFolderId = "draft";
            FoldersResponse foldersResponse;

            try
            {
                foldersResponse = foldersApi.MoveEnvelopes(testConfig.AccountId, ToFolderId, foldersRequest);
            }
            catch (Exception ex)
            {
                Assert.Fail("Expected no exception, Actual error message: " + ex.Message);
            }

            // Test if we moved the envelope to the correct folder
            FoldersApi.ListItemsOptions searchOptions = new FoldersApi.ListItemsOptions();
            searchOptions.includeItems = "true";

            var listfromDraftsFolder = foldersApi.ListItems(testConfig.AccountId, ToFolderId, searchOptions);

            Assert.IsNotNull(listfromDraftsFolder);

            bool doesExists = false;

            foreach (var folders in listfromDraftsFolder.Folders)
            {
                foreach (var item in folders.FolderItems)
                {
                    if (item.EnvelopeId == testConfig.EnvelopeId)
                    {
                        doesExists = true;
                        break;
                    }
                }
            }

            Assert.IsTrue(doesExists);
        }
Example #13
0
        public TestOutcome GetFolderByPath(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderFind";
            try
            {
                FoldersApi foldersApi = new FoldersApi(_url);
                Folder     folder     = foldersApi.FolderFind(_session.SessionId, path);
                Console.WriteLine(folder.Description);
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
Example #14
0
        public TestOutcome CreateFolder(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderCreate";
            string folderName = "folder_new" + System.DateTime.Now.ToString("G", CultureInfo.CreateSpecificCulture("en-US")).Replace('/', '-').Replace(':', '_');

            try
            {
                FoldersApi foldersApi = new FoldersApi(_url);
                Folder     newFolder  = new Folder(null, folderName, null, "this is a new folder", null, "ProjectFolder");
                Folder     folder     = foldersApi.FolderCreate(_session.SessionId, path, newFolder);
                Console.WriteLine(folder.Path);
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
Example #15
0
        public TestOutcome GetFolderBySearch()
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderSearch";
            try
            {
                FoldersApi  foldersApi = new FoldersApi(_url);
                FolderArray folders    = foldersApi.FolderSearch(_session.SessionId, "", true, 100, FilterGenerator.SimpleFilter("_", "contains", "method"));
                foreach (Folder folder in folders)
                {
                    Console.WriteLine(folder.Name);
                }
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
Example #16
0
        public TestOutcome GetFoldersUnder(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderList";
            try
            {
                FoldersApi  foldersApi = new FoldersApi(_url);
                FolderArray folders    = foldersApi.FolderList(_session.SessionId, path, 100);
                foreach (Folder folder in folders)
                {
                    Console.WriteLine(folder.Name);
                }
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
        public static IEnumerable <FolderItem> GetFolderItems(DocuSignApiConfiguration config, DocuSignQuery docuSignQuery)
        {
            var resultItems = new List <FolderItem>();

            FoldersApi api = new FoldersApi(config.Configuration);

            if (string.IsNullOrEmpty(docuSignQuery.Folder))
            {
                //return all envelopes from all folders
                var folders = api.List(config.AccountId).Folders.Where(a => a.Filter == null);
                if (folders != null)
                {
                    foreach (var item in folders)
                    {
                        var envelopesResponse = api.ListItems(config.AccountId, item.FolderId,
                                                              new FoldersApi.SearchOptions()
                        {
                            status     = docuSignQuery.Status,
                            searchText = docuSignQuery.SearchText
                        });
                        resultItems.AddRange(envelopesResponse.FolderItems);
                    }
                }
            }
            else
            {
                var envelopesResponse = api.ListItems(config.AccountId, docuSignQuery.Folder,
                                                      new FoldersApi.SearchOptions()
                {
                    status     = docuSignQuery.Status,
                    searchText = docuSignQuery.SearchText
                });
                resultItems.AddRange(envelopesResponse.FolderItems);
            }

            return(resultItems);
        }
Example #18
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());
        }
Example #20
0
        public TestOutcome UpdateFolder(string path)
        {
            TestOutcome outcome = new TestOutcome();

            outcome.moduleName = "Folders";
            outcome.methodName = "FolderUpdate";
            try
            {
                FoldersApi foldersApi = new FoldersApi(_url);
                Folder     folder     = foldersApi.FolderFind(_session.SessionId, path);
                folder.Description = "this is a new description";
                //! CMillshttps://edge-ka.atlassian.net/browse/BR4M2-693 means you have to set folder name to null may want to take this if the bug if fixed
                folder.Name = String.Empty;
                Folder upFolder = foldersApi.FolderUpdate(_session.SessionId, folder.Id, folder);
                Console.WriteLine(upFolder.Description);
                outcome.outcome = "Success";
                return(outcome);
            }
            catch (Exception ex)
            {
                outcome.outcome = ex.Message;
                return(outcome);
            }
        }
        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);
        }
Example #22
0
 public FoldersApiTests()
 {
     instance = new FoldersApi();
 }
        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);
        }
        //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);
            }
        }
 public void Init()
 {
     instance = new FoldersApi();
 }
Example #26
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());
        }
            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);
                }
            }
 public void TestInitialize()
 {
     _testConfig = new TestConfig();
     JwtLoginMethod.RequestJWTUserToken_CorrectInputParameters_ReturnsOAuthToken(ref _testConfig);
     _foldersApi = new FoldersApi(_testConfig.ApiClient);
 }
        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);
            }
        }