Exemplo n.º 1
0
        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);
            }
        }
Exemplo n.º 2
0
        private async Task ExecuteMainAsync()
        {
            var config  = ConfigureBoxApi();
            var session = new BoxJWTAuth(config);

            // client with permissions to manage application users
            var adminToken = session.AdminToken();
            var client     = session.AdminClient(adminToken);

            var user = await CreateNewUser(client);

            Console.WriteLine("New app user created with Id = {0}", user.Id);

            // user client with access to user's data (folders, files, etc)
            var userToken  = session.UserToken(user.Id);
            var userClient = session.UserClient(userToken, user.Id);

            // root folder has id = 0
            var newFolder = await CreateNewFolder(userClient);

            Console.WriteLine("New folder created with Id = {0}", newFolder.Id);

            var timer    = Stopwatch.StartNew();
            var file     = File.OpenRead("box_logo.png");
            var uploaded = await UploadFile(newFolder, userClient, file);

            Console.WriteLine("New file uploaded with Id = {0} in {1} ms", uploaded.Id, timer.ElapsedMilliseconds);
        }
Exemplo n.º 3
0
        public void GetToken_ValidSession()
        {
            // Arrange
            _handler.Setup(h => h.ExecuteAsyncWithoutRetry <OAuthSession>(It.IsAny <BoxRequest>()))
            .Returns(Task <IBoxResponse <OAuthSession> > .Factory.StartNew(() => new BoxResponse <OAuthSession>()
            {
                Status        = ResponseStatus.Success,
                ContentString = "{\"access_token\":\"T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl\",\"expires_in\":3600,\"restricted_to\":[],\"token_type\":\"bearer\"}"
            }));;

            // Act
            String accessToken = _jwtAuth.AdminToken();

            // Assert
            Assert.AreEqual(accessToken, "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl");
        }
        public void retriesWithNewJWTAssertionOnErrorResponseAndSucceeds()
        {
            var config     = new BoxConfig(ClientId, ClientSecret, EnterpriseId, privateKey, passphrase, publicKeyID);
            var session    = new BoxJWTAuth(config);
            var adminToken = session.AdminToken();

            adminClient = session.AdminClient(adminToken);
        }
Exemplo n.º 5
0
        static async Task MainAsync()
        {
            // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file
            var privateKey = File.ReadAllText("private_key.pem");

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);

            // Proxy configuration - set isProxyEnabled = true if using Fiddler!!
            if (isProxyEnabled != false)
            {
                System.Net.WebProxy webProxy   = new System.Net.WebProxy("http://127.0.0.1:8888");
                NetworkCredential   credential = new NetworkCredential("testUser", "testPass");
                webProxy.Credentials = credential;
                boxConfig.WebProxy   = webProxy;
            }

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);
            Console.WriteLine();

            var adminClient = boxJWT.AdminClient(adminToken);

            var adminFunc = new Func(adminClient);

            adminFunc.GetFolderItems();

            var       userId     = "3768478578";
            var       userToken  = boxJWT.UserToken(userId); // valid for 60 minutes so should be cached and re-used
            BoxClient userClient = boxJWT.UserClient(userToken, userId);

            var userFunc = new Func(userClient);

            userFunc.GetFolderItems();

            // Stream fileContents = await userClient.FilesManager.DownloadStreamAsync(id: "675996854920"); // Download the file 675996854920

            // var userRequest = new BoxUserRequest() { Name = "test appuser", IsPlatformAccessOnly = true };
            // var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);
            // Console.WriteLine("Created App User");

            // var userToken = boxJWT.UserToken(appUser.Id);
            // var userClient = boxJWT.UserClient(userToken, appUser.Id);

            // var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();
            // Console.WriteLine("\nApp User Details:");
            // Console.WriteLine("\tId: {0}", userDetails.Id);
            // Console.WriteLine("\tName: {0}", userDetails.Name);
            // Console.WriteLine("\tStatus: {0}", userDetails.Status);
            // Console.WriteLine();

            // await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true);
            // Console.WriteLine("Deleted App User");
        }
Exemplo n.º 6
0
        static async Task MainAsync()
        {
            // rename the private_key.pem.example to private_key.pem and put your JWT private key in the file
            var privateKey = File.ReadAllText("private_key.pem");

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT    = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);
            Console.WriteLine();

            var adminClient = boxJWT.AdminClient(adminToken);

            Console.WriteLine("Admin root folder items");
            var items = await adminClient.FoldersManager.GetFolderItemsAsync("0", 500);

            items.Entries.ForEach(i =>
            {
                Console.WriteLine("\t{0}", i.Name);
                //if (i.Type == "file")
                //{
                //    var previewLink = adminClient.FilesManager.GetPreviewLinkAsync(i.Id).Result;
                //    Console.WriteLine("\tPreview Link: {0}", previewLink.ToString());
                //    Console.WriteLine();
                //}
            });
            Console.WriteLine();

            var userRequest = new BoxUserRequest()
            {
                Name = "test appuser", IsPlatformAccessOnly = true
            };
            var appUser = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);

            Console.WriteLine("Created App User");

            var userToken  = boxJWT.UserToken(appUser.Id);
            var userClient = boxJWT.UserClient(userToken, appUser.Id);

            var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("\nApp User Details:");
            Console.WriteLine("\tId: {0}", userDetails.Id);
            Console.WriteLine("\tName: {0}", userDetails.Name);
            Console.WriteLine("\tStatus: {0}", userDetails.Status);
            Console.WriteLine();

            await adminClient.UsersManager.DeleteEnterpriseUserAsync(appUser.Id, false, true);

            Console.WriteLine("Deleted App User");
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            var boxConfig = BoxConfig.CreateFromJsonString(GetConfigJson());

            // Set web proxy
            boxConfig.WebProxy = new BoxHttpProxy();

            var boxJWT = new BoxJWTAuth(boxConfig);

            var adminToken  = boxJWT.AdminToken();
            var adminClient = boxJWT.AdminClient(adminToken);

            var items = adminClient.FoldersManager.GetFolderItemsAsync("0", 500).Result;
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            var appConfig  = new ConfigurationBuilder().AddUserSecrets <Program>().Build();
            var configJson = appConfig["BoxConfigJson"];

            Console.WriteLine($"Creating a Box Admin Client");
            var config     = BoxConfig.CreateFromJsonString(configJson);
            var auth       = new BoxJWTAuth(config);
            var adminToken = auth.AdminToken();
            var boxClient  = auth.AdminClient(adminToken);

            Console.WriteLine($"Created a Box Admin Client");
            GetUser(config, boxClient);
        }
Exemplo n.º 9
0
        public static async Task FindAppUsersAsync()
        {
            Console.WriteLine("FindAppUsersAsync Start");

            // BOX API実行用のClientを準備
            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // 非同期処理の同時実行数を制限
            var throttling = new SemaphoreSlim(Config.ApiRateLimit);


            var users = await saClient.UsersManager.GetEnterpriseUsersAsync(limit : 1000);

            var appUserList = new List <string>();
            var listSize    = users.Entries.Count;

            for (int i = 0; i < listSize; i++)
            {
                Console.Write("user {0}/{1}", i, listSize);
                Console.SetCursorPosition(0, Console.CursorTop);

                var user = users.Entries[i];

                if (user.Name.StartsWith("ST_APP_USER_") && user.Login.StartsWith("AppUser_"))
                {
                    if (user.Name == "ST_APP_USER_SEARCH")
                    {
                        Console.WriteLine("Search appUser ID: {0} ", user.Id);
                    }

                    appUserList.Add(user.Id);
                }
            }

            Console.WriteLine($"Found AppUser {appUserList.Count}");

            // ファイルに書き出す
            await File.WriteAllTextAsync(PathToAppUserIDsForTest, JsonSerializer.Serialize(appUserList));

            Console.WriteLine("FindAppUsersAsync Done");
        }
Exemplo n.º 10
0
        static async Task MainAsync()
        {
            string CLIENT_ID                = Configuration["Config:ClientID"];
            string CLIENT_SECRET            = Configuration["Config:ClientSecret"];
            string ENTERPRISE_ID            = Configuration["Config:EnterpriseID"];
            string JWT_PRIVATE_KEY_PATH     = Configuration["Config:PrivateKeyPath"];
            string JWT_PRIVATE_KEY_PASSWORD = Configuration["Config:PrivateKeyPass"];
            string JWT_PUBLIC_KEY_ID        = Configuration["Config:PublicKeyID"];

            var privateKey = File.ReadAllText(JWT_PRIVATE_KEY_PATH);

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT    = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();

            Console.WriteLine("Admin Token: " + adminToken);

            var adminClient = boxJWT.AdminClient(adminToken);

            var userRequest = new BoxUserRequest
            {
                Name = "John Smith",
                IsPlatformAccessOnly = true
            };
            var user = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);

            Console.Write("New app user created with Id = {0}", user.Id);

            /*BoxFile newFile;
             *
             * // Create request object with name and parent folder the file should be uploaded to
             * using (FileStream stream = new FileStream(@"/Users/jleblanc/localhost/box/net-jwt/tax.txt", FileMode.Open))
             * {
             *  BoxFileRequest req = new BoxFileRequest()
             *  {
             *      Name = "tax.txt",
             *      Parent = new BoxRequestEntity() { Id = "0" }
             *  };
             *  newFile = await adminClient.FilesManager.UploadAsync(req, stream);
             * }*/
        }
Exemplo n.º 11
0
    static async Task validateUser(string name, string sub)
    {
        // Configure Box SDK instance
        var       reader = new StreamReader("config.json");
        var       json   = reader.ReadToEnd();
        var       config = BoxConfig.CreateFromJsonString(json);
        var       sdk    = new BoxJWTAuth(config);
        var       token  = sdk.AdminToken();
        BoxClient client = sdk.AdminClient(token);

        // Search for matching Box app user for Okta ID
        BoxCollection <BoxUser> users = await client.UsersManager.GetEnterpriseUsersAsync(externalAppUserId : sub);

        System.Diagnostics.Debug.WriteLine(users.TotalCount);

        if (users.TotalCount > 0)
        {
            // Box user found, get token
            var       userId     = users.Entries[0].Id;
            var       userToken  = sdk.UserToken(userId);
            BoxClient userClient = sdk.UserClient(userToken, userId);

            // Get current user
            BoxUser currentUser = await userClient.UsersManager.GetCurrentUserInformationAsync();

            System.Diagnostics.Debug.WriteLine("Current user name: " + currentUser.Name);
        }
        else
        {
            // No associated user found, create app user
            var userRequest = new BoxUserRequest()
            {
                Name = name,
                ExternalAppUserId    = sub,
                IsPlatformAccessOnly = true
            };
            var user = await client.UsersManager.CreateEnterpriseUserAsync(userRequest);

            System.Diagnostics.Debug.WriteLine("New user created: " + user.Name);
        }
    }
Exemplo n.º 12
0
        /// <summary>
        /// Get an authenticated client for the JWT app service account.
        /// </summary>
        /// <param name="pathToConfigJson">The path to the JWT app configuration JSON file.</param>
        /// <returns>An authenticated Box client</returns>
        private static BoxClient GetAuthenticatedClient(string pathToConfigJson)
        {
            if (string.IsNullOrWhiteSpace(pathToConfigJson) || !File.Exists(pathToConfigJson))
            {
                throw new Exception("Please set 'pathToConfigJson' with the path to your JWT app config JSON file.");
            }

            // Read the configuration from the file.
            IBoxConfig config;

            using (var configStream = File.OpenRead(pathToConfigJson))
                config = BoxConfig.CreateFromJsonFile(configStream);

            Console.Out.WriteLine("Authenticating...");

            // Create a Box client and authenticate as the service account
            var boxJwtAuth = new BoxJWTAuth(config);
            var adminToken = boxJwtAuth.AdminToken();

            return(boxJwtAuth.AdminClient(adminToken));
        }
        public BoxClient AdminClient(string asUser = null)
        {
            //check cache for existing admin token
            var cacheKey   = $"/box/{_boxConfig.ClientId}/admin-token";
            var adminToken = _distributedCache.GetString(cacheKey);

            if (string.IsNullOrEmpty(adminToken))
            {
                //fetch a new admin token from Box
                adminToken = _boxJWTAuth.AdminToken();

                //store the token in the cache with a 45 minute expiration
                var options = new DistributedCacheEntryOptions()
                {
                    AbsoluteExpirationRelativeToNow = CACHE_ITEM_TTL
                };
                _distributedCache.SetString(cacheKey, adminToken, options);
            }

            return(_boxJWTAuth.AdminClient(adminToken, asUser: asUser));
        }
        public string GetAccessToken()
        {
            ReturnUpload returnUpload   = new ReturnUpload();
            string       configFileName = System.Web.Hosting.HostingEnvironment.MapPath("~/Models/Clientconfiguration.json");
            StreamReader reader         = new StreamReader(configFileName);
            string       json           = reader.ReadToEnd();
            Config       config         = JsonConvert.DeserializeObject <Config>(json);

            BoxConfig boxConfig = new BoxConfig(config.boxAppSettings.clientID, config.boxAppSettings.clientSecret, config.enterpriseID, config.boxAppSettings.appAuth.privateKey, config.boxAppSettings.appAuth.passphrase, config.boxAppSettings.appAuth.publicKeyID);

            try
            {
                BoxJWTAuth boxJWT     = new BoxJWTAuth(boxConfig);
                string     adminToken = boxJWT.AdminToken();

                return(adminToken);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Exemplo n.º 15
0
        static void test_app_mycapp_2()
        {
            IBoxConfig config = null;

            using (FileStream fs = new FileStream("87881712_nqkf95rj_config.json", FileMode.Open))
            {
                config = BoxConfig.CreateFromJsonFile(fs);
            }

            var boxJWT = new BoxJWTAuth(config);

            var adminToken  = boxJWT.AdminToken();
            var adminClient = boxJWT.AdminClient(adminToken);
            var user_info   = adminClient.UsersManager.GetCurrentUserInformationAsync().Result;
            var items       = adminClient.FoldersManager.GetFolderItemsAsync("0", 100).Result;
            var users       = adminClient.UsersManager.GetEnterpriseUsersAsync().Result;

            user_info = adminClient.UsersManager.GetUserInformationAsync("224172711").Result;

            var client_token = boxJWT.UserToken("224172711");
            var client       = boxJWT.UserClient(client_token, "224172711");

            items = client.FoldersManager.GetFolderItemsAsync("0", 100).Result;
        }
Exemplo n.º 16
0
        static async Task MainAsync()
        {
            string CLIENT_ID                = Configuration["Config:ClientID"];
            string CLIENT_SECRET            = Configuration["Config:ClientSecret"];
            string ENTERPRISE_ID            = Configuration["Config:EnterpriseID"];
            string JWT_PRIVATE_KEY_PATH     = Configuration["Config:PrivateKeyPath"];
            string JWT_PRIVATE_KEY_PASSWORD = Configuration["Config:PrivateKeyPass"];
            string JWT_PUBLIC_KEY_ID        = Configuration["Config:PublicKeyID"];

            var privateKey = File.ReadAllText(JWT_PRIVATE_KEY_PATH);

            var boxConfig = new BoxConfig(CLIENT_ID, CLIENT_SECRET, ENTERPRISE_ID, privateKey, JWT_PRIVATE_KEY_PASSWORD, JWT_PUBLIC_KEY_ID);
            var boxJWT    = new BoxJWTAuth(boxConfig);

            var adminToken = boxJWT.AdminToken();
            //Console.WriteLine("Admin Token: " + adminToken);

            var client = boxJWT.AdminClient(adminToken);

            /* var userRequest = new BoxUserRequest
             * {
             *  Name = "John Smith",
             *  IsPlatformAccessOnly = true
             * };
             * var user = await adminClient.UsersManager.CreateEnterpriseUserAsync(userRequest);
             * Console.Write("New app user created with Id = {0}", user.Id);*/

            /******************************************************
            * Preflight Check + File Upload / Update
            ******************************************************/
            /* var fileName = "tax.txt";
             * var folderId = "0";
             * using (FileStream toUpload = new FileStream(@"/Users/jleblanc/localhost/box/net-jwt/tax.txt", FileMode.Open))
             * {
             *  var preflightRequest = new BoxPreflightCheckRequest
             *  {
             *      Name = fileName,
             *      Size = toUpload.Length,
             *      Parent = new BoxRequestEntity
             *      {
             *          Id = folderId
             *      }
             *  };
             *  try
             *  {
             *      var preflightCheck = await client.FilesManager.PreflightCheck(preflightRequest);
             *      System.Console.WriteLine($"Preflight check passed: {preflightCheck.Success}");
             *
             *      //-----------------------------------------------------
             *      // Preflight Check Passed - Upload File
             *      //-----------------------------------------------------
             *      BoxFile newFile;
             *
             *      // Create request object with name and parent folder the file should be uploaded to
             *      using (FileStream stream = new FileStream(@"/Users/jleblanc/localhost/box/net-jwt/tax.txt", FileMode.Open))
             *      {
             *          BoxFileRequest req = new BoxFileRequest()
             *          {
             *              Name = "tax.txt",
             *              Parent = new BoxRequestEntity() { Id = "0" }
             *          };
             *          BoxFile file = await client.FilesManager.UploadAsync(req, stream);
             *          System.Console.WriteLine($"New file version uploaded for file ID: {file.Id}");
             *      }
             *  }
             *  catch (BoxPreflightCheckConflictException<BoxFile> e)
             *  {
             *      System.Console.WriteLine($"Preflight check failed for file ID: {e.ConflictingItem.Id}");
             *
             *      //-----------------------------------------------------
             *      // Preflight Check Failed - Upload New File Version
             *      //-----------------------------------------------------
             *      using (FileStream fileStream = new FileStream(@"/Users/jleblanc/localhost/box/net-jwt/tax.txt", FileMode.Open))
             *      {
             *          BoxFile file = await client.FilesManager.UploadNewVersionAsync(e.ConflictingItem.Name, e.ConflictingItem.Id, fileStream);
             *          System.Console.WriteLine($"New file version uploaded for file ID: {file.Id}");
             *      }
             *  }
             * }*/

            /******************************************************
            * Metadata Upload / Update
            ******************************************************/
            /* var metadataValues = new Dictionary<string, object>()
             * {
             *  { "field1", "Tax information" },
             *  { "field2", "Internal" },
             *  { "field3", "active" }
             * };
             *
             * try
             * {
             *  Dictionary<string, object> metadata = await client.MetadataManager.CreateFileMetadataAsync("438321273202", metadataValues, "enterprise", "customer_md_template1");
             *  System.Console.WriteLine("Added new metadata");
             * }
             * catch (Exception e)
             * {
             *  JObject json = JObject.Parse(e.Message);
             *  var code = (string) json["code"];
             *  if (code == "tuple_already_exists")
             *  {
             *      var updates = new List<BoxMetadataUpdate>()
             *      {
             *          new BoxMetadataUpdate()
             *          {
             *              Op = MetadataUpdateOp.replace,
             *              Path = "/field1",
             *              Value = "New Data"
             *          }
             *      };
             *
             *      Dictionary<string, object> updatedMetadata = await client.MetadataManager
             *          .UpdateFileMetadataAsync("438321273202", updates, "enterprise", "customer_md_template1");
             *
             *      System.Console.WriteLine("Updated metadata");
             *  }
             * }*/

            //var results = await client.SearchManager.SearchAsync("tax");
            //System.Console.WriteLine(results);
        }
Exemplo n.º 17
0
 public static string EnterpriseToken()
 {
     return(BoxJwtAuth.AdminToken());
 }
Exemplo n.º 18
0
        public static async Task CheckAppUsersAndFolders()
        {
            Console.WriteLine("CheckAppUsersAndFolders Start");

            // サービスアカウントのClientを準備
            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // AppUser毎の処理
            var totalAppUsers = Config.AppUsers.Length;

            for (var i = 0; i < totalAppUsers; i++)
            {
                var appUserCounter = i + 1;
                var appUserId      = Config.AppUsers[i];

                Console.WriteLine($"AppUser:{appUserId} {appUserCounter}/{totalAppUsers} Start");

                // 検索用ユーザーだった場合は何もしない
                if (appUserId == Config.SearchUserId)
                {
                    Console.WriteLine($"Skip. AppUser:{appUserId} is Search User");
                    continue;
                }

                // RateLimit対応スロットリング
                var throttle = TimeLimiter.GetFromMaxCountByInterval(Config.ApiRateLimit, TimeSpan.FromSeconds(1));


                // AppUser専用のClientを用意
                var auClient = new BoxClient(saClient.Config, saClient.Auth, asUser: appUserId);


                // ユーザーが所有するトップレベルのフォルダのリストを取得
                var topFolders = await GetFolders(auClient, "0", 100, throttle);

                // フォルダが1つだけでない、または、フォルダ名が指定と異なる場合
                if (topFolders.Count != 1 || topFolders.First().Name != Config.TopFolderName)
                {
                    Console.WriteLine(
                        $"ERROR トップフォルダが間違っている。 appUserId = {appUserId}, founder count = {topFolders.Count}, folder name = {topFolders.First().Name}");
                    return;
                }


                // トップフォルダのフォルダチェック
                BoxFolder topFolder = (BoxFolder)topFolders.First();

                // トップフォルダに検索ユーザーが招待されているか
                // フォルダのコラボレーションを一覧
                await throttle;
                var   topCollabs = await auClient.FoldersManager
                                   .GetCollaborationsAsync(topFolder.Id);

                var topCollab = topCollabs.Entries.SingleOrDefault(c => c.AccessibleBy.Id == Config.SearchUserId);
                if (topCollab == null)
                {
                    Console.WriteLine($"ERROR トップフォルダに検索ユーザーが招待されていない。appUserId = {appUserId}");
                    return;
                }

                // トップフォルダ下のサブフォルダをチェック
                var subFolders = await GetFolders(auClient, topFolder.Id, 1000, throttle);

                Console.WriteLine($"AppUser:{appUserId} {appUserCounter}/{totalAppUsers} number of subfolder = {subFolders.Count}");

                // タスクの待ち合わせ用リスト
                var folderTasks = new List <Task>();

                var forLock    = new object();
                var checkCount = 0;
                // サブフォルダに検索ユーザーがついていないこと
                foreach (var subItem in subFolders)
                {
                    var task = Task.Run(async() =>
                    {
                        BoxFolder subFolder = (BoxFolder)subItem;
                        // フォルダのコラボレーションを一覧
                        await throttle;
                        var subCollabs = await auClient.FoldersManager
                                         .GetCollaborationsAsync(subFolder.Id);

                        var subCollabListForSearch =
                            subCollabs.Entries.Where(c => c.AccessibleBy.Id == Config.SearchUserId);

                        // サブフォルダについている、検索用ユーザーのコラボレーションが1つだけかチェック
                        if (subCollabListForSearch.Count() != 1)
                        {
                            Console.WriteLine(
                                $"ERROR サブフォルダにコラボレーションが残っている。appUserId = {appUserId} subFolderId = {subFolder.Id} subFolderName = {subFolder.Name}");
                            return;
                        }

                        // サブフォルダについている唯一のコラボレーションが、トップフォルダについているコラボレーションと同じものか
                        var subCollabForSearch = subCollabListForSearch.First();

                        if (subCollabForSearch.Id != topCollab.Id)
                        {
                            // トップフォルダとサブフォルダで異なるコラボレーションがついている
                            Console.WriteLine(
                                $"ERROR サブフォルダとトップフォルダのコラボレーションが異なる。appUserId = {appUserId} subFolderId = {subFolder.Id} subFolderName = {subFolder.Name}");
                        }

                        lock (forLock)
                        {
                            checkCount++;
                            Console.Write("folder checked {0}", checkCount);
                            Console.SetCursorPosition(0, Console.CursorTop);
                        }
                    }); // end Task.Run
                    folderTasks.Add(task);
                } // end foreach on sub folders

                await Task.WhenAll(folderTasks);

                Console.WriteLine($"AppUser:{appUserId} {appUserCounter}/{totalAppUsers} folder check done");
            } // end for on appUsers

            Console.WriteLine("CheckAppUsersAndFolders Done");
        }
Exemplo n.º 19
0
        public static async Task CreateRootFolderAndMoveAllFolders()
        {
            Console.WriteLine("CreateRootFolderAndMoveAllFolders Start");

            // サービスアカウントのClientを準備
            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // RateLimit対応スロットリング
            var throttle = TimeLimiter.GetFromMaxCountByInterval(Config.ApiRateLimit, TimeSpan.FromSeconds(1));

            // AppUser毎の処理
            var totalAppUsers = Config.AppUsers.Length;

            for (var i = 0; i < totalAppUsers; i++)
            {
                var appUserCounter = i + 1;
                var appUserId      = Config.AppUsers[i];

                Console.WriteLine($"Start AppUser:{appUserId} {appUserCounter}/{totalAppUsers}");

                // 検索用ユーザーだった場合は何もしない
                if (appUserId == Config.SearchUserId)
                {
                    Console.WriteLine($"Skip. AppUser:{appUserId} is Search User");
                    continue;
                }

                // AppUser専用のClientを用意
                var auClient = new BoxClient(saClient.Config, saClient.Auth, asUser: appUserId);

                // タスクの待ち合わせ用リスト
                var tasks = new List <Task>();

                // トップレベルに親フォルダを作成する(作成済みの場合はそれを利用する)
                var topFolder = await EnsureTopFolder(auClient, throttle);

                // 親フォルダに検索用AppUserのコラボレーションを作成する(作成済みの場合は無視する)
                await CreateSearchUserCollaboration(topFolder, auClient, throttle);

                // コンソール表示時の排他用オブジェクト
                var forLock = new object();
                // プロセスが終わったフォルダの数をカウント
                var folderCount = 0;

                // 1ユーザーのフォルダリストを処理
                var offset     = 0;
                var totalCount = 0;
                do
                {
                    // AppUserのトップレベルのフォルダを一覧 基本的に1回で済む想定(約480 folder)だが、念の為1000件づつすべてのフォルダを処理する
                    var folderItems = await GetTopLevelFolderItems(auClient, offset, throttle);

                    if (totalCount == 0)
                    {
                        totalCount = folderItems.TotalCount;
                    }

                    offset += 1000;

                    // 取得したトップレベルのアイテムをループする
                    var totalFolders = folderItems.Entries.Count;
                    for (var j = 0; j < totalFolders; j++)
                    {
                        // アイテムを取り出す
                        var item = folderItems.Entries[j];

                        // フォルダではないか、フォルダが移動先の場合は無視
                        if (item.Type != "folder" || item.Id == topFolder.Id)
                        {
                            continue;
                        }

                        // 以下の処理を非同期で行う。
                        var task = Task.Run(async() =>
                        {
                            // 検索ユーザーをコラボレーションから外す
                            await RemoveSearchUserCollaboration(auClient, item, throttle);

                            // フォルダを更新し、親フォルダを変更する
                            await MoveFolder(item, topFolder, auClient, throttle);


                            // コンソールの表示が非同期でされないように順番待ちをする
                            lock (forLock)
                            {
                                folderCount += 1;
                                // 進捗の表示
                                Console.Write("AppUser {0}/{1}, Folder {2}/{3}",
                                              appUserCounter, totalAppUsers, folderCount, totalFolders);
                                Console.SetCursorPosition(0, Console.CursorTop);
                            }
                        });

                        tasks.Add(task);
                    }
                } while (totalCount > offset);

                // 非同期処理の待機
                await Task.WhenAll(tasks);

                Console.WriteLine();
            } // end for appUsers

            Console.WriteLine("CreateRootFolderAndMoveAllFolders Done");
        }
Exemplo n.º 20
0
        public static async Task CreateAppUsersAndFoldersAsync()
        {
            Console.WriteLine("CreateAppUsersAndFoldersAsync Start");

            // BOX API実行用のClientを準備
            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // RateLimit対応スロットリング
            var throttle = TimeLimiter.GetFromMaxCountByInterval(Config.ApiRateLimit, TimeSpan.FromSeconds(1));

            // test用のappUserを作成する。
            var userTasks = new Task <BoxUser> [NumberOfAppUsersForTest];

            for (var i = 0; i < NumberOfAppUsersForTest; i++)
            {
                var num = i;
                userTasks[i] = Task.Run(() => CreateAppUserAsync(num, saClient, throttle));
            }

            // 待機
            await Task.WhenAll(userTasks);

            Console.WriteLine("finished app user creation");

            // 検索用AppUserを作成
            var searchUser = await CreateSearchUser(saClient, throttle);

            var searchUserId = searchUser.Id;

            Console.WriteLine("created searchUser ID:{0}", searchUserId);

            for (int i = 0; i < NumberOfAppUsersForTest; i++)
            {
                var appUser     = userTasks[i].Result;
                var currAppUser = i + 1;

                var     auClient   = new BoxClient(saClient.Config, saClient.Auth, asUser: appUser.Id);
                BoxFile sampleFile = null;
                await using (var fileStream = new FileStream(@"Sample.docx", FileMode.Open))
                {
                    BoxFileRequest requestParams = new BoxFileRequest()
                    {
                        Name   = $"Sample-for-{appUser.Id}.docx",
                        Parent = new BoxRequestEntity()
                        {
                            Id = "0"
                        }
                    };

                    sampleFile = await auClient.FilesManager.UploadAsync(requestParams, fileStream);

                    Console.WriteLine($"uploaded {sampleFile.Name} {currAppUser}/{NumberOfAppUsersForTest}");
                }

                // ユーザー毎にフォルダを作成
                var folderTasks = new List <Task>();

                Console.WriteLine($"creating folders for {currAppUser}/{NumberOfAppUsersForTest}");
                for (var j = 0; j < NumberOfFoldersForTest; j++)
                {
                    var currFolder = j + 1;
                    folderTasks.Add(Task.Run(async() =>
                    {
                        // フォルダを作成する
                        var folder = await CreateFolderAsync(auClient, appUser, currFolder, throttle);

                        // 検索ユーザーを招待する
                        await CreateCollaboration(folder, searchUserId, auClient, throttle);

                        // サンプルファイルをコピーする
                        if (sampleFile != null)
                        {
                            var requestParams = new BoxFileRequest()
                            {
                                Id     = sampleFile.Id,
                                Parent = new BoxRequestEntity()
                                {
                                    Id = folder.Id
                                }
                            };

                            await throttle;
                            await auClient.FilesManager.CopyAsync(requestParams);
                        }

                        Console.WriteLine(
                            $"appUser {currAppUser}/{NumberOfAppUsersForTest}, Folder {currFolder}/{NumberOfFoldersForTest}");
                    }));
                }

                // フォルダ作成を待機
                await Task.WhenAll(folderTasks);
            }


            // 削除できるように、appUserのIDをファイルに残す
            var toBeDeletedIds = userTasks.Select(t => t.Result.Id).ToList();

            // 検索用ユーザーも削除対象に追加しておく
            toBeDeletedIds.Add(searchUserId);
            // ファイルに書き出す
            await File.WriteAllTextAsync(PathToAppUserIDsForTest, JsonSerializer.Serialize(toBeDeletedIds));

            Console.WriteLine("CreateAppUsersAndFoldersAsync Done");
        }
Exemplo n.º 21
0
        public static async Task DeleteAppUsersAsync()
        {
            Console.WriteLine("DeleteAppUsersAsync Start");

            var config     = Program.ConfigureBoxApi();
            var boxJwt     = new BoxJWTAuth(config);
            var adminToken = boxJwt.AdminToken();
            var saClient   = boxJwt.AdminClient(adminToken);

            // サービスアカウントが取れているかチェック
            var sa = await saClient.UsersManager.GetCurrentUserInformationAsync();

            Console.WriteLine("SA user ID:{0}, Login:{1}, Name:{2}", sa.Id, sa.Login, sa.Name);

            // RateLimit対応スロットリング
            var throttle = TimeLimiter.GetFromMaxCountByInterval(Config.ApiRateLimit, TimeSpan.FromSeconds(1));

            // ファイルを読み込む
            if (!File.Exists(PathToAppUserIDsForTest))
            {
                Console.WriteLine(PathToAppUserIDsForTest + " が存在しません。");
            }

            var fileData = await File.ReadAllTextAsync(PathToAppUserIDsForTest, Encoding.UTF8);

            var appUserIds = JsonSerializer.Deserialize <string[]>(fileData);


            // AppUserを削除
            if (appUserIds != null)
            {
                var tasks = new Task[appUserIds.Length];

                var totalAppUser = appUserIds.Length;

                for (int i = 0; i < totalAppUser; i++)
                {
                    var appUserId = appUserIds[i];
                    var num       = i + 1;
                    tasks[i] = Task.Run(() =>
                                        DeleteAppUserAsync(appUserId, saClient, sa.Id, num, totalAppUser, throttle));
                }

                // 待機
                await Task.WhenAll(tasks);
            }

            // サービスアカウントの退避フォルダをクリア
            {
                var offset     = 0;
                var totalCount = 0;
                do
                {
                    var items = await saClient.FoldersManager.GetFolderItemsAsync("0", 1000);

                    totalCount = items.TotalCount;
                    offset    += 1000;

                    List <Task> tasks = new List <Task>();
                    foreach (var entry in items.Entries)
                    {
                        if (entry.Type != "folder" || !entry.Name.Contains("ST_APP_USER"))
                        {
                            continue;
                        }
                        var task = Task.Run(async() =>
                        {
                            await throttle;
                            Console.WriteLine($"deleting {entry.Name}");
                            await saClient.FoldersManager.DeleteAsync(entry.Id, recursive: true);
                        });

                        tasks.Add(task);
                    }

                    await Task.WhenAll(tasks);
                } while (totalCount > offset);
            }

            Console.WriteLine("DeleteAppUsersAsync Done");
        }
Exemplo n.º 22
0
        public async void ImportFiles(string basePath)
        {
            try
            {
                // Get Box Auth Token
                if (!string.IsNullOrEmpty(Settings.PrivateKey))
                {
                    Settings.PrivateKey = Settings.PrivateKey.Replace("\\n", "\n");
                }

                var boxConfig = new BoxConfig(
                    Settings.ClientID,
                    Settings.ClientSecret,
                    Settings.EnterpriceId,
                    Settings.PrivateKey,
                    Settings.JwtPrivateKeyPassword,
                    Settings.JwtPublicKeyId);

                var boxJWTAuth = new BoxJWTAuth(boxConfig);
                var adminToken = boxJWTAuth.AdminToken();
                var client     = boxJWTAuth.AdminClient(adminToken);
                boxManager = new BoxManager(adminToken);

                var enrolledServices = repositoryEnrolledService.GetServicesByImportMode(ServiceReportImportModes.BoxAPI);

                if (enrolledServices.Model == null || enrolledServices.Model.List.Count() == 0)
                {
                    return;
                }

                foreach (var listItem in enrolledServices.Model.List)
                {
                    string importPath = Path.Combine(basePath, listItem.BusinessId.ToString(), "Sales", listItem.ServiceName);

                    BoxItem sharedItemInServiceFolder = await client.SharedItemsManager.SharedItemsAsync(listItem.BoxUrl);

                    var sharedServiceEnties = await client.FoldersManager.GetFolderItemsAsync(sharedItemInServiceFolder.Id, 100, 0,
                                                                                              new List <string>
                    {
                        BoxFolder.FieldName,
                        BoxFolder.FieldPathCollection,
                        BoxFolder.FieldModifiedAt,
                        BoxFolder.FieldItemCollection
                    }
                                                                                              );

                    foreach (var sharedEntry in sharedServiceEnties.Entries)
                    {
                        if (sharedEntry.Type.ToLower() == "file")
                        {
                            bool isFileExists = new RepositorySales().IsSalesFileExists(sharedEntry.Name, listItem.BusinessId, listItem.Id) || File.Exists(Path.Combine(importPath, sharedEntry.Name));
                            if (isFileExists)
                            {
                                continue;
                            }

                            if (!Directory.Exists(importPath))
                            {
                                Directory.CreateDirectory(importPath);
                            }

                            using (FileStream fileStream = new FileStream(Path.Combine(importPath, sharedEntry.Name), FileMode.CreateNew, System.IO.FileAccess.Write))
                            {
                                using (Stream stream = await client.FilesManager.DownloadStreamAsync(sharedEntry.Id))
                                {
                                    int bytesRead;
                                    var buffer = new byte[8192];
                                    do
                                    {
                                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                                        await fileStream.WriteAsync(buffer, 0, bytesRead);
                                    } while (bytesRead > 0);
                                }
                            }

                            // Move download file to archive folder

                            var subfolder  = new BoxApi.V2.Model.Folder();
                            var folderInfo = await client.FoldersManager.GetInformationAsync(sharedItemInServiceFolder.Id);

                            if (folderInfo.ItemCollection.Entries.OfType <BoxFolder>().Count() > 0)
                            {
                                var foundFolder = folderInfo.ItemCollection.Entries.OfType <BoxFolder>().Any((f) => f.Name == "Archive");
                                // var foundFolder = entryItems.Parent.ItemCollection.Entries.OfType<BoxFolder>().First((a) => a.Name == "my subfolder");
                                if (foundFolder == false)
                                {
                                    subfolder = boxManager.CreateFolder(sharedItemInServiceFolder.Id, "Archive");
                                    boxManager.MoveFile(sharedEntry.Id, subfolder.Id);
                                }
                                // Move the file to the subfolder
                                var foundFolderDetails = folderInfo.ItemCollection.Entries.OfType <BoxFolder>().First((f) => f.Name == "Archive");
                                boxManager.MoveFile(sharedEntry.Id, foundFolderDetails.Id);
                                // getfolderDetails(folderItems.Id, path);
                            }
                            else
                            {
                                subfolder = boxManager.CreateFolder(sharedItemInServiceFolder.Id, "Archive");
                                boxManager.MoveFile(sharedEntry.Id, subfolder.Id);
                            }
                        }
                        //else case entry type is 'folder'
                    }
                }
            }
            catch (Exception ex)
            {
                ex.Log();
                throw ex;
            }
        }
Exemplo n.º 23
0
        static async Task MainAsync()
        {
            try
            {
                /* Read the config file that is provided when an application is
                 * created in the Box Dev Consolse
                 * */

                string jsonConfig = System.IO.File.ReadAllText(configFile());
                var    config     = BoxConfig.CreateFromJsonString(jsonConfig);
                /* Authenticate. This will provide access to the service account */
                var boxJWT     = new BoxJWTAuth(config);
                var adminToken = "";
                adminToken = boxJWT.AdminToken();
                Console.WriteLine("Admin Token:" + adminToken);

                /*
                 * Searching for a particular user from the enterprise given the login name
                 */
                BoxClient boxClient = boxJWT.AdminClient(adminToken);
                BoxCollection <BoxUser> boxUserCollection = await boxClient.UsersManager.GetEnterpriseUsersAsync(userLogin(), 0, 100, null, "managed", null, false);

                List <BoxUser> userList = boxUserCollection.Entries;
                Console.WriteLine("Entries:" + userList.Count);
                if (userList.Count > 0)
                {
                    foreach (var user in userList)
                    {
                        Console.WriteLine("User Login:"******" ID:" + user.Id);
                    }
                }

                /* Replace this variable for the user you want. This is the users
                 * internal Box ID and is all numbers e.g. 3445252385. Suggest that
                 * the list of users in the system is cached in the Token Factory
                 * and synced perdiodically.
                 */
                var userId = userInformation();
                /* Ask box for a token for the user */
                var userToken = boxJWT.UserToken(userId);

                Console.WriteLine("User Token:" + userToken);
                /* Generate a downscoped token to the ITEM_PREVIEW scope */
                var exchanger = new TokenExchange(adminToken, "item_preview");

                /*Optionally you can downscope to a particular resource. Omitting this will downscope
                 * all resources to the scope set above regardless of resource.
                 * exchanger.SetResource("https://api.box.com/2.0/files/123456789");
                 */
                string downscopedToken = exchanger.Exchange();
                Console.WriteLine("Downscoped ITEM_PREVIEW Token:" + downscopedToken);
                /* Print out some user information for the demo */
                var userClient = boxJWT.UserClient(userToken, userId);

                var userDetails = await userClient.UsersManager.GetCurrentUserInformationAsync();

                Console.WriteLine("\n User Details:");
                Console.WriteLine("\tId: {0}", userDetails.Id);
                Console.WriteLine("\tName: {0}", userDetails.Name);
                Console.WriteLine("\tStatus: {0}", userDetails.Status);
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }
        }
Exemplo n.º 24
0
        public static string EnterpriseToken()
        {
            object enterpriseTokenObject = CacheHelper.Fetch(ENTERPRISE_TOKEN_CACHE_KEY, CACHE_EXPIRES_IN_DEFAULT, () => { return(BOX_JWT_HELPER.AdminToken()); });

            return((string)enterpriseTokenObject);
        }
Exemplo n.º 25
0
        public static void UploadFilesToBox(string releaseVersion, int lastBuild, out string sharedLinkUrl)
        {
            Console.Out.WriteLine("Uploading Files to the Box Server");
            var fullReleaseVersion = $"{releaseVersion}.{lastBuild}";
            var reader             = new StreamReader(ConfigurationManager.AppSettings.Get("BoxConfigPath"));
            var json   = reader.ReadToEnd();
            var config = BoxConfig.CreateFromJsonString(json);

            var       sdk    = new BoxJWTAuth(config);
            var       token  = sdk.AdminToken();
            BoxClient client = sdk.AdminClient(token);

            var releaseNumbers = releaseVersion.Split('.');
            var firstNumber    = releaseNumbers[0];
            var secondNumber   = releaseNumbers[1];

            var result = client.SearchManager.QueryAsync(query: $"Releases_{firstNumber}.{secondNumber}", type: "Folder").Result;

            string parentFolderId;

            if (result.TotalCount > 0)
            {
                parentFolderId = result.Entries.First().Id;
            }
            else //create parent release folder in the root folder
            {
                var folderRequest = new BoxFolderRequest
                {
                    Name   = $"Releases_{firstNumber}.{secondNumber}",
                    Parent = new BoxRequestEntity()
                    {
                        Id = "0"//root folder id
                    }
                };
                var createdFolder = client.FoldersManager.CreateAsync(folderRequest).Result;
                parentFolderId = createdFolder.Id;
            }

            string releaseFolderId;

            result = client.SearchManager.QueryAsync(query: releaseVersion, type: "Folder").Result;
            if (result.TotalCount > 0 && result.Entries.First().Parent.Id == parentFolderId)
            {
                releaseFolderId = result.Entries.First().Id; //Release Folder already exists in Box
            }
            else
            {
                var folderRequest = new BoxFolderRequest
                {
                    Name   = releaseVersion,
                    Parent = new BoxRequestEntity()
                    {
                        Id = parentFolderId
                    }
                };
                var createdFolder = client.FoldersManager.CreateAsync(folderRequest).Result;
                releaseFolderId = createdFolder.Id;
            }

            UploadFileToBox(client, $"GetScripts_Version_{fullReleaseVersion}.sql", $"{ConfigurationManager.AppSettings.Get("OutputFinalScriptPath")}{releaseVersion}/GetScripts_Version_{fullReleaseVersion}.sql", releaseFolderId);
            UploadFileToBox(client, $"Release_Notes_{fullReleaseVersion}.sql", $"{ConfigurationManager.AppSettings.Get("OutputFinalScriptPath")}{releaseVersion}/Release_Notes_{fullReleaseVersion}.txt", releaseFolderId);

            var sharedLinkParams = new BoxSharedLinkRequest()
            {
                Access = BoxSharedLinkAccessType.open
            };
            BoxFolder sharedFolder = client.FoldersManager.CreateSharedLinkAsync(parentFolderId, sharedLinkParams).Result;

            sharedLinkUrl = sharedFolder.SharedLink.Url;

            Console.Out.WriteLine($"Files Uploaded to the Box Server: {sharedLinkUrl}");
        }