コード例 #1
0
ファイル: Move.cs プロジェクト: kobay/script-for-troubleshoot
        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);
        }
コード例 #2
0
        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"));
        }
コード例 #3
0
        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);
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: box/box-windows-sdk-v2
        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);
        }
コード例 #5
0
        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());
        }
コード例 #6
0
ファイル: AuthBox.cs プロジェクト: zhangluqi/GoogleDriveDemo
        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);
        }
コード例 #7
0
ファイル: BoxAPI.cs プロジェクト: rbhttchr/WebAPI
        /// <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;
            }
        }
コード例 #8
0
        /// <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);
            }
        }
コード例 #9
0
ファイル: Move.cs プロジェクト: kobay/script-for-troubleshoot
        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;
                }
            }
        }
コード例 #10
0
        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);
            }
        }
コード例 #12
0
ファイル: Utility.cs プロジェクト: The-New-Guy/Posh-Box
        /// <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);
            }
        }
コード例 #13
0
        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);
        }
コード例 #14
0
ファイル: Main.aspx.cs プロジェクト: albertocampos8/Box
 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;
     }
 }
コード例 #15
0
ファイル: Main.aspx.cs プロジェクト: albertocampos8/Box
 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;
     }
 }
コード例 #16
0
        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);
        }
コード例 #17
0
        public MainViewModel() : base()
        {
            OAuthSession session = null;

            Config = new BoxConfig(ClientId, ClientSecret, RedirectUri);
            Client = new BoxClient(Config, session);
        }
コード例 #18
0
        /// <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;
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        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);
        }
コード例 #21
0
        /// <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);
        }
コード例 #22
0
        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);
            }
        }
コード例 #23
0
ファイル: BoxCCGAuth.cs プロジェクト: box/box-windows-sdk-v2
        /// <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);
        }
コード例 #24
0
 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;
 }
コード例 #25
0
 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;
 }
コード例 #26
0
        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);
        }
コード例 #27
0
        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);
        }
コード例 #28
0
        /// <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);
        }
コード例 #29
0
        public MainViewModel()
            : base()
        {
            OAuthSession session = null;

            Config = new BoxConfig(ClientId, ClientSecret, RedirectUri);
            Client = new BoxClient(Config, session);
        }
コード例 #30
0
        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;
        }
コード例 #31
0
        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);
        }
コード例 #32
0
        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);
        }
コード例 #33
0
        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);
        }
コード例 #34
0
        /// <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;
        }
コード例 #35
0
        /// <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;
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: box/box-windows-sdk-v2
 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);
 }
コード例 #37
0
ファイル: Program.cs プロジェクト: box/box-windows-sdk-v2
 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);
 }
コード例 #38
0
ファイル: Program.cs プロジェクト: box/box-windows-sdk-v2
        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);
        }
コード例 #40
0
        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);
        }
コード例 #41
0
ファイル: Program.cs プロジェクト: box/box-windows-sdk-v2
 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);
 }
コード例 #42
0
        public void InitializePlugins_UnregisteredResource_InvalidOperationException()
        {
            // Arrange
            BoxClient client = new BoxClient(_config.Object);

            // Act
            client.AddResourcePlugin<BoxFilesManager>();

            // Assert
            var dm = client.ResourcePlugins.Get<BoxFoldersManager>();
        }
コード例 #43
0
        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);
        }
コード例 #44
0
        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
        }
コード例 #45
0
        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");
        }
コード例 #46
0
        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);
        }
コード例 #47
0
 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);
 }
コード例 #48
0
 public BoxItemPickerViewModel(BoxClient client)
 {
     _client = client;
 }
コード例 #49
0
 internal BoxFolderPickerPage(BoxClient client)
 {
     InitializeComponent();
     Init(client);
 }
コード例 #50
0
 public BoxItemViewModel(BoxItem item, BoxClient client)
 {
     _client = client;
     UpdateBaseBindings(item);
 }
コード例 #51
0
 internal BoxFilePickerPage(BoxClient client)
 {
     this.InitializeComponent();
     Init(client);
 }
コード例 #52
0
 private async Task SetThumbnailAsync(string id, BoxClient client)
 {
     var image = await GetThumbnailAsync(id, client);
     Image = image;
 }
コード例 #53
0
        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;
            }
        }