示例#1
0
        /// <summary>
        /// Get a down scoped token.
        /// </summary>
        /// <returns>The down scoped access token.</returns>
        public string Exchange()
        {
            BoxRequest boxRequest = new BoxRequest(new Uri(Constants.BoxApiHostUriString), Constants.AuthTokenEndpointString)
                .Method(RequestMethod.Post)
                .Payload(Constants.RequestParameters.SubjectToken, token)
                .Payload(Constants.RequestParameters.SubjectTokenType, Constants.RequestParameters.AccessTokenTypeValue)
                .Payload(Constants.RequestParameters.Scope, scope)
                .Payload(Constants.RequestParameters.Resource, resourceUrl)
                .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.TokenExchangeGrantTypeValue);

            if (actorToken != null)
            {
                boxRequest = boxRequest.Payload(Constants.RequestParameters.ActorToken, actorToken)
                    .Payload(Constants.RequestParameters.ActorTokenType, Constants.RequestParameters.IdTokenTypeValue);
            }

            var handler = new HttpRequestHandler();
            var converter = new BoxJsonConverter();
            var service = new BoxService(handler);

            IBoxResponse<OAuthSession> boxResponse = service.ToResponseAsync<OAuthSession>(boxRequest).Result;
            boxResponse.ParseResults(converter);

            return boxResponse.ResponseObject.AccessToken;
        }
        public async Task<OAuthSession> AuthenticateAsync(string authCode)
        {
            if (string.IsNullOrWhiteSpace(authCode))
                throw new ArgumentException("Auth code cannot be null or empty", "authCode");

            BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString)
                                            .Method(RequestMethod.Post)
                                            .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.AuthorizationCode)
                                            .Payload(Constants.RequestParameters.Code, authCode)
                                            .Payload(Constants.RequestParameters.ClientId, _config.ClientId)
                                            .Payload(Constants.RequestParameters.ClientSecret, _config.ClientSecret)
                                            .Payload(Constants.RequestParameters.BoxDeviceId, _config.DeviceId)
                                            .Payload(Constants.RequestParameters.BoxDeviceName, _config.DeviceName);

            IBoxResponse<OAuthSession> boxResponse = await _service.ToResponseAsync<OAuthSession>(boxRequest).ConfigureAwait(false);
            boxResponse.ParseResults(_converter);

            using (await _mutex.LockAsync().ConfigureAwait(false))
            {
                Session = boxResponse.ResponseObject;
                
                var handler = SessionAuthenticated;
                if (handler != null)
                {
                    handler(this, new SessionAuthenticatedEventArgs(Session));
                }
            }

            return boxResponse.ResponseObject;
        }
        public async Task QueueTask_MultipleThreads_OrderedResponse()
        {
            /*** Arrange ***/
            int numTasks = 1000;

            int count = 0;

            // Increments the access token each time a call is made to the API
            _handler.Setup(h => h.ExecuteAsync<OAuthSession>(It.IsAny<IBoxRequest>()))
                .Returns(() => Task.FromResult<IBoxResponse<OAuthSession>>(new BoxResponse<OAuthSession>()
                {
                    Status = ResponseStatus.Success,
                    ContentString = "{\"access_token\": \"" + count + "\",\"expires_in\": 3600,\"token_type\": \"bearer\",\"refresh_token\": \"J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR\"}"
                })).Callback(() => System.Threading.Interlocked.Increment(ref count));

            /*** Act ***/
            IBoxRequest request = new BoxRequest(new Uri("http://box.com"), "folders");

            List<Task<IBoxResponse<OAuthSession>>> tasks = new List<Task<IBoxResponse<OAuthSession>>>();
            for (int i = 0; i < numTasks; i++)
                tasks.Add(_service.EnqueueAsync<OAuthSession>(request));

            await Task.WhenAll(tasks);

            /*** Assert ***/
            for (int i = 0; i < numTasks; i++)
            {
                OAuthSession session = _converter.Parse<OAuthSession>(tasks[i].Result.ContentString);
                Assert.AreEqual(session.AccessToken, i.ToString());
            }
        }
        /// <summary>
        /// Returns a collection of search results that match the keyword, if there are are no matching search results
        /// an empty collection will be returned
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="extraParameters">additional search parameters, see https://developers.box.com/docs/#search-searching-for-content </param>
        /// <returns></returns>
        public async Task<BoxCollection<BoxItem>> SearchAsync(string keyword, int limit, int offset = 0, Dictionary<string,string> extraParameters = null)
        {
            keyword.ThrowIfNullOrWhiteSpace("keyword");

            BoxRequest request = new BoxRequest(_config.SearchEndpointUri)
                .Param("query", keyword)
                .Param("limit", limit.ToString())
                .Param("offset", offset.ToString());

            if (extraParameters != null)
            {
                if (extraParameters.ContainsKey("query"))
                {
                    throw new ArgumentException("ExtraParamters can not contain query paramter","extraParamters");
                }

                foreach (string key in extraParameters.Keys)
                {
                    request.Param(key, extraParameters[key]);
                }
            }

            IBoxResponse<BoxCollection<BoxItem>> response = await ToResponseAsync<BoxCollection<BoxItem>>(request).ConfigureAwait(false);
                    
            return response.ResponseObject;
        }
        /// <summary>
        /// Retrieves all of the groups for given enterprise. Must have permissions to see an enterprise's groups.
        /// </summary>
        /// <param name="limit">The number of results to return with this request. Refer to the Box API for defaults.</param>
        /// <param name="offset">The offset of the results. Refer to the Box API for more details.</param>
        /// <param name="fields">Attribute(s) to include in the response.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all groups; defaults to false.</param>
        /// <returns>A collection of groups.</returns>
        public async Task<BoxCollection<BoxGroup>> GetAllGroupsAsync(int? limit = null, int? offset = null, List<string> fields = null, bool autoPaginate = false)
        {
            BoxRequest request = new BoxRequest(_config.GroupsEndpointUri)
                .Param(ParamFields, fields)
                .Param("limit", limit.ToString())
                .Param("offset", offset.ToString());

            if (autoPaginate)
            {
                if (!limit.HasValue)
                {
                    limit = 100;
                    request.Param("limit", limit.ToString());      
                }
                if (!offset.HasValue)
                    request.Param("offset", "0");

                return await AutoPaginateLimitOffset<BoxGroup>(request, limit.Value);
            }
            else
            {
                IBoxResponse<BoxCollection<BoxGroup>> response = await ToResponseAsync<BoxCollection<BoxGroup>>(request).ConfigureAwait(false);
                return response.ResponseObject;
            }
        }
        /// <summary>
        /// Use this to get events for a given user.
        /// </summary>
        /// <param name="limit">Limits the number of events returned (defaults to 500).</param>
        /// <param name="streamType">Restricts the types of events returned: all returns all events; changes returns events that may cause file tree changes such as file updates or collaborations; sync returns events that may cause file tree changes only for synced folders.</param>
        /// <param name="streamPosition">The location in the event stream from which you want to start receiving events. You can specify the special value 'now' to get 0 events and the latest stream_position value. Defaults to 'now'.</param>
        /// <param name="dedupeEvents">Whether or not to automatically de-duplicate events as they are received. Defaults to true.</param>
        /// <returns></returns>
        public async Task<BoxEventCollection<BoxEnterpriseEvent>> UserEventsAsync(int limit = 500, 
                                                                                  UserEventsStreamType streamType = UserEventsStreamType.all,
                                                                                  string streamPosition = "now", 
                                                                                  bool dedupeEvents = true)
        {
            BoxRequest request = new BoxRequest(_config.EventsUri)
                .Param("stream_type", streamType.ToString())
                .Param("limit", limit.ToString())
                .Param("stream_position", streamPosition);

            IBoxResponse<BoxEventCollection<BoxEnterpriseEvent>> response = await ToResponseAsync<BoxEventCollection<BoxEnterpriseEvent>>(request).ConfigureAwait(false);

            if (dedupeEvents)
            {
                List<BoxEnterpriseEvent> filteredEvents = new List<BoxEnterpriseEvent>();
                foreach (var e in response.ResponseObject.Entries)
                {
                    bool notUsed = true;
                    if (!USER_EVENTS_DEDUPE_CACHE.TryGetValue(e.EventId, out notUsed))
                    {
                        USER_EVENTS_DEDUPE_CACHE.Add(e.EventId, true);
                        filteredEvents.Add(e);
                    }
                }

                response.ResponseObject.Entries = filteredEvents;
            }   

            return response.ResponseObject;
        }
        /// <summary>
        /// Gets information about an individual device pin.
        /// </summary>
        /// <param name="id">Device pin id.</param>
        /// <returns>Information about the device pin.</returns>
        public async Task<BoxDevicePin> GetDevicePin(string id)
        {
            BoxRequest request = new BoxRequest(_config.DevicePinUri, id);

            IBoxResponse<BoxDevicePin> response = await ToResponseAsync<BoxDevicePin>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
 /// <summary>
 /// Shared items are any files or folders that are represented by a shared link. Shared items are different from other API resources in that a shared resource doesn’t necessarily have to be in the account of the user accessing it. The actual shared link itself is used along with a normal access token.
 /// </summary>
 /// <param name="sharedLink">The shared link for this item.</param>
 /// <param name="sharedLinkPassword">The password for the shared link (if required)</param>
 /// <returns>A full file or folder object is returned if the shared link is valid and the user has access to it. An error may be returned if the link is invalid, if a password is required, or if the user does not have access to the file.</returns>
 public async Task<BoxItem> SharedItemsAsync(string sharedLink, string sharedLinkPassword=null)
 {
     sharedLink.ThrowIfNullOrWhiteSpace("sharedLink");
     BoxRequest request = new BoxRequest(_config.SharedItemsUri, null)
         .Header("BoxApi", string.Format("shared_link={0}{1}", sharedLink, (string.IsNullOrEmpty(sharedLinkPassword) ? "" : ("&shared_link_password=" + sharedLinkPassword))));
     IBoxResponse<BoxItem> response = await ToResponseAsync<BoxItem>(request).ConfigureAwait(false);
     return response.ResponseObject;
 }
        /// <summary>
        /// Delete individual device pin.
        /// </summary>
        /// <param name="id">Device pin id.</param>
        /// <returns>True if successfully deleted.</returns>
        public async Task<bool> DeleteDevicePin(string id)
        {
            BoxRequest request = new BoxRequest(_config.DevicePinUri, id)
                .Method(RequestMethod.Delete);

            IBoxResponse<BoxDevicePin> response = await ToResponseAsync<BoxDevicePin>(request).ConfigureAwait(false);

            return response.Status == ResponseStatus.Success;
        }
        /// <summary>
        /// Retrieves information about the user who is currently logged in i.e. the user for whom this auth token was generated.
        /// </summary>
        /// <returns></returns>
        public async Task<BoxUser> GetCurrentUserInformationAsync(List<string> fields = null)
        {
            BoxRequest request = new BoxRequest(_config.UserEndpointUri, "me")
                .Param(ParamFields, fields);

            IBoxResponse<BoxUser> response = await ToResponseAsync<BoxUser>(request);

            return response.ResponseObject;
        }
        /// <summary>
        /// Retrieves the collections for the given user. Currently, only the favorites collection is supported.
        /// </summary>
        /// <returns>An array of collection instances</returns>
        public async Task<BoxCollection<BoxCollectionItem>> GetCollectionsAsync()
        {
            BoxRequest request = new BoxRequest(_config.CollectionsEndpointUri, null)
                .Method(RequestMethod.Get);

            IBoxResponse<BoxCollection<BoxCollectionItem>> response = await ToResponseAsync<BoxCollection<BoxCollectionItem>>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Retrieves the metadata for the given file id
        /// </summary>
        /// <param name="id">ID of the file to retrieve metadata from</param>
        /// <param name="typeInstance">Name of the metadata type instance</param>
        /// <returns>A BoxMetadata object that includes key:value pairs defined by a user or application. 
        /// If there is no type instance present, a 404 HTTP status code of not_found will be returned.</returns>
        public async Task<BoxMetadata> GetMetadata(string id, string typeInstance = DefaultTypeInstance)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(new Uri(Constants.BoxApiUriString + string.Format(CultureInfo.InvariantCulture, MetadataEndpointPath, id, typeInstance)));

            IBoxResponse<BoxMetadata> response = await ToResponseAsync<BoxMetadata>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        public void ValidParameters_ValidRequest()
        {
            Uri baseUri = new Uri("http://api.box.com/v2");
            IBoxRequest request = new BoxRequest(baseUri, "auth/oauth2");
            request.Parameters.Add("test", "test2");

            Assert.AreEqual(request.Method, RequestMethod.Get);
            Assert.AreEqual(baseUri, request.Host);
            Assert.IsNotNull(request.Parameters);
        }
示例#14
0
        /// <summary>
        /// Returns the stream of the requested file.
        /// </summary>
        /// <param name="id">Id of the file to download.</param>
        /// <param name="versionId">The ID specific version of this file to download.</param>
        /// <param name="timeout">Optional timeout for response.</param>
        /// <returns>Stream of the requested file.</returns>
        public async Task<Stream> DownloadStreamAsync(string id, string versionId = null, TimeSpan? timeout = null)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ContentPathString, id)) { Timeout = timeout }
                .Param("version", versionId);

            IBoxResponse<Stream> response = await ToResponseAsync<Stream>(request).ConfigureAwait(false);
            return response.ResponseObject;
        }
        /// <summary>
        /// Create a new webhook.
        /// </summary>
        /// <param name="webhookRequest">BoxWebhookRequest object.</param>
        /// <returns>Returns a webhook object if creation succeeds.</returns>
        public async Task<BoxWebhook> CreateWebhookAsync(BoxWebhookRequest webhookRequest)
        {
            BoxRequest request = new BoxRequest(_config.WebhooksUri)
                .Method(RequestMethod.Post)
                .Payload(_converter.Serialize<BoxWebhookRequest>(webhookRequest));

            IBoxResponse<BoxWebhook> response = await ToResponseAsync<BoxWebhook>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Get a webhook.
        /// </summary>
        /// <param name="id">Webhook id.</param>
        /// <returns>Returns a webhook object.</returns>
        public async Task<BoxWebhook> GetWebhookAsync(string id)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.WebhooksUri, id);

            IBoxResponse<BoxWebhook> response = await ToResponseAsync<BoxWebhook>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
 /// <summary>
 /// Returns the stream of the requested file
 /// </summary>
 /// <param name="id">Id of the file to download</param>
 /// <param name="versionId">The ID specific version of this file to download.</param>
 /// <param name="timeout">Optional timeout for response</param>
 /// <returns>MemoryStream of the requested file</returns>
 public async Task<Stream> DownloadStreamAsync(string id, string versionId = null, TimeSpan? timeout = null)
 {
     var uri = await GetDownloadUriAsync(id, versionId);
     BoxRequest request = new BoxRequest(uri)
     {
         Timeout = timeout
     };
     IBoxResponse<Stream> response = await ToResponseAsync<Stream>(request).ConfigureAwait(false);
     return response.ResponseObject;
 }
        /// <summary>
        /// Used to edit the settings and information about a user. This method only works for enterprise admins. To roll a user out 
        /// of the enterprise (and convert them to a standalone free user), update the special enterprise attribute to be null
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userRequest"></param>
        /// <returns></returns>
        public async Task<BoxUser> UpdateUserInformationAsync(BoxUserRequest userRequest, List<string> fields = null)
        {
            BoxRequest request = new BoxRequest(_config.UserEndpointUri, userRequest.Id)
                .Param(ParamFields, fields)
                .Payload(_converter.Serialize(userRequest));

            IBoxResponse<BoxUser> response = await ToResponseAsync<BoxUser>(request);

            return response.ResponseObject;
        }
        /// <summary>
        /// Used to create a new retention policy.
        /// </summary>
        /// <param name="retentionPolicyRequest">BoxRetentionPolicyRequest object.</param>
        /// <returns>A new retention policy object will be returned upon success.</returns>
        public async Task<BoxRetentionPolicy> CreateRetentionPolicyAsync(BoxRetentionPolicyRequest retentionPolicyRequest)
        {
            BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri)
                .Method(RequestMethod.Post)
                .Payload(_converter.Serialize(retentionPolicyRequest));

            IBoxResponse<BoxRetentionPolicy> response = await ToResponseAsync<BoxRetentionPolicy>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Used to delete a single collaboration.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> RemoveCollaborationAsync(string id)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.CollaborationsEndpointUri, id)
                .Method(RequestMethod.Delete);

            IBoxResponse<BoxCollaboration> response = await ToResponseAsync<BoxCollaboration>(request).ConfigureAwait(false);

            return response.Status == ResponseStatus.Success;
        }
        /// <summary>
        /// Use to get information about the web link.
        /// </summary>
        /// <param name="webLinkId">Id of the weblink.</param>
        /// <returns>The web link object is returned.</returns>
        public async Task<BoxWebLink> GetWebLinkAsync(string webLinkId)
        {
            webLinkId.ThrowIfNullOrWhiteSpace("webLinkId");

            BoxRequest request = new BoxRequest(_config.WebLinksEndpointUri, webLinkId)
                .Method(RequestMethod.Get);

            IBoxResponse<BoxWebLink> response = await ToResponseAsync<BoxWebLink>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Get details of a single Legal Hold Policy.
        /// </summary>
        /// <param name="legalHoldId">Id of the legal hold policy.</param>
        /// <returns>If the Id is valid, information about the Legal Hold Policy is returned.</returns>
        public async Task<BoxLegalHoldPolicy> GetLegalHoldPolicyAsync(string legalHoldId)
        {
            legalHoldId.ThrowIfNullOrWhiteSpace("legalHoldId");

            BoxRequest request = new BoxRequest(_config.LegalHoldPoliciesEndpointUri, legalHoldId)
                .Method(RequestMethod.Get);

            IBoxResponse<BoxLegalHoldPolicy> response = await ToResponseAsync<BoxLegalHoldPolicy>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Returns all the groups created by the current user
        /// </summary>
        /// <param name="limit">The number of results to return with this request. Refer to the Box API for defaults.</param>
        /// <param name="offset">The offset of the results. Refer to the Box API for more details.</param>
        /// <param name="fields">The fields to return for this request.</param>
        /// <returns>A collection of groups</returns>
        public async Task<BoxCollection<BoxGroup>> GetAllGroupsAsync(int? limit = null, int? offset = null, List<string> fields = null)
        {
            BoxRequest request = new BoxRequest(_config.GroupsEndpointUri)
                .Param(ParamFields, fields)
                .Param("limit", limit.ToString())
                .Param("offset", offset.ToString());

            IBoxResponse<BoxCollection<BoxGroup>> response = await ToResponseAsync<BoxCollection<BoxGroup>>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Deletes a web link and moves it to the trash.
        /// </summary>
        /// <param name="webLinkId">Id of the weblink.</param>
        /// <returns>True, if successfully deleted and moved to trash</returns>
        public async Task<bool> DeleteWebLinkAsync(string webLinkId)
        {
            webLinkId.ThrowIfNullOrWhiteSpace("webLinkId");

            BoxRequest request = new BoxRequest(_config.WebLinksEndpointUri, webLinkId)
                .Method(RequestMethod.Delete);

            IBoxResponse<BoxWebLink> response = await ToResponseAsync<BoxWebLink>(request).ConfigureAwait(false);

            return response.Status == ResponseStatus.Success;
        }
        /// <summary>
        /// Returns the stream of the requested file
        /// </summary>
        /// <param name="id">Id of the file to download</param>
        /// <returns>MemoryStream of the requested file</returns>
        public async Task<Stream> DownloadStreamAsync(string id)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ContentPathString, id));
                

            IBoxResponse<Stream> response = await ToResponseAsync<Stream>(request);

            return response.ResponseObject;
        }
        /// <summary>
        /// Delete a webhook.
        /// </summary>
        /// <param name="id">Webhook id.</param>
        /// <returns>Returns true if deleted successfully.</returns>
        public async Task<bool> DeleteWebhookAsync(string id)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.WebhooksUri, id)
                .Method(RequestMethod.Delete);

            IBoxResponse<BoxWebhook> response = await ToResponseAsync<BoxWebhook>(request).ConfigureAwait(false);

            return response.Status == ResponseStatus.Success;
        }
        /// <summary>
        /// A full comment object is returned is the ID is valid and if the user has access to the comment.
        /// </summary>
        /// <param name="commentRequest"></param>
        /// <returns></returns>
        public async Task<BoxComment> GetInformationAsync(string id, List<string> fields = null)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.CommentsEndpointUri, id)
                .Param(ParamFields, fields);

            IBoxResponse<BoxComment> response = await ToResponseAsync<BoxComment>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
        /// <summary>
        /// Create a new Box Enterprise user.
        /// </summary>
        /// <returns></returns>
        public async Task<BoxUser> CreateEnterpriseUserAsync(BoxUserRequest userRequest, List<string> fields = null)
        {
            BoxRequest request = new BoxRequest(_config.UserEndpointUri, userRequest.Id)
                .Param(ParamFields, fields)
                .Payload(_converter.Serialize(userRequest))
                .Method(RequestMethod.Post);

            IBoxResponse<BoxUser> response = await ToResponseAsync<BoxUser>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
示例#29
0
        /// <summary>
        /// Fetches a specific task assignment.
        /// </summary>
        /// <param name="taskAssignmentId">Id of the task assignment.</param>
        /// <returns>The specified task assignment object will be returned upon success.</returns>
        public async Task<BoxTaskAssignment> GetTaskAssignmentAsync(string taskAssignmentId)
        {
            taskAssignmentId.ThrowIfNull("taskAssignmentId");

            BoxRequest request = new BoxRequest(_config.TaskAssignmentsEndpointUri, taskAssignmentId)
                .Method(RequestMethod.Get);

            IBoxResponse<BoxTaskAssignment> response = await ToResponseAsync<BoxTaskAssignment>(request).ConfigureAwait(false);

            return response.ResponseObject;
        }
示例#30
0
        /// <summary>
        /// Retrieves the temporary direct Uri to a file (valid for 15 minutes). This is typically used to send as a redirect to a browser to make the browser download the file directly from Box.
        /// </summary>
        /// <param name="id">Id of the file.</param>
        /// <param name="versionId">Version of the file.</param>
        /// <returns></returns>
        public async Task<Uri> GetDownloadUriAsync(string id, string versionId = null)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ContentPathString, id)) { FollowRedirect = false }
                .Param("version", versionId);

            IBoxResponse<BoxFile> response = await ToResponseAsync<BoxFile>(request).ConfigureAwait(false);
            var locationUri = response.Headers.Location;

            return locationUri;
        }
示例#31
0
        /// <summary>
        /// Used to create a shared link for this particular file. Please see here for more information on the permissions available for shared links.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sharedLinkRequest"></param>
        /// <returns></returns>
        public async Task <BoxFile> CreateSharedLinkAsync(string id, BoxSharedLinkRequest sharedLinkRequest, List <string> fields = null)
        {
            id.ThrowIfNullOrWhiteSpace("id");
            if (!sharedLinkRequest.ThrowIfNull("sharedLinkRequest").Access.HasValue)
            {
                throw new ArgumentNullException("sharedLink.Access");
            }

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, id)
                                 .Method(RequestMethod.Put)
                                 .Param(ParamFields, fields)
                                 .Payload(_converter.Serialize(new BoxItemRequest()
            {
                SharedLink = sharedLinkRequest
            }));

            IBoxResponse <BoxFile> response = await ToResponseAsync <BoxFile>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
        /// <summary>
        /// Used to whitelist a domain for a Box collaborator. You can specify the domain and direction of the whitelist. When whitelisted successfully, only users from the whitelisted
        /// domain can be invited as a collaborator.
        /// </summary>
        /// <param name="domainToWhitelist">This is the domain to whitelist collaboration.</param>
        /// <param name="directionForWhitelist">Can be set to inbound, outbound, or both for the direction of the whitelist.</param>
        /// <returns>The whitelist entry if successfully created.</returns>
        public async Task <BoxCollaborationWhitelistEntry> AddCollaborationWhitelistEntryAsync(string domainToWhitelist, string directionForWhitelist)
        {
            domainToWhitelist.ThrowIfNullOrWhiteSpace("domainToWhitelist");
            directionForWhitelist.ThrowIfNullOrWhiteSpace("directionForWhitelist");

            dynamic req = new JObject();

            req.domain    = domainToWhitelist;
            req.direction = directionForWhitelist;

            string jsonStr = req.ToString();

            BoxRequest request = new BoxRequest(_config.CollaborationWhitelistEntryUri)
                                 .Method(RequestMethod.Post)
                                 .Payload(jsonStr);

            IBoxResponse <BoxCollaborationWhitelistEntry> response = await ToResponseAsync <BoxCollaborationWhitelistEntry>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
示例#33
0
        /// <summary>
        /// Retrieves all of the group memberships for a given user.
        /// Note this is only available to group admins.
        /// To retrieve group memberships for the user making the API request, use the users/me/memberships endpoint.
        /// </summary>
        /// <param name="userId">Id of the user.</param>
        /// <param name="offset">The item at which to begin the response.</param>
        /// <param name="limit">Default is 100. Max is 1000.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all group memberships; defaults to false.</param>
        /// <returns>A collection of group membership objects will be returned upon success.</returns>
        public async Task <BoxCollection <BoxGroupMembership> > GetMembershipsForUserAsync(string userId, uint offset = 0, uint limit = 100, bool autoPaginate = false)
        {
            userId.ThrowIfNullOrWhiteSpace("userId");

            BoxRequest request = new BoxRequest(_config.UserEndpointUri, string.Format(Constants.GroupMembershipForUserPathString, userId))
                                 .Param("offset", offset.ToString())
                                 .Param("limit", limit.ToString())
                                 .Method(RequestMethod.Get);

            if (autoPaginate)
            {
                return(await AutoPaginateLimitOffset <BoxGroupMembership>(request, (int)limit));
            }
            else
            {
                IBoxResponse <BoxCollection <BoxGroupMembership> > response = await ToResponseAsync <BoxCollection <BoxGroupMembership> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
        private OAuthSession JWTAuthPost(string assertion)
        {
            BoxRequest boxRequest = new BoxRequest(this.boxConfig.BoxApiHostUri, Constants.AuthTokenEndpointString)
                                    .Method(RequestMethod.Post)
                                    .Header(Constants.RequestParameters.UserAgent, this.boxConfig.UserAgent)
                                    .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.JWTAuthorizationCode)
                                    .Payload(Constants.RequestParameters.Assertion, assertion)
                                    .Payload(Constants.RequestParameters.ClientId, this.boxConfig.ClientId)
                                    .Payload(Constants.RequestParameters.ClientSecret, this.boxConfig.ClientSecret);

            var handler   = new HttpRequestHandler();
            var converter = new BoxJsonConverter();
            var service   = new BoxService(handler);

            IBoxResponse <OAuthSession> boxResponse = service.ToResponseAsync <OAuthSession>(boxRequest).Result;

            boxResponse.ParseResults(converter);

            return(boxResponse.ResponseObject);
        }
示例#35
0
        /// <summary>
        /// Used to add a comment by the user to a specific file, discussion, or comment (i.e. as a reply comment).
        /// </summary>
        /// <param name="commentRequest"></param>
        /// <returns></returns>
        public async Task <BoxComment> AddCommentAsync(BoxCommentRequest commentRequest, List <string> fields = null)
        {
            commentRequest.ThrowIfNull("commentRequest")
            .Item.ThrowIfNull("commentRequest.Item")
            .Id.ThrowIfNullOrWhiteSpace("commentRequest.Item.Id");
            if (commentRequest.Item.Type == null)
            {
                throw new ArgumentNullException("commentRequest.Item.Type");
            }

            BoxRequest request = new BoxRequest(_config.CommentsEndpointUri)
                                 .Method(RequestMethod.Post)
                                 .Param(ParamFields, fields)
                                 .Payload(_converter.Serialize(commentRequest))
                                 .Authorize(_auth.Session.AccessToken);

            IBoxResponse <BoxComment> response = await ToResponseAsync <BoxComment>(request);

            return(response.ResponseObject);
        }
        /// <summary>
        /// Retrieves the files and/or folders contained within this folder without any other metadata about the folder.
        /// Any attribute in the full files or folders objects can be passed in with the fields parameter to get specific attributes,
        /// and only those specific attributes back; otherwise, the mini format is returned for each item by default.
        /// Multiple attributes can be passed in using the fields parameter. Paginated results can be
        /// retrieved using the limit and offset parameters.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="limit">The maximum number of items to return in a page. The default is 100 and the max is 1000.</param>
        /// <param name="offset">The offset at which to begin the response. An offset of value of 0 will start at the beginning of the folder-listing.
        /// Note: If there are hidden items in your previous response, your next offset should be = offset + limit, not the # of records you received back.
        /// The default is 0.</param>
        /// <param name="fields">Attribute(s) to include in the response</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <returns>A collection of items contained in the folder is returned. An error is thrown if the folder does not exist,
        /// or if any of the parameters are invalid. The total_count returned may not match the number of entries when using enterprise scope,
        /// because external folders are hidden the list of entries.</returns>
        public async Task <BoxCollection <BoxItem> > GetFolderItemsAsync(string id, int limit, int offset = 0, IEnumerable <string> fields = null, bool autoPaginate = false)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.FoldersEndpointUri, string.Format(Constants.ItemsPathString, id))
                                 .Param("limit", limit.ToString())
                                 .Param("offset", offset.ToString())
                                 .Param(ParamFields, fields);

            if (autoPaginate)
            {
                return(await AutoPaginateLimitOffset <BoxItem>(request, limit));
            }
            else
            {
                IBoxResponse <BoxCollection <BoxItem> > response = await ToResponseAsync <BoxCollection <BoxItem> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
        /// <summary>
        /// Retrieves a thumbnail, or smaller image representation, of this file. Sizes of 32x32,
        /// 64x64, 128x128, and 256x256 can be returned in the .png format
        /// and sizes of 32x32, 94x94, 160x160, and 320x320 can be returned in the .jpg format.
        /// Thumbnails can be generated for the image and video file formats listed here.
        /// <see cref="http://community.box.com/t5/Managing-Your-Content/What-file-types-are-supported-by-Box-s-Content-Preview/ta-p/327"/>
        /// </summary>
        /// <param name="id">Id of the file.</param>
        /// <param name="minHeight">The minimum height of the thumbnail.</param>
        /// <param name="minWidth">The minimum width of the thumbnail.</param>
        /// <param name="maxHeight">The maximum height of the thumbnail.</param>
        /// <param name="maxWidth">The maximum width of the thumbnail.</param>
        /// <param name="handleRetry">Specifies whether the method handles retries. If true, then the method would retry the call if the HTTP response is 'Accepted'. The delay for the retry is determined
        /// by the RetryAfter header, or if that header is not set, by the constant DefaultRetryDelay.</param>
        /// <param name="throttle">Whether the requests will be throttled. Recommended to be left true to prevent spamming the server.</param>
        /// <returns>Contents of thumbnail as Stream.</returns>
        public async Task <Stream> GetThumbnailAsync(string id, int?minHeight = null, int?minWidth = null, int?maxHeight = null, int?maxWidth = null, bool throttle = true, bool handleRetry = true)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.ThumbnailPathString, id))
                                 .Param("min_height", minHeight.ToString())
                                 .Param("min_width", minWidth.ToString())
                                 .Param("max_height", maxHeight.ToString())
                                 .Param("max_width", maxWidth.ToString());

            IBoxResponse <Stream> response = await ToResponseAsync <Stream>(request, throttle).ConfigureAwait(false);

            while (response.StatusCode == HttpStatusCode.Accepted && handleRetry)
            {
                await CrossPlatform.Delay(GetTimeDelay(response.Headers));

                response = await ToResponseAsync <Stream>(request, throttle).ConfigureAwait(false);
            }

            return(response.ResponseObject);
        }
示例#38
0
        private async Task <OAuthSession> ExchangeRefreshToken(string refreshToken)
        {
            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                throw new ArgumentException("Refresh token cannot be null or empty", "refreshToken");
            }

            BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString)
                                    .Method(RequestMethod.Post)
                                    .Payload("grant_type", "refresh_token")
                                    .Payload("refresh_token", refreshToken)
                                    .Payload("client_id", _config.ClientId)
                                    .Payload("client_secret", _config.ClientSecret);

            IBoxResponse <OAuthSession> boxResponse = await _service.ToResponseAsync <OAuthSession>(boxRequest).ConfigureAwait(false);

            boxResponse.ParseResults(_converter);

            // Return new session
            return(boxResponse.ResponseObject);
        }
        /// <summary>
        /// Update the storage policy information for storage policy assignment.
        /// </summary>
        /// <param name="assignmentId">Storage Policy assignment Id to update.</param>
        /// <param name="policyId">"The Id of the Storage Policy to update to."</param>
        /// <returns></returns> The updated Storage Policy object with new assignment.
        public async Task <BoxStoragePolicyAssignment> UpdateStoragePolicyAssignment(string assignmentId, String policyId)
        {
            policyId.ThrowIfNullOrWhiteSpace("policyId");

            dynamic req = new JObject();
            dynamic storagePolicyObject = new JObject();

            storagePolicyObject.type = "storage_policy";
            storagePolicyObject.id   = policyId;
            req.storage_policy       = storagePolicyObject;

            string jsonStr = req.ToString();

            BoxRequest request = new BoxRequest(_config.StoragePolicyAssignmentsUri, assignmentId)
                                 .Method(RequestMethod.Put)
                                 .Payload(jsonStr);

            IBoxResponse <BoxStoragePolicyAssignment> response = await ToResponseAsync <BoxStoragePolicyAssignment>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
示例#40
0
        /// <summary>
        /// Gets all the device pins within a given enterprise. Must be an enterprise admin with the manage enterprise scope to make this call.
        /// </summary>
        /// <param name="enterpriseId">Box enterprise id.</param>
        /// <param name="marker">Needs not be passed or can be empty for first invocation of the API. Use the one returned in response for each subsequent call.</param>
        /// <param name="limit">Default value is 100. Max value is 10000.</param>
        /// <param name="direction">Default is "asc". Valid values are asc, desc. Case in-sensitive, ASC/DESC works just fine.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <returns>Returns all the device pins within a given enterprise up to limit amount.</returns>
        public async Task <BoxCollectionMarkerBased <BoxDevicePin> > GetEnterpriseDevicePinsAsync(string enterpriseId, string marker = null,
                                                                                                  int limit = 100,
                                                                                                  BoxSortDirection direction = BoxSortDirection.ASC,
                                                                                                  bool autoPaginate          = false)
        {
            BoxRequest request = new BoxRequest(_config.EnterprisesUri, string.Format(Constants.GetEnterpriseDevicePinsPathString, enterpriseId))
                                 .Param("limit", limit.ToString())
                                 .Param("marker", marker)
                                 .Param("direction", direction.ToString());

            if (autoPaginate)
            {
                return(await AutoPaginateMarker <BoxDevicePin>(request, limit));
            }
            else
            {
                IBoxResponse <BoxCollectionMarkerBased <BoxDevicePin> > response = await ToResponseAsync <BoxCollectionMarkerBased <BoxDevicePin> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
示例#41
0
        /// <summary>
        /// Retrieve a chunk of Enterprise Events.  You must be using a token that is scoped to admin level in order to use this endpoint.
        /// </summary>
        /// <param name="limit">Limits the number of events returned (defaults to 500)</param>
        /// <param name="streamPosition">The starting position for fetching the events. This is used in combination with the limit to determine which events to return to the caller. Use the results from the next_stream_position of your last call to get the next set of events.</param>
        /// <param name="eventTypes">events to filter by</param>
        /// <param name="createdAfter">A lower bound on the timestamp of the events returned</param>
        /// <param name="createdBefore">An upper bound on the timestamp of the events returned</param>
        /// <returns></returns>
        public async Task <BoxEventCollection <BoxEnterpriseEvent> > EnterpriseEventsAsync(int limit                = 500,
                                                                                           string streamPosition    = null,
                                                                                           List <string> eventTypes = null,
                                                                                           DateTime?createdAfter    = null,
                                                                                           DateTime?createdBefore   = null)
        {
            var createdAfterString  = createdAfter.HasValue ? createdAfter.Value.ToString(Constants.RFC3339DateFormat) : null;
            var createdBeforeString = createdBefore.HasValue ? createdBefore.Value.ToString(Constants.RFC3339DateFormat) : null;

            BoxRequest request = new BoxRequest(_config.EventsUri)
                                 .Param("stream_type", ENTERPRISE_EVENTS_STREAM_TYPE)
                                 .Param("limit", limit.ToString())
                                 .Param("stream_position", streamPosition)
                                 .Param("event_type", eventTypes)
                                 .Param("created_after", createdAfterString)
                                 .Param("created_before", createdBeforeString);

            IBoxResponse <BoxEventCollection <BoxEnterpriseEvent> > response = await ToResponseAsync <BoxEventCollection <BoxEnterpriseEvent> >(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
示例#42
0
        /// <summary>
        /// Moves all of the owned content from within one user’s folder into a new folder in another user’s account.
        /// You can move folders across users as long as the you have administrative permissions and the ‘source’ user owns the folders.
        /// To move everything from the root folder, use “0” which always represents the root folder of a Box account.
        /// </summary>
        /// <param name="userId">Id of the user.</param>
        /// <param name="ownedByUserId">The ID of the user who the folder will be transferred to.</param>
        /// <param name="folderId">Currently only moving of the root folder (0) is supported.</param>
        /// <param name="notify">Determines if the destination user should receive email notification of the transfer.</param>
        /// <returns>Returns the information for the newly created destination folder. An error is thrown if you do not have the necessary permissions to move the folder.</returns>
        public async Task <BoxFolder> MoveUserFolderAsync(string userId, string ownedByUserId, string folderId = "0", bool notify = false)
        {
            userId.ThrowIfNullOrWhiteSpace("userId");
            ownedByUserId.ThrowIfNullOrWhiteSpace("ownedByUserId");
            folderId.ThrowIfNullOrWhiteSpace("folderId");

            BoxRequest request = new BoxRequest(_config.UserEndpointUri, string.Format(Constants.MoveUserFolderPathString, userId, folderId))
                                 .Param("notify", notify.ToString())
                                 .Payload(_converter.Serialize(new BoxMoveUserFolderRequest()
            {
                OwnedBy = new BoxUserRequest()
                {
                    Id = ownedByUserId
                }
            }))
                                 .Method(RequestMethod.Put);

            IBoxResponse <BoxFolder> response = await ToResponseAsync <BoxFolder>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
示例#43
0
        /// <summary>
        /// Used to add a user to the exempt user list. Once on the exempt user list this user is whitelisted as a collaborator.
        /// </summary>
        /// <param name="userId">This is the Box User to add to the exempt list.</param>
        /// <returns>The specific exempt user or user on the collaborator whitelist.</returns>
        public async Task <BoxCollaborationWhitelistTargetEntry> AddCollaborationWhitelistExemptUserAsync(string userId)
        {
            userId.ThrowIfNull("userId");

            dynamic user = new JObject();
            dynamic req  = new JObject();

            user.id   = userId;
            user.type = "user";
            req.user  = user;

            string jsonStr = req.ToString();

            BoxRequest request = new BoxRequest(_config.CollaborationWhitelistTargetEntryUri)
                                 .Method(RequestMethod.Post)
                                 .Payload(jsonStr);

            IBoxResponse <BoxCollaborationWhitelistTargetEntry> response = await ToResponseAsync <BoxCollaborationWhitelistTargetEntry>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
        /// <summary>
        /// Retrieves the files and/or folders contained within this collection. Collection item lists behave a lot like getting a folder’s items.
        /// </summary>
        /// <param name="collectionId">The collection identifier.</param>
        /// <param name="limit">The maximum number of items to return in a page.</param>
        /// <param name="offset">The offset at which to begin the response. An offset of value of 0 will start at the beginning of the folder-listing. Offset of 2 would start at the 2nd record, not the second page. Note: If there are hidden items in your previous response, your next offset should be = offset + limit, not the # of records you received back.</param>
        /// <param name="fields">Attribute(s) to include in the response.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <returns></returns>
        public async Task <BoxCollection <BoxItem> > GetCollectionItemsAsync(string collectionId, int limit = 100, int offset = 0, List <string> fields = null, bool autoPaginate = false)
        {
            collectionId.ThrowIfNullOrWhiteSpace("collectionId");

            BoxRequest request = new BoxRequest(_config.CollectionsEndpointUri, string.Format(Constants.ItemsPathString, collectionId))
                                 .Method(RequestMethod.Get)
                                 .Param(ParamFields, fields)
                                 .Param("limit", limit.ToString())
                                 .Param("offset", offset.ToString());

            if (autoPaginate)
            {
                return(await AutoPaginateLimitOffset <BoxItem>(request, limit));
            }
            else
            {
                IBoxResponse <BoxCollection <BoxItem> > response = await ToResponseAsync <BoxCollection <BoxItem> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
示例#45
0
        /// <summary>
        /// Retrieves all of the retention policies for the given enterprise.
        /// </summary>
        /// <param name="policyName">A name to filter the retention policies by. A trailing partial match search is performed.</param>
        /// <param name="policyType">A policy type to filter the retention policies by.</param>
        /// <param name="createdByUserId">A user id to filter the retention policies by.</param>
        /// <param name="fields">Attribute(s) to include in the response.</param>
        /// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
        /// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <returns>Returns the list of all retention policies for the enterprise.</returns>
        public async Task <BoxCollectionMarkerBased <BoxRetentionPolicy> > GetRetentionPoliciesAsync(string policyName = null, string policyType = null, string createdByUserId = null, IEnumerable <string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false)
        {
            BoxRequest request = new BoxRequest(_config.RetentionPoliciesEndpointUri)
                                 .Param("policy_name", policyName)
                                 .Param("policy_type", policyType)
                                 .Param("created_by_user_id", createdByUserId)
                                 .Param(ParamFields, fields)
                                 .Param("limit", limit.ToString())
                                 .Param("marker", marker);

            if (autoPaginate)
            {
                return(await AutoPaginateMarker <BoxRetentionPolicy>(request, limit));
            }
            else
            {
                IBoxResponse <BoxCollectionMarkerBased <BoxRetentionPolicy> > response = await ToResponseAsync <BoxCollectionMarkerBased <BoxRetentionPolicy> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
        private async Task <OAuthSession> ExchangeRefreshToken(string refreshToken)
        {
            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                throw new ArgumentException("Refresh token cannot be null or empty", "refreshToken");
            }

            BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString)
                                    .Method(RequestMethod.Post)
                                    .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.RefreshToken)
                                    .Payload(Constants.RequestParameters.RefreshToken, refreshToken)
                                    .Payload(Constants.RequestParameters.ClientId, _config.ClientId)
                                    .Payload(Constants.RequestParameters.ClientSecret, _config.ClientSecret)
                                    .Payload(Constants.RequestParameters.BoxDeviceId, _config.DeviceId)
                                    .Payload(Constants.RequestParameters.BoxDeviceName, _config.DeviceName);

            IBoxResponse <OAuthSession> boxResponse = await _service.ToResponseAsync <OAuthSession>(boxRequest).ConfigureAwait(false);

            if (boxResponse.Status == ResponseStatus.Success)
            {
                // Parse and return the new session
                boxResponse.ParseResults(_converter);
                return(boxResponse.ResponseObject);
            }

            // The session has been invalidated, notify subscribers
            var handler = SessionInvalidated;

            if (handler != null)
            {
                handler(this, new EventArgs());
            }

            // As well as the caller
            throw new BoxSessionInvalidatedException()
                  {
                      StatusCode = boxResponse.StatusCode,
                  };
        }
示例#47
0
        /// <summary>
        /// Performs the authentication request using the provided auth code
        /// </summary>
        /// <param name="authCode"></param>
        /// <returns></returns>
        protected async Task <OAuthSession> ExchangeAuthCode(string authCode)
        {
            if (string.IsNullOrWhiteSpace(authCode))
            {
                throw new ArgumentException("Auth code cannot be null or empty", "authCode");
            }

            BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString)
                                    .Method(RequestMethod.Post)
                                    .Payload(Constants.RequestParameters.GrantType, Constants.RequestParameters.AuthorizationCode)
                                    .Payload(Constants.RequestParameters.Code, authCode)
                                    .Payload(Constants.RequestParameters.ClientId, _config.ClientId)
                                    .Payload(Constants.RequestParameters.ClientSecret, _config.ClientSecret)
                                    .Payload(Constants.RequestParameters.BoxDeviceId, _config.DeviceId)
                                    .Payload(Constants.RequestParameters.BoxDeviceName, _config.DeviceName);

            IBoxResponse <OAuthSession> boxResponse = await _service.ToResponseAsync <OAuthSession>(boxRequest).ConfigureAwait(false);

            boxResponse.ParseResults(_converter);

            return(boxResponse.ResponseObject);
        }
        private async Task <IBoxResponse <Stream> > GetPreviewResponseAsync(string id, int page, int?maxWidth = null, int?minWidth = null, int?maxHeight = null, int?minHeight = null, bool handleRetry = true)
        {
            id.ThrowIfNullOrWhiteSpace("id");

            BoxRequest request = new BoxRequest(_config.FilesEndpointUri, string.Format(Constants.PreviewPathString, id))
                                 .Param("page", page.ToString())
                                 .Param("max_width", maxWidth.ToString())
                                 .Param("max_height", maxHeight.ToString())
                                 .Param("min_width", minWidth.ToString())
                                 .Param("min_height", minHeight.ToString());

            var response = await ToResponseAsync <Stream>(request).ConfigureAwait(false);

            while (response.StatusCode == HttpStatusCode.Accepted && handleRetry)
            {
                await CrossPlatform.Delay(GetTimeDelay(response.Headers));

                response = await ToResponseAsync <Stream>(request).ConfigureAwait(false);
            }

            return(response);
        }
        /// <summary>
        /// Used to add a collaboration for a single user to a folder. Descriptions of the various roles can be found
        /// <see cref="https://support.box.com/entries/20366031-what-are-the-different-collaboration-permissions-and-what-access-do-they-provide"/>
        /// Either an email address or a user ID can be used to create the collaboration.
        /// </summary>
        /// <param name="collaborationRequest"></param>
        /// <param name="fields">Attribute(s) to include in the response</param>
        /// <param name="notify">Determines if the user, (or all the users in the group) should receive email notification of the collaboration.</param>
        /// <returns></returns>
        public async Task <BoxCollaboration> AddCollaborationAsync(BoxCollaborationRequest collaborationRequest, List <string> fields = null, bool?notify = null)
        {
            collaborationRequest.ThrowIfNull("collaborationRequest")
            .Item.ThrowIfNull("collaborationRequest.Item")
            .Id.ThrowIfNullOrWhiteSpace("collaborationRequest.Item.Id");
            collaborationRequest.AccessibleBy.ThrowIfNull("collaborationRequest.AccessibleBy");

            BoxRequest request = new BoxRequest(_config.CollaborationsEndpointUri)
                                 .Method(RequestMethod.Post)
                                 .Param(ParamFields, fields)
                                 .Payload(_converter.Serialize(collaborationRequest));

            if (notify.HasValue)
            {
                var value = notify.Value ? "true" : "false";
                request.Param("notify", value);
            }

            IBoxResponse <BoxCollaboration> response = await ToResponseAsync <BoxCollaboration>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
示例#50
0
        /// <summary>
        /// Creates a metadata cascade policy on a folder and the sub folder items.
        /// </summary>
        /// <param name="folderId">The id of the folder to assign the cascade policy to.</param>
        /// <param name="scope">The scope of the metadata cascade policy.</param>
        /// <param name="templateKey">The template key of the metadata cascade policy.</param>
        /// <returns>The metadata cascade policy if successfully created.</returns>
        public async Task <BoxMetadataCascadePolicy> CreateCascadePolicyAsync(string folderId, string scope, string templateKey)
        {
            folderId.ThrowIfNullOrWhiteSpace("folderId");
            scope.ThrowIfNullOrWhiteSpace("scope");
            templateKey.ThrowIfNullOrWhiteSpace("templateKey");

            dynamic jsonObject = new JObject();

            jsonObject.folder_id   = folderId;
            jsonObject.scope       = scope;
            jsonObject.templateKey = templateKey;

            string jsonString = jsonObject.ToString();

            BoxRequest request = new BoxRequest(_config.MetadataCascadePolicyUri)
                                 .Method(RequestMethod.Post)
                                 .Payload(jsonString);

            IBoxResponse <BoxMetadataCascadePolicy> response = await ToResponseAsync <BoxMetadataCascadePolicy>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
        /// <summary>
        /// Restores an item that has been moved to the trash. Default behavior is to restore the item to the folder it was in
        /// before it was moved to the trash. If that parent folder no longer exists or if there is now an item with the same
        /// name in that parent folder, the new parent folder and/or new name will need to be included in the request.
        /// </summary>
        /// <param name="folderRequest">BoxFolderRequest object (specify Parent.Id if you wish to restore to a different parent)</param>
        /// <param name="fields">Attribute(s) to include in the response</param>
        /// <returns>The full item will be returned if success. By default it is restored to the parent folder it was in before it was trashed.</returns>
        public async Task <BoxFolder> RestoreTrashedFolderAsync(BoxFolderRequest folderRequest, List <string> fields = null)
        {
            folderRequest.ThrowIfNull("folderRequest")
            .Id.ThrowIfNullOrWhiteSpace("folderRequest.Id");

            BoxRequest request = new BoxRequest(_config.FoldersEndpointUri, folderRequest.Id)
                                 .Method(RequestMethod.Post)
                                 .Param(ParamFields, fields);

            // ID shall not be used in request body it is used only as url attribute
            string oldId = folderRequest.Id;

            folderRequest.Id = null;

            request.Payload(_converter.Serialize(folderRequest));

            folderRequest.Id = oldId;

            IBoxResponse <BoxFolder> response = await ToResponseAsync <BoxFolder>(request).ConfigureAwait(false);

            return(response.ResponseObject);
        }
示例#52
0
        public async Task <OAuthSession> AuthenticateAsync(string authCode)
        {
            if (string.IsNullOrWhiteSpace(authCode))
            {
                throw new ArgumentException("Auth code cannot be null or empty", "authCode");
            }

            BoxRequest boxRequest = new BoxRequest(_config.BoxApiHostUri, Constants.AuthTokenEndpointString)
                                    .Method(RequestMethod.Post)
                                    .Payload("grant_type", "authorization_code")
                                    .Payload("code", authCode)
                                    .Payload("client_id", _config.ClientId)
                                    .Payload("client_secret", _config.ClientSecret);

            IBoxResponse <OAuthSession> boxResponse = await _service.ToResponseAsync <OAuthSession>(boxRequest).ConfigureAwait(false);

            boxResponse.ParseResults(_converter);

            using (await _mutex.LockAsync().ConfigureAwait(false))
                Session = boxResponse.ResponseObject;

            return(boxResponse.ResponseObject);
        }
示例#53
0
        /// <summary>
        /// Get assignments for a single policy.
        /// </summary>
        /// <param name="legalHoldPolicyId">ID of Policy to get Assignments for.</param>
        /// <param name="fields">Attribute(s) to include in the response.</param>
        /// <param name="assignToType">Filter assignments of this type only. Can be file_version, file, folder, or user.</param>
        /// <param name="assignToId">Filter assignments to this ID only. Note that this will only show assignments applied directly to this entity.</param>
        /// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
        /// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <returns>Returns the list of Assignments for the passed in Policy, as well as any optional filter parameters passed in. By default, will only return only type, and id, but you can specify more by using the fields parameter.</returns>
        public async Task <BoxCollectionMarkerBased <BoxLegalHoldPolicyAssignment> > GetAssignmentsAsync(string legalHoldPolicyId, string fields = null, string assignToType = null, string assignToId = null, int limit = 100, string marker = null, bool autoPaginate = false)
        {
            legalHoldPolicyId.ThrowIfNullOrWhiteSpace("legalHoldPolicyId");

            BoxRequest request = new BoxRequest(_config.LegalHoldPoliciesEndpointUri, string.Format(Constants.LegalHoldPolicyAssignmentsPathString, legalHoldPolicyId))
                                 .Method(RequestMethod.Get)
                                 .Param(ParamFields, fields)
                                 .Param("assign_to_type", assignToType)
                                 .Param("assign_to_id", assignToId)
                                 .Param("limit", limit.ToString())
                                 .Param("marker", marker);

            if (autoPaginate)
            {
                return(await AutoPaginateMarker <BoxLegalHoldPolicyAssignment>(request, limit));
            }
            else
            {
                IBoxResponse <BoxCollectionMarkerBased <BoxLegalHoldPolicyAssignment> > response = await ToResponseAsync <BoxCollectionMarkerBased <BoxLegalHoldPolicyAssignment> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
示例#54
0
        /// <summary>
        /// Used to fetch all results using pagination based on next_marker
        /// </summary>
        /// <typeparam name="T">The type of BoxCollectionMarkerBased item to expect.</typeparam>
        /// <param name="request">The pre-configured BoxRequest object.</param>
        /// <param name="limit">The limit specific to the endpoint.</param>
        /// <returns></returns>
        protected async Task <BoxCollectionMarkerBased <T> > AutoPaginateMarker <T>(BoxRequest request, int limit) where T : BoxEntity, new()
        {
            var allItemsCollection = new BoxCollectionMarkerBased <T>();

            allItemsCollection.Entries = new List <T>();

            bool keepGoing;

            do
            {
                var response = await ToResponseAsync <BoxCollectionMarkerBased <T> >(request).ConfigureAwait(false);

                var newItems = response.ResponseObject;
                allItemsCollection.Entries.AddRange(newItems.Entries);
                allItemsCollection.Order = newItems.Order;

                request.Param("marker", newItems.NextMarker);

                keepGoing = !string.IsNullOrWhiteSpace(newItems.NextMarker);
            } while (keepGoing);

            return(allItemsCollection);
        }
示例#55
0
        public async Task <BoxCollectionMarkerBased <BoxMetadataCascadePolicy> > GetAllMetadataCascadePoliciesAsync(string folderId, string ownerEnterpriseId = null, int limit = 100, string nextMarker = null, IEnumerable <string> fields = null, bool autopaginate = false)
        {
            folderId.ThrowIfNullOrWhiteSpace("folderId");

            BoxRequest request = new BoxRequest(_config.MetadataCascadePolicyUri)
                                 .Method(RequestMethod.Get)
                                 .Param(ParamFields, fields)
                                 .Param("folder_id", folderId)
                                 .Param("owner_enterprise_id", ownerEnterpriseId)
                                 .Param("limit", limit.ToString())
                                 .Param("marker", nextMarker);

            if (autopaginate)
            {
                return(await AutoPaginateMarker <BoxMetadataCascadePolicy>(request, limit));
            }
            else
            {
                IBoxResponse <BoxCollectionMarkerBased <BoxMetadataCascadePolicy> > response =
                    await ToResponseAsync <BoxCollectionMarkerBased <BoxMetadataCascadePolicy> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
        /// <summary>
        /// Retrieves all file version retentions for the given enterprise.
        /// </summary>
        /// <param name="fields">Attribute(s) to include in the response.</param>
        /// <param name="limit">Limit result size to this number. Defaults to 100, maximum is 1,000.</param>
        /// <param name="marker">Take from "next_marker" column of a prior call to get the next page.</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <param name="fileId">Filters results by files with this ID.</param>
        /// <param name="fileVersionId">Filters results by file versions with this ID.</param>
        /// <param name="policyId">Filters results by the retention policy with this ID.</param>
        /// <param name="dispositionBefore">Filters results by files that will have their disposition come into effect before this date.</param>
        /// <param name="dispositionAfter">Filters results by files that will have their disposition come into effect after this date.</param>
        /// <param name="dispositionAction">Filters results by the retention policy with this disposition action.</param>
        /// <returns>The specified file version retention will be returned upon success.</returns>
        public async Task <BoxCollectionMarkerBased <BoxFileVersionRetention> > GetFileVersionRetentionsAsync(IEnumerable <string> fields = null, int limit = 100, string marker = null, bool autoPaginate = false, string fileId = null, string fileVersionId = null, string policyId = null, DateTime?dispositionBefore = null, DateTime?dispositionAfter = null, DispositionAction?dispositionAction = null)
        {
            BoxRequest request = new BoxRequest(_config.FileVersionRetentionsUri)
                                 .Param(ParamFields, fields)
                                 .Param("limit", limit.ToString())
                                 .Param("marker", marker)
                                 .Param("file_id", fileId)
                                 .Param("file_version_id", fileVersionId)
                                 .Param("policy_id", policyId)
                                 .Param("disposition_before", Helper.ConvertToRFCString(dispositionBefore))
                                 .Param("disposition_after", Helper.ConvertToRFCString(dispositionAfter))
                                 .Param("disposition_action", dispositionAction.ToString());

            if (autoPaginate)
            {
                return(await AutoPaginateMarker <BoxFileVersionRetention>(request, limit));
            }
            else
            {
                var response = await ToResponseAsync <BoxCollectionMarkerBased <BoxFileVersionRetention> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
        public async Task <BoxCollectionMarkerBased <BoxMetadataQueryItem> > ExecuteMetadataQueryAsync(string from, string ancestorFolderId, string query = null, Dictionary <string, object> queryParameters = null, string indexName = null, List <BoxMetadataQueryOrderBy> orderBy = null, int limit = 100, string marker = null, bool autoPaginate = false)
        {
            from.ThrowIfNullOrWhiteSpace("from");
            ancestorFolderId.ThrowIfNullOrWhiteSpace("ancestorFolderId");

            JObject bodyObject = getMetadataQueryBody(from, ancestorFolderId, query, queryParameters, indexName, orderBy, null, limit, marker);

            BoxRequest request = new BoxRequest(_config.MetadataQueryUri)
                                 .Method(RequestMethod.Post)
                                 .Payload(_converter.Serialize(bodyObject));

            request.ContentType = Constants.RequestParameters.ContentTypeJson;

            if (autoPaginate)
            {
                return(await AutoPaginateMarkerMetadataQuery <BoxMetadataQueryItem>(request));
            }
            else
            {
                IBoxResponse <BoxCollectionMarkerBased <BoxMetadataQueryItem> > response = await ToResponseAsync <BoxCollectionMarkerBased <BoxMetadataQueryItem> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
示例#58
0
        /// <summary>
        /// Allows you to query by metadata on Box items
        /// </summary>
        /// <param name="from">The template used in the query. Must be in the form scope.templateKey</param>
        /// <param name="ancestorFolderId">The folder_id to which to restrain the query</param>
        /// <param name="query">The logical expression of the query</param>
        /// <param name="queryParameters">Required if query present. The arguments for the query</param>
        /// <param name="indexName">The name of the Index to use</param>
        /// <param name="orderBy">A list of BoxMetadataQueryOrderBy objects that contain field_key(s) to order on and the corresponding direction(s)</param>
        /// <param name="limit">The maximum number of items to return in a page. The default is 100 and the max is 1000.</param>
        /// <param name="marker">The marker to use for requesting the next page</param>
        /// <param name="autoPaginate">Whether or not to auto-paginate to fetch all items; defaults to false.</param>
        /// <returns>A collection of items and their associated metadata</returns>
        public async Task <BoxCollectionMarkerBased <BoxMetadataQueryItem> > ExecuteMetadataQueryAsync(string from, string ancestorFolderId, string query = null, Dictionary <string, object> queryParameters = null, string indexName = null, List <BoxMetadataQueryOrderBy> orderBy = null, int limit = 100, string marker = null, bool autoPaginate = false)
        {
            from.ThrowIfNullOrWhiteSpace("from");
            ancestorFolderId.ThrowIfNullOrWhiteSpace("ancestorFolderId");

            dynamic queryObject = new JObject();

            queryObject.from = from;
            queryObject.ancestor_folder_id = ancestorFolderId;
            queryObject.limit = limit;

            if (query != null)
            {
                queryObject.query = query;
            }

            if (queryParameters != null)
            {
                queryObject.query_params = JObject.FromObject(queryParameters);
            }

            if (indexName != null)
            {
                queryObject.use_index = indexName;
            }

            if (orderBy != null)
            {
                List <JObject> orderByList = new List <JObject>();
                foreach (var order in orderBy)
                {
                    dynamic orderByObject = new JObject();
                    orderByObject.field_key = order.FieldKey;
                    orderByObject.direction = order.Direction.ToString();
                    orderByList.Add(orderByObject);
                }
                queryObject.order_by = JArray.FromObject(orderByList);
            }

            if (marker != null)
            {
                queryObject.marker = marker;
            }

            string queryStr = _converter.Serialize(queryObject);

            BoxRequest request = new BoxRequest(_config.MetadataQueryUri)
                                 .Method(RequestMethod.Post)
                                 .Payload(queryStr);

            request.ContentType = Constants.RequestParameters.ContentTypeJson;

            if (autoPaginate)
            {
                return(await AutoPaginateMarkerMetadataQuery <BoxMetadataQueryItem>(request));
            }
            else
            {
                IBoxResponse <BoxCollectionMarkerBased <BoxMetadataQueryItem> > response = await ToResponseAsync <BoxCollectionMarkerBased <BoxMetadataQueryItem> >(request).ConfigureAwait(false);

                return(response.ResponseObject);
            }
        }
        /// <summary>
        /// Used to get real-time notification of activity in a Box account.
        /// </summary>
        /// <param name="streamPosition">The location in the event stream from which you want to start receiving events.</param>
        /// <param name="newEventsCallback">Method to invoke when new events are received.</param>
        /// <param name="cancellationToken">Used to request that the long polling process terminate.</param>
        /// <param name="streamType">Restricts the types of events returned: all returns all events; changes returns events that may cause file tree changes such as file updates or collaborations; sync returns events that may cause file tree changes only for synced folders.</param>
        /// <param name="dedupeEvents">Whether or not to automatically de-duplicate events as they are received. Defaults to true.</param>
        /// <param name="retryTimeoutOverride">Used to override the retry timeout value returned from the long polling OPTIONS request.</param>
        /// <returns></returns>
        public async Task LongPollUserEvents(string streamPosition,
                                             Action <BoxEventCollection <BoxEnterpriseEvent> > newEventsCallback,
                                             CancellationToken cancellationToken,
                                             UserEventsStreamType streamType = UserEventsStreamType.all,
                                             bool dedupeEvents        = true,
                                             int?retryTimeoutOverride = null)
        {
            const string NEW_CHANGE_MESSAGE = "new_change";

            string nextStreamPosition = streamPosition;

            while (true)
            {
                BoxRequest optionsRequest = new BoxRequest(_config.EventsUri)
                                            .Param("stream_type", streamType.ToString())
                                            .Method(RequestMethod.Options);

                IBoxResponse <BoxLongPollInfoCollection <BoxLongPollInfo> > optionsResponse = await ToResponseAsync <BoxLongPollInfoCollection <BoxLongPollInfo> >(optionsRequest).ConfigureAwait(false);

                var longPollInfo = optionsResponse.ResponseObject.Entries[0];
                var numRetries   = Int32.Parse(longPollInfo.MaxRetries);

                bool pollAgain = true;
                do
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                    }
                    try
                    {
                        var        timeout     = retryTimeoutOverride.HasValue ? retryTimeoutOverride.Value : longPollInfo.RetryTimeout;
                        BoxRequest pollRequest = new BoxRequest(longPollInfo.Url)
                        {
                            Timeout = TimeSpan.FromSeconds(timeout)
                        };
                        IBoxResponse <BoxLongPollMessage> pollResponse = await ToResponseAsync <BoxLongPollMessage>(pollRequest).ConfigureAwait(false);

                        var message = pollResponse.ResponseObject.Message;
                        if (message == NEW_CHANGE_MESSAGE)
                        {
                            BoxEventCollection <BoxEnterpriseEvent> newEvents = null;
                            do
                            {
                                newEvents = await UserEventsAsync(streamType : streamType, streamPosition : nextStreamPosition, dedupeEvents : dedupeEvents).ConfigureAwait(false);

                                nextStreamPosition = newEvents.NextStreamPosition;
                                if (newEvents.Entries.Count > 0)
                                {
                                    newEventsCallback.Invoke(newEvents);
                                }
                            } while (newEvents.Entries.Count > 0);
                        }
                    }
                    catch
                    {
                        //Most likely request timed out.
                        //If we've reached maximum number of retries then bounce all the way back to the OPTIONS request.
                        pollAgain = numRetries-- > 0;
                    }
                } while (pollAgain);
            }
        }
示例#60
0
        /// <summary>
        /// Used to fetch all results using pagination for metadata queries
        /// </summary>
        /// <typeparam name="T">The type of BoxCollectionMarkerBased item to expect.</typeparam>
        /// <param name="request">The pre-configured BoxRequest object.</param>
        /// <returns></returns>
        protected async Task <BoxCollectionMarkerBased <T> > AutoPaginateMarkerMetadataQuery <T>(BoxRequest request) where T : BoxMetadataQueryItem, new()
        {
            var allItemsCollection = new BoxCollectionMarkerBased <T>();

            allItemsCollection.Entries = new List <T>();

            bool keepGoing;

            do
            {
                var response = await ToResponseAsync <BoxCollectionMarkerBased <T> >(request).ConfigureAwait(false);

                var newItems = response.ResponseObject;
                allItemsCollection.Entries.AddRange(newItems.Entries);
                allItemsCollection.Order = newItems.Order;

                dynamic body = JObject.Parse(request.Payload);
                body.marker     = newItems.NextMarker;
                request.Payload = body.ToString();

                keepGoing = !string.IsNullOrWhiteSpace(newItems.NextMarker);
            } while (keepGoing);

            return(allItemsCollection);
        }