private static async Task <BoxFolder> EnsureTopFolder(BoxClient auClient, TimeLimiter throttle) { BoxFolder topFolder; try { // トップレベルに親フォルダを作成 var folderParams = new BoxFolderRequest() { Name = Config.TopFolderName, Parent = new BoxRequestEntity() { Id = "0" } }; await throttle; topFolder = await auClient.FoldersManager.CreateAsync(folderParams); } catch (BoxConflictException <BoxFolder> bce) { // スクリプトを一度実行して、既にトップレベルフォルダが存在している topFolder = bce.ConflictingItems.First(); Console.WriteLine($"{topFolder.Name} already exists"); } return(topFolder); }
public async Task <IActionResult> BoxRedirect(String code) { // AUTHコードが受け取れたか確認 Console.WriteLine("BoxRedirect {0}", code); var config = new BoxConfig(ClientId, ClientSecret, new System.Uri(CallBackUrl)); var client = new BoxClient(config); // AUTHコード → アクセストークンへ交換 await client.Auth.AuthenticateAsync(code); var accessToken = client.Auth.Session.AccessToken; //var refreshToken = client.Auth.Session.RefreshToken; OAuthSession session = client.Auth.Session; HttpContext.Session.SetString("AccessToken", session.AccessToken); HttpContext.Session.SetString("RefreshToken", session.RefreshToken); HttpContext.Session.SetInt32("ExpiresIn", session.ExpiresIn); HttpContext.Session.SetString("TokenType", session.TokenType); // clientが動くかテスト var user = await client.UsersManager.GetCurrentUserInformationAsync(); Console.WriteLine($"Login User: Id={user.Id}, Name={user.Name}, Login={user.Login}"); ViewBag.accessToken = accessToken; return(RedirectToAction("UIElements")); }
private static async Task <List <FileFolderInfo> > GetFolderListInternal(BoxClient client, string folderID, int offset, int recurseDepth, int currentDepth, string levelName) { var list = new List <FileFolderInfo>(); var folderItems = await client.FoldersManager.GetFolderItemsAsync(folderID, FolderItemsCollectionLimit, offset, new List <string> { BoxItem.FieldName, BoxItem.FieldModifiedAt }).ConfigureAwait(false); foreach (var item in folderItems.Entries) { if (item.Type == "folder") { list.Add(new FileFolderInfo { ID = item.Id, ParentFolderID = folderID, Name = string.IsNullOrEmpty(levelName) ? item.Name : string.Format("{0}\\{1}", levelName, item.Name), ModifiedAt = item.ModifiedAt }); if (currentDepth < recurseDepth || recurseDepth == 0) { list.AddRange(await GetFolderListInternal(client, item.Id, 0, recurseDepth, currentDepth + 1, string.IsNullOrEmpty(levelName) ? item.Name : string.Format("{0}\\{1}", levelName, item.Name)).ConfigureAwait(false)); } } } if (folderItems.Offset + folderItems.Limit < folderItems.TotalCount) { list.AddRange(await GetFolderListInternal(client, folderID, offset + folderItems.Limit, recurseDepth, currentDepth, levelName).ConfigureAwait(false)); } return(list); }
private async Task ExecuteMainAsync() { Console.WriteLine("Access token: "); var accessToken = Console.ReadLine(); Console.WriteLine("Remote file name: "); var fileName = Console.ReadLine(); Console.WriteLine("Local file path: "); var localFilePath = Console.ReadLine(); Console.WriteLine("Parent folder Id: "); var parentFolderId = Console.ReadLine(); var timer = Stopwatch.StartNew(); var auth = new OAuthSession(accessToken, "YOUR_REFRESH_TOKEN", 3600, "bearer"); var config = new BoxConfig("YOUR_CLIENT_ID", "YOUR_CLIENT_ID", new Uri("http://boxsdk")); var client = new BoxClient(config, auth); var file = File.OpenRead(localFilePath); var fileRequest = new BoxFileRequest { Name = fileName, Parent = new BoxFolderRequest { Id = parentFolderId } }; var bFile = await client.FilesManager.UploadAsync(fileRequest, file); Console.WriteLine("{0} uploaded to folder: {1} as file: {2}",localFilePath, parentFolderId, bFile.Id); Console.WriteLine("Time spend : {0} ms", timer.ElapsedMilliseconds); }
public async Task <IActionResult> UIElements() { // セッションからアクセストークン等を取り出す // ここはおそらくよりよい方法があるはず var accessToken = HttpContext.Session.GetString("AccessToken"); var refreshToken = HttpContext.Session.GetString("RefreshToken"); // expiresInはそのまま利用すべきではないと思われるが・・ var expiresIn = HttpContext.Session.GetInt32("ExpiresIn") ?? default(int); var tokenType = HttpContext.Session.GetString("TokenType"); Console.WriteLine($"session accessToken {accessToken}"); Console.WriteLine($"session refreshToken {refreshToken}"); Console.WriteLine($"session expiresIn {expiresIn}"); Console.WriteLine($"session tokenType {tokenType}"); // sessionを組み立て直し var session = new OAuthSession(accessToken, refreshToken, expiresIn, tokenType); // clientをSessionを元に作成 var config = new BoxConfig(ClientId, ClientSecret, new System.Uri(CallBackUrl)); var client = new BoxClient(config, session); // 動作確認として認証したユーザーの情報を表示 var user = await client.UsersManager.GetCurrentUserInformationAsync(); Console.WriteLine($"Login User: Id={user.Id}, Name={user.Name}, Login={user.Login}"); ViewBag.accessToken = accessToken; return(View()); }
public async Task <BoxClient> GetBoxClient() { BoxClient boxClient = null; Uri uri = string.IsNullOrEmpty(RedirectUri) ? null : new Uri(RedirectUri); var BoxAuthorizeRequest = GetAuthorizeUri(OAuthResponseType.Code, clientId, uri).ToString(); var http = new HttpListener(); http.Prefixes.Add(RedirectUri); http.Start(); System.Diagnostics.Process.Start(BoxAuthorizeRequest); var context = await http.GetContextAsync(); string code = context.Request.QueryString.Get("code"); if (!string.IsNullOrEmpty(code)) { string token = await BoxAuthAsync(code); if (!string.IsNullOrEmpty(token)) { var config = new BoxConfig(clientId, secret, new Uri(RedirectUri)); var session = new OAuthSession(token, "NOT_NEEDED", 3600, "bearer"); boxClient = new BoxClient(config, session); } } return(boxClient); }
/// <summary> /// Updates the accessToken and refreshToken. These keys must already exist in the Dictionary table. /// </summary> public async Task RefreshAccessTokenAsync() { try { using (var _context = CTDbContext.CreateDbContext()) { var accessToken = await _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_ACCESS_TOKEN).FirstAsync(); var refreshToken = await _context.Dictionaries.Where(d => d.Key == CommonUtils.BOX_REFRESH_TOKEN).FirstAsync(); var config = new BoxConfig(Globals.appSettings.BOX_CLIENT_ID, Globals.appSettings.BOX_CLIENT_SECRET, new Uri("http://locahost")); var auth = new OAuthSession(accessToken.Value, refreshToken.Value, 3600, "bearer"); var client = new BoxClient(config, auth); /// Try to refresh the access token auth = await client.Auth.RefreshAccessTokenAsync(auth.AccessToken); /// Create the client again client = new BoxClient(config, auth); _logger.LogInformation("Refreshed Tokens"); accessToken.Value = auth.AccessToken; refreshToken.Value = auth.RefreshToken; await _context.SaveChangesAsync(); } } catch (Box.V2.Exceptions.BoxSessionInvalidatedException e) { _logger.LogError(e, "Box Token Failure."); await _slack.PostErrorAsync(e, "Box Token Failure."); throw; } }
/// <summary> /// Validates parameter input before processing the pipeline. /// </summary> /// <remarks> /// This method gets called once for each cmdlet in the pipeline when the pipeline starts executing (before the process block of any other command). /// </remarks> protected override void BeginProcessing() { if (!PoshBoxAuth.IsInitialized) { ThrowTerminatingError( new ErrorRecord( new Exception("No Box configuration found. Use Connect-Box to import a configuration."), "9000", ErrorCategory.InvalidOperation, null )); } if (Array.Exists(Properties, name => name == "*")) { Properties = BoxCollaborationPropertyNameCompleter.AllPropertyNames; } fieldNames = PropertyUtility.GetPropertyNames(typeof(BoxCollaboration), Properties); if (UserID == null) { WriteVerbose("Using admin client already established: " + PoshBoxAuth.BoxConfiguration.ClientId); client = PoshBoxAuth.BoxClient; } else { WriteVerbose("Retrieving user client for user: " + UserID); client = PoshBoxAuth.NewUserClient(UserID); } }
private static async Task CreateSearchUserCollaboration(BoxFolder topFolder, BoxClient auClient, TimeLimiter throttle) { var requestParams = new BoxCollaborationRequest() { Item = new BoxRequestEntity() { Type = BoxType.folder, Id = topFolder.Id }, Role = Config.SearchUserRole, AccessibleBy = new BoxCollaborationUserRequest() { Id = Config.SearchUserId } }; try { await throttle; await auClient.CollaborationsManager.AddCollaborationAsync(requestParams); } catch (BoxException be) { if (be.Message.Contains("user_already_collaborator")) { // ignore Console.WriteLine("コラボレーション設定済み"); } else { throw; } } }
private async Task <BitmapImage> GetThumbnailAsync(string id, BoxClient client) { BitmapImage image = new BitmapImage(); using (MemoryStream ms = new MemoryStream()) { using (Stream imageStream = await _client.FilesManager.GetThumbnailAsync(Item.Id, 50, 50)) { if (imageStream == null) { return(image); } await imageStream.CopyToAsync(ms); if (ms.Length == 0) { return(image); } } #if DEBUG Debug.WriteLine(string.Format("Stream received: {0}", Item.Id)); #endif #if WINDOWS_PHONE image.SetSource(ms); #else IRandomAccessStream randStream = await ConvertToRandomAccessStream(ms); await image.SetSourceAsync(randStream); #endif return(image); } }
public static void Initialize(TestContext testContext) { jsonConfig = Environment.GetEnvironmentVariable("JSON_CONFIG"); if (string.IsNullOrEmpty(jsonConfig)) { Debug.WriteLine("No json config found!"); } else { Debug.WriteLine("json config content length : " + jsonConfig.Length); var config = BoxConfig.CreateFromJsonString(jsonConfig); var session = new BoxJWTAuth(config); // create a new app user // client with permissions to manage application users var adminToken = session.AdminToken(); adminClient = session.AdminClient(adminToken); var user = CreateNewUser(adminClient).Result; userId = user.Id; Debug.WriteLine("New app user created : " + userId); // user client with access to user's data (folders, files, etc) userToken = session.UserToken(userId); userClient = session.UserClient(userToken, userId); } }
/// <summary> /// Walk a Box folder tree, applying the specified action to every file and folder encountered. /// </summary> /// <param name="client">An authenticated Box client.</param> /// <param name="folder">The Box folder to traverse.</param> /// <param name="action">An action to apply to the Box files and folders. This can be any method that accepts a BoxItem as a parameter.</param> /// <param name="verboseAPIAction">(Optional) An action that takes a string and displays it as verbose information for each Box API call made. This can be any method that accepts a string as a parameter.</param> /// <param name="properties">(Optional) A string array of Box file/folder properties to fetch with every folder item.</param> /// <param name="pageSize">(Optional) The number of items per request page. Default is 1000.</param> /// <param name="recursionDepth">(Optional) The maximum depth to recur if the -Recurse switch is given. A value less than 0 will recur infinitely. The default is -1 (infinite).</param> /// <exception cref="System.AggregateException">Throws when errors occur with the Box API. Typically consisting of BoxException objects.</exception> public static void WalkFolderTree( BoxClient client, BoxFolder folder, Action <BoxItem> action, Action <String> verboseAPIAction = null, string[] properties = null, int pageSize = 1000, int recursionDepth = -1 ) { properties = properties ?? BoxItemPropertyNameCompleter.DefaultPropertyNames; var fieldNames = PropertyUtility.GetPropertyNames(typeof(BoxFolder), properties); // Apply the action to this folder. action(folder); // Get all items in this folder. ApplyVerboseAPIAction(verboseAPIAction, "Retrieving child items for folder: " + folder.Id); var items = client.FoldersManager.GetFolderItemsAsync(folder.Id, pageSize, fields: fieldNames, autoPaginate: true).Result.Entries; // Recur to each subfolder. foreach (var subfolder in items.Where(i => i.Type == "folder")) { if (recursionDepth != 0) { WalkFolderTree(client, (BoxFolder)subfolder, action, verboseAPIAction, properties, pageSize, recursionDepth - 1); } } // Apply the action to each item in this folder. foreach (var file in items.Where(i => i.Type == "file")) { action(file); } }
private async Task ExecuteMainAsync() { Console.WriteLine("Access token: "); var accessToken = Console.ReadLine(); Console.WriteLine("Remote file name: "); var fileName = Console.ReadLine(); Console.WriteLine("Local file path: "); var localFilePath = Console.ReadLine(); Console.WriteLine("Parent folder Id: "); var parentFolderId = Console.ReadLine(); var timer = Stopwatch.StartNew(); var auth = new OAuthSession(accessToken, "YOUR_REFRESH_TOKEN", 3600, "bearer"); var config = new BoxConfig("YOUR_CLIENT_ID", "YOUR_CLIENT_ID", new Uri("http://boxsdk")); var client = new BoxClient(config, auth); var file = File.OpenRead(localFilePath); var fileRequest = new BoxFileRequest { Name = fileName, Parent = new BoxFolderRequest { Id = parentFolderId } }; var bFile = await client.FilesManager.UploadAsync(fileRequest, file); Console.WriteLine("{0} uploaded to folder: {1} as file: {2}", localFilePath, parentFolderId, bFile.Id); Console.WriteLine("Time spend : {0} ms", timer.ElapsedMilliseconds); }
protected void btnRemoveTags_Click(object sender, EventArgs e) { try { BoxClient b = (BoxClient)Session[BOXCLIENT]; Boolean errOccurred = false; Boolean OAuth2Req = false; List <string> lstT = txtTags.Text.Split(',').ToList(); List <string> TagResult = b.RemoveFolderTags(Int64.Parse(txtTagFolderID.Text), lstT, ref errOccurred, ref OAuth2Req); if (errOccurred) { jsonTextArea.Text = b.ErrMsg; } else if (OAuth2Req) { jsonTextArea.Text = "Need to refresh tokens with call to box."; } else { jsonTextArea.Text = String.Join(Environment.NewLine, TagResult.ToArray()); } } catch (Exception ex) { jsonTextArea.Text = ex.Message + Environment.NewLine + ex.StackTrace; } }
protected void btnCopy_Click(object sender, EventArgs e) { try { BoxClient b = (BoxClient)Session[BOXCLIENT]; string version = null; if (txtCopyVersion.Text != "") { version = txtCopyVersion.Text; } string newName = null; if (txtCopyNewName.Text != "") { newName = txtCopyNewName.Text; } jsonTextArea.Text = b.JSON_Item_Copy((BoxEnums.ObjectType) int.Parse(cboCopyItemType.SelectedValue), Int64.Parse(txtCopyItemID.Text), Int64.Parse(txtCopyDestinationFolderID.Text), txtFields.Text, newName, version); } catch (Exception ex) { jsonTextArea.Text = ex.Message + Environment.NewLine + ex.StackTrace; } }
public async Task <bool> Claim(Uri uri, string documentTitle) { IDictionary <string, string> keyDictionary = new Dictionary <string, string>(); var qSplit = uri.Query.Split('?'); foreach (var kvp in qSplit[qSplit.Length - 1].Split('&')) { var kvpSplit = kvp.Split('='); if (kvpSplit.Length == 2) { keyDictionary.Add(kvpSplit[0], kvpSplit[1]); } } if (!keyDictionary.ContainsKey("code")) { return(false); } var authCode = keyDictionary["code"]; if (string.IsNullOrEmpty(authCode)) { return(false); } _api = BoxHelper.GetClient(); _token = await _api.Auth.AuthenticateAsync(authCode); return(_token != null && _token.RefreshToken != null && _token.AccessToken != null); }
public MainViewModel() : base() { OAuthSession session = null; Config = new BoxConfig(ClientId, ClientSecret, RedirectUri); Client = new BoxClient(Config, session); }
/// <summary> /// Validates parameter input before processing the pipeline. /// </summary> /// <remarks> /// This method gets called once for each cmdlet in the pipeline when the pipeline starts executing (before the process block of any other command). /// </remarks> protected override void BeginProcessing() { if (!PoshBoxAuth.IsInitialized) { ThrowTerminatingError( new ErrorRecord( new Exception("No Box configuration found. Use Connect-Box to import a configuration."), "9000", ErrorCategory.InvalidOperation, null )); } if (Array.Exists(Properties, name => name == "*")) { Properties = BoxUserPropertyNameCompleter.AllPropertyNames; } fieldNames = PropertyUtility.GetPropertyNames(typeof(BoxUser), Properties); SearchUser = (SearchUser == "*") ? null : SearchUser; UserType = UserType.ToLower(); WriteVerbose("Using admin client already established: " + PoshBoxAuth.BoxConfiguration.ClientId); client = PoshBoxAuth.BoxClient; }
private static async Task <FileFolderInfo> FindFolderInternal(BoxClient client, string parentFolderID, int offset, string name) { var list = new List <FileFolderInfo>(); var folderItems = await client.FoldersManager.GetFolderItemsAsync(parentFolderID, FolderItemsCollectionLimit, offset, new List <string> { BoxItem.FieldName, BoxItem.FieldModifiedAt }).ConfigureAwait(false); foreach (var item in folderItems.Entries) { if (item.Type == "folder" && item.Name == name) { return(new FileFolderInfo { ID = item.Id, Name = item.Name, ParentFolderID = parentFolderID, ModifiedAt = item.ModifiedAt }); } } if (folderItems.Offset + folderItems.Limit < folderItems.TotalCount) { return(await FindFolderInternal(client, parentFolderID, offset + folderItems.Limit, name).ConfigureAwait(false)); } return(null); }
public async Task <bool> DeleteFileOrFolderAsync(BoxClient client, string fileID, bool isFile) { bool _isDeleteSuccess = false; if (client == null) { return(_isDeleteSuccess); } if (string.IsNullOrEmpty(fileID)) { return(_isDeleteSuccess); } try { if (isFile) { _isDeleteSuccess = await client.FilesManager.DeleteAsync(fileID); } else { _isDeleteSuccess = await client.FoldersManager.DeleteAsync(fileID); } } catch (Exception ex) { Debug.WriteLine("Delete folder or file on Box:" + ex.ToString()); return(_isDeleteSuccess); } return(_isDeleteSuccess); }
/// <summary> /// Pass teh token /// </summary> /// <param name="token"></param> public BoxDotComUploadService(string token) { var config = new BoxConfig("", "", new Uri("http://localhost")); var session = new OAuthSession(token, "NOT_NEEDED", 3600, "bearer"); _boxClient = new BoxClient(config, session); }
public static async Task Setup(BoxClient boxClient) { var folderRequest = new BoxFolderRequest() { Name = "Test Folder", Parent = new BoxRequestEntity() { Id = "0" } }; var newFolder = await boxClient.FoldersManager.CreateAsync(folderRequest); var pathToFile = HttpContext.Current.Server.MapPath("~/"); var fileName = "text.txt"; using (FileStream fs = File.Open(pathToFile + fileName, FileMode.Open)) { // Create request object with name and parent folder the file should be uploaded to BoxFileRequest request = new BoxFileRequest() { Name = fileName, Parent = new BoxRequestEntity() { Id = "0" } }; var boxFile = await boxClient.FilesManager.UploadAsync(request, fs); } }
/// <summary> /// Create user BoxClient using a user access token /// </summary> /// <param name="userToken">User access token</param> /// <param name="userId">Id of the user</param> /// <returns>BoxClient that uses CCG authentication</returns> public IBoxClient UserClient(string userToken, string userId) { var userSession = Session(userToken); var authRepo = new CCGAuthRepository(userSession, this, userId); var userClient = new BoxClient(_boxConfig, authRepo); return(userClient); }
static void test_app_mycapp() { var config = new BoxConfig("m4i3pi5dpz0wbanc2fm8m0ir66qyr4dh", "zCvs6w94X8tgkFce1d5RbGbiudYjfylK", new Uri("http://localhost")); var session = new OAuthSession("O35fialsYuSQH1vblbaYR0K6oBY0gwK0", "NOT_NEEDED", 3600, "bearer"); var client = new BoxClient(config, session); var user_info = client.UsersManager.GetCurrentUserInformationAsync().Result; var items = client.FoldersManager.GetFolderItemsAsync("0", 100).Result; }
static void test_app_myapp0926() { var config = new BoxConfig("ol91r17fhsvzdsnny8xgkaiy5jkgxfw8", "956pFqJsfy1Nn7yAajRhIn6eHc2eidMa", new Uri("http://localhost")); var session = new OAuthSession("nHe4pvCa3BXqnVbXnjOI4xnfCjpkobBj", "NOT_NEEDED", 3600, "bearer"); var client = new BoxClient(config, session); var user_info = client.UsersManager.GetCurrentUserInformationAsync().Result; var items = client.FoldersManager.GetFolderItemsAsync("0", 100).Result; }
public BoxService(BoxAuthTokenDO authToken) { var config = new BoxConfig(BoxHelpers.ClientId, BoxHelpers.Secret, new Uri(BoxHelpers.RedirectUri)); var expiresIn = (int)(authToken.ExpiresAt - DateTime.UtcNow).TotalSeconds; Box.V2.Auth.OAuthSession session = new Box.V2.Auth.OAuthSession(authToken.AccessToken, authToken.RefreshToken, expiresIn, "bearer"); _boxClient = new BoxClient(config, session); }
private async void init() { var config = new BoxConfig(KEY, SECRET, RedirectUri); client = new BoxClient(config); // string authCode = await OAuth2Sample.GetAuthCode(config.AuthCodeUri, config.RedirectUri); // await client.Auth.AuthenticateAsync(authCode); }
/// <summary> /// Create admin BoxClient using an admin access token /// </summary> /// <param name="adminToken">Admin access token</param> /// <param name="asUser">The user ID to set as the 'As-User' header parameter; used to make calls in the context of a user using an admin token</param> /// <param name="suppressNotifications">Whether or not to suppress both email and webhook notifications. Typically used for administrative API calls. Your application must have “Manage an Enterprise” scope, and the user making the API calls is a co-admin with the correct "Edit settings for your company" permission.</param> /// <returns>BoxClient that uses JWT authentication</returns> public BoxClient AdminClient(string adminToken, string asUser = null, bool?suppressNotifications = null) { var adminSession = this.Session(adminToken); var authRepo = new JWTAuthRepository(adminSession, this); var adminClient = new BoxClient(this.boxConfig, authRepo, asUser: asUser, suppressNotifications: suppressNotifications); return(adminClient); }
public BoxClient AdminClient(string adminToken) { var adminSession = this.Session(adminToken); var authRepo = new JWTAuthRepository(adminSession, this); var adminClient = new BoxClient(this.boxConfig, authRepo); return adminClient; }
public BoxClient AdminClient(string adminToken) { var adminSession = this.Session(adminToken); var authRepo = new JWTAuthRepository(adminSession, this); var adminClient = new BoxClient(this.boxConfig, authRepo); return(adminClient); }
public static BoxClient GetBoxClientWithApiKeyAndToken(string apiKey, string accessToken) { var auth = new OAuthSession(accessToken, "NOT_USED", 3600, "bearer"); var boxConfig = new BoxConfig(apiKey, "NOT_USED", new Uri("http://boxsdk")); var boxClient = new BoxClient(boxConfig, auth); return(boxClient); }
public BoxClient UserClient(string userToken, string userId) { var userSession = this.Session(userToken); var authRepo = new JWTAuthRepository(userSession, this, userId); var userClient = new BoxClient(this.boxConfig, authRepo); return(userClient); }
/// <summary> /// Create admin BoxClient by admin access token /// </summary> /// <param name="adminToken">Admin access token</param> /// <param name="asUser">The user ID to set as the 'As-User' header parameter; used to make calls in the context of a user using an admin token</param> /// <param name="suppressNotifications">Whether or not to suppress both email and webhook notifications. Typically used for administrative API calls. Your application must have “Manage an Enterprise” scope, and the user making the API calls is a co-admin with the correct "Edit settings for your company" permission.</param> /// <returns>BoxClient that uses JWT authentication</returns> public BoxClient AdminClient(string adminToken, string asUser = null, bool? suppressNotifications = null) { var adminSession = this.Session(adminToken); var authRepo = new JWTAuthRepository(adminSession, this); var adminClient = new BoxClient(this.boxConfig, authRepo, asUser: asUser, suppressNotifications: suppressNotifications); return adminClient; }
/// <summary> /// Create user BoxClient by user access token /// </summary> /// <param name="userToken">User access token</param> /// <param name="userId">Id of the user</param> /// <returns>BoxClient that uses JWT authentication</returns> public BoxClient UserClient(string userToken, string userId) { var userSession = this.Session(userToken); var authRepo = new JWTAuthRepository(userSession, this, userId); var userClient = new BoxClient(this.boxConfig, authRepo); return userClient; }
private static Task<BoxFile> UploadFile(BoxFolder newFolder, BoxClient userClient, Stream file) { var fileRequest = new BoxFileRequest { Name = "logo.png", Parent = new BoxFolderRequest { Id = newFolder.Id } }; return userClient.FilesManager.UploadAsync(fileRequest, file); }
private static Task<BoxUser> CreateNewUser(BoxClient client) { var userRequest = new BoxUserRequest { Name = "First user", IsPlatformAccessOnly = true // creating application specific user, not a Box.com user }; return client.UsersManager.CreateEnterpriseUserAsync(userRequest); }
private static BoxClient CreateClientByToken(string token) { var auth = new OAuthSession(token, "YOUR_REFRESH_TOKEN", 3600, "bearer"); var config = new BoxConfig(string.Empty, string.Empty, new Uri("http://boxsdk")); var client = new BoxClient(config, auth); return client; }
public BoxResourceManagerTestIntegration() { _auth = new OAuthSession("YOUR_ACCESS_TOKEN", "YOUR_REFRESH_TOKEN", 3600, "bearer"); _handler = new HttpRequestHandler(); _parser = new BoxJsonConverter(); _config = new BoxConfig(ClientId, ClientSecret, RedirectUri); _client = new BoxClient(_config, _auth); }
public BoxResourceManagerTestIntegration() { _auth = new OAuthSession("HrMywfaXCtAStbY9FTvoCbMZCBPeBgud", "Qx34izsfUuvbcm90x88gPs6ZiRXexxN3jbQGqNoY2r9to6mppRBoCD4iqlSVrm0F", 3600, "bearer"); _handler = new HttpRequestHandler(); _parser = new BoxJsonConverter(); _config = new BoxConfig(ClientId, ClientSecret, RedirectUri); _client = new BoxClient(_config, _auth); }
private static Task<BoxFolder> CreateNewFolder(BoxClient userClient) { var folderRequest = new BoxFolderRequest { Description = "Test folder", Name = "Misc", Parent = new BoxFolderRequest { Id = "0" } }; return userClient.FoldersManager.CreateAsync(folderRequest); }
public void InitializePlugins_UnregisteredResource_InvalidOperationException() { // Arrange BoxClient client = new BoxClient(_config.Object); // Act client.AddResourcePlugin<BoxFilesManager>(); // Assert var dm = client.ResourcePlugins.Get<BoxFoldersManager>(); }
public BoxResourceManagerTestIntegration() { _auth = new OAuthSession("YOUR_ACCESS_TOKEN", "YOUR_REFRESH_TOKEN", 3600, "bearer"); _handler = new HttpRequestHandler(); _parser = new BoxJsonConverter(); _config = new BoxConfig(ClientId, ClientSecret, RedirectUri); _client = new BoxClient(_config, _auth); _boxDeveloperEditionConfig = new BoxConfig(EnterpriseId, "enterprise", ClientId, ClientSecret, PrivateKey, PrivateKeyPassword); _boxDeveloperEditionClient = new BoxClient(_boxDeveloperEditionConfig); }
public void Init(BoxClient client) { _vm = new BoxItemPickerViewModel(client); this.DataContext = _vm; // Set page to screen size #if WINDOWS_PHONE LayoutWidth = Application.Current.Host.Content.ActualWidth; LayoutHeight = Application.Current.Host.Content.ActualHeight; #else var bounds = Window.Current.Bounds; LayoutWidth = bounds.Width; LayoutHeight = bounds.Height; #endif }
private static async Task AssertFolderContents(BoxClient boxClient) { const int totalCount = 11; const int numFiles = 9; const int numFolders = 2; BoxCollection<BoxItem> c = await boxClient.FoldersManager.GetFolderItemsAsync("0", 3, 0, new List<string>() { BoxItem.FieldName, BoxItem.FieldSize, BoxFolder.FieldItemCollection }, autoPaginate: true); Assert.AreEqual(totalCount, c.TotalCount, "Incorrect total count"); Assert.AreEqual(totalCount, c.Entries.Count, "Incorrect number if items returned"); Assert.AreEqual(numFolders, c.Entries.Count(item => item is BoxFolder), "Wrong number of Folders"); Assert.AreEqual(numFiles, c.Entries.Count(item => item is BoxFile), "Wrong number of Files"); }
public void InitializePlugins_ValidResource_ValidPlugins() { // Arrange BoxClient client = new BoxClient(_config.Object); // Act client .AddResourcePlugin<BoxFilesManager>() .AddResourcePlugin<BoxFoldersManager>() .AddResourcePlugin<BoxCommentsManager>() .AddResourcePlugin<BoxGroupsManager>(); var fm = client.ResourcePlugins.Get<BoxFilesManager>(); var dm = client.ResourcePlugins.Get<BoxFoldersManager>(); var cm = client.ResourcePlugins.Get<BoxCommentsManager>(); var gm = client.ResourcePlugins.Get<BoxGroupsManager>(); // Assert Assert.IsNotNull(fm); Assert.IsNotNull(dm); Assert.IsNotNull(cm); Assert.IsNotNull(gm); }
public async Task GetFolder_LiveSession_ValidResponse_DeflateCompression() { var boxConfig = new BoxConfig(ClientId, ClientSecret, RedirectUri) { AcceptEncoding = CompressionType.deflate }; var boxClient = new BoxClient(boxConfig, _auth); await AssertFolderContents(boxClient); }
public BoxItemPickerViewModel(BoxClient client) { _client = client; }
internal BoxFolderPickerPage(BoxClient client) { InitializeComponent(); Init(client); }
public BoxItemViewModel(BoxItem item, BoxClient client) { _client = client; UpdateBaseBindings(item); }
internal BoxFilePickerPage(BoxClient client) { this.InitializeComponent(); Init(client); }
private async Task SetThumbnailAsync(string id, BoxClient client) { var image = await GetThumbnailAsync(id, client); Image = image; }
private async Task<BitmapImage> GetThumbnailAsync(string id, BoxClient client) { BitmapImage image = new BitmapImage(); using (MemoryStream ms = new MemoryStream()) { using (Stream imageStream = await _client.FilesManager.GetThumbnailAsync(Item.Id, 50, 50)) { if (imageStream == null) return image; await imageStream.CopyToAsync(ms); if (ms.Length == 0) return image; } #if DEBUG Debug.WriteLine(string.Format("Stream received: {0}", Item.Id)); #endif #if WINDOWS_PHONE image.SetSource(ms); #else IRandomAccessStream randStream = await ConvertToRandomAccessStream(ms); await image.SetSourceAsync(randStream); #endif return image; } }