public async Task InvokeApiTypedOverloads_HasCorrectFeaturesHeader()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual("AT", request.Headers.GetValues("X-ZUMO-FEATURES").First());
                return(Task.FromResult(request));
            };

            MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);

            hijack.SetResponseContent("{\"id\":3}");
            await service.InvokeApiAsync <IntType>("apiName");

            hijack.SetResponseContent("{\"id\":3}");
            await service.InvokeApiAsync <IntType, IntType>("apiName", new IntType { Id = 1 });

            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual("AT,QS", request.Headers.GetValues("X-ZUMO-FEATURES").First());
                return(Task.FromResult(request));
            };

            var dic = new Dictionary <string, string> {
                { "a", "b" }
            };

            hijack.SetResponseContent("{\"id\":3}");
            await service.InvokeApiAsync <IntType>("apiName", HttpMethod.Get, dic);

            hijack.SetResponseContent("{\"hello\":\"world\"}");
            await service.InvokeApiAsync <IntType, IntType>("apiName", new IntType { Id = 1 }, HttpMethod.Put, dic);
        }
        public async Task InvokeApiJsonOverloads_HasCorrectFeaturesHeader()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual("AJ", request.Headers.GetValues("X-ZUMO-FEATURES").First());
                return(Task.FromResult(request));
            };

            MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);

            hijack.SetResponseContent("{\"hello\":\"world\"}");
            await service.InvokeApiAsync("apiName");

            hijack.SetResponseContent("{\"hello\":\"world\"}");
            await service.InvokeApiAsync("apiName", JObject.Parse("{\"a\":1}"));

            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual("AJ,QS", request.Headers.GetValues("X-ZUMO-FEATURES").First());
                return(Task.FromResult(request));
            };

            var dic = new Dictionary <string, string> {
                { "a", "b" }
            };

            hijack.SetResponseContent("{\"hello\":\"world\"}");
            await service.InvokeApiAsync("apiName", HttpMethod.Get, dic);

            hijack.SetResponseContent("{\"hello\":\"world\"}");
            await service.InvokeApiAsync("apiName", null, HttpMethod.Delete, dic);
        }
        public async Task ErrorMessageConstruction()
        {
            string appUrl     = MobileAppUriValidator.DummyMobileApp;
            string appKey     = "secret...";
            string collection = "tests";
            string query      = "$filter=id eq 12";

            TestHttpHandler       hijack  = new TestHttpHandler();
            IMobileServiceClient  service = new MobileServiceClient(appUrl, hijack);
            MobileAppUriValidator mobileAppUriValidator = new MobileAppUriValidator(service);

            // Verify the error message is correctly pulled out
            hijack.SetResponseContent("{\"error\":\"error message\",\"other\":\"donkey\"}");
            hijack.Response.StatusCode   = HttpStatusCode.Unauthorized;
            hijack.Response.ReasonPhrase = "YOU SHALL NOT PASS.";
            try
            {
                JToken response = await service.GetTable(collection).ReadAsync(query);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, "error message");
            }

            // Verify all of the exception parameters
            hijack.Response              = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            hijack.Response.Content      = new StringContent("{\"error\":\"error message\",\"other\":\"donkey\"}", Encoding.UTF8, "application/json");
            hijack.Response.ReasonPhrase = "YOU SHALL NOT PASS.";
            try
            {
                JToken response = await service.GetTable(collection).ReadAsync(query);
            }
            catch (MobileServiceInvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, "error message");
                Assert.AreEqual(HttpStatusCode.Unauthorized, ex.Response.StatusCode);
                Assert.Contains(ex.Response.Content.ReadAsStringAsync().Result, "donkey");
                Assert.StartsWith(ex.Request.RequestUri.ToString(), mobileAppUriValidator.TableBaseUri);
                Assert.AreEqual("YOU SHALL NOT PASS.", ex.Response.ReasonPhrase);
            }

            // If no error message in the response, we'll use the
            // StatusDescription instead
            hijack.Response              = new HttpResponseMessage(HttpStatusCode.Unauthorized);
            hijack.Response.Content      = new StringContent("{\"error\":\"error message\",\"other\":\"donkey\"}", Encoding.UTF8, "application/json");
            hijack.Response.ReasonPhrase = "YOU SHALL NOT PASS.";
            hijack.SetResponseContent("{\"other\":\"donkey\"}");

            try
            {
                JToken response = await service.GetTable(collection).ReadAsync(query);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual("The request could not be completed.  (YOU SHALL NOT PASS.)", ex.Message);
            }
        }
        public async Task StandardRequestFormat()
        {
            string appUrl     = MobileAppUriValidator.DummyMobileApp;
            string collection = "tests";
            string query      = "$filter=id eq 12";

            TestHttpHandler      hijack  = new TestHttpHandler();
            IMobileServiceClient service = new MobileServiceClient(appUrl, hijack);

            service.CurrentUser = new MobileServiceUser("someUser");
            service.CurrentUser.MobileServiceAuthenticationToken = "Not rhubarb";

            hijack.SetResponseContent("[{\"id\":12,\"value\":\"test\"}]");
            JToken response = await service.GetTable(collection).ReadAsync(query);

            Assert.IsNotNull(hijack.Request.Headers.GetValues("X-ZUMO-INSTALLATION-ID").First());
            Assert.AreEqual("application/json", hijack.Request.Headers.Accept.First().MediaType);
            Assert.AreEqual("Not rhubarb", hijack.Request.Headers.GetValues("X-ZUMO-AUTH").First());
            Assert.IsNotNull(hijack.Request.Headers.GetValues("ZUMO-API-VERSION").First());

            // Workaround mono bug https://bugzilla.xamarin.com/show_bug.cgi?id=15128
            // use commented line below once the bug fix has hit stable channel for xamarin.iOS
            // string userAgent = hijack.Request.Headers.UserAgent.ToString();

            string userAgent = string.Join(" ", hijack.Request.Headers.GetValues("user-agent"));

            Assert.IsTrue(userAgent.Contains("ZUMO/3."));
            Assert.IsTrue(userAgent.Contains("version=3."));
        }
        public async Task MultipleHttpHandlerConstructor()
        {
            string          appUrl = MobileAppUriValidator.DummyMobileApp;
            TestHttpHandler hijack = new TestHttpHandler();

            string firstBeforeMessage  = "Message before 1";
            string firstAfterMessage   = "Message after 1";
            string secondBeforeMessage = "Message before 2";
            string secondAfterMessage  = "Message after 2";

            ComplexDelegatingHandler firstHandler  = new ComplexDelegatingHandler(firstBeforeMessage, firstAfterMessage);
            ComplexDelegatingHandler secondHandler = new ComplexDelegatingHandler(secondBeforeMessage, secondAfterMessage);

            IMobileServiceClient service =
                new MobileServiceClient(appUrl, handlers: new HttpMessageHandler[] { firstHandler, secondHandler, hijack });

            // Validate that handlers are properly chained
            Assert.AreSame(hijack, secondHandler.InnerHandler);
            Assert.AreSame(secondHandler, firstHandler.InnerHandler);

            // Clears the messages on the handler
            ComplexDelegatingHandler.ClearStoredMessages();

            // Set the handler to return an empty array
            hijack.SetResponseContent("[]");
            JToken response = await service.GetTable("foo").ReadAsync("bar");

            var storedMessages = new List <string>(ComplexDelegatingHandler.AllMessages);

            Assert.AreEqual(4, storedMessages.Count);
            Assert.AreEqual(firstBeforeMessage, storedMessages[0]);
            Assert.AreEqual(secondBeforeMessage, storedMessages[1]);
            Assert.AreEqual(secondAfterMessage, storedMessages[2]);
            Assert.AreEqual(firstAfterMessage, storedMessages[3]);
        }
        public async Task StandardRequestFormat()
        {
            string appUrl     = "http://www.test.com";
            string appKey     = "secret...";
            string collection = "tests";
            string query      = "$filter=id eq 12";

            TestHttpHandler      hijack  = new TestHttpHandler();
            IMobileServiceClient service = new MobileServiceClient(appUrl, appKey, hijack);

            service.CurrentUser = new MobileServiceUser("someUser");
            service.CurrentUser.MobileServiceAuthenticationToken = "Not rhubarb";

            hijack.SetResponseContent("[{\"id\":12,\"value\":\"test\"}]");
            JToken response = await service.GetTable(collection).ReadAsync(query);

            Assert.IsNotNull(hijack.Request.Headers.GetValues("X-ZUMO-INSTALLATION-ID").First());
            Assert.AreEqual("secret...", hijack.Request.Headers.GetValues("X-ZUMO-APPLICATION").First());
            Assert.AreEqual("application/json", hijack.Request.Headers.Accept.First().MediaType);
            Assert.AreEqual("Not rhubarb", hijack.Request.Headers.GetValues("X-ZUMO-AUTH").First());

            string userAgent = hijack.Request.Headers.UserAgent.ToString();

            Assert.IsTrue(userAgent.Contains("ZUMO/1.0"));
            Assert.IsTrue(userAgent.Contains("version=1.0.0.0"));
        }
        public async Task ReadAsync_WithRelativeUri_Generic()
        {
            var data = new[]
            {
                new 
                {
                    ServiceUri = "http://www.test.com", 
                    QueryUri = "/about?$filter=a eq b&$orderby=c", 
                    RequestUri = "http://www.test.com/about?$filter=a eq b&$orderby=c"
                },
                new 
                {
                    ServiceUri = "http://www.test.com/", 
                    QueryUri = "/about?$filter=a eq b&$orderby=c", 
                    RequestUri = "http://www.test.com/about?$filter=a eq b&$orderby=c"
                }
            };

            foreach (var item in data)
            {
                var hijack = new TestHttpHandler();
                hijack.SetResponseContent("[{\"col1\":\"Hey\"}]");
                IMobileServiceClient service = new MobileServiceClient(item.ServiceUri, "secret...", hijack);

                IMobileServiceTable<ToDo> table = service.GetTable<ToDo>();

                await table.ReadAsync<ToDo>(item.QueryUri);

                Assert.AreEqual("TT", hijack.Request.Headers.GetValues("X-ZUMO-FEATURES").First());
                Assert.AreEqual(item.RequestUri, hijack.Request.RequestUri.ToString());
            }
        }
        static DelegatingHandler CreateTestHttpHandler(string expectedUri, HttpMethod expectedMethod, string responseContent, HttpStatusCode?httpStatusCode = null, Uri location = null, string expectedRequestContent = null)
        {
            var handler = new TestHttpHandler
            {
                OnSendingRequest = message =>
                {
                    Assert.AreEqual(expectedUri, message.RequestUri.OriginalString, "The Http Uri used to send the request is different than expected.");
                    Assert.AreEqual(expectedMethod, message.Method, "The Http Method used to send the request is different than expected.");

                    if (expectedRequestContent != null)
                    {
                        Assert.AreEqual(expectedRequestContent, message.Content.ReadAsStringAsync().Result, "The Http request content is different than expected.");
                    }

                    return(Task.FromResult(message));
                }
            };

            if (responseContent != null)
            {
                handler.SetResponseContent(responseContent);
            }

            if (location != null)
            {
                handler.Response.Headers.Location = location;
            }

            if (httpStatusCode.HasValue)
            {
                handler.Response.StatusCode = httpStatusCode.Value;
            }

            return(handler);
        }
        public async Task ReadAsyncWithStringIdTypeAndStringIdResponseContent()
        {
            string[] testIdData = IdTestData.ValidStringIds.Concat(
                                  IdTestData.EmptyStringIds).Concat(
                                  IdTestData.InvalidStringIds).ToArray();

            foreach (string testId in testIdData)
            {
                TestHttpHandler hijack = new TestHttpHandler();

                // Make the testId JSON safe
                string jsonTestId = testId.Replace("\\", "\\\\").Replace("\"", "\\\"");

                hijack.SetResponseContent("[{\"id\":\"" + jsonTestId + "\",\"String\":\"Hey\"}]");
                IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

                IMobileServiceTable<StringIdType> table = service.GetTable<StringIdType>();

                IEnumerable<StringIdType> results = await table.ReadAsync();
                StringIdType[] items = results.ToArray();

                Assert.AreEqual(1, items.Count());
                Assert.AreEqual(testId, items[0].Id);
                Assert.AreEqual("Hey", items[0].String);
            }
        }
        public async Task InvokeApiAsync_DoesNotAppendApiPath_IfApiStartsWithSlash()
        {
            TestHttpHandler hijack  = new TestHttpHandler();
            var             service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);

            hijack.SetResponseContent("{\"id\":3}");

            await service.InvokeApiAsync <IntType>("/calculator/add?a=1&b=2", HttpMethod.Get, null);

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, "/calculator/add");
            Assert.AreEqual(hijack.Request.RequestUri.Query, "?a=1&b=2");
        }
        public async Task InvokeCustomAPIPost()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var     body     = "{\"test\" : \"one\"}";
            IntType expected = await service.InvokeApiAsync <string, IntType>("calculator/add", body);

            Assert.IsNotNull(hijack.Request.Content);
        }
        public async Task InvokeCustomAPIPostJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            JObject body     = JToken.Parse("{\"test\":\"one\"}") as JObject;
            JToken  expected = await service.InvokeApiAsync("calculator/add", body);

            Assert.IsNotNull(hijack.Request.Content);
        }
        public async Task DateUri()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            IMobileServiceClient client = new MobileServiceClient("http://www.test.com", null, hijack);
            IMobileServiceTable<DateExample> table = client.GetTable<DateExample>();

            hijack.Response = new HttpResponseMessage(HttpStatusCode.OK);
            hijack.SetResponseContent("[]");

            // Verify a full UTC date
            DateTime date = new DateTime(2009, 11, 21, 14, 22, 59, 860, DateTimeKind.Utc);
            await table.Where(b => b.Date == date).ToEnumerableAsync();
            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "$filter=(DateExampleDate eq datetime'2009-11-21T14:22:59.860Z')");

            // Local date is converted to UTC
            hijack.Response = new HttpResponseMessage(HttpStatusCode.OK);
            hijack.SetResponseContent("[]");
            date = new DateTime(2009, 11, 21, 14, 22, 59, 860, DateTimeKind.Local);
            await table.Where(b => b.Date == date).ToEnumerableAsync();
            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "Z')");
        }
        public async Task OrderByAscDescAsyncGeneric()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("[]");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable <StringType> table = service.GetTable <StringType>();
            List <StringType> people = await table.OrderBy(p => p.Id).ThenByDescending(p => p.String).ToListAsync();

            Assert.Contains(hijack.Request.RequestUri.ToString(), "StringType");
            Assert.Contains(hijack.Request.RequestUri.ToString(), "orderby=id,String desc");
        }
        public async Task InvokeCustomAPIGetJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            JToken expected = await service.InvokeApiAsync("calculator/add?a=1&b=2", HttpMethod.Get, null);

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, "/api/calculator/add");
            Assert.Contains(hijack.Request.RequestUri.Query, "?a=1&b=2");
            Assert.AreEqual(3, (int)expected["id"]);
        }
        public async Task ReadAsync_WithAbsoluteUri_Generic()
        {
            var hijack = new TestHttpHandler();
            hijack.SetResponseContent("[{\"col1\":\"Hey\"}]");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable<ToDo> table = service.GetTable<ToDo>();

            await table.ReadAsync<ToDo>("http://www.test.com/about?$filter=a eq b&$orderby=c");

            Assert.AreEqual("TT,LH", hijack.Request.Headers.GetValues("X-ZUMO-FEATURES").First());
            Assert.AreEqual("http://www.test.com/about?$filter=a eq b&$orderby=c", hijack.Request.RequestUri.ToString());
        }
        public async Task DateOffsetUri()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            IMobileServiceClient client = new MobileServiceClient("http://www.test.com", null, hijack);
            IMobileServiceTable<DateOffsetExample> table = client.GetTable<DateOffsetExample>();

            hijack.Response.StatusCode = HttpStatusCode.OK;
            hijack.SetResponseContent("[]");

            DateTimeOffset date = new DateTimeOffset(2009, 11, 21, 14, 22, 59, 860, TimeSpan.FromHours(-8));
            await table.Where(b => b.Date == date).ToEnumerableAsync();
            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "$filter=(DateOffsetExampleDate eq datetimeoffset'2009-11-21T14:22:59.8600000-08:00')");
        }
        public async Task DateOffsetUri()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            IMobileServiceClient client = new MobileServiceClient("http://www.test.com", null, hijack);
            IMobileServiceTable<DateOffsetExample> table = client.GetTable<DateOffsetExample>();

            hijack.Response = new HttpResponseMessage(HttpStatusCode.OK);
            hijack.SetResponseContent("[]");

            var date = DateTimeOffset.Parse("2009-11-21T06:22:59.8600000-08:00");
            await table.Where(b => b.Date == date).ToEnumerableAsync();
            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "$filter=(DateOffsetExampleDate eq datetimeoffset'2009-11-21T06:22:59.8600000-08:00')");
        }
        public async Task InvokeCustomAPISimple()
        {
            TestHttpHandler     hijack  = new TestHttpHandler();
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            hijack.SetResponseContent("{\"id\":3}");

            IntType expected = await service.InvokeApiAsync <IntType>("calculator/add?a=1&b=2");

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, "/api/calculator/add");
            Assert.Contains(hijack.Request.RequestUri.Query, "a=1&b=2");
            Assert.AreEqual(3, expected.Id);
        }
        public async Task LookupAsync()
        {
            TestHttpHandler      hijack  = new TestHttpHandler();
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            IMobileServiceTable  table   = service.GetTable("tests");

            hijack.SetResponseContent("{\"id\":12,\"String\":\"Hello\"}");

            JToken expected = await table.LookupAsync(12);

            Assert.AreEqual(12, (int)expected["id"]);
            Assert.AreEqual("Hello", (string)expected["String"]);
        }
        public async Task SkipAndTakeAsyncGeneric()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("[]");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable <StringType> table = service.GetTable <StringType>();
            List <StringType> people = await table.Skip(100).Take(10).ToListAsync();

            Assert.Contains(hijack.Request.RequestUri.ToString(), "StringType");
            Assert.Contains(hijack.Request.RequestUri.ToString(), "$skip=100");
            Assert.Contains(hijack.Request.RequestUri.ToString(), "$top=10");
        }
        public async Task DateOffsetUri()
        {
            TestHttpHandler      hijack = new TestHttpHandler();
            IMobileServiceClient client = new MobileServiceClient("http://www.test.com", null, hijack);
            IMobileServiceTable <DateOffsetExample> table = client.GetTable <DateOffsetExample>();

            hijack.Response.StatusCode = HttpStatusCode.OK;
            hijack.SetResponseContent("[]");

            DateTimeOffset date = new DateTimeOffset(2009, 11, 21, 14, 22, 59, 860, TimeSpan.FromHours(-8));
            await table.Where(b => b.Date == date).ToEnumerableAsync();

            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "$filter=(DateOffsetExampleDate eq datetimeoffset'2009-11-21T14:22:59.8600000-08:00')");
        }
        public async Task DateUri()
        {
            TestHttpHandler      hijack             = new TestHttpHandler();
            IMobileServiceClient client             = new MobileServiceClient("http://www.test.com", null, hijack);
            IMobileServiceTable <DateExample> table = client.GetTable <DateExample>();

            hijack.Response.StatusCode = HttpStatusCode.OK;
            hijack.SetResponseContent("[]");

            // Verify a full UTC date
            DateTime date = new DateTime(2009, 11, 21, 14, 22, 59, 860, DateTimeKind.Utc);
            await table.Where(b => b.Date == date).ToEnumerableAsync();

            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "$filter=(DateExampleDate eq datetime'2009-11-21T14:22:59.860Z')");

            // Local date is converted to UTC
            hijack.Response = new HttpResponseMessage(HttpStatusCode.OK);
            hijack.SetResponseContent("[]");
            date = new DateTime(2009, 11, 21, 14, 22, 59, 860, DateTimeKind.Local);
            await table.Where(b => b.Date == date).ToEnumerableAsync();

            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "Z')");
        }
        public async Task LookupAsyncGeneric()
        {
            TestHttpHandler                  hijack  = new TestHttpHandler();
            IMobileServiceClient             service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            IMobileServiceTable <StringType> table   = service.GetTable <StringType>();

            hijack.SetResponseContent("{\"id\":12,\"String\":\"Hello\"}");

            StringType expected = await table.LookupAsync(12);

            Assert.Contains(hijack.Request.RequestUri.ToString(), "12");
            Assert.AreEqual(12, expected.Id);
            Assert.AreEqual("Hello", expected.String);
        }
        public async Task InvokeCustomAPISimple()
        {
            TestHttpHandler       hijack  = new TestHttpHandler();
            MobileServiceClient   service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);
            MobileAppUriValidator mobileAppUriValidator = new MobileAppUriValidator(service);

            hijack.SetResponseContent("{\"id\":3}");

            IntType expected = await service.InvokeApiAsync <IntType>("calculator/add?a=1&b=2");

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, mobileAppUriValidator.GetApiUriPath("calculator/add"));
            Assert.AreEqual(hijack.Request.RequestUri.Query, "?a=1&b=2");
            Assert.AreEqual(3, expected.Id);
        }
        public async Task InvokeCustomAPIGetJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient   service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);
            MobileAppUriValidator mobileAppUriValidator = new MobileAppUriValidator(service);

            JToken expected = await service.InvokeApiAsync("calculator/add?a=1&b=2", HttpMethod.Get, null);

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, mobileAppUriValidator.GetApiUriPath("calculator/add"));
            Assert.AreEqual(hijack.Request.RequestUri.Query, "?a=1&b=2");
            Assert.AreEqual(3, (int)expected["id"]);
        }
        public async Task LookupAsyncGeneric()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            IMobileServiceTable<StringType> table = service.GetTable<StringType>();

            hijack.SetResponseContent("{\"id\":12,\"String\":\"Hello\"}");

            StringType expected = await table.LookupAsync(12);

            Assert.Contains(hijack.Request.RequestUri.ToString(), "12");
            Assert.AreEqual(12, expected.Id);
            Assert.AreEqual("Hello", expected.String);
        }
示例#28
0
        public async Task DateOffsetUri()
        {
            TestHttpHandler      hijack = new TestHttpHandler();
            IMobileServiceClient client = new MobileServiceClient("http://www.test.com", null, hijack);
            IMobileServiceTable <DateOffsetExample> table = client.GetTable <DateOffsetExample>();

            hijack.Response = new HttpResponseMessage(HttpStatusCode.OK);
            hijack.SetResponseContent("[]");

            var date = DateTimeOffset.Parse("2009-11-21T06:22:59.8600000-08:00");
            await table.Where(b => b.Date == date).ToEnumerableAsync();

            Assert.EndsWith(hijack.Request.RequestUri.ToString(), "$filter=(DateOffsetExampleDate eq datetimeoffset'2009-11-21T06:22:59.8600000-08:00')");
        }
        public async Task InvokeCustomAPIGetWithParams()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);

            var myParams = new Dictionary <string, string>()
            {
                { "a", "1" }, { "b", "2" }
            };
            IntType expected = await service.InvokeApiAsync <IntType>("calculator/add", HttpMethod.Get, myParams);

            Assert.AreEqual(hijack.Request.RequestUri.Query, "?a=1&b=2");
        }
        public async Task InvokeCustomAPIGetWithODataParamsJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, hijack);

            var myParams = new Dictionary <string, string>()
            {
                { "$select", "one,two" }
            };
            JToken expected = await service.InvokeApiAsync("calculator/add", HttpMethod.Get, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?%24select=one%2Ctwo");
        }
        public async Task UpdateAsync()
        {
            TestHttpHandler      hijack  = new TestHttpHandler();
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            IMobileServiceTable  table   = service.GetTable("tests");

            JObject obj = JToken.Parse("{\"id\":12,\"value\":\"new\"}") as JObject;

            hijack.SetResponseContent("{\"id\":12,\"value\":\"new\",\"other\":\"123\"}");
            JToken newObj = await table.UpdateAsync(obj);

            Assert.AreEqual("123", (string)newObj["other"]);
            Assert.AreNotEqual(newObj, obj);
            Assert.Contains(hijack.Request.RequestUri.ToString(), "tests");
        }
        public async Task ReadAsyncWithStringIdTypeAndNullIdResponseContent()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("[{\"id\":null,\"String\":\"Hey\"}]");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable<StringIdType> table = service.GetTable<StringIdType>();

            IEnumerable<StringIdType> results = await table.ReadAsync();
            StringIdType[] items = results.ToArray();

            Assert.AreEqual(1, items.Count());
            Assert.AreEqual(null, items[0].Id);
            Assert.AreEqual("Hey", items[0].String);
        }
        public async Task InvokeCustomAPIGetWithParamsJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var myParams = new Dictionary <string, string>()
            {
                { "a", "1" }, { "b", "2" }
            };
            JToken expected = await service.InvokeApiAsync("calculator/add", HttpMethod.Get, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?a=1&b=2");
        }
        public async Task InvokeCustomAPIGetWithODataParams()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var myParams = new Dictionary <string, string>()
            {
                { "$select", "one,two" }, { "$take", "1" }
            };
            IntType expected = await service.InvokeApiAsync <IntType>("calculator/add", HttpMethod.Get, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?%24select=one%2Ctwo&%24take=1");
        }
        public async Task InvokeCustomAPIPostJTokenNullPrimative()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            hijack.OnSendingRequest = async(HttpRequestMessage request) =>
            {
                string content = await request.Content.ReadAsStringAsync();

                Assert.AreEqual(content, "null");
            };

            JToken expected = await service.InvokeApiAsync("calculator/add", new JValue((object)null));
        }
        public async Task InsertAsyncGeneric()
        {
            TestHttpHandler                  hijack  = new TestHttpHandler();
            IMobileServiceClient             service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            IMobileServiceTable <StringType> table   = service.GetTable <StringType>();

            StringType obj = new StringType();

            obj.String = "new";

            hijack.SetResponseContent("{\"id\":12,\"value\":\"new\"}");
            await table.InsertAsync(obj);

            Assert.AreEqual(12, obj.Id);
            Assert.Contains(hijack.Request.RequestUri.ToString(), "StringType");
        }
        [AsyncTestMethod] // this is the default buggy behavior that we've already shipped
        public async Task ReadAsync_ModifiesStringId_IfItContainsIsoDateValue()
        {
            var hijack = new TestHttpHandler();
            hijack.SetResponseContent(@"[{
                                        ""id"": ""2014-01-29T23:01:33.444Z"",
                                        ""__createdAt"": ""2014-01-29T23:01:33.444Z""
                                        }]");

            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            IMobileServiceTable<ToDoWithSystemPropertiesType> table = service.GetTable<ToDoWithSystemPropertiesType>();

            IEnumerable<ToDoWithSystemPropertiesType> results = await table.ReadAsync();
            ToDoWithSystemPropertiesType item = results.First();

            Assert.AreEqual(item.Id, "01/29/2014 23:01:33");
            Assert.AreEqual(item.CreatedAt, DateTime.Parse("2014-01-29T23:01:33.444Z"));
        }
        public async Task WhereAsyncGeneric()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("[{\"id\":12,\"String\":\"Hey\"}]");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable <StringType> table = service.GetTable <StringType>();
            List <StringType> people = await table.Where(p => p.Id == 12).ToListAsync();

            Assert.Contains(hijack.Request.RequestUri.ToString(), "StringType");
            Assert.Contains(hijack.Request.RequestUri.ToString(), "$filter=(id eq 12)");

            Assert.AreEqual(1, people.Count);
            Assert.AreEqual(12, people[0].Id);
            Assert.AreEqual("Hey", people[0].String);
        }
        public async Task ReadAsyncGeneric()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("[{\"id\":12,\"String\":\"Hey\"}]");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable<StringType> table = service.GetTable<StringType>();

            IEnumerable<StringType> results = await table.ReadAsync();
            StringType[] people = results.Cast<StringType>().ToArray();

            Assert.Contains(hijack.Request.RequestUri.ToString(), "StringType");

            Assert.AreEqual(1, people.Count());
            Assert.AreEqual(12, people[0].Id);
            Assert.AreEqual("Hey", people[0].String);
        }
        public async Task InvokeCustomAPIPostWithBodyJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var myParams = new Dictionary <string, string>()
            {
                { "a", "1" }, { "b", "2" }
            };
            JObject body     = JToken.Parse("{\"test\":\"one\"}") as JObject;
            JToken  expected = await service.InvokeApiAsync("calculator/add", body, HttpMethod.Post, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?a=1&b=2");
            Assert.IsNotNull(hijack.Request.Content);
        }
        public async Task ReadAsync()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"Count\":1, People: [{\"Id\":\"12\", \"String\":\"Hey\"}] }");

            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            IMobileServiceTable table = service.GetTable("tests");
            JToken people = await table.ReadAsync("$filter=id eq 12");

            Assert.Contains(hijack.Request.RequestUri.ToString(), "tests");
            Assert.Contains(hijack.Request.RequestUri.ToString(), "$filter=id eq 12");

            Assert.AreEqual(1, (int)people["Count"]);
            Assert.AreEqual(12, (int)people["People"][0]["Id"]);
            Assert.AreEqual("Hey", (string)people["People"][0]["String"]);
        }
        [AsyncTestMethod] // user has to set the serializer setting to round trip dates in string fields correctly
        public async Task ReadAsync_DoesNotModifyStringId_IfItContainsIsoDateValueAndSerializerIsConfiguredToNotParseDates()
        {
            var hijack = new TestHttpHandler();
            hijack.SetResponseContent(@"[{
                                        ""id"": ""2014-01-29T23:01:33.444Z"",
                                        ""__createdAt"": ""2014-01-29T23:01:33.444Z""
                                        }]");

            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            service.SerializerSettings.DateParseHandling = DateParseHandling.None;
            IMobileServiceTable<ToDoWithSystemPropertiesType> table = service.GetTable<ToDoWithSystemPropertiesType>();

            IEnumerable<ToDoWithSystemPropertiesType> results = await table.ReadAsync();
            ToDoWithSystemPropertiesType item = results.First();

            Assert.AreEqual(item.Id, "2014-01-29T23:01:33.444Z");
            Assert.AreEqual(item.CreatedAt, DateTime.Parse("2014-01-29T23:01:33.444Z"));
        }
        public async Task SingleHttpHandlerConstructor()
        {
            TestHttpHandler hijack = new TestHttpHandler();

            IMobileServiceClient service =
                new MobileServiceClient(MobileAppUriValidator.DummyMobileApp, handlers: hijack);
            MobileAppUriValidator mobileAppUriValidator = new MobileAppUriValidator(service);

            // Ensure properties are copied over
            Assert.AreEqual(MobileAppUriValidator.DummyMobileApp, service.MobileAppUri.ToString());

            // Set the handler to return an empty array
            hijack.SetResponseContent("[]");
            JToken response = await service.GetTable("foo").ReadAsync("bar");

            // Verify the handler was in the loop
            Assert.StartsWith(hijack.Request.RequestUri.ToString(), mobileAppUriValidator.TableBaseUri);
        }
        public async Task SingleHttpHandlerConstructor()
        {
            string appUrl = "http://www.test.com/";
            string appKey = "secret...";
            TestHttpHandler hijack = new TestHttpHandler();

            IMobileServiceClient service =
                new MobileServiceClient(new Uri(appUrl), appKey, hijack);

            // Ensure properties are copied over
            Assert.AreEqual(appUrl, service.ApplicationUri.ToString());
            Assert.AreEqual(appKey, service.ApplicationKey);

            // Set the handler to return an empty array
            hijack.SetResponseContent("[]");
            JToken response = await service.GetTable("foo").ReadAsync("bar");

            // Verify the handler was in the loop
            Assert.StartsWith(hijack.Request.RequestUri.ToString(), appUrl);
        }
        public async Task ReadAsyncWithUserParameters()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"Count\":1, People: [{\"Id\":\"12\", \"String\":\"Hey\"}] }");
            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var userDefinedParameters = new Dictionary<string, string>() { { "tags", "#pizza #beer" } };

            IMobileServiceTable table = service.GetTable("tests");

            JToken people = await table.ReadAsync("$filter=id eq 12", userDefinedParameters);

            Assert.Contains(hijack.Request.RequestUri.ToString(), "tests");
            Assert.Contains(hijack.Request.RequestUri.AbsoluteUri, "tags=%23pizza%20%23beer");
            Assert.Contains(hijack.Request.RequestUri.ToString(), "$filter=id eq 12");

            Assert.AreEqual(1, (int)people["Count"]);
            Assert.AreEqual(12, (int)people["People"][0]["Id"]);
            Assert.AreEqual("Hey", (string)people["People"][0]["String"]);
        }
        public async Task ReadAsync_WithAbsoluteUri_Generic()
        {
            var data = new[]
            {
                new 
                {
                    ServiceUri = MobileAppUriValidator.DummyMobileApp, 
                    Result = MobileAppUriValidator.DummyMobileApp + "about?$filter=a eq b&$orderby=c"
                },
                new 
                {
                    ServiceUri = MobileAppUriValidator.DummyMobileAppWithoutTralingSlash, 
                    Result = MobileAppUriValidator.DummyMobileAppWithoutTralingSlash + "/about?$filter=a eq b&$orderby=c"
                },
                new 
                {
                    ServiceUri = MobileAppUriValidator.DummyMobileAppUriWithFolder, 
                    Result = MobileAppUriValidator.DummyMobileAppUriWithFolder + "about?$filter=a eq b&$orderby=c"
                },
                new 
                {
                    ServiceUri = MobileAppUriValidator.DummyMobileAppUriWithFolderWithoutTralingSlash, 
                    Result = MobileAppUriValidator.DummyMobileAppUriWithFolderWithoutTralingSlash + "/about?$filter=a eq b&$orderby=c"
                },
            };

            foreach (var item in data)
            {
                var hijack = new TestHttpHandler();
                hijack.SetResponseContent("[{\"col1\":\"Hey\"}]");
                IMobileServiceClient service = new MobileServiceClient(item.ServiceUri, hijack);
                MobileAppUriValidator mobileAppUriValidator = new MobileAppUriValidator(service);

                IMobileServiceTable<ToDo> table = service.GetTable<ToDo>();

                await table.ReadAsync<ToDo>(item.Result);

                Assert.AreEqual("TT,LH", hijack.Request.Headers.GetValues("X-ZUMO-FEATURES").First());
                Assert.AreEqual(item.Result, hijack.Request.RequestUri.ToString());
            }
        }
        public static DelegatingHandler CreateTestHttpHandler(string expectedUri, HttpMethod expectedMethod, string responseContent, HttpStatusCode? httpStatusCode = null, Uri location = null, string expectedRequestContent = null)
        {
            var handler = new TestHttpHandler
            {
                OnSendingRequest = message =>
                {
                    Assert.AreEqual(expectedUri, message.RequestUri.OriginalString, "The Http Uri used to send the request is different than expected.");
                    Assert.AreEqual(expectedMethod, message.Method, "The Http Method used to send the request is different than expected.");

                    if (expectedRequestContent != null)
                    {
                        var messageContent = Regex.Replace(message.Content.ReadAsStringAsync().Result, @"\s+", String.Empty);
                        expectedRequestContent = Regex.Replace(expectedRequestContent, @"\s+", String.Empty);
                        Assert.AreEqual(expectedRequestContent, messageContent, "The Http request content is different than expected.");
                    }

                    return Task.FromResult(message);
                }
            };

            if (responseContent != null)
            {
                handler.SetResponseContent(responseContent);
            }
            else
            {
                handler.Response = new HttpResponseMessage(HttpStatusCode.OK);
            }

            if (location != null)
            {
                handler.Response.Headers.Location = location;
            }

            if (httpStatusCode.HasValue)
            {
                handler.Response.StatusCode = httpStatusCode.Value;
            }
            return handler;
        }
        public async Task ReadAsyncWithNonStringAndNonIntIdResponseContent()
        {
            object[] testIdData = IdTestData.NonStringNonIntValidJsonIds;

            foreach (object testId in testIdData)
            {
                string stringTestId = testId.ToString().ToLower();

                TestHttpHandler hijack = new TestHttpHandler();
                hijack.SetResponseContent("[{\"id\":" + stringTestId + ",\"String\":\"Hey\"}]");
                IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

                IMobileServiceTable table = service.GetTable("someTable");

                JToken results = await table.ReadAsync("");
                JToken[] items = results.ToArray();

                Assert.AreEqual(1, items.Count());
                Assert.AreEqual(testId, items[0]["id"].ToObject(testId.GetType()));
                Assert.AreEqual("Hey", (string)items[0]["String"]);
            }
        }
        public async Task ReadAsyncWithIntIdResponseContent()
        {
            long[] testIdData = IdTestData.ValidIntIds.Concat(
                                 IdTestData.InvalidIntIds).ToArray();

            foreach (long testId in testIdData)
            {
                string stringTestId = testId.ToString();

                TestHttpHandler hijack = new TestHttpHandler();
                hijack.SetResponseContent("[{\"id\":" + stringTestId + ",\"String\":\"Hey\"}]");
                IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

                IMobileServiceTable table = service.GetTable("someTable");

                JToken results = await table.ReadAsync("");
                JToken[] items = results.ToArray();

                Assert.AreEqual(1, items.Count());
                Assert.AreEqual(testId, (long)items[0]["id"]);
                Assert.AreEqual("Hey", (string)items[0]["String"]);
            }
        }
        public async Task ReadAsyncWithStringIdTypeAndNonStringIdResponseContent()
        {
            object[] testIdData = IdTestData.ValidIntIds.Concat(
                                  IdTestData.InvalidIntIds).Cast<object>().Concat(
                                  IdTestData.NonStringNonIntValidJsonIds).ToArray();

            foreach (object testId in testIdData)
            {
                string stringTestId = testId.ToString().ToLower();

                TestHttpHandler hijack = new TestHttpHandler();
                hijack.SetResponseContent("[{\"id\":" + stringTestId + ",\"String\":\"Hey\"}]");
                IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

                IMobileServiceTable<StringIdType> table = service.GetTable<StringIdType>();

                IEnumerable<StringIdType> results = await table.ReadAsync();
                StringIdType[] items = results.ToArray();

                Assert.AreEqual(1, items.Count());
                Assert.AreEqual(testId.ToString(), items[0].Id);
                Assert.AreEqual("Hey", items[0].String);
            }
        }
        public async Task InvokeApiTypedOverloads_HasCorrectFeaturesHeader()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual("AT", request.Headers.GetValues("X-ZUMO-FEATURES").First());
                return Task.FromResult(request);
            };

            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            hijack.SetResponseContent("{\"id\":3}");
            await service.InvokeApiAsync<IntType>("apiName");

            hijack.SetResponseContent("{\"id\":3}");
            await service.InvokeApiAsync<IntType, IntType>("apiName", new IntType { Id = 1 });

            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual("AT,QS", request.Headers.GetValues("X-ZUMO-FEATURES").First());
                return Task.FromResult(request);
            };

            var dic = new Dictionary<string, string> { { "a", "b" } };
            hijack.SetResponseContent("{\"id\":3}");
            await service.InvokeApiAsync<IntType>("apiName", HttpMethod.Get, dic);

            hijack.SetResponseContent("{\"hello\":\"world\"}");
            await service.InvokeApiAsync<IntType, IntType>("apiName", new IntType { Id = 1 }, HttpMethod.Put, dic);
        }
        public async Task InvokeCustomAPIPostWithBodyJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var myParams = new Dictionary<string, string>() { { "a", "1" }, { "b", "2" } };
            JObject body = JToken.Parse("{\"test\":\"one\"}") as JObject;
            JToken expected = await service.InvokeApiAsync("calculator/add", body, HttpMethod.Post, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?a=1&b=2");
            Assert.IsNotNull(hijack.Request.Content);
        }
        public async Task InvokeCustomAPIGetWithODataParamsJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var myParams = new Dictionary<string, string>() { { "$select", "one,two" } };
            JToken expected = await service.InvokeApiAsync("calculator/add", HttpMethod.Get, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?%24select=one%2Ctwo");
        }
        public async Task InvokeCustomAPIGetWithParams()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            var myParams = new Dictionary<string, string>() { { "a", "1" }, { "b", "2" } };
            IntType expected = await service.InvokeApiAsync<IntType>("calculator/add", HttpMethod.Get, myParams);

            Assert.Contains(hijack.Request.RequestUri.Query, "?a=1&b=2");
        }
        public async Task InvokeCustomAPIGetJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            JToken expected = await service.InvokeApiAsync("calculator/add?a=1&b=2", HttpMethod.Get, null);

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, "/api/calculator/add");
            Assert.Contains(hijack.Request.RequestUri.Query, "?a=1&b=2");
            Assert.AreEqual(3, (int)expected["id"]);
        }
        public async Task InvokeCustomAPIPostJTokenNullPrimative()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            hijack.OnSendingRequest = async request =>
            {
                string content = await request.Content.ReadAsStringAsync();
                Assert.AreEqual(content, "null");

                return request;
            };

            JToken expected = await service.InvokeApiAsync("calculator/add", new JValue((object)null));
        }
        public async Task InvokeCustomAPIPostJToken()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            hijack.SetResponseContent("{\"id\":3}");
            MobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            JObject body = JToken.Parse("{\"test\":\"one\"}") as JObject;
            JToken expected = await service.InvokeApiAsync("calculator/add", body);
            Assert.IsNotNull(hijack.Request.Content);
        }
        private async Task ValidateFeaturesHeader(string expectedFeaturesHeader, Func<IMobileServiceClient, Task> operation)
        {
            TestHttpHandler hijack = new TestHttpHandler();
            bool validationDone = false;
            hijack.OnSendingRequest = (request) =>
            {
                Assert.AreEqual(expectedFeaturesHeader, request.Headers.GetValues("X-ZUMO-FEATURES").First());
                validationDone = true;
                return Task.FromResult(request);
            };

            IMobileServiceClient service = new MobileServiceClient("http://www.test.com", "secret...", hijack);

            hijack.SetResponseContent("{\"id\":3}");
            await operation(service);
            Assert.IsTrue(validationDone);
        }
        public async Task MultipleHttpHandlerConstructor()
        {
            string appUrl = "http://www.test.com/";
            string appKey = "secret...";
            TestHttpHandler hijack = new TestHttpHandler();

            string firstBeforeMessage = "Message before 1";
            string firstAfterMessage = "Message after 1";
            string secondBeforeMessage = "Message before 2";
            string secondAfterMessage = "Message after 2";

            ComplexDelegatingHandler firstHandler = new ComplexDelegatingHandler(firstBeforeMessage, firstAfterMessage);
            ComplexDelegatingHandler secondHandler = new ComplexDelegatingHandler(secondBeforeMessage, secondAfterMessage);

            IMobileServiceClient service =
                new MobileServiceClient(new Uri(appUrl), appKey, firstHandler, secondHandler, hijack);

            // Validate that handlers are properly chained
            Assert.AreSame(hijack, secondHandler.InnerHandler);
            Assert.AreSame(secondHandler, firstHandler.InnerHandler);

            // Clears the messages on the handler
            ComplexDelegatingHandler.ClearStoredMessages();

            // Set the handler to return an empty array
            hijack.SetResponseContent("[]");
            JToken response = await service.GetTable("foo").ReadAsync("bar");

            var storedMessages = new List<string>(ComplexDelegatingHandler.AllMessages);
            Assert.AreEqual(4, storedMessages.Count);
            Assert.AreEqual(firstBeforeMessage, storedMessages[0]);
            Assert.AreEqual(secondBeforeMessage, storedMessages[1]);
            Assert.AreEqual(secondAfterMessage, storedMessages[2]);
            Assert.AreEqual(firstAfterMessage, storedMessages[3]);
        }
        public async Task InvokeApiAsync_DoesNotAppendApiPath_IfApiStartsWithSlash()
        {
            TestHttpHandler hijack = new TestHttpHandler();
            var service = new MobileServiceClient("http://www.test.com", "secret...", hijack);
            hijack.SetResponseContent("{\"id\":3}");

            await service.InvokeApiAsync<IntType>("/calculator/add?a=1&b=2", HttpMethod.Get, null);

            Assert.AreEqual(hijack.Request.RequestUri.LocalPath, "/calculator/add");
            Assert.Contains(hijack.Request.RequestUri.Query, "a=1&b=2");
        }