コード例 #1
0
        public void XmlDownloadTest()
        {
            UTF8Encoding encoding = new UTF8Encoding();

            byte[]       contentAsBytes       = encoding.GetBytes(TestResources.CharacterSheet);
            MemoryStream sourceResponseStream = new MemoryStream();

            sourceResponseStream.Write(contentAsBytes, 0, contentAsBytes.Length);
            sourceResponseStream.Position = 0;
            XmlDocument contentAsXml = new XmlDocument();

            contentAsXml.Load(new StringReader(TestResources.CharacterSheet));

            Mock <HttpWebRequest>        mockRequest  = MockManager.Mock <HttpWebRequest>(Constructor.NotMocked);
            MockObject <HttpWebResponse> mockResponse = MockManager.MockObject <HttpWebResponse>(Constructor.Mocked);

            mockResponse.ExpectAndReturn("GetResponseStream", sourceResponseStream);
            mockRequest.ExpectAndReturn("GetResponse", mockResponse.Object);

            HttpWebService service = new HttpWebService();
            XmlDocument    result  = service.DownloadXml("http://www.battleclinic.com");

            StringAssert.AreEqualIgnoringCase(contentAsXml.ToString(), result.ToString());

            sourceResponseStream.Close();
        }
コード例 #2
0
    public void WhenOrdering_ThenSucceeds()
    {
        var config = HttpHostConfiguration.Create();

        config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

        using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", config))
        {
            var client = new HttpClient("http://localhost:20000");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

            var context = new DataServiceContext(new Uri("http://localhost:20000"));
            // We always specify how many to take, to be explicit.
            var query = context.CreateQuery <Product>("products")
                        .Where(x => x.Owner.Name == "kzu")
                        .OrderBy(x => x.Id)
                        .ThenBy(x => x.Owner.Id)
                        .Skip(1)
                        .Take(1);

            //var uri = ((DataServiceQuery)query).RequestUri;
            var uri = new Uri(((DataServiceQuery)query).RequestUri.ToString().Replace("()?$", "?$"));
            Console.WriteLine(uri);
            var response = client.Get(uri);

            Assert.True(response.IsSuccessStatusCode, "Failed : " + response.StatusCode + " " + response.ReasonPhrase);

            var products = new JsonSerializer().Deserialize <List <Product> >(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

            Assert.Equal(1, products.Count);
        }
    }
コード例 #3
0
        public void ImageAsyncDownloadTest()
        {
            MemoryStream sourceResponseStream = new MemoryStream();

            TestResources.testimage.Save(sourceResponseStream, ImageFormat.Png);
            sourceResponseStream.Position = 0;

            Mock <HttpWebRequest>        mockRequest  = MockManager.Mock <HttpWebRequest>(Constructor.NotMocked);
            MockObject <HttpWebResponse> mockResponse = MockManager.MockObject <HttpWebResponse>(Constructor.Mocked);

            mockResponse.ExpectAndReturn("GetResponseStream", sourceResponseStream);
            mockRequest.ExpectAndReturn("GetResponse", mockResponse.Object);

            _imageAsyncCompletedTrigger = new AutoResetEvent(false);
            HttpWebService service = new HttpWebService();

            service.DownloadImageAsync("http://www.battleclinic.com", ImageAysncDownloadTestCompleted, null);
            _imageAsyncCompletedTrigger.WaitOne();
            if (_imageAsyncDownloadResult.Error != null)
            {
                Assert.Fail(_imageAsyncDownloadResult.Error.Message);
            }
            Assert.IsNotNull(_imageAsyncDownloadResult.Result, "No image retrieved");
            _imageAsyncCompletedTrigger = null;
            _imageAsyncDownloadResult   = null;
        }
コード例 #4
0
        public void ImageDownloadExceptionTest()
        {
            UTF8Encoding encoding = new UTF8Encoding();

            byte[]       contentAsBytes       = encoding.GetBytes("This is not image data");
            MemoryStream sourceResponseStream = new MemoryStream();

            sourceResponseStream.Write(contentAsBytes, 0, contentAsBytes.Length);
            sourceResponseStream.Position = 0;

            Mock <HttpWebRequest>        mockRequest  = MockManager.Mock <HttpWebRequest>(Constructor.NotMocked);
            MockObject <HttpWebResponse> mockResponse = MockManager.MockObject <HttpWebResponse>(Constructor.Mocked);

            mockResponse.ExpectAndReturn("GetResponseStream", sourceResponseStream);
            mockRequest.ExpectAndReturn("GetResponse", mockResponse.Object);

            HttpWebService service = new HttpWebService();

            try
            {
                service.DownloadImage("http://www.battleclinic.com");
                Assert.Fail("Expected exception was not thrown");
            }
            catch (HttpWebServiceException ex)
            {
                Assert.AreEqual(HttpWebServiceExceptionStatus.ImageException, ex.Status);
            }
            finally
            {
                sourceResponseStream.Close();
            }
        }
コード例 #5
0
        public void StringAsyncDownloadTest()
        {
            UTF8Encoding encoding = new UTF8Encoding();

            byte[]       contentAsBytes       = encoding.GetBytes(TestResources.CharacterSheet);
            MemoryStream sourceResponseStream = new MemoryStream();

            sourceResponseStream.Write(contentAsBytes, 0, contentAsBytes.Length);
            sourceResponseStream.Position = 0;
            Mock <HttpWebRequest>        mockRequest  = MockManager.Mock <HttpWebRequest>(Constructor.NotMocked);
            MockObject <HttpWebResponse> mockResponse = MockManager.MockObject <HttpWebResponse>(Constructor.Mocked);

            mockResponse.ExpectAndReturn("GetResponseStream", sourceResponseStream);
            mockRequest.ExpectAndReturn("GetResponse", mockResponse.Object);

            _stringAsyncCompletedTrigger = new AutoResetEvent(false);
            HttpWebService service = new HttpWebService();

            service.DownloadStringAsync("http://www.battleclinic.com", StringAysncDownloadTestCompleted, null);
            _stringAsyncCompletedTrigger.WaitOne();
            if (_stringAsyncDownloadResult.Error != null)
            {
                Assert.Fail(_stringAsyncDownloadResult.Error.Message);
            }
            Assert.AreEqual(TestResources.CharacterSheet, _stringAsyncDownloadResult.Result);
            sourceResponseStream.Close();
            _stringAsyncCompletedTrigger = null;
            _stringAsyncDownloadResult   = null;
        }
コード例 #6
0
	public void WhenOrdering_ThenSucceeds()
	{
		var config = HttpHostConfiguration.Create();
		config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

		using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", config))
		{
			var client = new HttpClient("http://localhost:20000");
			client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

			var context = new DataServiceContext(new Uri("http://localhost:20000"));
			// We always specify how many to take, to be explicit.
			var query = context.CreateQuery<Product>("products")
				.Where(x => x.Owner.Name == "kzu")
				.OrderBy(x => x.Id)
				.ThenBy(x => x.Owner.Id)
				.Skip(1)
				.Take(1);

			//var uri = ((DataServiceQuery)query).RequestUri;
			var uri = new Uri(((DataServiceQuery)query).RequestUri.ToString().Replace("()?$", "?$"));
			Console.WriteLine(uri);
			var response = client.Get(uri);

			Assert.True(response.IsSuccessStatusCode, "Failed : " + response.StatusCode + " " + response.ReasonPhrase);

			var products = new JsonSerializer().Deserialize<List<Product>>(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

			Assert.Equal(1, products.Count);
		}
	}
コード例 #7
0
        public void UrlExceptionTests()
        {
            HttpWebService service = new HttpWebService();

            try
            {
                service.DownloadString(null);
                Assert.Fail("Expected ArgumentException for null url");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(ArgumentException), ex, "null url");
            }
            try
            {
                service.DownloadString(string.Empty);
                Assert.Fail("Expected ArgumentException for empty string");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(ArgumentException), ex, "empty url");
            }
            try
            {
                service.DownloadString("not a url");
                Assert.Fail("Expected ArgumentException for invalid url");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(typeof(ArgumentException), ex, "invalid url");
            }
        }
コード例 #8
0
        public void WhenQueryingWithExtraCriteria_ThenPopulatesMatchingEntities()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var products = client.Query <Product>(resourceName, new { search = "kzu" }).ToList();

                Assert.True(products.All(x => x.Owner.Name == "kzu"));
            }
        }
コード例 #9
0
        public void WhenQueryingAndNoMatches_ThenReturnsEmptyEnumerable()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var products = client.Query <Product>(resourceName).Where(x => x.Owner.Name == "foo").ToList();

                Assert.Equal(0, products.Count);
            }
        }
コード例 #10
0
        public void IsValidURLTests()
        {
            string errorMsg;

            Assert.IsFalse(HttpWebService.IsValidURL(null, out errorMsg), "Null URL string is not valid");
            Assert.IsFalse(HttpWebService.IsValidURL(string.Empty, out errorMsg), "Empty string is not valid");
            Assert.IsFalse(HttpWebService.IsValidURL("This is not a URL", out errorMsg), "Simple text is not valid");
            Assert.IsFalse(HttpWebService.IsValidURL("ftp://FTPIsNotSupported", out errorMsg), "Incorrect scheme");
            Assert.IsTrue(HttpWebService.IsValidURL("http://battleclinic.com", out errorMsg), "URL is valid");
        }
コード例 #11
0
        public void WhenDeleteFails_ThenThrows()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client = new HttpEntityClient(ws.BaseUri);

                var exception = Assert.Throws <HttpEntityException>(() => client.Delete(resourceName, "25"));

                Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
            }
        }
コード例 #12
0
		public void WhenDeleteFails_ThenThrows()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);

				var exception = Assert.Throws<HttpEntityException>(() => client.Delete<Product>("25"));

				Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
			}
		}
コード例 #13
0
		public void WhenPostFails_ThenThrows()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);

				var exception = Assert.Throws<HttpEntityException>(() => client.Post<Product>(null));

				Assert.Equal(HttpStatusCode.InternalServerError, exception.StatusCode);
			}
		}
コード例 #14
0
        public void WhenPutFails_ThenThrows()
        {
            using (var ws = new HttpWebService <HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client = new HttpEntityConventionClient(ws.BaseUri);
                // We're putting a null which is invalid.
                var exception = Assert.Throws <HttpEntityException>(() => client.Put <Product>("25", null));

                Assert.Equal(HttpStatusCode.InternalServerError, exception.StatusCode);
            }
        }
コード例 #15
0
        public void WhenPostFails_ThenThrows()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client = new HttpEntityClient(ws.BaseUri);

                var exception = Assert.Throws <HttpEntityException>(() => client.Post <Product>(resourceName, null));

                Assert.Equal(HttpStatusCode.InternalServerError, exception.StatusCode);
            }
        }
コード例 #16
0
        public void WhenSkipTakeOnly_ThenReturnsSingleElement()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var products = client.Query <Product>(resourceName).Skip(1).Take(1).ToList();

                Assert.Equal(1, products.Count);
                Assert.Equal(2, products[0].Id);
            }
        }
コード例 #17
0
        public void WhenTryGetFails_ThenReturnsResponse()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var product  = default(Product);
                var response = client.TryGet <Product>(resourceName, "25", out product);

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
                Assert.Null(product);
            }
        }
コード例 #18
0
        public void WhenGetting_ThenRetrieves()
        {
            using (var ws = new HttpWebService <HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client = new HttpEntityConventionClient(ws.BaseUri);

                var product = client.Get <Product>("1");

                Assert.NotNull(product);
                Assert.Equal("kzu", product.Owner.Name);
            }
        }
コード例 #19
0
        public void WhenQuerying_ThenPopulatesMatchingEntities()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var ids      = client.Query <Product>(resourceName).Where(x => x.Owner.Name == "kzu").Select(x => x.Id).ToList();
                var products = client.Query <Product>(resourceName).Where(x => x.Owner.Name == "kzu").ToList();

                Assert.Equal(2, ids.Count);
                Assert.True(products.All(x => x.Owner.Name == "kzu"));
            }
        }
コード例 #20
0
        public void WhenDeletingEntity_ThenGetFails()
        {
            using (var ws = new HttpWebService <HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client = new HttpEntityConventionClient(ws.BaseUri);

                client.Delete <Product>("1");
                var exception = Assert.Throws <HttpEntityException>(() => client.Get <Product>("25"));

                Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
            }
        }
コード例 #21
0
		public void WhenGetting_ThenRetrieves()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);

				var product = client.Get<Product>("1");

				Assert.NotNull(product);
				Assert.Equal("kzu", product.Owner.Name);
			}
		}
コード例 #22
0
        public void WhenGettingWithoutId_ThenRetrieves()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client = new HttpEntityClient(ws.BaseUri);

                var product = client.Get <Product>(resourceName + "/latest");

                Assert.NotNull(product);
                Assert.Equal("vga", product.Owner.Name);
            }
        }
コード例 #23
0
		public void WhenGettingWithoutId_ThenRetrieves()
		{
			using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityClient(ws.BaseUri);

				var product = client.Get<Product>(resourceName + "/latest");

				Assert.NotNull(product);
				Assert.Equal("vga", product.Owner.Name);
			}
		}
コード例 #24
0
        public void WhenOrderByTake_ThenReturnsOrdered()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var products = client.Query <Product>(resourceName).OrderBy(x => x.Title).Take(2).ToList();

                Assert.Equal(2, products.Count);
                Assert.Equal("A", products[0].Title);
                Assert.Equal("B", products[1].Title);
            }
        }
コード例 #25
0
		public void WhenDeletingEntity_ThenGetFails()
		{
			using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityClient(ws.BaseUri);

				client.Delete(resourceName, "1");
				var exception = Assert.Throws<HttpEntityException>(() => client.Get<Product>(resourceName, "25"));

				Assert.Equal(HttpStatusCode.NotFound, exception.StatusCode);
			}
		}
コード例 #26
0
        public void WhenTryGetSucceeds_ThenPopulatesEntity()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client   = new HttpEntityClient(ws.BaseUri);
                var product  = default(Product);
                var response = client.TryGet <Product>(resourceName, "1", out product);

                Assert.True(response.IsSuccessStatusCode);
                Assert.NotNull(product);
                Assert.Equal("kzu", product.Owner.Name);
            }
        }
コード例 #27
0
		public void WhenPostNew_ThenSavesAndRetrievesId()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var product = new Product { Owner = new User { Id = 1, Name = "kzu" } };

				var saved = client.Post(product);

				Assert.Equal(4, saved.Id);

				Assert.Equal(saved.Owner.Id, product.Owner.Id);
				Assert.Equal(saved.Owner.Name, product.Owner.Name);
			}
		}
コード例 #28
0
	public void WhenHostingDisposableService_ThenDefaultActivatorFactoryDisposesIt()
	{
		using (var webservice = new HttpWebService<TestService>(
			serviceBaseUrl: "http://localhost:20000",
			serviceResourcePath: "test",
			serviceConfiguration: HttpHostConfiguration.Create()))
		{
			var client = new HttpClient(webservice.BaseUri);

			// Builds: http://localhost:2000/test/23
			var uri = webservice.Uri("23");
			var response = client.Get(uri);
		}

		Assert.True(TestService.IsDisposed);
	}
コード例 #29
0
    public void WhenHostingDisposableService_ThenDefaultActivatorFactoryDisposesIt()
    {
        using (var webservice = new HttpWebService <TestService>(
                   serviceBaseUrl: "http://localhost:20000",
                   serviceResourcePath: "test",
                   serviceConfiguration: HttpHostConfiguration.Create()))
        {
            var client = new HttpClient(webservice.BaseUri);

            // Builds: http://localhost:2000/test/23
            var uri      = webservice.Uri("23");
            var response = client.Get(uri);
        }

        Assert.True(TestService.IsDisposed);
    }
コード例 #30
0
        /*
         * /// <summary>
         * /// Consulta Web Service para verificar se o número está cadastrado, serve para testar conexão
         * /// </summary>
         * public static async void Inicializar()
         * {
         *  //Página de Inicialização do Aplicativo até efetuar a consulta do WebService
         *  App.Current.MainPage = new SplashPage();
         *
         *  bool numberRegistred = false;
         *
         *  try
         *  {
         *      numberRegistred = await Base.IsPhoneNumberRegistred();
         *
         *      if (numberRegistred)
         *      {
         *          App.Current.MainPage = new PrincipalPage();
         *      }
         *      else
         *      {
         *          App.Current.MainPage = new TermsCondictionsPage();
         *      }
         *  }
         *  catch (Exception)
         *  {
         *      App.Current.MainPage = new TimeOutPage();
         *  }
         * }
         *
         */

        public static async Task <bool> IsPhoneNumberRegistred()
        {
            try
            {
                HttpWebService _httpWebService = new HttpWebService();
                var            response        = await _httpWebService.GetAsync("");

                Usuario user = new Usuario();
                user = await _httpWebService.ReadContentAsync <Usuario>(response);

                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #31
0
	public void WhenHostingService_ThenCanInvokeIt()
	{
		using (var webservice = new HttpWebService<TestService>(
			serviceBaseUrl: "http://localhost:20000",
			serviceResourcePath: "test",
			serviceConfiguration: HttpHostConfiguration.Create()))
		{
			var client = new HttpClient(webservice.BaseUri);

			// Builds: http://localhost:2000/test/23
			var uri = webservice.Uri("23");
			var response = client.Get(uri);

			Assert.True(response.IsSuccessStatusCode, response.ToString());
			Assert.True(response.Content.ReadAsString().Contains("23"));
		}
	}
コード例 #32
0
    public void WhenHostingService_ThenCanInvokeIt()
    {
        using (var webservice = new HttpWebService <TestService>(
                   serviceBaseUrl: "http://localhost:20000",
                   serviceResourcePath: "test",
                   serviceConfiguration: HttpHostConfiguration.Create()))
        {
            var client = new HttpClient(webservice.BaseUri);

            // Builds: http://localhost:2000/test/23
            var uri      = webservice.Uri("23");
            var response = client.Get(uri);

            Assert.True(response.IsSuccessStatusCode, response.ToString());
            Assert.True(response.Content.ReadAsString().Contains("23"));
        }
    }
コード例 #33
0
        public void WhenPutUpdate_ThenSaves()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", true, new ServiceConfiguration()))
            {
                var client  = new HttpEntityClient(ws.BaseUri);
                var product = new Product {
                    Id = 1, Owner = new User {
                        Id = 1, Name = "vga"
                    }
                };

                client.Put(resourceName, "1", product);

                var saved = client.Get <Product>(resourceName, "1");

                Assert.Equal(saved.Owner.Name, product.Owner.Name);
            }
        }
コード例 #34
0
    public void WhenHostingSpecificServiceInstance_ThenGetsConfiguredResult()
    {
        var id = Guid.NewGuid();

        using (var webservice = HttpWebService.Create(new TestService(id),
                                                      serviceBaseUrl: "http://localhost:20000",
                                                      serviceResourcePath: "test"))
        {
            var client = new HttpClient(webservice.BaseUri);

            // Builds: http://localhost:2000/test
            var uri      = webservice.Uri("");
            var response = client.Get(uri);

            Assert.True(response.IsSuccessStatusCode, response.ToString());
            Assert.True(response.Content.ReadAsString().Contains(id.ToString()));
        }
    }
コード例 #35
0
	private static void TestWithContentType(string contentType, Func<HttpContent, JsonReader> readerFactory)
	{
		var config = HttpHostConfiguration.Create().UseJsonNet();

		using (var webservice = new HttpWebService<TestService>("http://localhost:20000", "test", config))
		{
			var client = new HttpClient(webservice.BaseUri);
			client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));

			var response = client.Get(webservice.Uri(25));

			Assert.True(response.IsSuccessStatusCode, response.ToString());

			var product = new JsonSerializer().Deserialize<Product>(readerFactory(response.Content));

			Assert.Equal(25, product.Id);
			Assert.Equal("kzu", product.Owner.Name);
		}
	}
コード例 #36
0
    private static void TestWithContentType(string contentType, Func <HttpContent, JsonReader> readerFactory)
    {
        var config = HttpHostConfiguration.Create().UseJsonNet();

        using (var webservice = new HttpWebService <TestService>("http://localhost:20000", "test", config))
        {
            var client = new HttpClient(webservice.BaseUri);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));

            var response = client.Get(webservice.Uri(25));

            Assert.True(response.IsSuccessStatusCode, response.ToString());

            var product = new JsonSerializer().Deserialize <Product>(readerFactory(response.Content));

            Assert.Equal(25, product.Id);
            Assert.Equal("kzu", product.Owner.Name);
        }
    }
コード例 #37
0
        public void WhenPostNew_ThenSavesAndRetrievesId()
        {
            using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
            {
                var client  = new HttpEntityClient(ws.BaseUri);
                var product = new Product {
                    Owner = new User {
                        Id = 1, Name = "kzu"
                    }
                };

                var saved = client.Post(resourceName, product);

                Assert.Equal(4, saved.Id);

                Assert.Equal(saved.Owner.Id, product.Owner.Id);
                Assert.Equal(saved.Owner.Name, product.Owner.Name);
            }
        }
コード例 #38
0
	public void WhenTakeOnly_ThenGetsResponse()
	{
		var config = HttpHostConfiguration.Create();
		config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

		using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", config))
		{
			var client = new HttpClient("http://localhost:20000");
			client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

			var response = client.Query<Product>("products", take: 1);

			Assert.True(response.IsSuccessStatusCode);

			var products = new JsonSerializer().Deserialize<List<Product>>(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

			Assert.Equal(1, products.Count);
			Assert.Equal(1, products[0].Id);
		}
	}
コード例 #39
0
        public void WhenPutNew_ThenSaves()
        {
            using (var ws = new HttpWebService <HttpEntityConventionClientTestService>("http://localhost:20000", "products", true, new ServiceConfiguration()))
            {
                var client  = new HttpEntityConventionClient(ws.BaseUri);
                var product = new Product {
                    Owner = new User {
                        Id = 1, Name = "kzu"
                    }
                };

                client.Put("4", product);

                var saved = client.Get <Product>("4");

                Assert.Equal(saved.Id, 4);
                Assert.Equal(saved.Owner.Id, product.Owner.Id);
                Assert.Equal(saved.Owner.Name, product.Owner.Name);
            }
        }
コード例 #40
0
	public void WhenExecutingRequest_ThenTracesInformationHeaders()
	{
		var listener = new ConsoleTraceListener();
		TracerExtensibility.AddListener(SourceName.For<TracingChannel>(), listener);
		TracerExtensibility.SetTracingLevel(SourceName.For<TracingChannel>(), SourceLevels.All);

		var config = HttpHostConfiguration.Create()
			.UseJsonNet()
			.AddMessageHandlers(typeof(TracingChannel));

		using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", true, config))
		{
			var client = new HttpEntityClient(ws.BaseUri);
			var products = client.Query<Product>().Skip(1).Take(1).ToList();

			Assert.Equal(1, products.Count);
			Assert.Equal(2, products[0].Id);
		}

		listener.Flush();
	}
コード例 #41
0
    public void WhenHostingCachedServiceInstance_ThenGetsSameResultAlways()
    {
        using (var webservice = new HttpWebService <TestService>(
                   cacheServiceInstance: true,
                   serviceBaseUrl: "http://localhost:20000",
                   serviceResourcePath: "test",
                   serviceConfiguration: HttpHostConfiguration.Create()))
        {
            var client = new HttpClient(webservice.BaseUri);

            // Builds: http://localhost:2000/test/23
            var uri      = webservice.Uri("23");
            var response = client.Get(uri);

            Assert.True(response.IsSuccessStatusCode, response.ToString());

            var content1 = response.Content.ReadAsString();
            var content2 = client.Get(uri).Content.ReadAsString();
            Assert.Equal(content1, content2);
        }
    }
コード例 #42
0
    public void WhenPaging_ThenGetsResponse()
    {
        var config = HttpHostConfiguration.Create();

        config.Configuration.OperationHandlerFactory.Formatters.Insert(0, new JsonNetMediaTypeFormatter());

        using (var ws = new HttpWebService <TestService>("http://localhost:20000", "products", config))
        {
            var client = new HttpClient("http://localhost:20000");
            client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/json"));

            var response = client.Query <Product>("products", x => x.Id <= 2, skip: 1, take: 1);

            Assert.True(response.IsSuccessStatusCode);

            var products = new JsonSerializer().Deserialize <List <Product> >(new JsonTextReader(new StreamReader(response.Content.ContentReadStream)));

            Assert.Equal(1, products.Count);
            Assert.Equal(2, products[0].Id);
        }
    }
コード例 #43
0
	public void WhenHostingCachedServiceInstance_ThenGetsSameResultAlways()
	{
		using (var webservice = new HttpWebService<TestService>(
			cacheServiceInstance: true,
			serviceBaseUrl: "http://localhost:20000",
			serviceResourcePath: "test",
			serviceConfiguration: HttpHostConfiguration.Create()))
		{
			var client = new HttpClient(webservice.BaseUri);

			// Builds: http://localhost:2000/test/23
			var uri = webservice.Uri("23");
			var response = client.Get(uri);

			Assert.True(response.IsSuccessStatusCode, response.ToString());

			var content1 = response.Content.ReadAsString();
			var content2 = client.Get(uri).Content.ReadAsString();
			Assert.Equal(content1, content2);
		}
	}
コード例 #44
0
		public void WhenPutFails_ThenThrows()
		{
			using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityClient(ws.BaseUri);
				// We're putting a null which is invalid.
				var exception = Assert.Throws<HttpEntityException>(() => client.Put<Product>(resourceName, "25", null));

				Assert.Equal(HttpStatusCode.InternalServerError, exception.StatusCode);
			}
		}
コード例 #45
0
		public void WhenQueryingWithExtraCriteria_ThenPopulatesMatchingEntities()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var products = client.Query<Product>(new { search = "kzu" }).ToList();

				Assert.True(products.All(x => x.Owner.Name == "kzu"));
			}
		}
コード例 #46
0
		public void WhenTryGetFails_ThenReturnsResponse()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var product = default(Product);
				var response = client.TryGet<Product>("25", out product);

				Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
				Assert.Null(product);
			}
		}
コード例 #47
0
		public void WhenTryGetSucceeds_ThenPopulatesEntity()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var product = default(Product);
				var response = client.TryGet<Product>("1", out product);

				Assert.True(response.IsSuccessStatusCode);
				Assert.NotNull(product);
				Assert.Equal("kzu", product.Owner.Name);
			}
		}
コード例 #48
0
		public void WhenQuerying_ThenPopulatesMatchingEntities()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var ids = client.Query<Product>().Where(x => x.Owner.Name == "kzu").Select(x => x.Id).ToList();
				var products = client.Query<Product>().Where(x => x.Owner.Name == "kzu").ToList();

				Assert.Equal(2, ids.Count);
				Assert.True(products.All(x => x.Owner.Name == "kzu"));
			}
		}
コード例 #49
0
		public void WhenQueryingAndNoMatches_ThenReturnsEmptyEnumerable()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var products = client.Query<Product>().Where(x => x.Owner.Name == "foo").ToList();

				Assert.Equal(0, products.Count);
			}
		}
コード例 #50
0
		public void WhenSkipTakeOnly_ThenReturnsSingleElement()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var products = client.Query<Product>().Skip(1).Take(1).ToList();

				Assert.Equal(1, products.Count);
				Assert.Equal(2, products[0].Id);
			}
		}
コード例 #51
0
		public void WhenPutUpdate_ThenSaves()
		{
			using (var ws = new HttpWebService<TestService>("http://localhost:20000", "products", true, new ServiceConfiguration()))
			{
				var client = new HttpEntityClient(ws.BaseUri);
				var product = new Product { Id = 1, Owner = new User { Id = 1, Name = "vga" } };

				client.Put(resourceName, "1", product);

				var saved = client.Get<Product>(resourceName, "1");

				Assert.Equal(saved.Owner.Name, product.Owner.Name);
			}
		}
コード例 #52
0
		public void WhenOrderByTake_ThenReturnsOrdered()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var products = client.Query<Product>().OrderBy(x => x.Title).Take(2).ToList();

				Assert.Equal(2, products.Count);
				Assert.Equal("A", products[0].Title);
				Assert.Equal("B", products[1].Title);
			}
		}
コード例 #53
0
		public void WhenPutNew_ThenSaves()
		{
			using (var ws = new HttpWebService<HttpEntityConventionClientTestService>("http://localhost:20000", "products", true, new ServiceConfiguration()))
			{
				var client = new HttpEntityConventionClient(ws.BaseUri);
				var product = new Product { Owner = new User { Id = 1, Name = "kzu" } };

				client.Put("4", product);

				var saved = client.Get<Product>("4");

				Assert.Equal(saved.Id, 4);
				Assert.Equal(saved.Owner.Id, product.Owner.Id);
				Assert.Equal(saved.Owner.Name, product.Owner.Name);
			}
		}