private BoxUtils.FileFolderInfo GetOrCreateFolderForEntity(UserTokenHandler tokenHandler, string parentFolderID, object entityRow, Guid?refNoteID)
        {
            // Try to find folder; if it doesn't exist, create it.
            string folderName = GetFolderNameForEntityRow(entityRow);

            return(GetOrCreateFolder(tokenHandler, parentFolderID, entityRow, refNoteID, folderName));
        }
 public static async Task SetFileDescription(UserTokenHandler tokenHandler, string fileID, string description)
 {
     var client      = GetNewBoxClient(tokenHandler);
     var fileRequest = new Box.V2.Models.BoxFileRequest {
         Id = fileID, Description = description
     };
     await client.FilesManager.UpdateInformationAsync(fileRequest).ConfigureAwait(false);
 }
        public static async Task CompleteAuthorization(UserTokenHandler tokenHandler, string authCode)
        {
            var config = new BoxConfig(ClientID, ClientSecret, new Uri(RedirectUri));
            var client = new BoxClient(config);

            client.Auth.SessionAuthenticated += tokenHandler.SessionAuthenticated;
            client.Auth.SessionInvalidated   += tokenHandler.SessionInvalidated;

            await client.Auth.AuthenticateAsync(authCode).ConfigureAwait(false);
        }
        public string GetOrCreateSublevelFolder(UserTokenHandler tokenHandler, string screenID, string parentFolderID, Guid?refNoteID, bool throwOnError)
        {
            BoxFolderSublevelCache sublevelFolder;
            var subLevelGrouping = GetSublevelName(refNoteID);

            if (string.IsNullOrEmpty(subLevelGrouping))
            {
                if (throwOnError)
                {
                    ScreenUtils.TraceAndThrowException(Messages.SubLevelConfigurationInvalid);
                }
                else
                {
                    PXTrace.WriteWarning(string.Format("No sublevel grouping found for note ID {0} (screen {1}, parent folder {2})", refNoteID, screenID, parentFolderID));
                    return(null);
                }
            }

            sublevelFolder = (BoxFolderSublevelCache)SubLevelByScreenAndGrouping.Select(screenID, subLevelGrouping);
            if (sublevelFolder == null)
            {
                var subLevelFolderInfo = GetOrCreateFolder(tokenHandler, parentFolderID, null, null, subLevelGrouping);

                sublevelFolder          = (BoxFolderSublevelCache)SubLevelByScreenAndGrouping.Cache.CreateInstance();
                sublevelFolder.FolderID = subLevelFolderInfo.ID;
                sublevelFolder.Grouping = subLevelGrouping;
                sublevelFolder.ScreenID = screenID;
                SubLevelByScreenAndGrouping.Insert(sublevelFolder);
            }
            else
            {
                try
                {
                    // Folder was found in BoxFolderCache, retrieve it by ID
                    var sublevelFolderInfo = BoxUtils.GetFolderInfo(tokenHandler, sublevelFolder.FolderID).Result;
                }
                catch (AggregateException ae)
                {
                    ScreenUtils.HandleAggregateException(ae, HttpStatusCode.NotFound, (exception) =>
                    {
                        using (new PXConnectionScope())
                        {
                            // Delete entry from BoxFolderCache so that it gets created again.
                            SubLevelByScreenAndGrouping.Delete(sublevelFolder);
                            Actions.PressSave();
                        }

                        throw new PXException(Messages.BoxFolderNotFoundTryAgain, sublevelFolder.FolderID, exception);
                    });
                }
            }

            return(sublevelFolder.FolderID);
        }
        private static async Task <FileFolderInfo> CreateFolder(BoxClient client, UserTokenHandler tokenHandler, string name, string parentFolderID)
        {
            var folderRequest = new BoxFolderRequest {
                Name = name, Parent = new BoxRequestEntity {
                    Id = parentFolderID
                }
            };

            Box.V2.Models.BoxFolder folder = await client.FoldersManager.CreateAsync(folderRequest, new List <string> {
                BoxItem.FieldName, BoxItem.FieldModifiedAt
            }).ConfigureAwait(false);

            return(new FileFolderInfo(folder.Id, folder.Name, parentFolderID, folder.ModifiedAt));
        }
        private BoxUtils.FileFolderInfo CreateBoxFolder(Guid?refNoteID, UserTokenHandler tokenHandler)
        {
            EntityHelper entityHelper     = new EntityHelper(this);
            object       entityRow        = entityHelper.GetEntityRow(refNoteID, true);
            Type         primaryGraphType = entityHelper.GetPrimaryGraphType(entityRow, false);

            if (primaryGraphType == null)
            {
                ScreenUtils.TraceAndThrowException(Messages.PrimaryGraphForNoteIDNotFound, refNoteID);
            }
            if (entityRow == null)
            {
                ScreenUtils.TraceAndThrowException(Messages.EntityRowForNoteIDNotFound, refNoteID);
            }

            object activityRefNoteID = entityRow.GetType().GetProperty("RefNoteID")?.GetValue(entityRow);

            if (activityRefNoteID != null && Type.GetType("PX.Objects.CR.CRActivity, PX.Objects").IsAssignableFrom(entityRow.GetType()))
            {
                return(GetOrCreateActivityFolder(refNoteID, tokenHandler, entityRow, activityRefNoteID));
            }
            else
            {
                // Create folder from screenID, for example "Customers (AR303000)"
                PXSiteMapNode siteMapNode = PXSiteMap.Provider.FindSiteMapNode(primaryGraphType);
                if (siteMapNode == null)
                {
                    throw new PXException(Messages.SiteMapNodeForGraphNotFound, primaryGraphType.FullName);
                }

                var bfcParent = (BoxFolderCache)FoldersByScreen.Select(siteMapNode.ScreenID);
                if (bfcParent == null)
                {
                    throw new PXException(Messages.ScreenMainFolderDoesNotExist, siteMapNode.ScreenID);
                }

                string parentFolderID = string.Empty;
                if (FieldsGroupingByScreenID.Select(siteMapNode.ScreenID).Any())
                {
                    parentFolderID = GetOrCreateSublevelFolder(tokenHandler, siteMapNode.ScreenID, bfcParent.FolderID, refNoteID, true);
                }
                else
                {
                    parentFolderID = bfcParent.FolderID;
                }

                return(GetOrCreateFolderForEntity(tokenHandler, parentFolderID, entityRow, refNoteID));
            }
        }
        public static async Task <FileFolderInfo> CreateFolder(UserTokenHandler tokenHandler, string name, string parentFolderID, string description)
        {
            var            client     = GetNewBoxClient(tokenHandler);
            FileFolderInfo folderInfo = await CreateFolder(client, tokenHandler, name, parentFolderID).ConfigureAwait(false);

            UpdateFolderDescription(client, tokenHandler, folderInfo.ID, description).Wait();

            return(new FileFolderInfo
            {
                ID = folderInfo.ID,
                Name = folderInfo.Name,
                ParentFolderID = folderInfo.ParentFolderID,
                ModifiedAt = folderInfo.ModifiedAt
            });
        }
        private BoxUtils.FileFolderInfo GetOrCreateActivityFolder(Guid?refNoteID, UserTokenHandler tokenHandler, object entityRow, object activityRefNoteID)
        {
            //Save an activity related file into the record's activity folder
            var activityRefNoteGuid = Guid.Parse(activityRefNoteID.ToString());

            //Get or create record folder
            string         folderID          = GetOrCreateBoxFolderForNoteID(activityRefNoteGuid);
            BoxFolderCache recordFolderCache = FoldersByFolderID.Select(folderID);

            //Get or create Activities folder
            BoxUtils.FileFolderInfo activityFolderInfo = null;
            if (string.IsNullOrEmpty(recordFolderCache.ActivityFolderID))
            {
                // Create Activities folder and update cache for future reference.
                activityFolderInfo = GetOrCreateFolder(tokenHandler, recordFolderCache.FolderID, null, null, Messages.ActivitiesFolderName);
                recordFolderCache.ActivityFolderID = activityFolderInfo.ID;
                FoldersByFolderID.Update(recordFolderCache);
                Actions.PressSave();
            }
            else
            {
                try
                {
                    // Folder was found in BoxFolderCache, retrieve it by ID
                    activityFolderInfo = BoxUtils.GetFolderInfo(tokenHandler, recordFolderCache.ActivityFolderID).Result;
                }
                catch (AggregateException ae)
                {
                    ScreenUtils.HandleAggregateException(ae, HttpStatusCode.NotFound, (exception) =>
                    {
                        using (new PXConnectionScope())
                        {
                            // Delete entry from BoxFolderCache so that it gets created again.
                            recordFolderCache.ActivityFolderID = null;
                            FoldersByNote.Update(recordFolderCache);
                            Actions.PressSave();
                        }

                        throw new PXException(Messages.BoxFolderNotFoundTryAgain, recordFolderCache.FolderID, exception);
                    });
                }
            }

            //Get/Create activityRecord folder
            string folderName = GetFolderNameForActivityRow(entityRow);

            return(GetOrCreateFolder(tokenHandler, activityFolderInfo.ID, entityRow, refNoteID, folderName));
        }
        public static async Task <FileFolderInfo> MoveFolder(UserTokenHandler tokenHandler, string movingFolderID, string newParentFolderID)
        {
            var client = GetNewBoxClient(tokenHandler);

            var folderRequest = new BoxFolderRequest {
                Id = movingFolderID, Parent = new BoxRequestEntity()
                {
                    Id = newParentFolderID, Type = BoxType.folder
                }
            };
            BoxFolder folder = await client.FoldersManager.UpdateInformationAsync(folderRequest, new List <string> {
                BoxItem.FieldName, BoxItem.FieldModifiedAt, BoxItem.FieldParent
            }).ConfigureAwait(false);

            return(new FileFolderInfo(folder.Id, folder.Name, folder.Parent.Id, folder.ModifiedAt));
        }
        public static async Task <FileFolderInfo> GetFolderInfo(UserTokenHandler tokenHandler, string folderID)
        {
            var client = GetNewBoxClient(tokenHandler);

            Box.V2.Models.BoxFolder folder = await client.FoldersManager.GetInformationAsync(folderID, new List <string> {
                BoxItem.FieldName, BoxItem.FieldModifiedAt, BoxItem.FieldParent
            }).ConfigureAwait(false);

            return(new FileFolderInfo
            {
                ID = folder.Id,
                Name = folder.Name,
                ParentFolderID = folder.Parent == null ? "0" : folder.Parent.Id,
                ModifiedAt = folder.ModifiedAt
            });
        }
        private BoxUtils.FileFolderInfo GetOrCreateFolder(UserTokenHandler tokenHandler, string parentFolderID, object entityRow, Guid?refNoteID, string folderName)
        {
            try
            {
                BoxUtils.FileFolderInfo folderInfo = BoxUtils.FindFolder(tokenHandler, parentFolderID, folderName).Result;

                if (folderInfo == null)
                {
                    // Folder doesn't exist on Box, create it.
                    var description = entityRow != null?GetFolderDescriptionForEntityRow(entityRow) : string.Empty;

                    folderInfo = BoxUtils.CreateFolder(tokenHandler, folderName, parentFolderID, description).Result;
                }

                if (!FoldersByFolderID.Select(folderInfo.ID).Any())
                {
                    // Store the folder info in our local cache for future reference
                    BoxFolderCache bfc = (BoxFolderCache)FoldersByFolderID.Cache.CreateInstance();
                    bfc.FolderID             = folderInfo.ID;
                    bfc.ParentFolderID       = folderInfo.ParentFolderID;
                    bfc.RefNoteID            = refNoteID;
                    bfc.LastModifiedDateTime = null; // To force initial sync of Box file list with record file ilst
                    bfc = FoldersByFolderID.Insert(bfc);
                }

                return(folderInfo);
            }
            catch (AggregateException ae)
            {
                ScreenUtils.HandleAggregateException(ae, HttpStatusCode.NotFound, (exception) =>
                {
                    using (new PXConnectionScope())
                    {
                        var bfc      = FoldersByFolderID.Cache.CreateInstance() as BoxFolderCache;
                        bfc.FolderID = parentFolderID;
                        FoldersByFolderID.Delete(bfc);
                        Actions.PressSave();
                    }

                    throw (new PXException(string.Format(Messages.BoxFolderNotFoundTryAgain, parentFolderID), exception));
                });

                return(null);
            }
        }
        public static async Task <FileFolderInfo> UploadFile(UserTokenHandler tokenHandler, string parentFolderID, string fileName, byte[] data)
        {
            var client      = GetNewBoxClient(tokenHandler);
            var fileRequest = new Box.V2.Models.BoxFileRequest {
                Name = fileName, Parent = new BoxRequestEntity {
                    Id = parentFolderID
                }
            };

            Box.V2.Models.BoxFile file = await client.FilesManager.UploadAsync(fileRequest, new MemoryStream(data)).ConfigureAwait(false);

            return(new FileFolderInfo
            {
                ID = file.Id,
                Name = file.Name,
                ParentFolderID = parentFolderID
            });
        }
        public static async Task <byte[]> DownloadFile(UserTokenHandler tokenHandler, string fileID)
        {
            var client       = GetNewBoxClient(tokenHandler);
            var memoryStream = new MemoryStream();

            using (Stream stream = await client.FilesManager.DownloadStreamAsync(fileID).ConfigureAwait(false))
            {
                int bytesRead;
                var buffer = new byte[8192];
                do
                {
                    bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

                    await memoryStream.WriteAsync(buffer, 0, bytesRead).ConfigureAwait(false);
                } while (bytesRead > 0);
            }
            return(memoryStream.ToArray());
        }
        private static BoxClient GetNewBoxClient(UserTokenHandler tokenHandler)
        {
            var currentUser = tokenHandler.GetCurrentUser();

            if (currentUser == null || currentUser.AccessToken == null || currentUser.RefreshToken == null)
            {
                throw new PXException(Messages.BoxUserNotFoundOrTokensExpired);
            }

            var          config  = new BoxConfig(ClientID, ClientSecret, new Uri(RedirectUri));
            OAuthSession session = new OAuthSession(tokenHandler.GetCurrentUser().AccessToken, tokenHandler.GetCurrentUser().RefreshToken, Expiration, "bearer");

            var client = new BoxClient(config, session);

            client.Auth.SessionAuthenticated += tokenHandler.SessionAuthenticated;
            client.Auth.SessionInvalidated   += tokenHandler.SessionInvalidated;

            return(client);
        }
        private static async Task <FileFolderInfo> UpdateFolderDescription(BoxClient client, UserTokenHandler tokenHandler, string folderID, string description)
        {
            if (!string.IsNullOrWhiteSpace(description))
            {
                var folderRequest = new BoxFolderRequest {
                    Id = folderID, Description = description
                };
                BoxFolder folder = await client.FoldersManager.UpdateInformationAsync(folderRequest, new List <string> {
                    BoxItem.FieldName, BoxItem.FieldParent, BoxItem.FieldModifiedAt
                }).ConfigureAwait(false);

                return(new FileFolderInfo
                {
                    ID = folderID,
                    Name = folder.Name,
                    ParentFolderID = folder.Parent.Id,
                    ModifiedAt = folder.ModifiedAt
                });
            }

            return(null);
        }
 public static async Task DeleteFile(UserTokenHandler tokenHandler, string fileID)
 {
     var client = GetNewBoxClient(tokenHandler);
     await client.FilesManager.DeleteAsync(fileID).ConfigureAwait(false);
 }
        public static async Task <List <FileFolderInfo> > GetFolderList(UserTokenHandler tokenHandler, string folderID, int recurseDepth)
        {
            var client = GetNewBoxClient(tokenHandler);

            return(await GetFolderListInternal(client, folderID, 0, recurseDepth, (int)RecursiveDepth.NoDepth, string.Empty).ConfigureAwait(false));
        }
        public static async Task <FileFolderInfo> CreateFolder(UserTokenHandler tokenHandler, string name, string parentFolderID)
        {
            var client = GetNewBoxClient(tokenHandler);

            return(await BoxUtils.CreateFolder(client, tokenHandler, name, parentFolderID).ConfigureAwait(false));
        }
        public static async Task <Box.V2.Models.BoxUser> GetUserInfo(UserTokenHandler tokenHandler)
        {
            var client = GetNewBoxClient(tokenHandler);

            return(await client.UsersManager.GetCurrentUserInformationAsync().ConfigureAwait(false));
        }
        public static async Task <FileFolderInfo> FindFolder(UserTokenHandler tokenHandler, string parentFolderID, string name)
        {
            var client = GetNewBoxClient(tokenHandler);

            return(await FindFolderInternal(client, parentFolderID, 0, name).ConfigureAwait(false));
        }
        public static async Task <FileFolderInfo> UpdateFolderDescription(UserTokenHandler tokenHandler, string folderID, string description)
        {
            var client = GetNewBoxClient(tokenHandler);

            return(await UpdateFolderDescription(client, tokenHandler, folderID, description).ConfigureAwait(false));
        }