/// <summary> /// Get a list of Legal Hold Policies that belong to your Enterprise. /// </summary> /// <param name="policyName">Case insensitive prefix-match filter on Policy name.</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 Legal Hold Policies in your Enterprise that match the filter parameters (if passed in). By default, will only return only 'type', 'id', and 'policy_name', but you can specify more by using the 'fields' parameter.</returns> public async Task <BoxCollectionMarkerBased <BoxLegalHoldPolicy> > GetListLegalHoldPoliciesAsync(string policyName = null, string fields = null, int limit = 100, string marker = null, bool autoPaginate = false) { BoxRequest request = new BoxRequest(_config.LegalHoldPoliciesEndpointUri) .Method(RequestMethod.Get) .Param("policy_name", policyName) .Param("fields", fields) .Param("limit", limit.ToString()) .Param("marker", marker); if (autoPaginate) { return(await AutoPaginateMarker <BoxLegalHoldPolicy>(request, limit).ConfigureAwait(false)); } else { IBoxResponse <BoxCollectionMarkerBased <BoxLegalHoldPolicy> > response = await ToResponseAsync <BoxCollectionMarkerBased <BoxLegalHoldPolicy> >(request).ConfigureAwait(false); return(response.ResponseObject); } }
/// <summary> /// Retrieves the files and/or folders that have been moved to the trash. 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="limit">The maximum number of items to return</param> /// <param name="offset">The item at which to begin the response</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> /// <param name="sort">The field to sort items on</param> /// <param name="direction">The direction to sort results in: ascending or descending</param> /// <returns>A collection of items contained in the trash is returned. An error is thrown if any of the parameters are invalid.</returns> public async Task <BoxCollection <BoxItem> > GetTrashItemsAsync(int limit, int offset = 0, IEnumerable <string> fields = null, bool autoPaginate = false, string sort = null, BoxSortDirection?direction = null) { BoxRequest request = new BoxRequest(_config.FoldersEndpointUri, Constants.TrashItemsPathString) .Param("limit", limit.ToString()) .Param("offset", offset.ToString()) .Param("sort", sort) .Param("direction", direction.ToString()) .Param(ParamFields, fields); if (autoPaginate) { return(await AutoPaginateLimitOffset <BoxItem>(request, limit).ConfigureAwait(false)); } else { IBoxResponse <BoxCollection <BoxItem> > response = await ToResponseAsync <BoxCollection <BoxItem> >(request).ConfigureAwait(false); return(response.ResponseObject); } }
private static string GetErrorMessage <T>(string message, IBoxResponse <T> response, BoxError error = null) where T : class { var requestID = error?.RequestId != null?string.Format(" | {0}", error.RequestId) : ""; IEnumerable <string> traceIDHeaders; if (response.Headers != null && response.Headers.TryGetValues("BOX-REQUEST-ID", out traceIDHeaders)) { foreach (var id in traceIDHeaders) { // Take the first trace ID header value (there should only be one) requestID += "." + id; break; } } var errorInfo = error?.Code != null && error?.Message != null?string.Format(" {0} - {1}", error.Code, error.Message) : ""; return(string.Format("{0} [{1}{2}]{3}", message, response.StatusCode, requestID, errorInfo)); }
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); }
/// <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); } }
protected internal static BoxError GetResponseError <T>(IBoxResponse <T> response) where T : class { BoxError error = null; if (!string.IsNullOrWhiteSpace(response.ContentString)) { var converter = new BoxJsonConverter(); try { error = converter.Parse <BoxError>(response.ContentString); } catch (Exception e) { Debug.WriteLine(string.Format("Unable to parse error message: {0} ({1})", response.ContentString, e.Message)); } } return(error); }
/// <summary> /// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads, /// these are performed as multipart form uploads An optional If-Match header can be included to ensure that client only /// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version. /// </summary> /// <param name="fileName"></param> /// <param name="stream"></param> /// <param name="etag"></param> /// <returns></returns> public async Task <BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, List <string> fields = null) { stream.ThrowIfNull("stream"); fileName.ThrowIfNullOrWhiteSpace("fileName"); BoxMultiPartRequest request = new BoxMultiPartRequest(new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId))) .Header("If-Match", etag) .Param(ParamFields, fields) .FormPart(new BoxFileFormPart() { Name = "filename", Value = stream, FileName = fileName }); IBoxResponse <BoxCollection <BoxFile> > response = await ToResponseAsync <BoxCollection <BoxFile> >(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return(response.ResponseObject.Entries.FirstOrDefault()); }
/// <summary> /// Used to create a shared link for this particular folder. Please see here for more information on the /// permissions available for shared links. In order to disable a shared link, send this same type of PUT /// request with the value of shared_link set to null, i.e. {"shared_link": null} /// </summary> /// <returns></returns> public async Task <BoxFolder> CreateSharedLinkAsync(string id, BoxSharedLinkRequest sharedLinkRequest, List <string> fields = null) { id.ThrowIfNullOrWhiteSpace("id"); if (!sharedLinkRequest.ThrowIfNull("sharedLinkRequest").Access.HasValue) { throw new ArgumentNullException("sharedLinkRequest.Access"); } BoxRequest request = new BoxRequest(_config.FoldersEndpointUri, id) .Method(RequestMethod.Put) .Param(ParamFields, fields) .Payload(_converter.Serialize(new BoxItemRequest() { SharedLink = sharedLinkRequest })); IBoxResponse <BoxFolder> response = await ToResponseAsync <BoxFolder>(request).ConfigureAwait(false); return(response.ResponseObject); }
/// <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> /// Used to assign a task to a single user. There can be multiple assignments on a given task. /// </summary> /// <param name="taskAssignmentRequest">BoxTaskAssignmentRequest object.</param> /// <returns>A new task assignment object will be returned upon success.</returns> public async Task <BoxTaskAssignment> CreateTaskAssignmentAsync(BoxTaskAssignmentRequest taskAssignmentRequest) { taskAssignmentRequest.ThrowIfNull("taskAssignmentRequest") .Task.ThrowIfNull("taskAssignmentRequest.Task") .Id.ThrowIfNullOrWhiteSpace("taskAssignmentRequest.Task.Id"); taskAssignmentRequest.AssignTo.ThrowIfNull("taskAssignmentRequest.AssignTo"); if (string.IsNullOrEmpty(taskAssignmentRequest.AssignTo.Login) && string.IsNullOrEmpty(taskAssignmentRequest.AssignTo.Id)) { throw new ArgumentException("At least one of Id or Login is required in this object.", "taskAssignmentRequest.AssignTo"); } BoxRequest request = new BoxRequest(_config.TaskAssignmentsEndpointUri) .Method(RequestMethod.Post) .Payload(_converter.Serialize(taskAssignmentRequest)); IBoxResponse <BoxTaskAssignment> response = await ToResponseAsync <BoxTaskAssignment>(request).ConfigureAwait(false); return(response.ResponseObject); }
/// <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).ConfigureAwait(false)); } else { IBoxResponse <BoxCollection <BoxGroupMembership> > response = await ToResponseAsync <BoxCollection <BoxGroupMembership> >(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.ThrowIfNull("domainToWhitelist"); directionForWhitelist.ThrowIfNull("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); }
/// <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); } }
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> /// 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); }
/// <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); }
/// <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); } }
/// <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); }
/// <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); } }
/// <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); }
/// <summary> /// This method is used to upload a new version of an existing file in a user’s account. Similar to regular file uploads, /// these are performed as multipart form uploads. An optional If-Match header can be included to ensure that client only /// overwrites the file if it knows about the latest version. The filename on Box will remain the same as the previous version. /// To update the file’s name, you can specify a new name for the file using the fileName parameter. /// A proper timeout should be provided for large uploads. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileId">Id of the file to upload a new version to.</param> /// <param name="stream">Stream of the uploading file.</param> /// <param name="etag">This ‘etag’ field of the file, which will be set in the If-Match header.</param> /// <param name="fields">Fields which shall be returned in result.</param> /// <param name="timeout">Optional timeout for response.</param> /// <param name="contentMD5">The SHA1 hash of the file.</param> /// <param name="setStreamPositionToZero">Set position for input stream to 0.</param> /// <param name="uploadUri">Optional url for uploading file.</param> /// <returns>A full file object is returned.</returns> public async Task <BoxFile> UploadNewVersionAsync(string fileName, string fileId, Stream stream, string etag = null, List <string> fields = null, TimeSpan?timeout = null, byte[] contentMD5 = null, bool setStreamPositionToZero = true, Uri uploadUri = null) { fileName.ThrowIfNullOrWhiteSpace("fileName"); fileId.ThrowIfNullOrWhiteSpace("fileId"); stream.ThrowIfNull("stream"); if (setStreamPositionToZero) { stream.Position = 0; } uploadUri = uploadUri == null ? new Uri(string.Format(Constants.FilesNewVersionEndpointString, fileId)) : uploadUri; BoxMultiPartRequest request = new BoxMultiPartRequest(uploadUri) { Timeout = timeout } .Header(Constants.RequestParameters.IfMatch, etag) .Param(ParamFields, fields) .FormPart(new BoxFileFormPart() { Name = "filename", Value = stream, FileName = fileName }); if (contentMD5 != null) { request.Header(Constants.RequestParameters.ContentMD5, HexStringFromBytes(contentMD5)); } IBoxResponse <BoxCollection <BoxFile> > response = await ToResponseAsync <BoxCollection <BoxFile> >(request).ConfigureAwait(false); // We can only upload one file at a time, so return the first entry return(response.ResponseObject.Entries.FirstOrDefault()); }
/// <summary> /// Parses the BoxResponse with the provided converter /// </summary> /// <typeparam name="T">The return type of the Box response</typeparam> /// <param name="response">The response to parse</param> /// <param name="converter">The converter to use for the conversion</param> /// <returns></returns> internal static IBoxResponse <T> ParseResults <T>(this IBoxResponse <T> response, IBoxConverter converter) where T : class { switch (response.Status) { case ResponseStatus.Success: if (!string.IsNullOrWhiteSpace(response.ContentString)) { response.ResponseObject = converter.Parse <T>(response.ContentString); } break; case ResponseStatus.Error: if (!string.IsNullOrWhiteSpace(response.ContentString)) { try { response.Error = converter.Parse <BoxError>(response.ContentString); if (response.Error != null && !string.IsNullOrWhiteSpace(response.Error.Name)) { throw new BoxException(string.Format("{0}: {1}", response.Error.Name, response.Error.Description)) { StatusCode = response.StatusCode } } ; } catch (Exception) { Debug.WriteLine(string.Format("Unable to parse error message: {0}", response.ContentString)); } } throw new BoxException() { StatusCode = response.StatusCode }; } return(response); }
/// <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); }
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, }; }
/// <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> /// 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); }
/// <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); }
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); }
/// <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 { IBoxResponse <BoxCollectionMarkerBased <T> > 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); }