Example #1
0
        public async Task Assign_DifferentStoragePolicy_ValidResponse()
        {
            /*** Arrange ***/
            var responseString = @"{
                                        ""next_marker"": null,
                                        ""limit"": 1000,
                                        ""entries"": [
                                            {
                                                ""type"": ""storage_policy_assignment"",
                                                ""id"": ""user_5678"",
                                                ""storage_policy"": {
                                                    ""type"": ""storage_policy"",
                                                    ""id"": ""5678""
                                                },
                                                ""assigned_to"": {
                                                    ""type"": ""enterprise"",
                                                    ""id"": ""1111""
                                                }
                                            }
                                        ]
                                    }";

            IBoxRequest boxRequest = null;
            var         storagePolicyAssignmentsUri = new Uri(Constants.StoragePolicyAssignmentsEndpointString);

            Config.SetupGet(x => x.StoragePolicyAssignmentsUri).Returns(storagePolicyAssignmentsUri);
            Handler.Setup(h => h.ExecuteAsync <BoxCollectionMarkerBased <BoxStoragePolicyAssignment> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxCollectionMarkerBased <BoxStoragePolicyAssignment> > >(new BoxResponse <BoxCollectionMarkerBased <BoxStoragePolicyAssignment> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Arrange ***/
            var putResponseString = @"{
                                        ""type"": ""storage_policy_assignment"",
                                        ""id"": ""user_7777"",
                                        ""storage_policy"": {
                                            ""type"": ""storage_policy"",
                                            ""id"": ""1111"",
                                        },
                                        ""assigned_to"": {
                                            ""type"": ""user"",
                                            ""id"": ""7777"",
                                        }
                                    }";


            IBoxRequest putBoxRequest = null;

            Config.SetupGet(x => x.StoragePolicyAssignmentsUri).Returns(storagePolicyAssignmentsUri);
            Handler.Setup(h => h.ExecuteAsync <BoxStoragePolicyAssignment>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxStoragePolicyAssignment> >(new BoxResponse <BoxStoragePolicyAssignment>()
            {
                Status        = ResponseStatus.Success,
                ContentString = putResponseString
            }))
            .Callback <IBoxRequest>(r => putBoxRequest = r);

            /*** Act ***/
            var result = await _storagePoliciesManager.AssignAsync("1111", "7777");

            //Response check
            Assert.AreEqual("storage_policy_assignment", result.Type);
            Assert.AreEqual("user_7777", result.Id);
            Assert.AreEqual("storage_policy", result.BoxStoragePolicy.Type);
            Assert.AreEqual("1111", result.BoxStoragePolicy.Id);
            Assert.AreEqual("user", result.AssignedTo.Type);
            Assert.AreEqual("7777", result.AssignedTo.Id);
        }
        public async Task <IBoxResponse <T> > ExecuteAsync <T>(IBoxRequest request)
            where T : class
        {
            // Need to account for special cases when the return type is a stream
            var isStream     = typeof(T) == typeof(Stream);
            var retryCounter = 0;
            var expBackoff   = new ExponentialBackoff();

            try
            {
                // TODO: yhu@ better handling of different request
                var isMultiPartRequest = request.GetType() == typeof(BoxMultiPartRequest);
                var isBinaryRequest    = request.GetType() == typeof(BoxBinaryRequest);

                while (true)
                {
                    using (HttpRequestMessage httpRequest = GetHttpRequest(request, isMultiPartRequest, isBinaryRequest))
                    {
                        Debug.WriteLine(string.Format("RequestUri: {0}", httpRequest.RequestUri));
                        HttpResponseMessage response = await GetResponse(request, isStream, httpRequest).ConfigureAwait(false);

                        //need to wait for Retry-After seconds and then retry request
                        var retryAfterHeader = response.Headers.RetryAfter;

                        // If we get a retryable/transient error code and this is not a multi part request (meaning a file upload, which cannot be retried
                        // because the stream cannot be reset) and we haven't exceeded the number of allowed retries, then retry the request.
                        // If we get a 202 code and has a retry-after header, we will retry after
                        if (!isMultiPartRequest &&
                            (response.StatusCode == TooManyRequests
                             ||
                             response.StatusCode == HttpStatusCode.InternalServerError
                             ||
                             response.StatusCode == HttpStatusCode.BadGateway
                             ||
                             response.StatusCode == HttpStatusCode.ServiceUnavailable
                             ||
                             response.StatusCode == HttpStatusCode.GatewayTimeout
                             ||
                             (response.StatusCode == HttpStatusCode.Accepted && retryAfterHeader != null)) &&
                            retryCounter++ < RetryLimit)
                        {
                            TimeSpan delay = expBackoff.GetRetryTimeout(retryCounter);

                            Debug.WriteLine("HttpCode : {0}. Waiting for {1} seconds to retry request. RequestUri: {2}", response.StatusCode, delay.Seconds, httpRequest.RequestUri);

                            await Task.Delay(delay);
                        }
                        else
                        {
                            BoxResponse <T> boxResponse = await GetBoxResponse <T>(isStream, response).ConfigureAwait(false);

                            return(boxResponse);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
                throw;
            }
        }
Example #3
0
        public async Task Copy_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString = @"{
                                        ""type"": ""web_link"",
                                        ""id"": ""6743065"",
                                        ""sequence_id"": ""0"",
                                        ""etag"": ""0"",
                                        ""name"": ""Box Website!"",
                                        ""url"": ""https://www.box.com"",
                                        ""created_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""10523870"",
                                            ""name"": ""Ted Blosser"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""created_at"": ""2015-05-07T15:00:01-07:00"",
                                        ""modified_at"": ""2015-05-07T15:00:01-07:00"",
                                        ""parent"": {
                                            ""type"": ""folder"",
                                            ""id"": ""848123342"",
                                            ""sequence_id"": ""1"",
                                            ""etag"": ""1"",
                                            ""name"": ""Documentation""
                                        },
                                        ""description"": ""Cloud Content Management"",
                                        ""item_status"": ""active"",
                                        ""trashed_at"": null,
                                        ""purged_at"": null,
                                        ""shared_link"": null,
                                        ""path_collection"": {
                                            ""total_count"": 2,
                                            ""entries"": [
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""0"",
                                                    ""sequence_id"": null,
                                                    ""etag"": null,
                                                    ""name"": ""All Files""
                                                },
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""848123342"",
                                                    ""sequence_id"": ""1"",
                                                    ""etag"": ""1"",
                                                    ""name"": ""Documentation""
                                                }
                                            ]
                                        },
                                        ""modified_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""10523870"",
                                            ""name"": ""Ted Blosser"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""owned_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""10523870"",
                                            ""name"": ""Ted Blosser"",
                                            ""login"": ""*****@*****.**""
                                        }
                                    }";
            IBoxRequest boxRequest     = null;
            var         webLinksUri    = new Uri(Constants.WebLinksEndpointString);

            Config.SetupGet(x => x.WebLinksEndpointUri).Returns(webLinksUri);
            Handler.Setup(h => h.ExecuteAsync <BoxWebLink>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxWebLink> >(new BoxResponse <BoxWebLink>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            var webLinkId           = "11111";
            var destinationFolderId = "22222";

            /*** Act ***/
            BoxWebLink result = await _webLinkManager.CopyAsync(webLinkId, destinationFolderId);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(new Uri("https://api.box.com/2.0/web_links/11111/copy"), boxRequest.AbsoluteUri);
            Assert.AreEqual("{\"parent\":{\"id\":\"22222\"}}", boxRequest.Payload);

            //Response check
            Assert.AreEqual("web_link", result.Type);
            Assert.AreEqual("6743065", result.Id);
            Assert.AreEqual(new Uri("https://www.box.com"), result.Url);
            Assert.AreEqual("Cloud Content Management", result.Description);
            Assert.AreEqual("0", result.PathCollection.Entries[0].Id);
            Assert.AreEqual("All Files", result.PathCollection.Entries[0].Name);
            Assert.AreEqual("848123342", result.PathCollection.Entries[1].Id);
            Assert.AreEqual("Documentation", result.PathCollection.Entries[1].Name);
        }
        public async Task GetAllFileMetadataTemplates_ValidResponse_ValidEntries()
        {
            /*** Arrange ***/
            string responseString = @"{
                                        ""entries"": [
                                            {
                                                ""currentDocumentStage"": ""Init"",
                                                ""$type"": ""documentFlow-452b4c9d-c3ad-4ac7-b1ad-9d5192f2fc5f"",
                                                ""$parent"": ""file_5010739061"",
                                                ""$id"": ""50ba0dba-0f89-4395-b867-3e057c1f6ed9"",
                                                ""$version"": 4,
                                                ""$typeVersion"": 2,
                                                ""needsApprovalFrom"": ""Smith"",
                                                ""$template"": ""documentFlow"",
                                                ""$scope"": ""enterprise_12345""
                                            },
                                            {
                                                ""$type"": ""productInfo-9d7b6993-b09e-4e52-b197-e42f0ea995b9"",
                                                ""$parent"": ""file_5010739061"",
                                                ""$id"": ""15d1014a-06c2-47ad-9916-014eab456194"",
                                                ""$version"": 2,
                                                ""$typeVersion"": 1,
                                                ""skuNumber"": 45334223,
                                                ""description"": ""Watch"",
                                                ""$template"": ""productInfo"",
                                                ""$scope"": ""enterprise_12345""
                                            },
                                            {
                                                ""Popularity"": ""25"",
                                                ""$type"": ""properties"",
                                                ""$parent"": ""file_5010739061"",
                                                ""$id"": ""b6f36cbc-fc7a-4eda-8889-130f350cc057"",
                                                ""$version"": 0,
                                                ""$typeVersion"": 2,
                                                ""$template"": ""properties"",
                                                ""$scope"": ""global""
                                            },

                                        ],
                                        ""limit"": 100
                                    }";

            IBoxRequest boxRequest = null;

            Handler.Setup(h => h.ExecuteAsync <BoxMetadataTemplateCollection <Dictionary <string, object> > >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxMetadataTemplateCollection <Dictionary <string, object> > > >(new BoxResponse <BoxMetadataTemplateCollection <Dictionary <string, object> > >()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            })).Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            BoxMetadataTemplateCollection <Dictionary <string, object> > result = await _metadataManager.GetAllFileMetadataTemplatesAsync("5010739061");

            /*** Request ***/
            Assert.AreEqual(string.Format("{0}/metadata", "5010739061"), boxRequest.Path);
            /*** Response ***/
            Assert.AreEqual("Init", result.Entries[0]["currentDocumentStage"]);
            Assert.AreEqual("50ba0dba-0f89-4395-b867-3e057c1f6ed9", result.Entries[0]["$id"]);
            Assert.AreEqual("file_5010739061", result.Entries[1]["$parent"]);
            Assert.AreEqual((long)2, result.Entries[1]["$version"]);
            Assert.AreEqual("25", result.Entries[2]["Popularity"]);
            Assert.AreEqual((long)2, result.Entries[2]["$typeVersion"]);
        }
        public async Task ExecuteMetadataQuery_ValidResponse()
        {
            /*** Arrange ***/
            string      responseString = "{\"entries\":[{\"item\":{\"type\":\"file\",\"id\":\"1617554169109\",\"file_version\":{\"type\":\"file_version\",\"id\":\"1451884469385\",\"sha1\":\"69888bb1bff455d1b2f8afea75ed1ff0b4879bf6\"},\"sequence_id\":\"0\",\"etag\":\"0\",\"sha1\":\"69888bb1bff455d1b2f8afea75ed1ff0b4879bf6\",\"name\":\"My Contract.docx\",\"description\":\"\",\"size\":25600,\"path_collection\":{\"total_count\":4,\"entries\":[{\"type\":\"folder\",\"id\":\"0\",\"sequence_id\":null,\"etag\":null,\"name\":\"All Files\"},{\"type\":\"folder\",\"id\":\"15017998644\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"Contracts\"},{\"type\":\"folder\",\"id\":\"15286891196\",\"sequence_id\":\"1\",\"etag\":\"1\",\"name\":\"North America\"},{\"type\":\"folder\",\"id\":\"16125613433\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"2017\"}]},\"created_at\":\"2017-04-20T12:55:27-07:00\",\"modified_at\":\"2017-04-20T12:55:27-07:00\",\"trashed_at\":null,\"purged_at\":null,\"content_created_at\":\"2017-01-06T17:59:01-08:00\",\"content_modified_at\":\"2017-01-06T17:59:01-08:00\",\"created_by\":{\"type\":\"user\",\"id\":\"193973366\",\"name\":\"Box Admin\",\"login\":\"[email protected]\"},\"modified_by\":{\"type\":\"user\",\"id\":\"193973366\",\"name\":\"Box Admin\",\"login\":\"[email protected]\"},\"owned_by\":{\"type\":\"user\",\"id\":\"193973366\",\"name\":\"Box Admin\",\"login\":\"[email protected]\"},\"shared_link\":null,\"parent\":{\"type\":\"folder\",\"id\":\"16125613433\",\"sequence_id\":\"0\",\"etag\":\"0\",\"name\":\"2017\"},\"item_status\":\"active\"},\"metadata\":{\"enterprise_123456\":{\"someTemplate\":{\"$parent\":\"file_161753469109\",\"$version\":0,\"customerName\":\"Phoenix Corp\",\"$type\":\"someTemplate-3d5fcaca-f496-4bb6-9046-d25c37bc5594\",\"$typeVersion\":0,\"$id\":\"ba52e2cc-371d-4659-8d53-50f1ac642e35\",\"amount\":100,\"claimDate\":\"2016-04-10T00:00:00Z\",\"region\":\"West\",\"$typeScope\":\"enterprise_123456\"}}}}],\"next_marker\":\"AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff\"}";
            IBoxRequest boxRequest     = null;

            Handler.Setup(h => h.ExecuteAsync <BoxCollectionMarkerBased <BoxMetadataQueryItem> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxCollectionMarkerBased <BoxMetadataQueryItem> > >(new BoxResponse <BoxCollectionMarkerBased <BoxMetadataQueryItem> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var queryParams = new Dictionary <string, object>();

            queryParams.Add("arg", 100);
            List <BoxMetadataQueryOrderBy> orderByList = new List <BoxMetadataQueryOrderBy>();
            var orderBy = new BoxMetadataQueryOrderBy()
            {
                FieldKey  = "amount",
                Direction = BoxSortDirection.ASC
            };

            orderByList.Add(orderBy);
            string marker = "q3f87oqf3qygou5t478g9gwrbul";
            BoxCollectionMarkerBased <BoxMetadataQueryItem> items = await _metadataManager.ExecuteMetadataQueryAsync(from : "enterprise_123456.someTemplate", query : "amount >= :arg", queryParameters : queryParams, ancestorFolderId : "5555", indexName : "amountAsc", orderBy : orderByList, marker : marker, autoPaginate : false);

            /*** Assert ***/

            // Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(MetadataQueryUri, boxRequest.AbsoluteUri.AbsoluteUri);
            JObject payload = JObject.Parse(boxRequest.Payload);

            Assert.AreEqual("enterprise_123456.someTemplate", payload["from"]);
            Assert.AreEqual("amount >= :arg", payload["query"]);
            Assert.AreEqual(100, payload["query_params"]["arg"]);
            Assert.AreEqual("5555", payload["ancestor_folder_id"]);
            Assert.AreEqual("amountAsc", payload["use_index"]);
            JArray payloadOrderBy = JArray.Parse(payload["order_by"].ToString());

            Assert.AreEqual("amount", payloadOrderBy[0]["field_key"]);
            Assert.AreEqual("ASC", payloadOrderBy[0]["direction"]);
            Assert.AreEqual(marker, payload["marker"]);

            // Response check
            Assert.AreEqual(items.Entries[0].Item.Type, "file");
            Assert.AreEqual(items.Entries[0].Item.Id, "1617554169109");
            Assert.AreEqual(items.Entries[0].Item.Name, "My Contract.docx");
            Assert.AreEqual(items.Entries[0].Item.SequenceId, "0");
            Assert.AreEqual(items.Entries[0].Item.CreatedBy.Type, "user");
            Assert.AreEqual(items.Entries[0].Item.CreatedBy.Login, "*****@*****.**");
            Assert.AreEqual(items.Entries[0].Item.Parent.Id, "16125613433");
            Assert.AreEqual(items.NextMarker, "AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff");
            var metadata = JObject.FromObject(items.Entries[0].Metadata["enterprise_123456"]);

            Assert.AreEqual(metadata["someTemplate"]["$parent"], "file_161753469109");
            Assert.AreEqual(metadata["someTemplate"]["customerName"], "Phoenix Corp");
            Assert.AreEqual(metadata["someTemplate"]["$typeVersion"], 0);
            Assert.AreEqual(metadata["someTemplate"]["region"], "West");
        }
Example #6
0
        public async Task CreateOrDeleteCollectionsForFolder_ValidResponse()
        {
            /*** Arrange ***/
            string      responseString = @"{
                                            ""type"": ""folder"",
                                            ""id"": ""11446498"",
                                            ""sequence_id"": ""1"",
                                            ""etag"": ""1"",
                                            ""name"": ""New Folder Name!"",
                                            ""created_at"": ""2012-12-12T10:53:43-08:00"",
                                            ""modified_at"": ""2012-12-12T11:15:04-08:00"",
                                            ""description"": ""Some pictures I took"",
                                            ""size"": 629644,
                                            ""path_collection"": {
                                                ""total_count"": 1,
                                                ""entries"": [
                                                    {
                                                        ""type"": ""folder"",
                                                        ""id"": ""0"",
                                                        ""sequence_id"": null,
                                                        ""etag"": null,
                                                        ""name"": ""All Files""
                                                    }
                                                ]
                                            },
                                            ""created_by"": {
                                                ""type"": ""user"",
                                                ""id"": ""17738362"",
                                                ""name"": ""sean rose"",
                                                ""login"": ""*****@*****.**""
                                            },
                                            ""modified_by"": {
                                                ""type"": ""user"",
                                                ""id"": ""17738362"",
                                                ""name"": ""sean rose"",
                                                ""login"": ""*****@*****.**""
                                            },
                                            ""owned_by"": {
                                                ""type"": ""user"",
                                                ""id"": ""17738362"",
                                                ""name"": ""sean rose"",
                                                ""login"": ""*****@*****.**""
                                            },
                                            ""shared_link"": {
                                                ""url"": ""https://www.box.com/s/vspke7y05sb214wjokpk"",
                                                ""download_url"": null,
                                                ""vanity_url"": null,
                                                ""is_password_enabled"": false,
                                                ""unshared_at"": null,
                                                ""download_count"": 0,
                                                ""preview_count"": 0,
                                                ""access"": ""open"",
                                                ""permissions"": {
                                                    ""can_download"": true,
                                                    ""can_preview"": true
                                                }
                                            },
                                            ""folder_upload_email"": {
                                                ""access"": ""open"",
                                                ""email"": ""*****@*****.**""
                                            },
                                            ""parent"": {
                                                ""type"": ""folder"",
                                                ""id"": ""0"",
                                                ""sequence_id"": null,
                                                ""etag"": null,
                                                ""name"": ""All Files""
                                            },
                                            ""item_status"": ""active"",
                                            ""item_collection"": {
                                                ""total_count"": 1,
                                                ""entries"": [
                                                    {
                                                        ""type"": ""file"",
                                                        ""id"": ""5000948880"",
                                                        ""sequence_id"": ""3"",
                                                        ""etag"": ""3"",
                                                        ""sha1"": ""134b65991ed521fcfe4724b7d814ab8ded5185dc"",
                                                        ""name"": ""tigers.jpeg""
                                                    }
                                                ],
                                                ""offset"": 0,
                                                ""limit"": 100
                                            }
                                        }";
            IBoxRequest boxRequest     = null;

            _handler.Setup(h => h.ExecuteAsync <BoxFolder>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxFolder> >(new BoxResponse <BoxFolder>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            BoxCollectionsRequest collectionsRequest = new BoxCollectionsRequest()
            {
                Collections = new List <BoxRequestEntity>()
                {
                    new BoxRequestEntity()
                    {
                        Id = "123"
                    }
                }
            };
            BoxFolder result = await _collectionsManager.CreateOrDeleteCollectionsForFolderAsync("11446498", collectionsRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Put, boxRequest.Method);
            Assert.AreEqual(_FoldersUri + "11446498", boxRequest.AbsoluteUri.AbsoluteUri);
            BoxCollectionsRequest payload = JsonConvert.DeserializeObject <BoxCollectionsRequest>(boxRequest.Payload);

            Assert.AreEqual(collectionsRequest.Collections[0].Id, payload.Collections[0].Id);

            //Response check
            Assert.AreEqual("11446498", result.Id);
            Assert.AreEqual(1, result.PathCollection.TotalCount);
            Assert.AreEqual("https://www.box.com/s/vspke7y05sb214wjokpk", result.SharedLink.Url);
            Assert.AreEqual("17738362", result.CreatedBy.Id);
        }
        public async Task CreateTermsOfServiceUserStatus_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString = @"{
                                        ""type"": ""terms_of_service_user_status"",
                                        ""id"": ""11446498"",
                                        ""created_at"": ""2012-12-12T10:53:43-08:00"",
                                        ""is_accepted"": ""true"",
                                        ""modified_at"": ""2012-12-12T10:53:43-08:00"",
                                        ""tos"": {
                                            ""type"": ""terms_of_service"",
                                            ""id"": ""11446498"",
                                        },
                                        ""user"": {
                                            ""type"": ""user"",
                                            ""id"": ""24446498"",
                                            ""name"": ""Aaron Levie"",
                                            ""login"": ""*****@*****.**""
                                        },
                                    }";
            IBoxRequest boxRequest     = null;
            var         tosUri         = new Uri(Constants.BoxApiUriString + Constants.TermsOfServiceUserStatusesString);

            Config.SetupGet(x => x.TermsOfServiceUserStatusesUri).Returns(tosUri);
            Handler.Setup(h => h.ExecuteAsync <BoxTermsOfServiceUserStatuses>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxTermsOfServiceUserStatuses> >(new BoxResponse <BoxTermsOfServiceUserStatuses>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var createStatusRequest = new BoxTermsOfServiceUserStatusCreateRequest()
            {
                TermsOfService = new BoxRequestEntity()
                {
                    Id   = "11446498",
                    Type = BoxType.terms_of_service
                },
                User = new BoxRequestEntity()
                {
                    Id   = "24446498",
                    Type = BoxType.user
                },
                IsAccepted = true
            };
            BoxTermsOfServiceUserStatuses result =
                await _termsOfServiceManager.CreateBoxTermsOfServiceUserStatusesAsync(createStatusRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(tosUri, boxRequest.AbsoluteUri.AbsoluteUri);
            BoxTermsOfServiceUserStatusCreateRequest payload = JsonConvert.DeserializeObject <BoxTermsOfServiceUserStatusCreateRequest>(boxRequest.Payload);

            Assert.AreEqual(createStatusRequest.TermsOfService.Id, payload.TermsOfService.Id);
            Assert.AreEqual(createStatusRequest.TermsOfService.Type, payload.TermsOfService.Type);
            Assert.AreEqual(createStatusRequest.User.Id, payload.User.Id);
            Assert.AreEqual(createStatusRequest.User.Type, payload.User.Type);
            Assert.AreEqual(createStatusRequest.IsAccepted, payload.IsAccepted);

            //Response check
            Assert.AreEqual("11446498", result.Id);
            Assert.AreEqual("terms_of_service_user_status", result.Type);
            Assert.AreEqual(true, result.IsAccepted);
            Assert.AreEqual("11446498", result.TermsOfService.Id);
            Assert.AreEqual("24446498", result.User.Id);
            Assert.AreEqual("Aaron Levie", result.User.Name);
        }
Example #8
0
        public async Task GetLegalHoldPolicy_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString        = @"{
                                          ""type"": ""legal_hold_policy"",
                                          ""id"": ""166757"",
                                          ""policy_name"": ""Policy 4"",
                                          ""description"": ""Postman created policy"",
                                          ""status"": ""active"",
                                          ""assignment_counts"": {
                                            ""user"": 1,
                                            ""folder"": 0,
                                            ""file"": 0,
                                            ""file_version"": 0
                                          },
                                          ""created_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""2030388321"",
                                            ""name"": ""Steve Boxuser"",
                                            ""login"": ""*****@*****.**""
                                          },
                                          ""created_at"": ""2016-05-18T10:28:45-07:00"",
                                          ""modified_at"": ""2016-05-18T11:25:59-07:00"",
                                          ""deleted_at"": null,
                                          ""filter_started_at"": ""2016-05-17T01:00:00-07:00"",
                                          ""filter_ended_at"": ""2016-05-21T01:00:00-07:00""
                                        }";
            IBoxRequest boxRequest            = null;
            var         legalHoldsPoliciesUri = new Uri(Constants.LegalHoldPoliciesEndpointString);

            Config.SetupGet(x => x.LegalHoldPoliciesEndpointUri).Returns(legalHoldsPoliciesUri);
            Handler.Setup(h => h.ExecuteAsync <BoxLegalHoldPolicy>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxLegalHoldPolicy> >(new BoxResponse <BoxLegalHoldPolicy>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            BoxLegalHoldPolicy result = await _legalHoldPoliciesManager.GetLegalHoldPolicyAsync("166757");

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Get, boxRequest.Method);
            Assert.AreEqual(legalHoldsPoliciesUri + "166757", boxRequest.AbsoluteUri.AbsoluteUri);

            //Response check
            Assert.AreEqual("legal_hold_policy", result.Type);
            Assert.AreEqual("166757", result.Id);
            Assert.AreEqual("Policy 4", result.PolicyName);
            Assert.AreEqual("Postman created policy", result.Description);
            Assert.AreEqual("active", result.Status);
            Assert.AreEqual(1, result.AssignmentCounts.User);
            Assert.AreEqual(0, result.AssignmentCounts.Folder);
            Assert.AreEqual(0, result.AssignmentCounts.File);
            Assert.AreEqual(0, result.AssignmentCounts.Version);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-18T10:28:45-07:00"), result.CreatedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-18T11:25:59-07:00"), result.ModifiedAt);
            Assert.IsNull(result.DeletedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-17T01:00:00-07:00"), result.FilterStartedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-21T01:00:00-07:00"), result.FilterEndedAt);
        }
Example #9
0
        public async Task CreateNewAssignment_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString = @"{
                                          ""type"": ""legal_hold_policy_assignment"",
                                          ""id"": ""255613"",
                                          ""legal_hold_policy"": {
                                            ""type"": ""legal_hold_policy"",
                                            ""id"": ""166757"",
                                            ""policy_name"": ""Bug Bash 5-12 Policy 3 updated""
                                          },
                                          ""assigned_to"": {
                                            ""type"": ""file"",
                                            ""id"": ""5025127885""
                                          },
                                          ""assigned_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""2030388321"",
                                            ""name"": ""Steve Boxuser"",
                                            ""login"": ""*****@*****.**""
                                          },
                                          ""assigned_at"": ""2016-05-18T17:38:03-07:00"",
                                          ""deleted_at"": null
                                        }";
            IBoxRequest boxRequest     = null;
            var         legalHoldPolicyAssignmentUri = new Uri(Constants.LegalHoldPolicyAssignmentsEndpointString);

            Config.SetupGet(x => x.LegalHoldPolicyAssignmentsEndpointUri).Returns(legalHoldPolicyAssignmentUri);
            Handler.Setup(h => h.ExecuteAsync <BoxLegalHoldPolicyAssignment>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxLegalHoldPolicyAssignment> >(new BoxResponse <BoxLegalHoldPolicyAssignment>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var createRequest = new BoxLegalHoldPolicyAssignmentRequest()
            {
                PolicyId = "166757",
                AssignTo = new BoxRequestEntity()
                {
                    Id   = "5025127885",
                    Type = BoxType.file
                }
            };
            BoxLegalHoldPolicyAssignment result = await _legalHoldPoliciesManager.CreateAssignmentAsync(createRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(legalHoldPolicyAssignmentUri, boxRequest.AbsoluteUri.AbsoluteUri);
            BoxLegalHoldPolicyAssignmentRequest payLoad = JsonConvert.DeserializeObject <BoxLegalHoldPolicyAssignmentRequest>(boxRequest.Payload);

            Assert.AreEqual("166757", payLoad.PolicyId);
            Assert.AreEqual("5025127885", payLoad.AssignTo.Id);
            Assert.AreEqual(BoxType.file, payLoad.AssignTo.Type);

            //Response check
            Assert.AreEqual("legal_hold_policy_assignment", result.Type);
            Assert.AreEqual("255613", result.Id);
            Assert.AreEqual("legal_hold_policy", result.LegalHoldPolicy.Type);
            Assert.AreEqual("166757", result.LegalHoldPolicy.Id);
            Assert.AreEqual("Bug Bash 5-12 Policy 3 updated", result.LegalHoldPolicy.PolicyName);
            Assert.AreEqual("file", result.AssignedTo.Type);
            Assert.AreEqual("5025127885", result.AssignedTo.Id);
            Assert.AreEqual("user", result.AssignedBy.Type);
            Assert.AreEqual("2030388321", result.AssignedBy.Id);
            Assert.AreEqual("Steve Boxuser", result.AssignedBy.Name);
            Assert.AreEqual("*****@*****.**", result.AssignedBy.Login);
            Assert.IsNull(result.DeletedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-18T17:38:03-07:00"), result.AssignedAt);
        }
Example #10
0
        public async Task CreateOrDeleteCollectionsForFile_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString = @"{
                                        ""type"": ""file"",
                                        ""id"": ""5000948880"",
                                        ""file_version"": {
                                            ""type"": ""file_version"",
                                            ""id"": ""26261748416"",
                                            ""sha1"": ""134b65991ed521fcfe4724b7d814ab8ded5185dc""
                                        },
                                        ""sequence_id"": ""3"",
                                        ""etag"": ""3"",
                                        ""sha1"": ""134b65991ed521fcfe4724b7d814ab8ded5185dc"",
                                        ""name"": ""tigers.jpeg"",
                                        ""description"": ""a picture of tigers"",
                                        ""size"": 629644,
                                        ""path_collection"": {
                                            ""total_count"": 2,
                                            ""entries"": [
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""0"",
                                                    ""sequence_id"": null,
                                                    ""etag"": null,
                                                    ""name"": ""All Files""
                                                },
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""11446498"",
                                                    ""sequence_id"": ""1"",
                                                    ""etag"": ""1"",
                                                    ""name"": ""Pictures""
                                                }
                                            ]
                                        },
                                        ""created_at"": ""2012-12-12T10:55:30-08:00"",
                                        ""modified_at"": ""2012-12-12T11:04:26-08:00"",
                                        ""created_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""17738362"",
                                            ""name"": ""sean rose"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""modified_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""17738362"",
                                            ""name"": ""sean rose"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""owned_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""17738362"",
                                            ""name"": ""sean rose"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""shared_link"": {
                                            ""url"": ""https://www.box.com/s/rh935iit6ewrmw0unyul"",
                                            ""download_url"": ""https://www.box.com/shared/static/rh935iit6ewrmw0unyul.jpeg"",
                                            ""vanity_url"": null,
                                            ""is_password_enabled"": false,
                                            ""unshared_at"": null,
                                            ""download_count"": 0,
                                            ""preview_count"": 0,
                                            ""access"": ""open"",
                                            ""permissions"": {
                                                ""can_download"": true,
                                                ""can_preview"": true
                                            }
                                        },
                                        ""parent"": {
                                            ""type"": ""folder"",
                                            ""id"": ""11446498"",
                                            ""sequence_id"": ""1"",
                                            ""etag"": ""1"",
                                            ""name"": ""Pictures""
                                        },
                                        ""item_status"": ""active""
                                    }";
            IBoxRequest boxRequest     = null;

            Handler.Setup(h => h.ExecuteAsync <BoxFile>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxFile> >(new BoxResponse <BoxFile>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var collectionsRequest = new BoxCollectionsRequest()
            {
                Collections = new List <BoxRequestEntity>()
                {
                    new BoxRequestEntity()
                    {
                        Id = "123"
                    }
                }
            };
            BoxFile result = await _collectionsManager.CreateOrDeleteCollectionsForFileAsync("5000948880", collectionsRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Put, boxRequest.Method);
            Assert.AreEqual(FilesUri + "5000948880", boxRequest.AbsoluteUri.AbsoluteUri);
            BoxCollectionsRequest payload = JsonConvert.DeserializeObject <BoxCollectionsRequest>(boxRequest.Payload);

            Assert.AreEqual(collectionsRequest.Collections[0].Id, payload.Collections[0].Id);

            //Response check
            Assert.AreEqual("5000948880", result.Id);
            Assert.AreEqual(2, result.PathCollection.TotalCount);
            Assert.AreEqual("https://www.box.com/s/rh935iit6ewrmw0unyul", result.SharedLink.Url);
            Assert.AreEqual("17738362", result.CreatedBy.Id);
        }
Example #11
0
        public async Task UpdateLegalHoldPolicy_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString        = @"{
                                          ""type"": ""legal_hold_policy"",
                                          ""id"": ""166921"",
                                          ""policy_name"": ""New Policy 3"",
                                          ""description"": ""Policy 3 New Description"",
                                          ""created_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""2030388321"",
                                            ""name"": ""Ryan Churchill"",
                                            ""login"": ""*****@*****.**""
                                          },
                                          ""created_at"": ""2016-05-18T16:18:49-07:00"",
                                          ""modified_at"": ""2016-05-18T16:20:47-07:00"",
                                          ""deleted_at"": null,
                                          ""filter_started_at"": ""2016-05-11T01:00:00-07:00"",
                                          ""filter_ended_at"": ""2016-05-13T01:00:00-07:00""
                                        }";
            IBoxRequest boxRequest            = null;
            var         legalHoldsPoliciesUri = new Uri(Constants.LegalHoldPoliciesEndpointString);

            Config.SetupGet(x => x.LegalHoldPoliciesEndpointUri).Returns(legalHoldsPoliciesUri);
            Handler.Setup(h => h.ExecuteAsync <BoxLegalHoldPolicy>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxLegalHoldPolicy> >(new BoxResponse <BoxLegalHoldPolicy>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var updateRequest = new BoxLegalHoldPolicyRequest()
            {
                PolicyName  = "New Policy 3",
                Description = "Policy 3 New Description"
            };
            BoxLegalHoldPolicy result = await _legalHoldPoliciesManager.UpdateLegalHoldPolicyAsync("166921", updateRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Put, boxRequest.Method);
            Assert.AreEqual(legalHoldsPoliciesUri + "166921", boxRequest.AbsoluteUri.AbsoluteUri);
            BoxLegalHoldPolicyRequest payLoad = JsonConvert.DeserializeObject <BoxLegalHoldPolicyRequest>(boxRequest.Payload);

            Assert.AreEqual("New Policy 3", payLoad.PolicyName);
            Assert.AreEqual("Policy 3 New Description", payLoad.Description);

            //Response check
            Assert.AreEqual("legal_hold_policy", result.Type);
            Assert.AreEqual("166921", result.Id);
            Assert.AreEqual("New Policy 3", result.PolicyName);
            Assert.AreEqual("Policy 3 New Description", result.Description);
            Assert.IsNull(result.Status);
            Assert.AreEqual("2030388321", result.CreatedBy.Id);
            Assert.AreEqual("Ryan Churchill", result.CreatedBy.Name);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-18T16:18:49-07:00"), result.CreatedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-18T16:20:47-07:00"), result.ModifiedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-11T01:00:00-07:00"), result.FilterStartedAt);
            Assert.AreEqual(DateTimeOffset.Parse("2016-05-13T01:00:00-07:00"), result.FilterEndedAt);
        }
Example #12
0
        public async Task <IBoxResponse <T> > ExecuteAsync <T>(IBoxRequest request)
            where T : class
        {
            // Need to account for special cases when the return type is a stream
            bool isStream   = typeof(T) == typeof(Stream);
            var  numRetries = 3;

            try
            {
                while (true)
                {
                    HttpRequestMessage httpRequest = request.GetType() == typeof(BoxMultiPartRequest) ?
                                                     BuildMultiPartRequest(request as BoxMultiPartRequest) :
                                                     BuildRequest(request);

                    // Add headers
                    foreach (var kvp in request.HttpHeaders)
                    {
                        if (kvp.Key == Constants.RequestParameters.ContentMD5)
                        {
                            httpRequest.Content.Headers.Add(kvp.Key, kvp.Value);
                        }
                        else
                        {
                            httpRequest.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value);
                        }
                    }

                    // If we are retrieving a stream, we should return without reading the entire response
                    HttpCompletionOption completionOption = isStream ?
                                                            HttpCompletionOption.ResponseHeadersRead :
                                                            HttpCompletionOption.ResponseContentRead;

                    Debug.WriteLine(string.Format("RequestUri: {0}", httpRequest.RequestUri));//, RequestHeader: {1} , httpRequest.Headers.Select(i => string.Format("{0}:{1}", i.Key, i.Value)).Aggregate((i, j) => i + "," + j)));

                    HttpClient      client      = CreateClient(request);
                    BoxResponse <T> boxResponse = new BoxResponse <T>();

                    HttpResponseMessage response = await client.SendAsync(httpRequest, completionOption).ConfigureAwait(false);

                    if (response.StatusCode == TooManyRequests && numRetries-- > 0)
                    {
                        //need to wait for Retry-After seconds and then retry request
                        var retryAfterHeader = response.Headers.RetryAfter;

                        TimeSpan delay;
                        if (retryAfterHeader.Delta.HasValue)
                        {
                            delay = retryAfterHeader.Delta.Value;
                        }
                        else
                        {
                            delay = TimeSpan.FromMilliseconds(2000);
                        }

                        Debug.WriteLine("TooManyRequests error (429). Waiting for {0} seconds to retry request. RequestUri: {1}", delay.Seconds, httpRequest.RequestUri);

                        await CrossPlatform.Delay(Convert.ToInt32(delay.TotalMilliseconds));
                    }
                    else
                    {
                        boxResponse.Headers = response.Headers;

                        // Translate the status codes that interest us
                        boxResponse.StatusCode = response.StatusCode;
                        switch (response.StatusCode)
                        {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Created:
                        case HttpStatusCode.NoContent:
                        case HttpStatusCode.Found:
                            boxResponse.Status = ResponseStatus.Success;
                            break;

                        case HttpStatusCode.Accepted:
                            boxResponse.Status = ResponseStatus.Pending;
                            break;

                        case HttpStatusCode.Unauthorized:
                            boxResponse.Status = ResponseStatus.Unauthorized;
                            break;

                        case HttpStatusCode.Forbidden:
                            boxResponse.Status = ResponseStatus.Forbidden;
                            break;

                        case TooManyRequests:
                            boxResponse.Status = ResponseStatus.TooManyRequests;
                            break;

                        default:
                            boxResponse.Status = ResponseStatus.Error;
                            break;
                        }

                        if (isStream && boxResponse.Status == ResponseStatus.Success)
                        {
                            var resObj = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            boxResponse.ResponseObject = resObj as T;
                        }
                        else
                        {
                            boxResponse.ContentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }

                        return(boxResponse);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
                throw;
            }
        }
Example #13
0
        public async Task CreateSignRequest_OptionalParams_Success()
        {
            /*** Arrange ***/
            IBoxRequest boxRequest = null;

            Handler.Setup(h => h.ExecuteAsync <BoxSignRequest>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxSignRequest> >(new BoxResponse <BoxSignRequest>()
            {
                Status        = ResponseStatus.Success,
                ContentString = LoadFixtureFromJson("Fixtures/BoxSignRequest/CreateSignRequest200.json")
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);;

            var sourceFiles = new List <BoxSignRequestCreateSourceFile>
            {
                new BoxSignRequestCreateSourceFile()
                {
                    Id = "12345"
                }
            };

            var signers = new List <BoxSignRequestSignerCreate>
            {
                new BoxSignRequestSignerCreate()
                {
                    Email = "*****@*****.**"
                }
            };

            var parentFolder = new BoxRequestEntity()
            {
                Id   = "12345",
                Type = BoxType.folder
            };

            var request = new BoxSignRequestCreateRequest
            {
                IsDocumentPreparationNeeded = true,
                AreRemindersEnabled         = true,
                AreTextSignaturesEnabled    = true,
                DaysValid    = 2,
                EmailMessage = "Hello! Please sign the document below",
                EmailSubject = "Sign Request from Acme",
                ExternalId   = "123",
                SourceFiles  = sourceFiles,
                Signers      = signers,
                ParentFolder = parentFolder,
                PrefillTags  = new List <BoxSignRequestPrefillTag>
                {
                    new BoxSignRequestPrefillTag
                    (
                        "1234",
                        "text"
                    )
                }
            };

            /*** Act ***/
            var response = await _signRequestsManager.CreateSignRequestAsync(request);

            /*** Assert ***/
            // Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(new Uri("https://api.box.com/2.0/sign_requests"), boxRequest.AbsoluteUri);

            // Response check
            Assert.AreEqual(1, response.SourceFiles.Count);
            Assert.AreEqual("12345", response.SourceFiles[0].Id);
            Assert.AreEqual(1, response.Signers.Count);
            Assert.AreEqual("*****@*****.**", response.Signers[0].Email);
            Assert.AreEqual("12345", response.ParentFolder.Id);
            Assert.IsTrue(response.IsDocumentPreparationNeeded);
            Assert.IsTrue(response.AreRemindersEnabled);
            Assert.IsTrue(response.AreTextSignaturesEnabled);
            Assert.AreEqual(2, response.DaysValid);
            Assert.AreEqual("Hello! Please sign the document below", response.EmailMessage);
            Assert.AreEqual("Sign Request from Acme", response.EmailSubject);
            Assert.AreEqual("123", response.ExternalId);
            Assert.AreEqual(1, response.PrefillTags.Count);
            Assert.AreEqual("1234", response.PrefillTags[0].DocumentTagId);
            Assert.AreEqual("text", response.PrefillTags[0].TextValue);
            Assert.AreEqual(DateTimeOffset.Parse("2021-04-26T08:12:13.982Z"), response.PrefillTags[0].DateValue);
        }
Example #14
0
 /// <summary>
 /// Executes the request according to the default TaskScheduler
 /// This will allow for concurrent requests and is managed by the thread pool
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="request"></param>
 /// <returns></returns>
 public async Task <IBoxResponse <T> > ToResponseAsync <T>(IBoxRequest request)
     where T : class
 {
     return(await _handler.ExecuteAsync <T>(request).ConfigureAwait(false));
 }
        public async Task CreateEnterpriseUser_ValidReponse()
        {
            /*** Arrange ***/
            string      responseString = "{\"type\": \"user\", \"id\": \"187273718\", \"name\": \"Ned Stark\",  \"login\": \"[email protected]\",  \"created_at\": \"2012-11-15T16:34:28-08:00\", \"modified_at\": \"2012-11-15T16:34:29-08:00\", \"role\": \"user\", \"language\": \"en\", \"space_amount\": 5368709120, \"space_used\": 0, \"max_upload_size\": 2147483648, \"tracking_codes\": [], \"can_see_managed_users\": true, \"is_sync_enabled\": true, \"status\": \"active\", \"job_title\": \"\", \"phone\": \"555-555-5555\", \"address\": \"555 Box Lane\", \"avatar_url\": \"https://www.box.com/api/avatar/large/187273718\", \"is_exempt_from_device_limits\": false,\"is_exempt_from_login_verification\": false }";
            IBoxRequest boxRequest     = null;

            Handler.Setup(h => h.ExecuteAsync <BoxUser>(It.IsAny <IBoxRequest>()))
            .Returns(() => Task.FromResult <IBoxResponse <BoxUser> >(new BoxResponse <BoxUser>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            BoxUserRequest userRequest = new BoxUserRequest()
            {
                Login         = "******",
                Name          = "Ned Stark",
                Role          = "user",
                Language      = "en",
                IsSyncEnabled = true,
                Phone         = "555-555-5555",
                Address       = "555 Box Lane",
            };

            /*** Act ***/
            BoxUser result = await _usersManager.CreateEnterpriseUserAsync(userRequest);

            /*** Assert ***/

            // Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(UserUri, boxRequest.AbsoluteUri.AbsoluteUri);
            Assert.IsNotNull(boxRequest.Payload);
            BoxUserRequest payload = JsonConvert.DeserializeObject <BoxUserRequest>(boxRequest.Payload);

            Assert.AreEqual(userRequest.Login, payload.Login);
            Assert.AreEqual(userRequest.Name, payload.Name);
            Assert.AreEqual(userRequest.IsSyncEnabled, payload.IsSyncEnabled);
            Assert.AreEqual(userRequest.Phone, payload.Phone);
            Assert.AreEqual(userRequest.Address, payload.Address);

            // Response check
            Assert.AreEqual("user", result.Type);
            Assert.AreEqual("187273718", result.Id);
            Assert.AreEqual("Ned Stark", result.Name);
            Assert.AreEqual("*****@*****.**", result.Login);
            Assert.AreEqual(DateTime.Parse("2012-11-15T16:34:28-08:00"), result.CreatedAt);
            Assert.AreEqual("user", result.Role);
            Assert.AreEqual("en", result.Language);
            Assert.AreEqual(5368709120, result.SpaceAmount);
            Assert.AreEqual(0, result.SpaceUsed);
            Assert.AreEqual(2147483648, result.MaxUploadSize);
            Assert.AreEqual(0, result.TrackingCodes.Count);
            Assert.AreEqual(true, result.CanSeeManagedUsers);
            Assert.AreEqual(true, result.IsSyncEnabled);
            Assert.AreEqual("active", result.Status);
            Assert.IsTrue(string.IsNullOrEmpty(result.JobTitle));
            Assert.AreEqual("555-555-5555", result.Phone);
            Assert.AreEqual("555 Box Lane", result.Address);
            Assert.AreEqual("https://www.box.com/api/avatar/large/187273718", result.AvatarUrl);
        }
        public async Task CreateTaskAssignment_ValidResponse()
        {
            /*** Arrange ***/
            string      responseString     = @"{
                                        ""type"": ""task_assignment"",
                                        ""id"": ""2698512"",
                                        ""item"": {
                                            ""type"": ""file"",
                                            ""id"": ""8018809384"",
                                            ""sequence_id"": ""0"",
                                            ""etag"": ""0"",
                                            ""sha1"": ""7840095ee096ee8297676a138d4e316eabb3ec96"",
                                            ""name"": ""scrumworksToTrello.js""
                                        },
                                        ""assigned_to"": {
                                            ""type"": ""user"",
                                            ""id"": ""1992432"",
                                            ""name"": ""*****@*****.**"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""message"": null,
                                        ""completed_at"": null,
                                        ""assigned_at"": ""2013-05-10T11:43:41-07:00"",
                                        ""reminded_at"": null,
                                        ""resolution_state"": ""incomplete"",
                                        ""assigned_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""11993747"",
                                            ""name"": ""sean"",
                                            ""login"": ""*****@*****.**""
                                        }
                                    }";
            IBoxRequest boxRequest         = null;
            Uri         taskAssignmentsUri = new Uri(Constants.TaskAssignmentsEndpointString);

            Config.SetupGet(x => x.TaskAssignmentsEndpointUri).Returns(taskAssignmentsUri);
            Handler.Setup(h => h.ExecuteAsync <BoxTaskAssignment>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxTaskAssignment> >(new BoxResponse <BoxTaskAssignment>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            BoxTaskAssignmentRequest taskAssignmentRequest = new BoxTaskAssignmentRequest()
            {
                Task = new BoxTaskRequest()
                {
                    Id = "1992432"
                },
                AssignTo = new BoxAssignmentRequest()
                {
                    Id = "1992432"
                }
            };
            BoxTaskAssignment result = await _tasksManager.CreateTaskAssignmentAsync(taskAssignmentRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(taskAssignmentsUri, boxRequest.AbsoluteUri.AbsoluteUri);
            BoxTaskAssignmentRequest payload = JsonConvert.DeserializeObject <BoxTaskAssignmentRequest>(boxRequest.Payload);

            Assert.AreEqual(taskAssignmentRequest.Task.Id, payload.Task.Id);
            Assert.AreEqual(taskAssignmentRequest.Task.Type, payload.Task.Type);
            Assert.AreEqual(taskAssignmentRequest.AssignTo.Id, payload.AssignTo.Id);
            Assert.AreEqual(taskAssignmentRequest.AssignTo.Login, payload.AssignTo.Login);

            //Response check
            Assert.AreEqual("2698512", result.Id);
            Assert.AreEqual("task_assignment", result.Type);
            Assert.AreEqual("8018809384", result.Item.Id);
            Assert.AreEqual("file", result.Item.Type);
            Assert.AreEqual("0", result.Item.ETag);
            Assert.AreEqual(ResolutionStateType.incomplete, result.ResolutionState);
            Assert.AreEqual("*****@*****.**", result.AssignedBy.Login);
            Assert.AreEqual("11993747", result.AssignedBy.Id);
            Assert.AreEqual("*****@*****.**", result.AssignedTo.Login);
            Assert.AreEqual("1992432", result.AssignedTo.Id);
        }
Example #17
0
        public async Task <IBoxResponse <T> > ExecuteAsync <T>(IBoxRequest request)
            where T : class
        {
            // Need to account for special cases when the return type is a stream
            bool isStream = typeof(T) == typeof(Stream);

            HttpRequestMessage httpRequest = request.GetType() == typeof(BoxMultiPartRequest) ?
                                             BuildMultiPartRequest(request as BoxMultiPartRequest) :
                                             BuildRequest(request);

            // Add headers
            foreach (var kvp in request.HttpHeaders)
            {
                httpRequest.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value);
            }

            // If we are retrieving a stream, we should return without reading the entire response
            HttpCompletionOption completionOption = isStream ?
                                                    HttpCompletionOption.ResponseHeadersRead :
                                                    HttpCompletionOption.ResponseContentRead;

            Debug.WriteLine(string.Format("RequestUri: {0}", httpRequest.RequestUri));//, RequestHeader: {1} , httpRequest.Headers.Select(i => string.Format("{0}:{1}", i.Key, i.Value)).Aggregate((i, j) => i + "," + j)));

            try
            {
                HttpResponseMessage response = await _client.SendAsync(httpRequest, completionOption).ConfigureAwait(false);

                BoxResponse <T> boxResponse = new BoxResponse <T>();
                boxResponse.Headers = response.Headers;

                // Translate the status codes that interest us
                boxResponse.StatusCode = response.StatusCode;
                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Created:
                case HttpStatusCode.NoContent:
                    boxResponse.Status = ResponseStatus.Success;
                    break;

                case HttpStatusCode.Accepted:
                    boxResponse.Status = ResponseStatus.Pending;
                    break;

                case HttpStatusCode.Unauthorized:
                    boxResponse.Status = ResponseStatus.Unauthorized;
                    break;

                default:
                    boxResponse.Status = ResponseStatus.Error;
                    break;
                }

                if (isStream && boxResponse.Status == ResponseStatus.Success)
                {
                    var resObj = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                    boxResponse.ResponseObject = resObj as T;
                }
                else
                {
                    boxResponse.ContentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                }
                return(boxResponse);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
                throw;
            }
        }
        public async Task GetTask_ValidResponse()
        {
            /*** Arrange ***/
            string      responseString = @"{
                                        ""type"": ""task"",
                                        ""id"": ""1839355"",
                                        ""item"": {
                                            ""type"": ""file"",
                                            ""id"": ""7287087200"",
                                            ""sequence_id"": ""0"",
                                            ""etag"": ""0"",
                                            ""sha1"": ""0bbd79a105c504f99573e3799756debba4c760cd"",
                                            ""name"": ""box-logo.png""
                                        },
                                        ""due_at"": ""2014-04-03T11:09:43-07:00"",
                                        ""action"": ""review"",
                                        ""message"": ""REVIEW PLZ K THX"",
                                        ""task_assignment_collection"": {
                                            ""total_count"": 0,
                                            ""entries"": []
                                        },
                                        ""is_completed"": false,
                                        ""created_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""11993747"",
                                            ""name"": ""sean"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""created_at"": ""2013-04-03T11:12:54-07:00""
                                    }";
            IBoxRequest boxRequest     = null;
            Uri         tasksUri       = new Uri(Constants.TasksEndpointString);

            Config.SetupGet(x => x.TasksEndpointUri).Returns(tasksUri);
            Handler.Setup(h => h.ExecuteAsync <BoxTask>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxTask> >(new BoxResponse <BoxTask>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            BoxTask result = await _tasksManager.GetTaskAsync("1839355");

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Get, boxRequest.Method);
            Assert.AreEqual(tasksUri + "1839355", boxRequest.AbsoluteUri.AbsoluteUri);

            //Response check
            Assert.AreEqual("1839355", result.Id);
            Assert.AreEqual("task", result.Type);
            Assert.AreEqual("7287087200", result.Item.Id);
            Assert.AreEqual("file", result.Item.Type);
            Assert.AreEqual("0", result.Item.ETag);
            Assert.AreEqual("REVIEW PLZ K THX", result.Message);
            Assert.AreEqual(false, result.IsCompleted);
            Assert.AreEqual("11993747", result.CreatedBy.Id);
            Assert.AreEqual("*****@*****.**", result.CreatedBy.Login);
            Assert.AreEqual(0, result.TaskAssignments.TotalCount);
        }
Example #19
0
        public async Task GetCollectionItems_ValidResponse()
        {
            /*** Arrange ***/
            string      responseString = @"{
                                            ""total_count"": 24,
                                            ""entries"": [
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""192429928"",
                                                    ""sequence_id"": ""1"",
                                                    ""etag"": ""1"",
                                                    ""name"": ""Stephen Curry Three Pointers""
                                                },
                                                {
                                                    ""type"": ""file"",
                                                    ""id"": ""818853862"",
                                                    ""sequence_id"": ""0"",
                                                    ""etag"": ""0"",
                                                    ""name"": ""Warriors.jpg""
                                                }
                                            ],
                                            ""offset"": 0,
                                            ""limit"": 2
                                        }";
            IBoxRequest boxRequest     = null;
            Uri         collectionUri  = new Uri(Constants.CollectionsEndpointString);

            _config.SetupGet(x => x.CollectionsEndpointUri).Returns(collectionUri);
            _handler.Setup(h => h.ExecuteAsync <BoxCollection <BoxItem> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxCollection <BoxItem> > >(new BoxResponse <BoxCollection <BoxItem> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/

            BoxCollection <BoxItem> result = await _collectionsManager.GetCollectionItemsAsync("405151", 2);

            /*** Assert ***/

            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Get, boxRequest.Method);
            Assert.AreEqual(collectionUri + "405151/items?limit=2&offset=0", boxRequest.AbsoluteUri.AbsoluteUri);

            //Response check
            Assert.AreEqual(24, result.TotalCount);
            Assert.IsNotNull(result.Entries);
            Assert.AreEqual(2, result.Entries.Count);
            Assert.AreEqual("folder", result.Entries[0].Type);
            Assert.AreEqual("192429928", result.Entries[0].Id);
            Assert.AreEqual("1", result.Entries[0].ETag);
            Assert.AreEqual("Stephen Curry Three Pointers", result.Entries[0].Name);
            Assert.AreEqual("file", result.Entries[1].Type);
            Assert.AreEqual("818853862", result.Entries[1].Id);
            Assert.AreEqual("0", result.Entries[1].ETag);
            Assert.AreEqual("Warriors.jpg", result.Entries[1].Name);
            Assert.AreEqual(2, result.Limit);
            Assert.AreEqual(0, result.Offset);
        }
        public async Task ExecuteMetadataQuery_ValidResponse()
        {
            /*** Arrange ***/
            IBoxRequest boxRequest = null;

            Handler.Setup(h => h.ExecuteAsync <BoxCollectionMarkerBased <BoxMetadataQueryItem> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxCollectionMarkerBased <BoxMetadataQueryItem> > >(new BoxResponse <BoxCollectionMarkerBased <BoxMetadataQueryItem> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = LoadFixtureFromJson("Fixtures/BoxMetadata/ExecuteMetadataQuery200.json")
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var queryParams = new Dictionary <string, object>
            {
                { "arg", 100 }
            };
            var orderByList = new List <BoxMetadataQueryOrderBy>();
            var orderBy     = new BoxMetadataQueryOrderBy()
            {
                FieldKey  = "amount",
                Direction = BoxSortDirection.ASC
            };

            orderByList.Add(orderBy);
            var marker = "q3f87oqf3qygou5t478g9gwrbul";
            BoxCollectionMarkerBased <BoxMetadataQueryItem> items = await _metadataManager.ExecuteMetadataQueryAsync(from : "enterprise_123456.someTemplate", query : "amount >= :arg", queryParameters : queryParams, ancestorFolderId : "5555", indexName : "amountAsc", orderBy : orderByList, marker : marker, autoPaginate : false);

            /*** Assert ***/

            // Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(MetadataQueryUri, boxRequest.AbsoluteUri.AbsoluteUri);
            var payload = JObject.Parse(boxRequest.Payload);

            Assert.AreEqual("enterprise_123456.someTemplate", payload["from"]);
            Assert.AreEqual("amount >= :arg", payload["query"]);
            Assert.AreEqual(100, payload["query_params"]["arg"]);
            Assert.AreEqual("5555", payload["ancestor_folder_id"]);
            var payloadOrderBy = JArray.Parse(payload["order_by"].ToString());

            Assert.AreEqual("amount", payloadOrderBy[0]["field_key"]);
            Assert.AreEqual("ASC", payloadOrderBy[0]["direction"]);
            Assert.AreEqual(marker, payload["marker"]);

            // Response check
            Assert.AreEqual(items.Entries[0].Item.Type, "file");
            Assert.AreEqual(items.Entries[0].Item.Id, "1617554169109");
            Assert.AreEqual(items.Entries[0].Item.Name, "My Contract.docx");
            Assert.AreEqual(items.Entries[0].Item.SequenceId, "0");
            Assert.AreEqual(items.Entries[0].Item.CreatedBy.Type, "user");
            Assert.AreEqual(items.Entries[0].Item.CreatedBy.Login, "*****@*****.**");
            Assert.AreEqual(items.Entries[0].Item.Parent.Id, "16125613433");
            Assert.AreEqual(items.NextMarker, "AAAAAmVYB1FWec8GH6yWu2nwmanfMh07IyYInaa7DZDYjgO1H4KoLW29vPlLY173OKsci6h6xGh61gG73gnaxoS+o0BbI1/h6le6cikjlupVhASwJ2Cj0tOD9wlnrUMHHw3/ISf+uuACzrOMhN6d5fYrbidPzS6MdhJOejuYlvsg4tcBYzjauP3+VU51p77HFAIuObnJT0ff");
            var metadata = JObject.FromObject(items.Entries[0].Metadata["enterprise_123456"]);

            Assert.AreEqual(metadata["someTemplate"]["$parent"], "file_161753469109");
            Assert.AreEqual(metadata["someTemplate"]["customerName"], "Phoenix Corp");
            Assert.AreEqual(metadata["someTemplate"]["$typeVersion"], 0);
            Assert.AreEqual(metadata["someTemplate"]["region"], "West");
        }
        public async Task GetFolderInformation_ValidResponse_ValidFolder()
        {
            IBoxRequest boxRequest = null;

            /*** Arrange ***/
            _handler.Setup(h => h.ExecuteAsync <BoxFolder>(It.IsAny <IBoxRequest>()))
            .Returns(() => Task.FromResult <IBoxResponse <BoxFolder> >(new BoxResponse <BoxFolder>()
            {
                Status        = ResponseStatus.Success,
                ContentString = "{ \"type\": \"folder\", \"id\": \"11446498\", \"sequence_id\": \"1\", \"etag\": \"1\", \"name\": \"Pictures\", \"created_at\": \"2012-12-12T10:53:43-08:00\", \"modified_at\": \"2012-12-12T11:15:04-08:00\", \"description\": \"Some pictures I took\", \"size\": 629644, \"path_collection\": { \"total_count\": 1, \"entries\": [ { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" } ] }, \"created_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"modified_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"owned_by\": { \"type\": \"user\", \"id\": \"17738362\", \"name\": \"sean rose\", \"login\": \"[email protected]\" }, \"shared_link\": { \"url\": \"https://www.box.com/s/vspke7y05sb214wjokpk\", \"download_url\": \"https://www.box.com/shared/static/vspke7y05sb214wjokpk\", \"vanity_url\": null, \"is_password_enabled\": false, \"unshared_at\": null, \"download_count\": 0, \"preview_count\": 0, \"access\": \"open\", \"permissions\": { \"can_download\": true, \"can_preview\": true } }, \"folder_upload_email\": { \"access\": \"open\", \"email\": \"[email protected]\" }, \"parent\": { \"type\": \"folder\", \"id\": \"0\", \"sequence_id\": null, \"etag\": null, \"name\": \"All Files\" }, \"item_status\": \"active\", \"item_collection\": { \"total_count\": 1, \"entries\": [ { \"type\": \"file\", \"id\": \"5000948880\", \"sequence_id\": \"3\", \"etag\": \"3\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\", \"name\": \"tigers.jpeg\" } ], \"offset\": 0, \"limit\": 100 } }"
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);;

            /*** Act ***/
            BoxFolder f = await _foldersManager.GetInformationAsync("11446498", new List <string>() { "f1", "f2", "f3" });

            /*** Assert ***/
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Get, boxRequest.Method);
            Assert.AreEqual(_FoldersUri + "11446498?fields=f1,f2,f3", boxRequest.AbsoluteUri.AbsoluteUri);

            Assert.AreEqual(f.Type, "folder");
            Assert.AreEqual(f.Id, "11446498");
            Assert.AreEqual(f.SequenceId, "1");
            Assert.AreEqual(f.ETag, "1");
            Assert.AreEqual(f.Name, "Pictures");
            Assert.AreEqual(f.CreatedAt, DateTime.Parse("2012-12-12T10:53:43-08:00"));
            Assert.AreEqual(f.ModifiedAt, DateTime.Parse("2012-12-12T11:15:04-08:00"));
            Assert.AreEqual(f.Description, "Some pictures I took");
            Assert.AreEqual(f.Size, 629644);
            Assert.AreEqual(f.PathCollection.TotalCount, 1);
            Assert.AreEqual(f.PathCollection.Entries.Count, 1);
            Assert.AreEqual(f.PathCollection.Entries[0].Type, "folder");
            Assert.AreEqual(f.PathCollection.Entries[0].Id, "0");
            Assert.IsNull(f.PathCollection.Entries[0].SequenceId);
            Assert.IsNull(f.PathCollection.Entries[0].ETag);
            Assert.AreEqual(f.PathCollection.Entries[0].Name, "All Files");
            Assert.AreEqual(f.CreatedBy.Type, "user");
            Assert.AreEqual(f.CreatedBy.Id, "17738362");
            Assert.AreEqual(f.CreatedBy.Name, "sean rose");
            Assert.AreEqual(f.CreatedBy.Login, "*****@*****.**");
            Assert.AreEqual(f.ModifiedBy.Type, "user");
            Assert.AreEqual(f.ModifiedBy.Id, "17738362");
            Assert.AreEqual(f.ModifiedBy.Name, "sean rose");
            Assert.AreEqual(f.ModifiedBy.Login, "*****@*****.**");
            Assert.AreEqual(f.OwnedBy.Type, "user");
            Assert.AreEqual(f.OwnedBy.Id, "17738362");
            Assert.AreEqual(f.OwnedBy.Name, "sean rose");
            Assert.AreEqual(f.OwnedBy.Login, "*****@*****.**");
            Assert.AreEqual(f.SharedLink.Url, "https://www.box.com/s/vspke7y05sb214wjokpk");
            Assert.AreEqual(f.SharedLink.DownloadUrl, "https://www.box.com/shared/static/vspke7y05sb214wjokpk");
            Assert.AreEqual(f.SharedLink.VanityUrl, null);
            Assert.IsFalse(f.SharedLink.IsPasswordEnabled);
            Assert.IsNull(f.SharedLink.UnsharedAt);
            Assert.AreEqual(f.SharedLink.DownloadCount, 0);
            Assert.AreEqual(f.SharedLink.PreviewCount, 0);
            Assert.AreEqual(f.SharedLink.Access, BoxSharedLinkAccessType.open);
            Assert.IsTrue(f.SharedLink.Permissions.CanDownload);
            Assert.IsTrue(f.SharedLink.Permissions.CanPreview);
            Assert.AreEqual(f.FolderUploadEmail.Acesss, "open");
            Assert.AreEqual(f.FolderUploadEmail.Address, "*****@*****.**");
            Assert.AreEqual(f.Parent.Type, "folder");
            Assert.AreEqual(f.Parent.Id, "0");
            Assert.IsNull(f.Parent.SequenceId);
            Assert.IsNull(f.Parent.ETag);
            Assert.AreEqual(f.Parent.Name, "All Files");
            Assert.AreEqual(f.ItemStatus, "active");
            Assert.AreEqual(f.ItemCollection.TotalCount, 1);
            Assert.AreEqual(f.ItemCollection.Entries.Count, 1);
            Assert.AreEqual(f.ItemCollection.Entries[0].Type, "file");
            Assert.AreEqual(f.ItemCollection.Entries[0].Id, "5000948880");
            Assert.AreEqual(f.ItemCollection.Entries[0].SequenceId, "3");
            Assert.AreEqual(f.ItemCollection.Entries[0].ETag, "3");
            Assert.AreEqual((f.ItemCollection.Entries[0] as BoxFile).Sha1, "134b65991ed521fcfe4724b7d814ab8ded5185dc");
            Assert.AreEqual(f.ItemCollection.Entries[0].Name, "tigers.jpeg");
            Assert.AreEqual(f.ItemCollection.Offset, 0);
            Assert.AreEqual(f.ItemCollection.Limit, 100);
        }
        public async Task ExecuteMetadataQueryWithoutUseIndexWithFields_ValidResponse()
        {
            /*** Arrange ***/
            IBoxRequest boxRequest = null;

            Handler.Setup(h => h.ExecuteAsync <BoxCollectionMarkerBased <BoxItem> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxCollectionMarkerBased <BoxItem> > >(new BoxResponse <BoxCollectionMarkerBased <BoxItem> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = LoadFixtureFromJson("Fixtures/BoxMetadata/ExecuteMetadataWithFieldsQuery200.json")
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var queryParams = new Dictionary <string, object>
            {
                { "arg", 100 }
            };
            var orderByList = new List <BoxMetadataQueryOrderBy>();
            var orderBy     = new BoxMetadataQueryOrderBy()
            {
                FieldKey  = "amount",
                Direction = BoxSortDirection.ASC
            };

            orderByList.Add(orderBy);
            var marker = "q3f87oqf3qygou5t478g9gwrbul";

            var metadataRequest = new BoxMetadataQueryRequest
            {
                From            = "enterprise_67890.catalogImages",
                Query           = "photographer = :arg",
                QueryParameters = new Dictionary <string, object>
                {
                    { "arg", "Bob Dylan" }
                },
                AncestorFolderId = "5555",
                OrderBy          = orderByList,
                Marker           = marker,
                AutoPaginate     = false,
                Fields           = new List <string>
                {
                    "id",
                    "name",
                    "sha1",
                    "metadata.enterprise_240748.catalogImages.photographer"
                }
            };

            BoxCollectionMarkerBased <BoxItem> items = await _metadataManager.ExecuteMetadataQueryAsync(metadataRequest);

            /*** Assert ***/

            // Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Post, boxRequest.Method);
            Assert.AreEqual(MetadataQueryUri, boxRequest.AbsoluteUri.AbsoluteUri);
            var payload = JObject.Parse(boxRequest.Payload);

            Assert.AreEqual("enterprise_67890.catalogImages", payload["from"]);
            Assert.AreEqual("photographer = :arg", payload["query"]);
            Assert.AreEqual("5555", payload["ancestor_folder_id"]);
            var payloadFields = JArray.Parse(payload["fields"].ToString());

            Assert.AreEqual("id", payloadFields[0]);
            Assert.AreEqual("name", payloadFields[1]);
            Assert.AreEqual("sha1", payloadFields[2]);
            Assert.AreEqual("metadata.enterprise_240748.catalogImages.photographer", payloadFields[3]);
            Assert.AreEqual(marker, payload["marker"]);
            Assert.AreEqual("Bob Dylan", payload["query_params"]["arg"]);
            var payloadOrderBy = JArray.Parse(payload["order_by"].ToString());

            Assert.AreEqual("amount", payloadOrderBy[0]["field_key"]);
            Assert.AreEqual("ASC", payloadOrderBy[0]["direction"]);

            // Response check
            Assert.AreEqual(items.Entries[0].Type, "file");
            Assert.AreEqual(items.Entries[0].Id, "1244738582");
            Assert.AreEqual(items.Entries[0].Name, "Very Important.docx");
            Assert.AreEqual(items.Entries[1].Type, "folder");
            Assert.AreEqual(items.Entries[1].Id, "124242482");
            Assert.AreEqual(items.Entries[1].Name, "Also Important.docx");
            var file = (BoxFile)items.Entries[0];

            Assert.AreEqual(file.Metadata["enterprise_67890"]["catalogImages"]["photographer"].Value, "Bob Dylan");
        }
        public async Task UpdateFileMetadata_ValidResponse_ValidEntries()
        {
            /*** Arrange ***/
            string responseString = @"{
                                        ""audience1"": ""internal"",
                                        ""documentType"": ""Q1 plans"",
                                        ""status"": ""inactive"",
                                        ""author"": ""Jones"",
                                        ""$type"": ""marketingCollateral-d086c908-2498-4d3e-8a1f-01e82bfc2abe"",
                                        ""$parent"": ""file_5010739061"",
                                        ""$id"": ""2094c584-68e1-475c-a581-534a4609594e"",
                                        ""$version"": 1,
                                        ""$typeVersion"": 0,
                                        ""editor"": ""Jones"",
                                        ""previousState"": ""proposal"",
                                        ""currentState"": ""reviewed"",
                                        ""$template"": ""marketingCollateral"",
                                        ""$scope"": ""enterprise_12345""
                                    }";

            IBoxRequest boxRequest = null;

            Handler.Setup(h => h.ExecuteAsync <Dictionary <string, object> >(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <Dictionary <string, object> > >(new BoxResponse <Dictionary <string, object> >()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            })).Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            List <BoxMetadataUpdate> updates = new List <BoxMetadataUpdate>()
            {
                new BoxMetadataUpdate()
                {
                    Op    = MetadataUpdateOp.test,
                    Path  = "/competitiveDocument",
                    Value = "no"
                },
                new BoxMetadataUpdate()
                {
                    Op   = MetadataUpdateOp.remove,
                    Path = "/competitiveDocument"
                },
                new BoxMetadataUpdate()
                {
                    Op    = MetadataUpdateOp.test,
                    Path  = "/status",
                    Value = "active"
                },
                new BoxMetadataUpdate()
                {
                    Op    = MetadataUpdateOp.replace,
                    Path  = "/competitiveDocument",
                    Value = "inactive"
                },
                new BoxMetadataUpdate()
                {
                    Op    = MetadataUpdateOp.test,
                    Path  = "/author",
                    Value = "Jones"
                },
                new BoxMetadataUpdate()
                {
                    Op   = MetadataUpdateOp.copy,
                    From = "/author",
                    Path = "/editor"
                },
                new BoxMetadataUpdate()
                {
                    Op    = MetadataUpdateOp.test,
                    Path  = "/currentState",
                    Value = "proposal"
                },
                new BoxMetadataUpdate()
                {
                    Op   = MetadataUpdateOp.move,
                    From = "/currentState",
                    Path = "/previousState"
                },
                new BoxMetadataUpdate()
                {
                    Op    = MetadataUpdateOp.add,
                    Path  = "/currentState",
                    Value = "reviewed"
                },
            };
            Dictionary <string, object> result = await _metadataManager.UpdateFileMetadataAsync("5010739061", updates, "enterprise", "marketingCollateral");

            /*** Assert ***/
            /***request***/
            List <BoxMetadataUpdate> payLoad = JsonConvert.DeserializeObject <List <BoxMetadataUpdate> >(boxRequest.Payload);

            for (int i = 0; i < payLoad.Count; i++)
            {
                Assert.AreEqual(updates[i].Op, payLoad[i].Op);
                Assert.AreEqual(updates[i].Path, payLoad[i].Path);
            }
            /***response***/
            Assert.AreEqual("internal", result["audience1"]);
            Assert.AreEqual("Q1 plans", result["documentType"]);
            Assert.AreEqual((long)1, result["$version"]);
            Assert.AreEqual("reviewed", result["currentState"]);
        }
Example #24
0
        public async Task UpdateWeblink_ValidResponse()
        {
            /*** Arrange ***/
            var         responseString = @"{
                                        ""type"": ""web_link"",
                                        ""id"": ""6742981"",
                                        ""sequence_id"": ""2"",
                                        ""etag"": ""2"",
                                        ""name"": ""Box Marketing Web Page"",
                                        ""url"": ""https://www.box.com"",
                                        ""created_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""10523870"",
                                            ""name"": ""Ted Blosser"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""created_at"": ""2015-05-07T14:31:16-07:00"",
                                        ""modified_at"": ""2015-05-07T15:45:04-07:00"",
                                        ""parent"": {
                                            ""type"": ""folder"",
                                            ""id"": ""848123342"",
                                            ""sequence_id"": ""1"",
                                            ""etag"": ""1"",
                                            ""name"": ""Documentation""
                                        },
                                        ""description"": ""Cloud Content Management"",
                                        ""item_status"": ""active"",
                                        ""trashed_at"": null,
                                        ""purged_at"": null,
                                        ""shared_link"": null,
                                        ""path_collection"": {
                                            ""total_count"": 2,
                                            ""entries"": [
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""0"",
                                                    ""sequence_id"": null,
                                                    ""etag"": null,
                                                    ""name"": ""All Files""
                                                },
                                                {
                                                    ""type"": ""folder"",
                                                    ""id"": ""848123342"",
                                                    ""sequence_id"": ""1"",
                                                    ""etag"": ""1"",
                                                    ""name"": ""Documentation""
                                                }
                                            ]
                                        },
                                        ""modified_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""10523870"",
                                            ""name"": ""Ted Blosser"",
                                            ""login"": ""*****@*****.**""
                                        },
                                        ""owned_by"": {
                                            ""type"": ""user"",
                                            ""id"": ""10523870"",
                                            ""name"": ""Ted Blosser"",
                                            ""login"": ""*****@*****.**""
                                        }
                                    }";
            IBoxRequest boxRequest     = null;
            var         webLinksUri    = new Uri(Constants.WebLinksEndpointString);

            Config.SetupGet(x => x.WebLinksEndpointUri).Returns(webLinksUri);
            Handler.Setup(h => h.ExecuteAsync <BoxWebLink>(It.IsAny <IBoxRequest>()))
            .Returns(Task.FromResult <IBoxResponse <BoxWebLink> >(new BoxResponse <BoxWebLink>()
            {
                Status        = ResponseStatus.Success,
                ContentString = responseString
            }))
            .Callback <IBoxRequest>(r => boxRequest = r);

            /*** Act ***/
            var updateWebLinkRequest = new BoxWebLinkRequest()
            {
                Name = "Box Marketing Web Page"
            };
            BoxWebLink result = await _webLinkManager.UpdateWebLinkAsync("6742981", updateWebLinkRequest);

            /*** Assert ***/
            //Request check
            Assert.IsNotNull(boxRequest);
            Assert.AreEqual(RequestMethod.Put, boxRequest.Method);
            Assert.AreEqual(webLinksUri + "6742981", boxRequest.AbsoluteUri.AbsoluteUri);
            BoxWebLinkRequest payload = JsonConvert.DeserializeObject <BoxWebLinkRequest>(boxRequest.Payload);

            Assert.AreEqual("Box Marketing Web Page", payload.Name);


            //Response check
            Assert.AreEqual("web_link", result.Type);
            Assert.AreEqual("6742981", result.Id);
            Assert.AreEqual(new Uri("https://www.box.com"), result.Url);
            Assert.AreEqual("Box Marketing Web Page", result.Name);
            Assert.AreEqual("Cloud Content Management", result.Description);
            Assert.AreEqual("0", result.PathCollection.Entries[0].Id);
            Assert.AreEqual("All Files", result.PathCollection.Entries[0].Name);
            Assert.AreEqual("848123342", result.PathCollection.Entries[1].Id);
            Assert.AreEqual("Documentation", result.PathCollection.Entries[1].Name);
            Assert.AreEqual("10523870", result.ModifiedBy.Id);
            Assert.AreEqual("10523870", result.OwnedBy.Id);
        }
Example #25
0
        public async Task <IBoxResponse <T> > ExecuteAsync <T>(IBoxRequest request)
            where T : class
        {
            // Need to account for special cases when the return type is a stream
            bool isStream                 = typeof(T) == typeof(Stream);
            var  retryCounter             = 0;
            ExponentialBackoff expBackoff = new ExponentialBackoff();

            try
            {
                // TODO: yhu@ better handling of different request
                var isMultiPartRequest = request.GetType() == typeof(BoxMultiPartRequest);
                var isBinaryRequest    = request.GetType() == typeof(BoxBinaryRequest);

                while (true)
                {
                    HttpRequestMessage httpRequest = null;

                    if (isMultiPartRequest)
                    {
                        httpRequest = BuildMultiPartRequest(request as BoxMultiPartRequest);
                    }
                    else if (isBinaryRequest)
                    {
                        httpRequest = BuildBinaryRequest(request as BoxBinaryRequest);
                    }
                    else
                    {
                        httpRequest = BuildRequest(request);
                    }

                    // Add headers
                    foreach (var kvp in request.HttpHeaders)
                    {
                        // They could not be added to the headers directly
                        if (kvp.Key == Constants.RequestParameters.ContentMD5 ||
                            kvp.Key == Constants.RequestParameters.ContentRange)
                        {
                            httpRequest.Content.Headers.Add(kvp.Key, kvp.Value);
                        }
                        else
                        {
                            httpRequest.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value);
                        }
                    }

                    // If we are retrieving a stream, we should return without reading the entire response
                    HttpCompletionOption completionOption = isStream ?
                                                            HttpCompletionOption.ResponseHeadersRead :
                                                            HttpCompletionOption.ResponseContentRead;

                    Debug.WriteLine(string.Format("RequestUri: {0}", httpRequest.RequestUri));

                    HttpClient client = GetClient(request);

                    // Not disposing the reponse since it will affect stream response
                    var response = await client.SendAsync(httpRequest, completionOption).ConfigureAwait(false);

                    //need to wait for Retry-After seconds and then retry request
                    var retryAfterHeader = response.Headers.RetryAfter;

                    // If we get a 429 error code and this is not a multi part request (meaning a file upload, which cannot be retried
                    // because the stream cannot be reset) and we haven't exceeded the number of allowed retries, then retry the request.
                    // If we get a 202 code and has a retry-after header, we will retry after
                    if (
                        ((response.StatusCode == TooManyRequests && !isMultiPartRequest)
                         ||
                         (response.StatusCode == HttpStatusCode.Accepted && retryAfterHeader != null)) &&
                        retryCounter++ < RetryLimit)
                    {
                        TimeSpan delay = expBackoff.GetRetryTimeout(retryCounter);

                        Debug.WriteLine("HttpCode : {0}. Waiting for {1} seconds to retry request. RequestUri: {2}", response.StatusCode, delay.Seconds, httpRequest.RequestUri);

                        await Task.Delay(delay);
                    }
                    else
                    {
                        BoxResponse <T> boxResponse = new BoxResponse <T>();
                        boxResponse.Headers = response.Headers;

                        // Translate the status codes that interest us
                        boxResponse.StatusCode = response.StatusCode;
                        switch (response.StatusCode)
                        {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Created:
                        case HttpStatusCode.NoContent:
                        case HttpStatusCode.Found:
                        case HttpStatusCode.PartialContent:     // Download with range
                            boxResponse.Status = ResponseStatus.Success;
                            break;

                        case HttpStatusCode.Accepted:
                            boxResponse.Status = ResponseStatus.Pending;
                            break;

                        case HttpStatusCode.Unauthorized:
                            boxResponse.Status = ResponseStatus.Unauthorized;
                            break;

                        case HttpStatusCode.Forbidden:
                            boxResponse.Status = ResponseStatus.Forbidden;
                            break;

                        case TooManyRequests:
                            boxResponse.Status = ResponseStatus.TooManyRequests;
                            break;

                        default:
                            boxResponse.Status = ResponseStatus.Error;
                            break;
                        }

                        if (isStream && boxResponse.Status == ResponseStatus.Success)
                        {
                            var resObj = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            boxResponse.ResponseObject = resObj as T;
                        }
                        else
                        {
                            boxResponse.ContentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                        }

                        return(boxResponse);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
                throw;
            }
        }
 private HttpClient GetClient(IBoxRequest request)
 {
     return(request.FollowRedirect ? ClientFactory.AutoRedirectClient : ClientFactory.NonAutoRedirectClient);
 }