コード例 #1
0
        public void Retry_success()
        {
            // Arrange the Http client
            var mockHttp = new MockHttpMessageHandler();

            // First attempt, we return HTTP 429 which means TOO MANY REQUESTS
            mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429);

            // Second attempt, we return the expected result
            mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}");

            var httpClient = new HttpClient(mockHttp);

            // Arrange the Request coordinator
            var coordinator = new RetryCoordinator(
                2,
                (response) => response.StatusCode == (HttpStatusCode)429,
                (attempts, response) => TimeSpan.Zero);

            // Arrange the fluent htpp client
            var fluentClient = new FluentClient("https://api.fictitious-vendor.com/v1/", httpClient)
                               .SetRequestCoordinator(coordinator);

            // Act
            var result = fluentClient
                         .GetAsync("endpoint")
                         .As <JObject>()
                         .Result;

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
            Assert.That(result.Value <string>("name"), Is.EqualTo("This is a test"));
        }
コード例 #2
0
        public async Task PostApiTestMethod()
        {
            var userModelObj = new UserModel()
            {
                FirstName = "Kishor",
                LastName  = "Naik"
            };

            IClient client = new FluentClient("http://localhost:49506/api/users");

            // Post Work
            //var data =
            //        await
            //            client
            //            .PostAsync<UserModel>("postdemo", userModelObj)
            //            .As<UserModel>();

            //// Post Array Work
            //var data =
            //        await
            //            client
            //            .PostAsync("postdemoarray")
            //            .As<List<UserModel>>();

            var data =
                await
                client
                .GetAsync("getdemo/11")
                .As <int>();

            Assert.IsNotNull(data);
        }
コード例 #3
0
 public static async Task <JObject> PostRequest_NoBody(FluentClient client, string uri, CancellationToken cancellationToken)
 {
     return(await client
            .PostAsync(uri)
            .WithCancellationToken(cancellationToken)
            .AsRawJsonObject());
 }
コード例 #4
0
        protected override async Task <Action <NativeActivityContext> > ExecuteAsync(NativeActivityContext context, CancellationToken cancellationToken)
        {
            // Inputs
            var username       = AccountUsername.Get(context);
            var password       = AppPassword.Get(context);
            var passwordString = new System.Net.NetworkCredential(string.Empty, password).Password;

            //Prepare default header
            var authHeaderString         = username + ":" + passwordString; // This is the format used in the HTTP request header.
            var base64EncodedCredentials = Base64Encode(authHeaderString);

            // Create client and assign default request header
            var defaultHttpClient = new HttpClient();

            defaultHttpClient.DefaultRequestHeaders
            .Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedCredentials);

            var client = new FluentClient("https://api.bitbucket.org/2.0/", defaultHttpClient);

            // Send to child activities
            _objectContainer.Add(client);

            return((ctx) =>
            {
                // Schedule child activities
                if (Body != null)
                {
                    ctx.ScheduleAction <IObjectContainer>(Body, _objectContainer, OnCompleted, OnFaulted);
                }

                // Outputs
            });
        }
コード例 #5
0
        public void Retry_failure()
        {
            // Arrange the Http client
            var mockHttp = new MockHttpMessageHandler();

            // Three successive HTTP 429 (which mean TOO MANY REQUESTS)
            mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429);
            mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429);
            mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429);

            var httpClient = new HttpClient(mockHttp);

            // Arrange the Request coordinator
            var coordinator = new RetryCoordinator(
                3,
                (response) => response.StatusCode == (HttpStatusCode)429,
                (attempts, response) => TimeSpan.Zero);

            // Arrange the fluent http client
            var fluentClient = new FluentClient("https://api.fictitious-vendor.com/v1/", httpClient)
                               .SetRequestCoordinator(coordinator);

            // Act
            Assert.ThrowsAsync <ApiException>(async() => await fluentClient.GetAsync("endpoint").As <JObject>());

            // Assert
            mockHttp.VerifyNoOutstandingExpectation();
            mockHttp.VerifyNoOutstandingRequest();
        }
コード例 #6
0
 public void GivenACollectionOfPostsExposedAsApi()
 {
     //arrange
     apiUrl         = "https://jsonplaceholder.typicode.com";
     client         = new FluentClient();
     client.BaseUri = new Uri(apiUrl, UriKind.Absolute);
 }
コード例 #7
0
        public IntegrationTestsBase(ITestOutputHelper output) : base(output)
        {
            var builder = new MvcWebApplicationBuilder <Startup>()
                          .UseSolutionRelativeContentRoot("src/Exceptionless.Api")
                          .ConfigureBeforeStartup(Configure)
                          .ConfigureAfterStartup(RegisterServices)
                          .UseApplicationAssemblies();

            _server = builder.Build();

            var settings = GetService <Newtonsoft.Json.JsonSerializerSettings>();

            _serializer = GetService <ITextSerializer>();
            _client     = new FluentClient(new JsonContentSerializer(settings), _server.CreateHandler())
            {
                BaseUri = new Uri(_server.BaseAddress + "api/v2")
            };
            _httpClient = new HttpClient(_server.CreateHandler())
            {
                BaseAddress = new Uri(_server.BaseAddress + "api/v2/")
            };

            _configuration = GetService <ExceptionlessElasticConfiguration>();
            _configuration.DeleteIndexesAsync().GetAwaiter().GetResult();
            _configuration.ConfigureIndexesAsync(beginReindexingOutdated: false).GetAwaiter().GetResult();
        }
コード例 #8
0
ファイル: EchoTests.cs プロジェクト: tablesmit/FluentRest
        private static FluentClient CreateClient()
        {
            var client = new FluentClient();

            client.BaseUri = new Uri("http://httpbin.org/", UriKind.Absolute);
            return(client);
        }
コード例 #9
0
ファイル: ClutchTests.cs プロジェクト: elmore/Clutch
        public void CreatesModel()
        {
            var model = new User
            {
                GenderId = 0,
                OccupationId = 0,
                Firstname = "",
                Lastname = "",
                Email = "",
                Phone = "",
                ShowPhone = false,
                LanguageCode = 1,
                Age = 18,
                AffiliateCode  = "",
                Ip = "",
            };

            FluentResponse<User, Error> result = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Post<User>(model).Result;

            Assert.IsNotNull(result);

            Assert.IsNotNull(result.Entity);

            Assert.IsNotNullOrEmpty(result.Entity.Id);
        }
コード例 #10
0
        public IntegrationTestsBase(ITestOutputHelper output, AppWebHostFactory factory) : base(output)
        {
            Log.MinimumLevel = LogLevel.Information;
            Log.SetLogLevel <ScheduledTimer>(LogLevel.Warning);
            Log.SetLogLevel <InMemoryMessageBus>(LogLevel.Warning);
            Log.SetLogLevel <InMemoryCacheClient>(LogLevel.Warning);
            Log.SetLogLevel <InMemoryMetricsClient>(LogLevel.Information);
            Log.SetLogLevel("StartupActions", LogLevel.Warning);
            Log.SetLogLevel <Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager>(LogLevel.Warning);

            var configuredFactory = factory.Factories.FirstOrDefault();

            if (configuredFactory == null)
            {
                configuredFactory = factory.WithWebHostBuilder(builder => {
                    builder.ConfigureTestServices(RegisterServices); // happens after normal container configure and overrides services
                });
            }

            _disposables.Add(_testSystemClock);

            _httpClient             = configuredFactory.CreateClient();
            _server                 = configuredFactory.Server;
            _httpClient.BaseAddress = new Uri(_server.BaseAddress + "api/v2/", UriKind.Absolute);

            var testScope = configuredFactory.Services.CreateScope();

            _disposables.Add(testScope);
            ServiceProvider = testScope.ServiceProvider;

            var settings = GetService <JsonSerializerSettings>();

            _client        = new FluentClient(_httpClient, new NewtonsoftJsonSerializer(settings));
            _configuration = GetService <ExceptionlessElasticConfiguration>();
        }
コード例 #11
0
        public NetFlagrHttpClient(HttpClient httpClient, IOptions <NetFlagrConfiguration> configuration)
        {
            if (configuration.Value == null)
            {
                configuration = Options.Create <NetFlagrConfiguration>(new NetFlagrConfiguration());
            }

            _configuration = configuration.Value;
            if (string.IsNullOrEmpty(_configuration.BasePath))
            {
                throw new ArgumentException("basePath cannot be empty");
            }

            httpClient.Timeout = TimeSpan.FromMilliseconds(_configuration.Timeout);
            _client            = new FluentClient(new Uri(_configuration.BasePath), httpClient);
            _client.Filters.Clear();
            if (!string.IsNullOrEmpty(_configuration.UserAgent))
            {
                _client.SetUserAgent(_configuration.UserAgent);
            }
            else
            {
                Version version = typeof(NetFlagrApiClient).GetTypeInfo().Assembly.GetName().Version;
                _client.SetUserAgent($"NetFlagrHttpClient/{version} (+http://github.com/checkr/NetFlagrHttpClient)");
            }
        }
コード例 #12
0
        public override AccountsResponse GetAccount(string AccountId, string bank_id, string view_id)
        {
            AccountsResponse result = new AccountsResponse();

            try {
                LoginBindResponse loginData = doLogin();
                //banks/322/accounts/21-1-99999-4-6/owner
                string urlData = String.Format("banks/{0}/accounts/{1}/{2}", bank_id, AccountId, view_id);

                string JsonResult = new FluentClient(config.Url)
                                    .GetAsync(urlData)
                                    .WithHeader("Authorization", "JWT " + loginData.token)
                                    .WithOptions(true)
                                    .AsString().Result;

                result.accounts = new List <Account>();
                result.accounts.Add(JsonConvert.DeserializeObject <Account>(JsonResult));

                result.executeStatus = getExecuteStatus(JsonResult, urlData);
            } catch (CustomException cEx) {
                result.executeStatus = cEx.convertToCustomStatus();
            } catch (Exception ex) {
                result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus();
            }

            return(result);
        }
コード例 #13
0
ファイル: Runner.cs プロジェクト: geddar2014/Updater2
 protected async Task <T> GetAsync <T>(string url)
 {
     using (var client = new FluentClient(baseUri))
     {
         return(await client.GetAsync(url).As <T>());
     }
 }
コード例 #14
0
        public void CreatesModel()
        {
            var model = new User
            {
                GenderId      = 0,
                OccupationId  = 0,
                Firstname     = "",
                Lastname      = "",
                Email         = "",
                Phone         = "",
                ShowPhone     = false,
                LanguageCode  = 1,
                Age           = 18,
                AffiliateCode = "",
                Ip            = "",
            };

            FluentResponse <User, Error> result = new FluentClient <Error>("http://local.property.erm-api.com/v1/").Post <User>(model).Result;

            Assert.IsNotNull(result);

            Assert.IsNotNull(result.Entity);

            Assert.IsNotNullOrEmpty(result.Entity.Id);
        }
コード例 #15
0
        public override ViewsResponse GetViewsByBankId(string bank_id)
        {
            ViewsResponse result = new ViewsResponse();

            try {
                LoginBindResponse loginData = doLogin();
                string            urlData   = String.Format("banks/{0}/accounts", bank_id);

                string JsonResult = new FluentClient(config.Url)
                                    .GetAsync(urlData)
                                    .WithHeader("Authorization", "JWT " + loginData.token)
                                    .WithOptions(true)
                                    .AsString().Result;

                result.views = JsonConvert.DeserializeObject <List <View> >(JsonResult);

                result.executeStatus = getExecuteStatus(JsonResult, urlData);
            } catch (CustomException cEx) {
                result.executeStatus = cEx.convertToCustomStatus();
            } catch (Exception ex) {
                result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus();
            }

            return(result);
        }
コード例 #16
0
        public override Person GetPersonByCUIT(string cuit)
        {
            Person result = new Person();

            try {
                LoginBindResponse loginData = doLogin();

                string urlData = String.Format("persons/{0}/banks", cuit);

                string JsonResult = new FluentClient(config.Url)
                                    .GetAsync(urlData)
                                    .WithHeader("Authorization", "JWT " + loginData.token)
                                    .WithOptions(true)
                                    .AsString().Result;

                result = JsonConvert.DeserializeObject <Person>(JsonResult);
                CustomStatus bindException;

                result.executeStatus = getExecuteStatus(JsonResult, urlData);
            } catch (CustomException cEx) {
                result.executeStatus = cEx.convertToCustomStatus();
            } catch (Exception ex) {
                result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus();
            }
            return(result);
        }
コード例 #17
0
        /*********
        ** Protected methods
        *********/
        /// <summary>Construct an HTTP client with the JSON.NET formatter.</summary>
        /// <param name="url">The base URI prepended to relative request URIs.</param>
        protected IClient ConstructClient(string url)
        {
            IClient client = new FluentClient(url);

            client.Formatters.Remove(client.Formatters.JsonFormatter);
            client.Formatters.Add(new JsonNetFormatter());
            return(client);
        }
コード例 #18
0
ファイル: GoogleTests.cs プロジェクト: modulexcite/FluentRest
        private static FluentClient CreateClient(FakeResponseMode mode = FakeResponseMode.Capture)
        {
            var serializer = new JsonContentSerializer();
            var fakeHttp = new FakeMessageHandler { Mode = mode };

            var client = new FluentClient(serializer, fakeHttp);
            return client;
        }
コード例 #19
0
 public async Task <string> GetToken()
 {
     using (var fluentClient = new FluentClient($"{Addresses.ServerUrl}api/"))
     {
         //TODO: Use hash
         return(await(await fluentClient.GetAsync($"Authentication/terminal/hash/testing")).As <string>());
     }
 }
コード例 #20
0
 internal static async Task <IDictionary <string, ModInfoModel> > CheckModUpdate(string[] modKeys, MainWindow mf)
 {
     using (IClient client = new FluentClient("https://api.smapi.io/v2.0/"))
     {
         return(await client
                .PostAsync("mods", new ModSearchModel(modKeys))
                .As <IDictionary <string, ModInfoModel> >());
     }
 }
コード例 #21
0
        public static async Task <JObject> PostRequestAsync(String uri, String parameters)
        {
            {
                //using (var httpClient = new HttpClient())
                //{
                //    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.bitbucket.org/2.0/repositories/WildWoz/test-repo/src"))
                //    {
                //        var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("WildWoz:F4vTWxGmZTgQDkTYgk6m"));
                //        request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");

                //        var multipartContent = new MultipartFormDataContent();
                //        multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("C:/Users/adam.wozniak/Desktop/NewFolder/test.txt")), "/test15.txt", Path.GetFileName("C:/Users/adam.wozniak/Desktop/NewFolder/test.txt"));
                //        request.Content = multipartContent;

                //        var response = await httpClient.SendAsync(request);
                //    }
                //}


                var username = "******";
                var password = "******";
                var plainText_usernamePassword     = System.Text.Encoding.UTF8.GetBytes(username + ":" + password);
                var base64encoded_usernamePassword = System.Convert.ToBase64String(plainText_usernamePassword);


                var defaultHttpClient = new HttpClient();
                defaultHttpClient.DefaultRequestHeaders
                .Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encoded_usernamePassword);

                IClient client   = new FluentClient("https://api.bitbucket.org/2.0/", defaultHttpClient);
                var     messages = new JObject();

                var multipartContent = new MultipartFormDataContent();
                multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("C:/Users/adam.wozniak/Desktop/NewFolder/TestDoc.docx")), "/a-tashFile-docx.docx", Path.GetFileName("C:/Users/adam.wozniak/Desktop/NewFolder/TestDoc.docx"));
                multipartContent.Add(new StringContent("comitting Tash first docx file."), "message");

                var url         = "repositories/WildWoz/test-repo2/src";
                var responseRaw = await client
                                  .PostAsync(url)
                                  .WithBody(multipartContent)
                                  .AsString();

                var response = new JObject();
                if (responseRaw == "")
                {
                    response = JObject.Parse("{\"response\":\"Commit successful\"}");
                }
                else
                {
                    response = JObject.Parse(responseRaw);
                }
                Console.WriteLine(responseRaw);

                return(response);
            }
        }
コード例 #22
0
        public void RetrievesModelFromRoot()
        {
            Room room = new FluentClient <Error>("http://local.property.erm-api.com/v1/").Get <Room>("H151006172656205").Result.Entity;

            Assert.IsNotNull(room);

            Assert.AreEqual("H151006172656205", room.Id);

            Assert.AreEqual("my city", room.City);
        }
コード例 #23
0
        public static async Task <JObject> DeleteRequest(FluentClient client, string uri, CancellationToken cancellationToken)
        {
            var responseRaw = await client
                              .DeleteAsync(uri)
                              .WithCancellationToken(cancellationToken);

            var response = JObject.Parse("{\"response\":\"Deletion successful\"}");

            return(response);
        }
コード例 #24
0
        public static Pathoschild.Http.Client.IClient GetFluentClient(MockHttpMessageHandler httpMessageHandler)
        {
            var httpClient = httpMessageHandler.ToHttpClient();
            var client     = new FluentClient(SENDGRID_API_BASE_URI, httpClient);

            client.SetRequestCoordinator(new SendGridRetryStrategy());
            client.Filters.Remove <DefaultErrorFilter>();
            client.Filters.Add(new SendGridErrorHandler());
            return(client);
        }
コード例 #25
0
        private static IFluentClient CreateClient()
        {
            var httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri("http://httpbin.org/", UriKind.Absolute);

            var fluentClient = new FluentClient(httpClient);

            return(fluentClient);
        }
コード例 #26
0
            public static async Task <Responses.RemovePlayerGameBanResponse> RemovePlayerGameBan(ulong steamId)
            {
                var responseData = await FluentClient.PostAsync("ICheatReportingService/RequestPlayerGameBan/v1")
                                   .WithArgument("key", PublisherApiKey)
                                   .WithArgument("appid", AppId)
                                   .WithArgument("steamid", steamId)
                                   .As <SteamworksWebApiResponse2 <Responses.RemovePlayerGameBanResponse> >();

                return(responseData.Response);
            }
コード例 #27
0
        //Devuelve los tipos de origen
        public async Task <Types> getSourceTypes()
        {
            using (var client = new FluentClient(_baseUrl))
            {
                var rest = await client.GetAsync(API.ver + Config.SourceTypes)
                           .WithHeader(Config.Header.cache, Config.cache)
                           .WithHeader(Config.Header.key, _key).As <Types>();

                return(rest);
            }
        }
コード例 #28
0
        //Devuelve un esquema con un id específico.
        public async Task <Schema> getSchemaId(string id)
        {
            using (var client = new FluentClient(_baseUrl))
            {
                var rest = await client.GetAsync(API.ver + Config.SchemasId + id)
                           .WithHeader(Config.Header.cache, Config.cache)
                           .WithHeader(Config.Header.key, _key).As <Schema>();

                return(rest);
            }
        }
コード例 #29
0
        //Verifica si la tarea de promover un schema se está ejecutando
        public async Task <PromoteSchema> getPromoteSchema()
        {
            using (var client = new FluentClient(_baseUrl))
            {
                var rest = await client.GetAsync(API.ver + Config.PromoteSchema)
                           .WithHeader(Config.Header.cache, Config.cache)
                           .WithHeader(Config.Header.key, _key).As <PromoteSchema>();

                return(rest);
            }
        }
コード例 #30
0
        public async Task <IEnumerable <ModEntryModel> > PostAsync([FromBody] ModSearchModel model)
        {
            using IClient client = new FluentClient("https://smapi.io/api");

            Startup.ConfigureJsonNet(client.Formatters.JsonFormatter.SerializerSettings);

            return(await client
                   .PostAsync(this.Request.Path)
                   .WithBody(model)
                   .AsArray <ModEntryModel>());
        }
コード例 #31
0
        private FluentClient CreateClient()
        {
            var client = FluentClient.Create(c => c
                                             .Interceptor(new LogInterceptor(_output.WriteLine))
                                             .Defaults(d => d
                                                       .State("happy", "joy")
                                                       .BaseUri(new Uri("http://httpbin.org/", UriKind.Absolute)))
                                             );

            return(client);
        }
コード例 #32
0
        //Devuelve el estado de los procesos.
        public async Task <Status> getStatusProcesses()
        {
            using (var client = new FluentClient(_baseUrl))
            {
                var rest = await client.GetAsync(API.ver + Config.ProcessesStatus)
                           .WithHeader(Config.Header.cache, Config.cache)
                           .WithHeader(Config.Header.key, _key).As <Status>();

                return(rest);
            }
        }
コード例 #33
0
        private static FluentClient CreateClient()
        {
            var serializer = new JsonContentSerializer();

            var fakeStore = MemoryMessageStore.Current;
            var fakeHttp = new FakeMessageHandler(fakeStore, FakeResponseMode.Fake);

            var client = new FluentClient(serializer, fakeHttp);
            client.BaseUri = new Uri("http://httpbin.org/", UriKind.Absolute);

            return client;
        }
コード例 #34
0
ファイル: ClutchTests.cs プロジェクト: elmore/Clutch
        public void CanUseClientForDifferentCalls()
        {
            var client = new FluentClient<Error>("http://local.property.erm-api.com/v1/");

            Room room1 = client.Get<Room>("H151006172656205").Result.Entity;

            Room room2 = client.Get<Room>("H151006172656205").Result.Entity;

            Assert.IsNotNull(room1);

            Assert.IsNotNull(room2);
        }
コード例 #35
0
ファイル: GitHubTests.cs プロジェクト: modulexcite/FluentRest
        private static FluentClient CreateClient()
        {
            var serializer = new JsonContentSerializer();

            var fakeStore = new FileMessageStore();
            fakeStore.StorePath = @".\GitHub\Responses";

            var fakeHttp = new FakeMessageHandler(fakeStore, FakeResponseMode.Fake);

            var client = new FluentClient(serializer, fakeHttp);
            client.BaseUri = new Uri("https://api.github.com/", UriKind.Absolute);

            return client;
        }
コード例 #36
0
ファイル: ClutchTests.cs プロジェクト: elmore/Clutch
        public void HandlesNetworkFailure()
        {
            var client = new FluentClient<Error>("http://local.property.erm-api.com/v1/");

            // server set up to fail on this code
            FluentResponse<User, Error> room = client.Get<User>("forceerror").Result;

            Assert.IsNotNull(room);

            Assert.IsNull(room.Entity);

            Assert.AreEqual(401, (int)room.StatusCode);

            Assert.AreEqual("Authenticate", room.Error.Message);
        }
コード例 #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InterceptorResponseContext" /> class.
 /// </summary>
 /// <param name="client">The current <see cref="FluentClient" /> that called the interceptor.</param>
 /// <param name="httpResponse">The <see cref="HttpResponseMessage" /> received from the HTTP call.</param>
 /// <param name="exception">The exception that occurred during the HTTP request.</param>
 public InterceptorResponseContext(FluentClient client, HttpResponseMessage httpResponse, Exception exception)
 {
     Client = client;
     HttpResponse = httpResponse;
     Exception = exception;
 }
コード例 #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="InterceptorRequestContext"/> class.
 /// </summary>
 /// <param name="client">The current <see cref="FluentClient"/>.</param>
 /// <param name="request">The <see cref="FluentRequest"/> used to build the current request.</param>
 public InterceptorRequestContext(FluentClient client, FluentRequest request)
 {
     Client = client;
     Request = request;
 }
コード例 #39
0
ファイル: ClutchTests.cs プロジェクト: elmore/Clutch
        public void RetrievesModelFromRoot()
        {
            Room room = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Get<Room>("H151006172656205").Result.Entity;

            Assert.IsNotNull(room);

            Assert.AreEqual("H151006172656205", room.Id);

            Assert.AreEqual("my city", room.City);
        }
コード例 #40
0
ファイル: ClutchTests.cs プロジェクト: elmore/Clutch
 public void RetreivesSubModel()
 {
     var room = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Find<User>(1).Get<Room>("h123123");
 }
コード例 #41
0
ファイル: ClutchTests.cs プロジェクト: elmore/Clutch
 public void RetreivesSubModel()
 {
     var room = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Find<Room>("H151006172656205").Get<User>(1);
 }
コード例 #42
0
		/// <summary>Construct an <see cref="IClient"/> instance and assert that its initial state is valid.</summary>
		/// <param name="baseUri">The base URI prepended to relative request URIs.</param>
		/// <param name="inconclusiveOnFailure">Whether to throw an <see cref="InconclusiveException"/> if the initial state is invalid.</param>
		/// <exception cref="InconclusiveException">The initial state of the constructed client is invalid, and <paramref name="inconclusiveOnFailure"/> is <c>true</c>.</exception>
		/// <exception cref="AssertionException">The initial state of the constructed client is invalid, and <paramref name="inconclusiveOnFailure"/> is <c>false</c>.</exception>
		protected IClient ConstructClient(string baseUri = "http://example.com/", bool inconclusiveOnFailure = true)
		{
			try
			{
				// execute
				IClient client = new FluentClient(baseUri);

				// verify
				Assert.NotNull(client.BaseClient, "The base client is null.");
				Assert.AreEqual(baseUri, client.BaseClient.BaseAddress.ToString(), "The base path is invalid.");

				return client;
			}
			catch (AssertionException exc)
			{
				if (inconclusiveOnFailure)
					Assert.Inconclusive("The client could not be constructed: {0}", exc.Message);
				throw;
			}
		}
コード例 #43
0
ファイル: EchoTests.cs プロジェクト: modulexcite/FluentRest
 private static FluentClient CreateClient()
 {
     var client = new FluentClient();
     client.BaseUri = new Uri("http://httpbin.org/", UriKind.Absolute);
     return client;
 }