Ejemplo n.º 1
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService             tracer         = executionContext.GetExtension <ITracingService>();
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                DateTime dateToCheck = DateToCheck.Get(executionContext);
                string   dateOnly    = dateToCheck.ToString("dd-MM-yyyy");

                //Use the adapter pattern to create a wrapper for the standard HttpClient
                //Calls the underlying functionality but provides a testable interface
                HttpClientAdapter adapter = new HttpClientAdapter();

                var callWebServiceTask = Task.Run(async() => await CallWebService(adapter, dateOnly));

                Task.WaitAll(callWebServiceTask);

                bool isValid = callWebServiceTask.Result;

                IsPublicHoliday.Set(executionContext, isValid);
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Ejemplo n.º 2
0
        public async Task SendWithHeaders_MustWithHeadersSend(string method)
        {
            var ada = new HttpClientAdapter(new HttpClient());

            using (var ser = new EngineService())
            {
                var url = "http://localhost:" + (port++) + "/";
                ser.Listener.Prefixes.Add(url);
                ser.Listen();
                var req = new RequestSettings
                {
                    Address = url,
                    Accept  = "application/json",
                    Headers = new Dictionary <string, string>
                    {
                        ["A"] = "a",
                        ["B"] = "b"
                    },
                    Host     = "www.localhost.com",
                    Method   = method,
                    Referrer = "http://www.referrer.com",
                    Timeout  = 1000
                };
                var rep = await ada.GetMessageAsync(req);

                if (!string.Equals(rep.RequestMessage.Method.Method, req.Method, StringComparison.InvariantCulture))
                {
                    Assert.Fail();
                }
                Assert.AreEqual(req.Host, rep.RequestMessage.Headers.GetValues("host").First());
                Assert.AreEqual(req.Headers["A"], rep.RequestMessage.Headers.GetValues("A").First());
                Assert.AreEqual(req.Headers["B"], rep.RequestMessage.Headers.GetValues("B").First());
                Assert.AreEqual(req.Accept, rep.RequestMessage.Headers.GetValues("Accept").First());
            }
        }
Ejemplo n.º 3
0
        static async Task <int> runAsync(string roadName, IConfigurationSettings configuration)
        {
            httpClient.BaseAddress = configuration.BaseUri;
            var httpClientAdapter = new HttpClientAdapter(httpClient);

            // Construct the api Uri to pass
            var uri = $"/road/{roadName}?app_id={configuration.AppId}&app_key={configuration.AppKey}";

            IResponseInterpreter <RoadCorridor> responseInterpreter = new ResponseInterpreter <RoadCorridor>(r => new CurrentRoadStatus
            {
                DisplayName               = r.DisplayName,
                StatusSeverity            = r.StatusSeverity,
                StatusSeverityDescription = r.StatusSeverityDescription
            });

            // Construct the api requestor passing in the httpClient and the class that interprets the response
            var apiRequestor = new ApiRequestor <RoadCorridor>(httpClientAdapter, responseInterpreter);

            // Make the request and format the response into the CurrentRoadStatus entity
            var interpretedResponse = await apiRequestor.GetApiResult(uri);

            // Deconstruct the response tuple
            var responseCode      = interpretedResponse.Item1;
            var currentRoadStatus = interpretedResponse.Item2;

            // Write out the appropriate message
            FormattedOutputFactory formattedOutputFactory = new FormattedOutputFactory(Console.Out);
            var formattedOutput = formattedOutputFactory.GenerateFormattedOutput(responseCode);

            formattedOutput.WriteOutput(roadName, currentRoadStatus);

            // Return an integer result to return back to the console
            return((int)responseCode);
        }
Ejemplo n.º 4
0
        public void InitWithNotNullValue_MustCreated()
        {
            var client = new HttpClient();
            var ada    = new HttpClientAdapter(client);

            Assert.AreEqual(ada.HttpClient, client);
        }
        public void Initialize()
        {
            _httpMessageHandler = new Mock <HttpMessageHandler>();

            _httpClientFactory = new Mock <IHttpClientFactory>();

            _httpClientAdapter = new HttpClientAdapter(_httpClientFactory.Object);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Construct a <see cref="GitHubClientFactory"/>
        /// </summary>
        /// <param name="gitHubConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="gitHubConfiguration"/></param>
        /// <param name="webRequestManager">The value of <see cref="webRequestManager"/></param>
        /// <param name="logger">The value of <see cref="logger"/></param>
        public GitHubClientFactory(IOptions <GitHubConfiguration> gitHubConfigurationOptions, IWebRequestManager webRequestManager, ILogger <GitHubClientFactory> logger)
        {
            gitHubConfiguration    = gitHubConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(gitHubConfigurationOptions));
            this.webRequestManager = webRequestManager ?? throw new ArgumentNullException(nameof(webRequestManager));
            this.logger            = logger ?? throw new ArgumentNullException(nameof(logger));

            httpClientAdapter = new HttpClientAdapter(HttpMessageHandlerFactory.CreateDefault);
        }
        public async Task OkStatusShouldPassThrough()
        {
            var handler = CreateMockHttpHandler(new HttpResponseMessage(HttpStatusCode.OK));
            var adapter = new HttpClientAdapter(handler);

            var httpRequestMessage = CreateRequest(HttpMethod.Get);

            var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Same(response.RequestMessage, httpRequestMessage);
        }
Ejemplo n.º 8
0
        public void SendAsync_WhenCalled_ShouldReturnHttpResponseMessage(
            HttpRequestMessage requestMessage)
        {
            // Arrange
            var sut = new HttpClientAdapter();

            // Act
            var actual = sut.SendAsync(requestMessage);

            // Assert
            actual.Should().NotBeNull();
        }
Ejemplo n.º 9
0
        /// <summary>The get compute api client.</summary>
        /// <param name="geoKey">The geo Key.</param>
        /// <param name="credentials">The User credentials</param>
        /// <param name="logFile">The Log File Path</param>
        /// <param name="connectionName">The Connection Name</param>
        /// <returns>The <see cref="IComputeApiClient"/>.</returns>
        private IComputeApiClient GetComputeApiClient(Uri baseUri, ApiMessageHandler messageHandler)
        {
            // Handle disposing the message handler
            var httpClient = new HttpClientAdapter(
                new HttpClient(messageHandler, disposeHandler: true)
            {
                BaseAddress = baseUri,
                Timeout     = TimeSpan.FromMinutes(5),
            });

            // we will not try to login again, assuming the clientId remains the same accross the regions
            return(new ComputeApiClient(httpClient));
        }
Ejemplo n.º 10
0
        public static GitHubClient Build()
        {
            var credentialStore = new InMemoryCredentialStore(Helper.Credentials);
            var httpClient      = new HttpClientAdapter(HttpMessageHandlerFactory.CreateDefault);

            var connection = new Connection(
                new ProductHeaderValue("ReleaseNotesCompiler"),
                GitHubClient.GitHubApiUrl,
                credentialStore,
                httpClient,
                new SimpleJsonSerializer());

            return(new GitHubClient(connection));
        }
Ejemplo n.º 11
0
        public ApplicationService(IAccountsService accountsService)
        {
            _accountsService = accountsService;

            accountsService.WhenAnyObservable(x => x.ActiveAccountChanged)
            .StartWith(accountsService.ActiveAccount)
            .Subscribe(account =>
            {
                if (account == null)
                {
                    Client       = null;
                    GitHubClient = null;
                }
                else
                {
                    var githubAccount = account;
                    var domain        = githubAccount.Domain ?? Client.DefaultApi;
                    Credentials credentials;

                    if (!string.IsNullOrEmpty(githubAccount.OAuth))
                    {
                        Client      = Client.BasicOAuth(githubAccount.OAuth, domain);
                        credentials = new Credentials(githubAccount.OAuth);
                    }
                    else if (githubAccount.IsEnterprise || !string.IsNullOrEmpty(githubAccount.Password))
                    {
                        Client      = Client.Basic(githubAccount.Username, githubAccount.Password, domain);
                        credentials = new Credentials(githubAccount.Username, githubAccount.Password);
                    }
                    else
                    {
                        Debugger.Break();
                        return;
                    }

                    // Decorate the HttpClient
                    IHttpClient httpClient = new HttpClientAdapter();
                    //httpClient = new OctokitCacheClient(httpClient);
                    httpClient = new OctokitNetworkClient(httpClient, Locator.Current.GetService <INetworkActivityService>());

                    var connection = new Connection(
                        new ProductHeaderValue("CodeHub"),
                        new Uri(domain),
                        new InMemoryCredentialStore(credentials),
                        httpClient,
                        new Octokit.Internal.SimpleJsonSerializer());
                    GitHubClient = new GitHubClient(connection);
                }
            });
        }
Ejemplo n.º 12
0
        public static GitHubClient Create(Uri domain, Credentials credentials)
        {
            var networkActivityService = Locator.Current.GetService <INetworkActivityService>();
            var client     = new HttpClientAdapter(CreateMessageHandler);
            var httpClient = new OctokitNetworkClient(client, networkActivityService);

            var connection = new Connection(
                UserAgent,
                domain,
                new InMemoryCredentialStore(credentials),
                httpClient,
                new SimpleJsonSerializer());

            return(new GitHubClient(connection));
        }
Ejemplo n.º 13
0
        public static GitHubClient Build()
        {
            var credentialStore = new InMemoryCredentialStore(GitHubHelper.Credentials);

            var httpClient = new HttpClientAdapter(null);

            var connection = new Connection(
                new ProductHeaderValue("ReleaseStats"),
                GitHubClient.GitHubApiUrl,
                credentialStore,
                httpClient,
                new SimpleJsonSerializer());

            return(new GitHubClient(connection));
        }
Ejemplo n.º 14
0
 protected IHttpResponse ExecutePostRequest <T>(IApiRequest apiRequest)
 {
     Ensure.ArgumentNotNull(nameof(apiRequest), apiRequest);
     try
     {
         using (var client = new HttpClientAdapter())
         {
             var response = client.PostData(apiRequest);
             return(GetResponseData <T>(response, CRUD.CrudTypes.Create));
         }
     }
     catch (Exception exception)
     {
         return(HandleHttpResponseExceptions(exception));
     }
 }
        public async Task Status303ShouldRedirectChangeMethod()
        {
            var redirectResponse = new HttpResponseMessage(HttpStatusCode.SeeOther);

            redirectResponse.Headers.Location = new Uri("http://example.org/bar");

            var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
            var adapter = new HttpClientAdapter(handler);

            var httpRequestMessage = CreateRequest(HttpMethod.Post);

            var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());

            Assert.Equal(HttpMethod.Get, response.RequestMessage.Method);
            Assert.NotSame(response.RequestMessage, httpRequestMessage);
        }
        public async Task <IActionResult> Test(string firstName)
        {
            var newModel = new UserLoginModel()
            {
                firstName = firstName
            };

            var content = new StringContent(JsonConvert.SerializeObject(newModel), Encoding.UTF8, "application/json");
            var url     = "User/Test";

            var post = await HttpClientAdapter.Post(BaseUri + url, content);

            var data = await HttpClientAdapter.GetAsync <UserLoginModel>(BaseUri + "User");

            return(Content($"Hello {data.firstName}"));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GoogleMapsApiClient"/> class.
        /// </summary>
        /// <param name="apiKey">
        /// The api key.
        /// </param>
        public GoogleMapsApiClient(string apiKey)
        {
            var url = EndPointUris.GetBaseUri();

            var httpClientHandler = new HttpClientHandler();
            var httpClient        = new HttpClientAdapter(
                new HttpClient(httpClientHandler, true)
            {
                BaseAddress = url
            });
            var webApi = new WebApi(httpClient, apiKey);

            PlaceSearch       = new PlaceSearch(webApi);
            GeocodingService  = new GeocodingService(webApi);
            DirectionsService = new DirectionsService(webApi);
        }
Ejemplo n.º 18
0
        public async Task CanCancelARequest()
        {
            var httpClient = new HttpClientAdapter(HttpMessageHandlerFactory.CreateDefault);
            var request    = new Request
            {
                BaseAddress = new Uri("https://github.global.ssl.fastly.net/", UriKind.Absolute),
                Endpoint    = new Uri("/images/icons/emoji/poop.png?v=5", UriKind.RelativeOrAbsolute),
                Method      = HttpMethod.Get,
                Timeout     = TimeSpan.FromMilliseconds(10)
            };

            var response = httpClient.Send(request, CancellationToken.None);

            await Task.Delay(TimeSpan.FromSeconds(2));

            Assert.True(response.IsCanceled);
        }
Ejemplo n.º 19
0
        protected async Task <IHttpResponse> ExecuteGetRequestAsync <T>(IApiRequest apiRequest)
        {
            Ensure.ArgumentNotNull(nameof(apiRequest), apiRequest);
            try
            {
                using (var client = new HttpClientAdapter())
                {
                    var response = await client.GetDataAsync(apiRequest, CancellationToken.None);

                    return(GetResponseData <T>(response, CRUD.CrudTypes.Read));
                }
            }
            catch (Exception exception)
            {
                return(HandleHttpResponseExceptions(exception));
            }
        }
Ejemplo n.º 20
0
        public static GitHubClient Create(Uri domain, Credentials credentials)
        {
            // Decorate the HttpClient
            //IHttpClient httpClient = new HttpClientAdapter();
            //httpClient = new OctokitCacheClient(httpClient);
            var client     = new HttpClientAdapter(CreateMessageHandler);
            var httpClient = new OctokitNetworkClient(client, Locator.Current.GetService <INetworkActivityService>());

            var connection = new Connection(
                new ProductHeaderValue("CodeHub"),
                domain,
                new InMemoryCredentialStore(credentials),
                httpClient,
                new SimpleJsonSerializer());

            return(new GitHubClient(connection));
        }
Ejemplo n.º 21
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            HttpButton.IsEnabled = false;

            try
            {
                using (var client = new HttpClientAdapter())
                    using (var response = client.GetAsync("https://www.thinktecture.com").GetAwaiter().GetResult())
                    {
                        Output.Text += $"HTTP GET https://www.thinktecture.com returned {response.StatusCode}";
                    }
            }
            finally
            {
                HttpButton.IsEnabled = true;
            }
        }
        [InlineData(HttpStatusCode.TemporaryRedirect)] // 307
        public async Task RedirectWithDifferentHostShouldLoseAuthHeader(HttpStatusCode statusCode)
        {
            var redirectResponse = new HttpResponseMessage(statusCode);

            redirectResponse.Headers.Location = new Uri("http://example.net/bar");

            var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
            var adapter = new HttpClientAdapter(handler);

            var httpRequestMessage = CreateRequest(HttpMethod.Get);

            httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue("fooAuth", "aparam");

            var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());

            Assert.NotSame(response.RequestMessage, httpRequestMessage);
            Assert.Null(response.RequestMessage.Headers.Authorization);
        }
        [InlineData(HttpStatusCode.TemporaryRedirect)] // 307
        public async Task Status301ShouldRedirectPOSTWithBody(HttpStatusCode statusCode)
        {
            var redirectResponse = new HttpResponseMessage(statusCode);

            redirectResponse.Headers.Location = new Uri("http://example.org/bar");

            var handler = CreateMockHttpHandler(redirectResponse, new HttpResponseMessage(HttpStatusCode.OK));
            var adapter = new HttpClientAdapter(handler);

            var httpRequestMessage = CreateRequest(HttpMethod.Post);

            httpRequestMessage.Content = new StringContent("Hello World");

            var response = await adapter.SendAsync(httpRequestMessage, new CancellationToken());

            Assert.Equal(response.RequestMessage.Method, httpRequestMessage.Method);
            Assert.NotSame(response.RequestMessage, httpRequestMessage);
        }
        public async Task Exceed3RedirectsShouldReturn()
        {
            var redirectResponse = new HttpResponseMessage(HttpStatusCode.Found);

            redirectResponse.Headers.Location = new Uri("http://example.org/bar");

            var redirectResponse2 = new HttpResponseMessage(HttpStatusCode.Found);

            redirectResponse2.Headers.Location = new Uri("http://example.org/foo");

            var handler = CreateMockHttpHandler(redirectResponse, redirectResponse2);
            var adapter = new HttpClientAdapter(handler);

            var httpRequestMessage = CreateRequest(HttpMethod.Get);

            await Assert.ThrowsAsync <InvalidOperationException>(
                () => adapter.SendAsync(httpRequestMessage, new CancellationToken()));
        }
        /// <summary>
        /// Gets the <c>HttpClientAdapter</c> instance from the config settings.
        /// </summary>
        /// <returns>Returns the <c>HttpClientAdapter</c> instance.</returns>
        private IHttpClient GetHttpClientAdapter()
        {
            var proxy    = this._settings.Proxy;
            var url      = proxy.Url;
            var domain   = proxy.Domain;
            var username = proxy.Username;
            var password = proxy.Password;

            var useDefaultCredentials = proxy.UseDefaultCredentials;
            var credentials           = useDefaultCredentials ? CredentialCache.DefaultNetworkCredentials : new NetworkCredential(username, password, domain);
            var webProxy = new WebProxy(url)
            {
                UseDefaultCredentials = useDefaultCredentials, Credentials = credentials
            };

            var httpClient = new HttpClientAdapter(webProxy);

            return(httpClient);
        }
Ejemplo n.º 26
0
        public async Task CanDownloadImage()
        {
            var httpClient = new HttpClientAdapter();
            var request = new Request
            {
                BaseAddress = new Uri("https://github.global.ssl.fastly.net/", UriKind.Absolute),
                Endpoint = new Uri("/images/icons/emoji/poop.png?v=5", UriKind.RelativeOrAbsolute),
                AllowAutoRedirect = true,
                Method = HttpMethod.Get
            };

            var imageBytes = await httpClient.Send<byte[]>(request, CancellationToken.None);

            // Spot check some of dem bytes.
            Assert.Equal(137, imageBytes.BodyAsObject[0]);
            Assert.Equal(80, imageBytes.BodyAsObject[1]);
            Assert.Equal(78, imageBytes.BodyAsObject[2]);
            Assert.Equal(130, imageBytes.BodyAsObject.Last());
        }
Ejemplo n.º 27
0
        public async Task <bool> CallWebService(HttpClientAdapter httpClient, string dateOnly)
        {
            using (httpClient)
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get,
                                                                    new Uri($"https://kayaposoft.com/enrico/json/v1.0/?action=isPublicHoliday&date={dateOnly}&country=usa"));
                request.Headers.Add("Connection", "close");

                HttpResponseMessage response = await httpClient.SendAsync(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(false);
                }

                EnricoResponse enricoResponse = DeserializeResponse <EnricoResponse>(await response.Content.ReadAsStringAsync());
                return(enricoResponse.isPublicHoliday);
            }
        }
Ejemplo n.º 28
0
        public async Task CanDownloadImage()
        {
            var httpClient = new HttpClientAdapter(HttpMessageHandlerFactory.CreateDefault);
            var request    = new Request
            {
                BaseAddress = new Uri("https://github.global.ssl.fastly.net/", UriKind.Absolute),
                Endpoint    = new Uri("/images/icons/emoji/poop.png?v=5", UriKind.RelativeOrAbsolute),
                Method      = HttpMethod.Get
            };

            var response = await httpClient.Send(request, CancellationToken.None);

            // Spot check some of dem bytes.
            var imageBytes = (byte[])response.Body;

            Assert.Equal(137, imageBytes[0]);
            Assert.Equal(80, imageBytes[1]);
            Assert.Equal(78, imageBytes[2]);
            Assert.Equal(130, imageBytes.Last());
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Creates and returns a <see cref="IHttpClient"/> using the given options,
        /// which may share an internal <see cref="HttpClient"/> with other instances.
        /// </summary>
        /// <param name="handlerOptions"></param>
        /// <returns></returns>
        public IHttpClient Create(HttpClientHandlerOptions handlerOptions)
        {
            // You're not supposed to create an HttpClient for each request:
            // * https://github.com/mspnp/performance-optimization/blob/master/ImproperInstantiation/docs/ImproperInstantiation.md
            // * https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

            // But an HttpClient maybe never updates its DNS cache, so you
            // don't necessarily want to keep one open forever:
            // * https://github.com/dotnet/corefx/issues/11224
            // * http://byterot.blogspot.co.uk/2016/07/singleton-httpclient-dns.html
            // * http://www.nimaara.com/2016/11/01/beware-of-the-net-httpclient/

            // So for now we're going to keep a shared HttpClient alive, but
            // only for an hour or so before we recreate it.

            if (handlerOptions == null)
            {
                handlerOptions = CreateDefaultHttpClientHandlerOptions();
            }

            HttpClientNode httpClientNode;
            HttpClientNode oldHttpClientNode = null;

            if (cachedHttpClientDictionary.TryGetValue(handlerOptions, out httpClientNode))
            {
                if (httpClientNode.ExpirationTimeUtc < DateTime.UtcNow)
                {
                    cachedHttpClientDictionary.TryRemove(handlerOptions, out oldHttpClientNode);
                    httpClientNode = null;
                }
            }

            if (httpClientNode == null)
            {
                httpClientNode = cachedHttpClientDictionary.GetOrAdd(handlerOptions, CreateHttpClientNode);
            }

            var result = new HttpClientAdapter(httpClientNode.HttpClient);

            return(result);
        }
		public ComputeApiClient(string targetRegionName)
		{
			if (string.IsNullOrWhiteSpace(targetRegionName))
				throw new ArgumentException(
					"Argument cannot be null, empty, or composed entirely of whitespace: 'targetRegionName'.", "targetRegionName");

			KnownApiRegion region;
			if (!KnownApiRegion.TryParse(targetRegionName, true, out region))
				throw new ArgumentException("targetRegionName doesnt map to a valid region", "targetRegionName");

			Uri baseUri = KnownApiUri.Instance.GetBaseUri(KnownApiVendor.DimensionData, region);
			_httpClientHandler = new HttpClientHandler();
			var httpClient = new HttpClientAdapter(
				new HttpClient(
					_httpClientHandler, disposeHandler: true)
				{
					BaseAddress = baseUri
				});

			InitializeProperties(httpClient);
		}
Ejemplo n.º 31
0
        public static GitHubClient Create(
            Uri domain,
            Credentials credentials,
            TimeSpan?requestTimeout = null)
        {
            var networkActivityService = Locator.Current.GetService <INetworkActivityService>();
            var client     = new HttpClientAdapter(CreateMessageHandler);
            var httpClient = new OctokitNetworkClient(client, networkActivityService);

            var connection = new Connection(
                UserAgent,
                domain,
                new InMemoryCredentialStore(credentials),
                httpClient,
                new SimpleJsonSerializer());

            var gitHubClient = new GitHubClient(connection);

            gitHubClient.SetRequestTimeout(requestTimeout ?? TimeSpan.FromSeconds(20));
            return(gitHubClient);
        }
		public ComputeApiClient(KnownApiRegion region)
		{
			Uri baseUri = KnownApiUri.Instance.GetBaseUri(KnownApiVendor.DimensionData, region);
			_httpClientHandler = new HttpClientHandler();
			var httpClient = new HttpClientAdapter(
				new HttpClient(
					_httpClientHandler, disposeHandler: true)
				{
					BaseAddress = baseUri
				});

			InitializeProperties(httpClient);
		}
		/// <summary>
		/// The get compute api client.
		/// </summary>
		/// <param name="baseUri">
		/// The base uri.
		/// </param>
		/// <param name="credentials">
		/// The credentials.
		/// </param>
		/// <param name="organizationId">
		/// The organization id.
		/// </param>
		/// <returns>
		/// The <see cref="ComputeApiClient"/>.
		/// </returns>
		/// <exception cref="ArgumentNullException">
		/// </exception>
		/// <exception cref="ArgumentException">
		/// </exception>
		public static ComputeApiClient GetComputeApiClient(Uri baseUri, ICredentials credentials, Guid organizationId = default(Guid))
		{
			if (baseUri == null)
				throw new ArgumentNullException("baseUri", "baseUri cannot be null");

			if (!baseUri.IsAbsoluteUri)
				throw new ArgumentException("Base URI supplied is not an absolute URI", "baseUri");

			if (credentials == null)
				throw new ArgumentNullException("credentials", "credentials cannot be null");

			var messageHandler = new HttpClientHandler
			{
				Credentials = credentials,
				PreAuthenticate = true
			};
			// Handle disposing the message handler
			var httpClient = new HttpClientAdapter(
				new HttpClient(
					messageHandler, disposeHandler: true)
				{
					BaseAddress = baseUri
				});

			return new ComputeApiClient(httpClient, organizationId);
		}
		public ComputeApiClient(Uri baseUri)
		{
			if (baseUri == null)
				throw new ArgumentNullException("baseUri", "Argument cannot be null");

			if (!baseUri.IsAbsoluteUri)
				throw new ArgumentException("Base URI supplied is not an absolute URI", "baseUri");
			
			_httpClientHandler = new HttpClientHandler();

			var httpClient = new HttpClientAdapter(
				new HttpClient(
					_httpClientHandler, disposeHandler: true)
				{
					BaseAddress = baseUri
				});

			InitializeProperties(httpClient);
		}
Ejemplo n.º 35
0
 public StubAdapterFactory(HttpClientAdapter adapter)
 {
     _adapter = adapter;
 }