Exemplo n.º 1
1
        private static void twitterSample()
        {
            var client = new HttpClient(Urls.Twitter)
            {
                Channel = new HttpMessageInspector(new WebRequestChannel())
            };

            var request = new HttpRequestMessage(HttpMethod.Get, "1/users/show/{0}.xml".FormatWith("duarte_nunes"));
            request.With().Accept("application/xml");

            HttpResponseMessage response = client.Send(request);
            response.EnsureSuccessStatusCode();

            Console.WriteLine(response.Content.ReadAsString());

            XElement element = response.Content.ReadAsXElement();
            Console.WriteLine(element.Element("description").Value);

            var formatter = new JsonDataContractFormatter(new DataContractJsonSerializer(typeof(TwitterUser)));
            var c = new RestyClient<TwitterUser>(Urls.Twitter, new[] { formatter });
            Tuple<HttpStatusCode, TwitterUser> result = c.ExecuteGet("1/users/show/{0}.json".FormatWith("duarte_nunes"));
            Console.WriteLine(result.Item1);
            Console.WriteLine(result.Item2.Description);
            Console.WriteLine(result.Item2.ProfileImageUrl);
        }
Exemplo n.º 2
0
        public void Create_New_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers");
                request.Content = new StringContent("Id = 7; Name = NewCustomer7");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.Created, response.StatusCode, "The status code should have been 'Created'.");
                    Assert.IsNotNull(response.Headers.Location, "The location header should not have been null.");
                    Assert.AreEqual(new Uri("http://localhost:8080/Customers?id=7"), response.Headers.Location, "The location header should have beeen 'http://localhost:8080/Customers?id=7'.");
                    Assert.AreEqual("Id = 7; Name = NewCustomer7", response.Content.ReadAsString(), "The response content should have been 'Id = 7; Name = NewCustomer7'.");
                }

                // Put server back in original state
                request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=7");
                client.Send(request);
            }
        }
Exemplo n.º 3
0
        public static ICollection<HttpResponseMessage> RunClient(HttpClient client, TestHeaderOptions options, HttpMethod method)
        {
            var result = new HttpResponseMessage[TestServiceCommon.Iterations];
            for (var cnt = 0; cnt < TestServiceCommon.Iterations; cnt++)
            {
                var httpRequest = new HttpRequestMessage(method, "");
                if ((options & TestHeaderOptions.InsertRequest) > 0)
                {
                    TestServiceCommon.AddRequestHeader(httpRequest, cnt);
                }

                try
                {
                    result[cnt] = client.Send(httpRequest);
                    Assert.IsNotNull(result[cnt]);
                }
                catch (HttpException he)
                {
                    var we = he.InnerException as WebException;
                    Assert.IsNull(we.Response, "Response should not be null.");
                    continue;
                }

                if ((options & TestHeaderOptions.ValidateResponse) > 0)
                {
                    TestServiceCommon.ValidateResponseTestHeader(result[cnt], cnt);
                }
            }

            Assert.AreEqual(TestServiceCommon.Iterations, result.Length);
            return result;
        }
Exemplo n.º 4
0
        /// <summary>
        /// Send an Signature Version 4 signed HTTP request.
        /// </summary>
        /// <param name="self">
        /// The extension target.
        /// </param>
        /// <param name="request">
        /// The HTTP request message to send.
        /// </param>
        /// <param name="completionOption">
        /// One of the enumeration values that specifies when the operation should complete (as
        /// soon as a response is available or after reading the response content).
        /// </param>
        /// <param name="cancellationToken">
        /// The cancellation token to cancel operation.
        /// </param>
        /// <param name="regionName">
        /// The system name of the AWS region associated with the endpoint, e.g. "us-east-1".
        /// </param>
        /// <param name="serviceName">
        /// The signing name of the service, e.g. "execute-api".
        /// </param>
        /// <param name="credentials">
        /// AWS credentials containing the following parameters:
        /// - The AWS public key for the account making the service call.
        /// - The AWS secret key for the account making the call, in clear text.
        /// - The session token obtained from STS if request is authenticated using temporary
        ///   security credentials, e.g. a role.
        /// </param>
        /// <returns>
        /// The HTTP response message.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="request"/> is null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The request message was already sent by the <see cref="HttpClient"/> instance.
        /// </exception>
        /// <exception cref="HttpRequestException">
        /// The request failed due to an underlying issue such as network connectivity, DNS
        /// failure, or server certificate validation.
        /// </exception>
        /// <exception cref="TaskCanceledException">
        /// The request was canceled.
        /// <para/>
        /// -or-
        /// <para/>
        /// If the <see cref="TaskCanceledException"/> exception nests the
        /// <see cref="TimeoutException"/>: The request failed due to timeout.
        /// </exception>
        public static HttpResponseMessage Send(
            this HttpClient self,
            HttpRequestMessage request,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken,
            string regionName,
            string serviceName,
            AWSCredentials credentials)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }

            var immutableCredentials = credentials.GetCredentials();

            var response = self.Send(
                request,
                completionOption,
                cancellationToken,
                regionName,
                serviceName,
                immutableCredentials);

            return(response);
        }
        public IApplicationState NextState(HttpClient client)
        {
            if (applicationStateInfo.Endurance < 1)
            {
                return new Defeated(currentResponse, applicationStateInfo);
            }

            if (currentResponse.Content.Headers.ContentType.Equals(AtomMediaType.Feed))
            {
                var feed = currentResponse.Content.ReadAsObject<SyndicationFeed>(AtomMediaType.Formatter);
                if (feed.Categories.Contains(new SyndicationCategory("encounter"), CategoryComparer.Instance))
                {
                    var form = Form.ParseFromFeedExtension(feed);
                    form.Fields.Named("endurance").Value = applicationStateInfo.Endurance.ToString();

                    var newResponse = client.Send(form.CreateRequest(feed.BaseUri));

                    if (newResponse.Content.Headers.ContentType.Equals(AtomMediaType.Entry))
                    {
                        var newContent = newResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);
                        var newForm = Form.ParseFromEntryContent(newContent);
                        var newEndurance = int.Parse(newForm.Fields.Named("endurance").Value);

                        return new ResolvingEncounter(newResponse, applicationStateInfo.GetBuilder().UpdateEndurance(newEndurance).Build());
                    }
                }

                return new Error(currentResponse, applicationStateInfo);
            }

            if (currentResponse.Content.Headers.ContentType.Equals(AtomMediaType.Entry))
            {
                var entry = currentResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);

                if (entry.Categories.Contains(new SyndicationCategory("room"), CategoryComparer.Instance))
                {
                    return new Exploring(currentResponse, applicationStateInfo);
                }

                var continueLink = entry.Links.FirstOrDefault(l => l.RelationshipType.Equals("continue"));
                if (continueLink != null)
                {
                    return new ResolvingEncounter(client.Get(new Uri(entry.BaseUri, continueLink.Uri)), applicationStateInfo);
                }

                var form = Form.ParseFromEntryContent(entry);
                var newResponse = client.Send(form.CreateRequest(entry.BaseUri));

                if (newResponse.Content.Headers.ContentType.Equals(AtomMediaType.Entry))
                {
                    var newContent = newResponse.Content.ReadAsObject<SyndicationItem>(AtomMediaType.Formatter);
                    var newForm = Form.ParseFromEntryContent(newContent);
                    var newEndurance = int.Parse(newForm.Fields.Named("endurance").Value);

                    return new ResolvingEncounter(newResponse, applicationStateInfo.GetBuilder().UpdateEndurance(newEndurance).Build());
                }
            }

            return new Error(currentResponse, applicationStateInfo);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Send an Signature Version 4 signed HTTP request.
        /// </summary>
        /// <param name="self">
        /// The extension target.
        /// </param>
        /// <param name="request">
        /// The HTTP request message to send.
        /// </param>
        /// <param name="completionOption">
        /// One of the enumeration values that specifies when the operation should complete (as
        /// soon as a response is available or after reading the response content).
        /// </param>
        /// <param name="cancellationToken">
        /// The cancellation token to cancel operation.
        /// </param>
        /// <param name="regionName">
        /// The system name of the AWS region associated with the endpoint, e.g. "us-east-1".
        /// </param>
        /// <param name="serviceName">
        /// The signing name of the service, e.g. "execute-api".
        /// </param>
        /// <param name="credentials">
        /// AWS credentials containing the following parameters:
        /// - The AWS public key for the account making the service call.
        /// - The AWS secret key for the account making the call, in clear text.
        /// - The session token obtained from STS if request is authenticated using temporary
        ///   security credentials, e.g. a role.
        /// </param>
        /// <returns>
        /// The HTTP response message.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="request"/> is null.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// The request message was already sent by the <see cref="HttpClient"/> instance.
        /// </exception>
        /// <exception cref="HttpRequestException">
        /// The request failed due to an underlying issue such as network connectivity, DNS
        /// failure, or server certificate validation.
        /// </exception>
        /// <exception cref="TaskCanceledException">
        /// The request was canceled.
        /// <para/>
        /// -or-
        /// <para/>
        /// If the <see cref="TaskCanceledException"/> exception nests the
        /// <see cref="TimeoutException"/>: The request failed due to timeout.
        /// </exception>
        public static HttpResponseMessage Send(
            this HttpClient self,
            HttpRequestMessage request,
            HttpCompletionOption completionOption,
            CancellationToken cancellationToken,
            string regionName,
            string serviceName,
            ImmutableCredentials credentials)
        {
            if (self == null)
            {
                throw new ArgumentNullException(nameof(self));
            }

            Signer.Sign(
                request,
                self.BaseAddress,
                self.DefaultRequestHeaders,
                DateTime.UtcNow,
                regionName,
                serviceName,
                credentials);

            return(self.Send(request, completionOption, cancellationToken));
        }
        public AmadeusAPIServiceClient(System.Net.Http.HttpClient httpClient, IConfiguration configuration)
        {
            _config         = configuration;
            DurationOfCache = (_config.GetSection("Variables").GetValue <string>("DurationOfCache"));
            var nvc = new List <KeyValuePair <string?, string?> >();

            nvc.Add(new KeyValuePair <string?, string?>("grant_type", "client_credentials"));
            nvc.Add(new KeyValuePair <string?, string?>("client_id", _config.GetSection("Secrets").GetSection("AmadeusData").GetSection("APIKey").Value));
            nvc.Add(new KeyValuePair <string?, string?>("client_secret", _config.GetSection("Secrets").GetSection("AmadeusData").GetSection("APISecret").Value));
            _httpClient = httpClient;
            HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, _OAuthTokenURL)
            {
                Content = new FormUrlEncodedContent(nvc)
            };
            var res      = _httpClient.Send(req);
            var dataTask = res.Content.ReadAsStringAsync();
            var data     = Task.FromResult(dataTask);

            var authData = JsonConvert.DeserializeObject <AuthTokenResponse>(data.Result.Result);

            _tokenData = authData;
            _httpClient.DefaultRequestHeaders.Authorization =
                new AuthenticationHeaderValue(_tokenData.token_type, _tokenData.access_token);
            _settings = new System.Lazy <Newtonsoft.Json.JsonSerializerSettings>(() =>
            {
                var settings = new Newtonsoft.Json.JsonSerializerSettings();
                UpdateJsonSerializerSettings(settings);
                return(settings);
            });
        }
Exemplo n.º 8
0
        private static void Main(string[] args)
        {
            // create the event loop
            var loop = new EventLoop();

            // start it with a callback
            loop.Start(() => Console.WriteLine("Event loop has started"));

            // start a timer
            loop.SetTimeout(() => Console.WriteLine("Hello, I am a timeout happening after 1 second"), TimeSpan.FromSeconds(1));
            loop.SetInterval(() => Console.WriteLine("Hello, I am an interval happening every 2 seconds"), TimeSpan.FromSeconds(2));

            // read the app.config
            var appConfigFile = new FileInfo("NLoop.TestApp.exe.config");
            var promise = appConfigFile.ReadAllBytes(loop);
            promise.Then(content => Console.WriteLine("Success!! read {0} bytes from app.config", content.Length), reason => Console.WriteLine("Dread!! got an error: {0}", reason));

            // send a web request
            var httpClient = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com/");
            var httpPromise = httpClient.Send(loop, request);
            httpPromise.Then(content => Console.WriteLine("Success!! read {0} from google.com", content.StatusCode), reason => Console.WriteLine("Dread!! got an error: {0}", reason));
            //httpPromise.Cancel();

            // wait
            Console.WriteLine("Event loop is processing, press any key to exit");
            Console.Read();

            // we are done, dispose the loop so resources will be cleaned up
            loop.Dispose();
        }
Exemplo n.º 9
0
        private static HttpResponseMessage GetResponse(ServiceHost host, HttpRequestMessage request)
        {
            UriBuilder builder = new UriBuilder(host.BaseAddresses[0]);
            builder.Host = Environment.MachineName;

            request.RequestUri = new Uri(request.RequestUri.ToString(), UriKind.Relative);

            using (HttpClient client = new HttpClient(builder.Uri))
            {
                client.Channel = new WebRequestChannel();
                return client.Send(request);
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Send an Signature Version 4 signed HTTP request.
 /// </summary>
 /// <param name="self">
 /// The extension target.
 /// </param>
 /// <param name="request">
 /// The HTTP request message to send.
 /// </param>
 /// <param name="regionName">
 /// The system name of the AWS region associated with the endpoint, e.g. "us-east-1".
 /// </param>
 /// <param name="serviceName">
 /// The signing name of the service, e.g. "execute-api".
 /// </param>
 /// <param name="credentials">
 /// AWS credentials containing the following parameters:
 /// - The AWS public key for the account making the service call.
 /// - The AWS secret key for the account making the call, in clear text.
 /// - The session token obtained from STS if request is authenticated using temporary
 ///   security credentials, e.g. a role.
 /// </param>
 /// <returns>
 /// The HTTP response message.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// The <paramref name="request"/> is null.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// The request message was already sent by the <see cref="HttpClient"/> instance.
 /// </exception>
 /// <exception cref="HttpRequestException">
 /// The request failed due to an underlying issue such as network connectivity, DNS
 /// failure, or server certificate validation.
 /// </exception>
 /// <exception cref="TaskCanceledException">
 /// If the <see cref="TaskCanceledException"/> exception nests the
 /// <see cref="TimeoutException"/>: The request failed due to timeout.
 /// </exception>
 public static HttpResponseMessage Send(
     this HttpClient self,
     HttpRequestMessage request,
     string regionName,
     string serviceName,
     AWSCredentials credentials) =>
 self.Send(
     request,
     SendAsyncExtensions.DefaultCompletionOption,
     CancellationToken.None,
     regionName,
     serviceName,
     credentials);
Exemplo n.º 11
0
 /// <summary>
 /// Send an Signature Version 4 signed HTTP request.
 /// </summary>
 /// <param name="self">
 /// The extension target.
 /// </param>
 /// <param name="request">
 /// The HTTP request message to send.
 /// </param>
 /// <param name="completionOption">
 /// One of the enumeration values that specifies when the operation should complete (as
 /// soon as a response is available or after reading the response content).
 /// </param>
 /// <param name="regionName">
 /// The system name of the AWS region associated with the endpoint, e.g. "us-east-1".
 /// </param>
 /// <param name="serviceName">
 /// The signing name of the service, e.g. "execute-api".
 /// </param>
 /// <param name="credentials">
 /// AWS credentials containing the following parameters:
 /// - The AWS public key for the account making the service call.
 /// - The AWS secret key for the account making the call, in clear text.
 /// - The session token obtained from STS if request is authenticated using temporary
 ///   security credentials, e.g. a role.
 /// </param>
 /// <returns>
 /// The HTTP response message.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// The <paramref name="request"/> is null.
 /// </exception>
 /// <exception cref="InvalidOperationException">
 /// The request message was already sent by the <see cref="HttpClient"/> instance.
 /// </exception>
 /// <exception cref="HttpRequestException">
 /// The request failed due to an underlying issue such as network connectivity, DNS
 /// failure, or server certificate validation.
 /// </exception>
 /// <exception cref="TaskCanceledException">
 /// If the <see cref="TaskCanceledException"/> exception nests the
 /// <see cref="TimeoutException"/>: The request failed due to timeout.
 /// </exception>
 public static HttpResponseMessage Send(
     this HttpClient self,
     HttpRequestMessage request,
     HttpCompletionOption completionOption,
     string regionName,
     string serviceName,
     ImmutableCredentials credentials) =>
 self.Send(
     request,
     completionOption,
     CancellationToken.None,
     regionName,
     serviceName,
     credentials);
        public void Create_Customer_That_Already_Exists()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "Customers?id=2");
                request.Content = new StringContent("Id = 2; Name = AlreadyCustomer2");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.Conflict, response.StatusCode, "The status code should have been 'Conflict'.");
                    Assert.AreEqual("There already a customer with id '2'.", response.Content.ReadAsString(), "The response content should have been 'There already a customer with id '2'.'");
                }
            }
        }
Exemplo n.º 13
0
        public string RetrievePageHtml(int pageNumber)
        {
            using (HttpClientHandler handler = new HttpClientHandler())
            {
                handler.UseCookies = false;

                using (HttpClient client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("http://www.rllmukforum.com/");

                    var url = string.Format("{0}/page-{1}", ConfigurationManager.AppSettings["ThreadBaseAddress"], pageNumber);

                    HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, url);

                    var requestUri = message.RequestUri;

                    foreach (var cookieHeader in _signedInHeaders.Where(h => string.Equals(h.Key, "Set-Cookie")))
                    {
                        message.Headers.Add("Cookie", cookieHeader.Value);
                    }

                    var response = client.Send(message);

                    var currentUri = response.RequestMessage.RequestUri.AbsoluteUri;
                    var index = currentUri.IndexOf("page", StringComparison.OrdinalIgnoreCase);

                    var currentActualPageNumber = index == -1 ? 1 : int.Parse(currentUri.Substring(index + 5, currentUri.Length - (index + 5)));

                    if (pageNumber != currentActualPageNumber)
                    {
                        return string.Empty;
                    }

                    return response.GetContentAsString();
                }
            }
        }
        public void Delete_Existing_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Delete, "Customers?id=3");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "The status code should have been 'OK'.");
                    Assert.AreEqual(string.Empty, response.Content.ReadAsString(), "The response content should have been an empty string.");
                }

                // Put server back in the original state
                request = new HttpRequestMessage(HttpMethod.Post, "Customers");
                request.Content = new StringContent("Id = 3; Name = Customer3");
                client.Send(request);
            }
        }
Exemplo n.º 15
0
		public void Send_InvalidHandler ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.BaseAddress = new Uri ("http://xamarin.com");
			var request = new HttpRequestMessage ();

			mh.OnSend = l => {
				Assert.AreEqual (l, request, "#1");
				return null;
			};

			try {
				client.Send (request);
				Assert.Fail ("#2");
			} catch (InvalidOperationException) {
			}
		}
Exemplo n.º 16
0
		public void Send_Invalid ()
		{
			var client = new HttpClient ();
			try {
				client.Send (null);
				Assert.Fail ("#1");
			} catch (ArgumentNullException) {
			}

			try {
				var request = new HttpRequestMessage ();
				client.Send (request);
				Assert.Fail ("#2");
			} catch (InvalidOperationException) {
			}
		}
Exemplo n.º 17
0
		public void Send_Timeout ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.Timeout = TimeSpan.FromMilliseconds (100);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var response = new HttpResponseMessage ();

			mh.OnSendFull = (l, c) => {
				Assert.IsTrue (c.WaitHandle.WaitOne (500), "#2");
				return response;
			};

			Assert.AreEqual (response, client.Send (request), "#1");
		}
Exemplo n.º 18
0
		public void Send_Complete_Error ()
		{
			var listener = CreateListener (l => {
				var response = l.Response;
				response.StatusCode = 500;
			});

			try {
				var client = new HttpClient ();
				var request = new HttpRequestMessage (HttpMethod.Get, LocalServer);
				var response = client.Send (request, HttpCompletionOption.ResponseHeadersRead);

				Assert.AreEqual ("", response.Content.ReadAsString (), "#100");
				Assert.AreEqual (HttpStatusCode.InternalServerError, response.StatusCode, "#101");
			} finally {
				listener.Close ();
			}
		}
Exemplo n.º 19
0
        public void Send_Request_With_Unknown_Uri()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "UnknownUri");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode, "The status code should have been 'NotFound'.");
                    Assert.AreEqual("The uri and/or method is not valid for any customer resource.", response.Content.ReadAsString(), "The response content should have been 'The uri and/or method is not valid for any customer resource.'.");
                }
            }
        }
Exemplo n.º 20
0
        public void Get_With_Custom_Header_For_Customer_Names_Only()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "Customers");
                request.Headers.Add("NamesOnly", "Ok");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "The status code should have been 'OK'.");
                    Assert.AreEqual("Customer1, Customer2, Customer3", response.Content.ReadAsString(), "The response content should have been 'Customer1, Customer2, Customer3'.");
                }
            }
        }
Exemplo n.º 21
0
        public void Get_All_Existing_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "Customers");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "The status code should have been 'OK'.");
                    string[] responseContent = response.Content.ReadAsString().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    Assert.AreEqual("Id = 1; Name = Customer1", responseContent[0], "The response content should have been 'Id = 1; Name = Customer1'.");
                    Assert.AreEqual("Id = 2; Name = Customer2", responseContent[1], "The response content should have been 'Id = 2; Name = Customer2'.");
                    Assert.AreEqual("Id = 3; Name = Customer3", responseContent[2], "The response content should have been 'Id = 3; Name = Customer3'.");
                }
            }
        }
Exemplo n.º 22
0
        private HttpResponseHeaders SignIn()
        {
            using (var handler = new HttpClientHandler())
            {
                handler.AllowAutoRedirect = false;

                using (HttpClient client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("http://www.rllmukforum.com/"); //?app=core&module=global&section=login&do=process

                    var content = CreateContentToSignIn();

                    HttpRequestMessage message = CreateMessageToSignIn(content);

                    var response = client.Send(message);

                    var responseContent = DecodeHttpContentToString(response);

                    if (response.StatusCode != HttpStatusCode.Redirect)
                    {
                        throw new Exception("Could not sign in to the forum. Maybe username / password incorrect or not set?");
                    }

                    return response.Headers;
                }
            }
        }
Exemplo n.º 23
0
        public static ICollection<HttpResponseMessage> RunClient(HttpClient client, TestHeaderOptions options, TimeSpan timeout)
        {
            var result = new HttpResponseMessage[TestServiceCommon.Iterations];
            using (var timer = new Timer(TestServiceClient.TimeoutHandler, client, timeout, timeout))
            {
                for (var cnt = 0; cnt < TestServiceCommon.Iterations; cnt++)
                {
                    var httpRequest = new HttpRequestMessage(HttpMethod.Get, "");
                    if ((options & TestHeaderOptions.InsertRequest) > 0)
                    {
                        TestServiceCommon.AddRequestHeader(httpRequest, cnt);
                    }

                    try
                    {
                        result[cnt] = client.Send(httpRequest);
                        Assert.IsNotNull(result[cnt]);
                    }
                    catch (OperationCanceledException)
                    {
                        continue;
                    }

                    if ((options & TestHeaderOptions.ValidateResponse) > 0)
                    {
                        TestServiceCommon.ValidateResponseTestHeader(result[cnt], cnt);
                    }
                }
            }

            Assert.AreEqual(TestServiceCommon.Iterations, result.Length);
            return result;
        }
Exemplo n.º 24
0
		public void Send_Complete_Version_1_0 ()
		{
			var listener = CreateListener (l => {
				var request = l.Request;

				Assert.IsNull (request.AcceptTypes, "#1");
				Assert.AreEqual (0, request.ContentLength64, "#2");
				Assert.IsNull (request.ContentType, "#3");
				Assert.AreEqual (0, request.Cookies.Count, "#4");
				Assert.IsFalse (request.HasEntityBody, "#5");
				Assert.AreEqual (1, request.Headers.Count, "#6");
				Assert.AreEqual (TestHost, request.Headers["Host"], "#6a");
				Assert.AreEqual ("GET", request.HttpMethod, "#7");
				Assert.IsFalse (request.IsAuthenticated, "#8");
				Assert.IsTrue (request.IsLocal, "#9");
				Assert.IsFalse (request.IsSecureConnection, "#10");
				Assert.IsFalse (request.IsWebSocketRequest, "#11");
				Assert.IsFalse (request.KeepAlive, "#12");
				Assert.AreEqual (HttpVersion.Version10, request.ProtocolVersion, "#13");
				Assert.IsNull (request.ServiceName, "#14");
				Assert.IsNull (request.UrlReferrer, "#15");
				Assert.IsNull (request.UserAgent, "#16");
				Assert.IsNull (request.UserLanguages, "#17");
			});

			try {
				var client = new HttpClient ();
				var request = new HttpRequestMessage (HttpMethod.Get, LocalServer);
				request.Version = HttpVersion.Version10;
				var response = client.Send (request, HttpCompletionOption.ResponseHeadersRead);

				Assert.AreEqual ("", response.Content.ReadAsString (), "#100");
				Assert.AreEqual (HttpStatusCode.OK, response.StatusCode, "#101");
			} finally {
				listener.Close ();
			}
		}
Exemplo n.º 25
0
		public void Send_Complete_ClientHandlerSettings ()
		{
			var listener = CreateListener (l => {
				var request = l.Request;

				Assert.IsNull (request.AcceptTypes, "#1");
				Assert.AreEqual (0, request.ContentLength64, "#2");
				Assert.IsNull (request.ContentType, "#3");
				Assert.AreEqual (1, request.Cookies.Count, "#4");
				Assert.AreEqual (new Cookie ("mycookie", "vv"), request.Cookies[0], "#4a");
				Assert.IsFalse (request.HasEntityBody, "#5");
				Assert.AreEqual (3, request.Headers.Count, "#6");
				Assert.AreEqual (TestHost, request.Headers["Host"], "#6a");
				Assert.AreEqual ("gzip", request.Headers["Accept-Encoding"], "#6b");
				Assert.AreEqual ("mycookie=vv", request.Headers["Cookie"], "#6c");
				Assert.AreEqual ("GET", request.HttpMethod, "#7");
				Assert.IsFalse (request.IsAuthenticated, "#8");
				Assert.IsTrue (request.IsLocal, "#9");
				Assert.IsFalse (request.IsSecureConnection, "#10");
				Assert.IsFalse (request.IsWebSocketRequest, "#11");
				Assert.IsFalse (request.KeepAlive, "#12");
				Assert.AreEqual (HttpVersion.Version10, request.ProtocolVersion, "#13");
				Assert.IsNull (request.ServiceName, "#14");
				Assert.IsNull (request.UrlReferrer, "#15");
				Assert.IsNull (request.UserAgent, "#16");
				Assert.IsNull (request.UserLanguages, "#17");
			});

			try {
				var chandler = new HttpClientHandler ();
				chandler.AllowAutoRedirect = true;
				chandler.AutomaticDecompression = DecompressionMethods.GZip;
				chandler.MaxAutomaticRedirections = 33;
				chandler.MaxRequestContentBufferSize = 5555;
				chandler.PreAuthenticate = true;
				chandler.CookieContainer.Add (new Uri (LocalServer), new Cookie ( "mycookie", "vv"));
				chandler.UseCookies = true;
				chandler.UseDefaultCredentials = true;
				chandler.Proxy = new WebProxy ("ee");
				chandler.UseProxy = true;

				var client = new HttpClient (chandler);
				var request = new HttpRequestMessage (HttpMethod.Get, LocalServer);
				request.Version = HttpVersion.Version10;
				var response = client.Send (request, HttpCompletionOption.ResponseHeadersRead);

				Assert.AreEqual ("", response.Content.ReadAsString (), "#100");
				Assert.AreEqual (HttpStatusCode.OK, response.StatusCode, "#101");
			} finally {
				listener.Close ();
			}
		}
Exemplo n.º 26
0
		public void Send_SameMessage ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");

			mh.OnSend = l => {
				return new HttpResponseMessage ();
			};

			client.Send (request);
			try {
				client.Send (request);
			} catch (InvalidOperationException) {
			}
		}
Exemplo n.º 27
0
		public void CancelPendingRequests ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var mre = new ManualResetEvent (false);

			mh.OnSendFull = (l, c) => {
				mre.Set ();
				Assert.IsTrue (c.WaitHandle.WaitOne (1000), "#20");
				Assert.IsTrue (c.IsCancellationRequested, "#21");
				mre.Set ();
				return new HttpResponseMessage ();
			};

			var t = Task.Factory.StartNew (() => {
				client.Send (request);
			});

			Assert.IsTrue (mre.WaitOne (500), "#1");
			mre.Reset ();
			client.CancelPendingRequests ();
			Assert.IsTrue (t.Wait (500), "#2");

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return new HttpResponseMessage ();
			};

			client.Send (request);
		}
Exemplo n.º 28
0
		public void CancelPendingRequests_BeforeSend ()
		{
			var ct = new CancellationTokenSource ();
			ct.Cancel ();
			var rr = CancellationTokenSource.CreateLinkedTokenSource (new CancellationToken (), ct.Token);


			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			client.CancelPendingRequests ();

			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return new HttpResponseMessage ();
			};

			client.Send (request);

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			client.Send (request);
		}
Exemplo n.º 29
0
        public void Get_Existing_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "Customers?id=1");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, "The status code should have been 'OK'.");
                    Assert.AreEqual("Id = 1; Name = Customer1", response.Content.ReadAsString(), "The response content should have been 'Id = 1; Name = Customer1'.");
                }
            }
        }
Exemplo n.º 30
0
		public void Send ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.BaseAddress = new Uri ("http://xamarin.com");
			var request = new HttpRequestMessage ();
			var response = new HttpResponseMessage ();

			mh.OnSend = l => {
				Assert.AreEqual (l, request, "#2");
				Assert.AreEqual (client.BaseAddress, l.RequestUri, "#2");
				return response;
			};

			Assert.AreEqual (response, client.Send (request), "#1");
		}
Exemplo n.º 31
0
        public void Get_With_Non_Integer_Id()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "Customers?id=foo");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode, "The status code should have been 'BadRequest'.");
                    Assert.AreEqual("An 'id' with a integer value must be provided in the query string.", response.Content.ReadAsString(), "The response content should have been 'An 'id' with a integer value must be provided in the query string.'");
                }
            }
        }
Exemplo n.º 32
0
		public void Send_DefaultRequestHeaders ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			client.DefaultRequestHeaders.Referrer = new Uri ("http://google.com");
			client.DefaultRequestHeaders.Add ("Referer", "xxxx");

			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var response = new HttpResponseMessage ();

			mh.OnSend = l => {
				Assert.AreEqual (client.DefaultRequestHeaders.Referrer, l.Headers.Referrer, "#2");
				Assert.IsNotNull (l.Headers.Referrer, "#3");
				return response;
			};

			Assert.AreEqual (response, client.Send (request), "#1");
		}
Exemplo n.º 33
0
        public void Update_Non_Existing_Customer()
        {
            Uri baseAddress = new Uri("http://localhost:8080/");
            CustomServiceHost host = new CustomServiceHost(typeof(CustomerService), baseAddress);
            using (host)
            {
                host.Open();

                HttpClient client = new HttpClient(baseAddress);
                client.Channel = new WebRequestChannel();
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, "Customers?id=5");
                request.Content = new StringContent("Id = 5; Name = NewCustomerName1");
                HttpResponseMessage response = client.Send(request);
                using (response)
                {
                    Assert.IsNotNull(response, "The response should not have been null.");
                    Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode, "The status code should have been 'NotFound'.");
                    Assert.AreEqual("There is no customer with id '5'.", response.Content.ReadAsString(), "The response content should have been 'There is no customer with id '5'.'");
                }
            }
        }
Exemplo n.º 34
0
		public void Send_Complete_CustomHeaders ()
		{
			var listener = CreateListener (l => {
				var request = l.Request;
				Assert.AreEqual ("vv", request.Headers["aa"], "#1");
				Assert.AreEqual ("bytes=3-20", request.Headers["Range"], "#2");
				Assert.AreEqual (4, request.Headers.Count, "#3");

				var response = l.Response;
				response.Headers.Add ("rsp", "rrr");
				response.Headers.Add ("upgrade", "vvvvaa");
				response.Headers.Add ("date", "aa");
				response.Headers.Add ("cache-control", "audio");

				response.StatusDescription = "test description";
				response.ProtocolVersion = HttpVersion.Version10;
				response.SendChunked = true;
				response.RedirectLocation = "w3.org";
			});

			try {
				var client = new HttpClient ();
				var request = new HttpRequestMessage (HttpMethod.Get, LocalServer);
				request.Headers.AddWithoutValidation ("aa", "vv");
				request.Headers.Range = new RangeHeaderValue (3, 20);
				var response = client.Send (request, HttpCompletionOption.ResponseHeadersRead);

				Assert.AreEqual ("", response.Content.ReadAsString (), "#100");
				Assert.AreEqual (HttpStatusCode.OK, response.StatusCode, "#101");

				IEnumerable<string> values;
				Assert.IsTrue (response.Headers.TryGetValues ("rsp", out values), "#102");
				Assert.AreEqual ("rrr", values.First (), "#102a");

				Assert.IsTrue (response.Headers.TryGetValues ("Transfer-Encoding", out values), "#103");
				Assert.AreEqual ("chunked", values.First (), "#103a");
				Assert.AreEqual (true, response.Headers.TransferEncodingChunked, "#103b");

				Assert.IsTrue (response.Headers.TryGetValues ("Date", out values), "#104");
				Assert.AreEqual (2, values.Count (), "#104b");
				Assert.IsNull (response.Headers.Date, "#104c");

				Assert.AreEqual (new ProductHeaderValue ("vvvvaa"), response.Headers.Upgrade.First (), "#105");

				Assert.AreEqual ("audio", response.Headers.CacheControl.Extensions.First ().Name, "#106");

				Assert.AreEqual ("w3.org", response.Headers.Location.OriginalString, "#107");

				Assert.AreEqual ("test description", response.ReasonPhrase, "#110");
				Assert.AreEqual (HttpVersion.Version11, response.Version, "#111");
			} finally {
				listener.Close ();
			}
		}
 public override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) => _client.Send(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
Exemplo n.º 36
0
 public void InitializeResourceCollection()
 {
     using (var client = new HttpClient())
     {
         // TIP: Initialize your service to a known state before each test
         // Delete all records - service has special case code to do this
         using (var request = new HttpRequestMessage(HttpMethod.Delete, ServiceUri + "/all"))
         {
             client.Send(request);
         }
     }
 }