public void ByPostShouldReturnCorrectResponse()
        {
            var controller = typeof(CategoriesController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/categories/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
            }
        }
        [InlineData("GET", "http://localhost/Customers(12)/NS.SpecialCustomer/NS.GetSalary()", "GetSalaryFromSpecialCustomer_12")] // call function on derived entity type
        public async Task AttriubteRouting_SelectsExpectedControllerAndAction(string method, string requestUri,
            string expectedResult)
        {
            // Arrange
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            var controllers = new[] { typeof(CustomersController), typeof(MetadataAndServiceController), typeof(OrdersController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new MockAssembly(controllers));

            HttpConfiguration config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(typeof(IAssembliesResolver), resolver);

            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(new HttpMethod(method), requestUri);

            // Act
            var response = await client.SendAsync(request);

            // Assert
            if (!response.IsSuccessStatusCode)
            {
                Assert.False(true, await response.Content.ReadAsStringAsync());
            }
            var result = await response.Content.ReadAsAsync<AttributeRoutingTestODataResponse>();
            Assert.Equal(expectedResult, result.Value);
        }
 public ODataSingletonTest()
 {
     _configuration = new[] { typeof(OscorpController), typeof(OscorpSubsController) }.GetHttpConfiguration();
     _configuration.MapODataServiceRoute("odata", "odata", GetEdmModel());
     HttpServer server = new HttpServer(_configuration);
     _client = new HttpClient(server);
 }
Exemple #4
0
 public SensorErrorTests()
 {
     var configuration1 = new HttpConfiguration();
     configuration1.MapSensorRoutes(ctx => true);
     var server = new HttpServer(configuration1);
     apiClient = new HttpClient(server);
 }
Exemple #5
0
 public SensorRoutingTests()
 {
     configuration = new HttpConfiguration();
     configuration.MapSensorRoutes(ctx => true);
     var server = new HttpServer(configuration);
     apiClient = new HttpClient(server);
 }
		/// <summary>
		/// Configure all the OWIN modules that participate in each request.
		/// </summary>
		/// <param name="app">The OWIN appBuilder</param>
		/// <remarks>
		/// The order of configuration is IMPORTANT - it sets the sequence of the request processing pipeline.
		/// </remarks>
		public void Configuration(IAppBuilder app)
		{
#if DEBUG
			// Debug builds get full call stack in error pages.
			app.Properties["host.AppMode"] = "development";
#else
			app.Properties["host.AppMode"] = "release";
#endif

			// DependencyInjection config
			var diContainer = new Container { Options = { AllowOverridingRegistrations = true } };
			diContainer.RegisterModules(new ODataServiceModule(), new AppModule());

			// Configure logging
			ConfigureOwinLogging(app, diContainer);

			// Web API config
			var webApiConfig = new HttpConfiguration();
			webApiConfig.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(diContainer);

			// Map routes using class attributes
			webApiConfig.MapHttpAttributeRoutes();

			HttpServer webApiServer = new HttpServer(webApiConfig);
			WebApiConfig.ConfigureODataService(webApiConfig, webApiServer);

			app.UseWebApi(webApiServer);
		}
        public void IndexShouldNotThrow()
        {
            var controller = typeof(ChatController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}",
                defaults: new { id = RouteParameter.Optional }
            );

            var httpServer = new HttpServer(config);

            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/Chat/Index"),
                    Method= HttpMethod.Get
                };

                var result=httpInvoker.SendAsync(request, CancellationToken.None).Result;

            }
        }
Exemple #8
0
 public static async void RegisterTrippin(
     HttpConfiguration config, HttpServer server)
 {
     await config.MapRestierRoute<TrippinApi>(
         "TrippinApi", "api/Trippin",
         new RestierBatchHandler(server));
 }
        public static async Task<HttpResponseMessage> GetResponse(
            string requestUri,
            HttpMethod httpMethod,
            HttpContent requestContent,
            Action<HttpConfiguration, HttpServer> registerOData,
            IEnumerable<KeyValuePair<string, string>> headers = null)
        {
            using (HttpConfiguration config = new HttpConfiguration())
            {
                using (HttpServer server = new HttpServer(config))
                using (HttpMessageInvoker client = new HttpMessageInvoker(server))
                {
                    registerOData(config, server);
                    HttpRequestMessage request = new HttpRequestMessage(httpMethod, requestUri);
                    try
                    {
                        request.Content = requestContent;
                        if (headers != null)
                        {
                            foreach (var header in headers)
                            {
                                request.Headers.Add(header.Key, header.Value);
                            }
                        }

                        return await client.SendAsync(request, CancellationToken.None);
                    }
                    finally
                    {
                        request.DisposeRequestResources();
                        request.Dispose();
                    }
                }
            }
        }
 public BadClient(HttpServer server, ITestOutputHelper output)
 {
     client = new HttpClient(new RequestLogger(output, true, server), false)
     {
         BaseAddress = new Uri("http://bad-client-based")
     };
 }
        public static void BasicAuthentication()
        {
            using (var config = new HttpConfiguration())
            using (var server = new HttpServer(config))
            using (var client = new HttpClient(server))
            {
                config.Routes.MapHttpRoute(
                    name: "Api",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new {id = RouteParameter.Optional}
                );

                var authConfig = new AuthenticationConfiguration
                {
                    InheritHostClientIdentity = true,
                    ClaimsAuthenticationManager = FederatedAuthentication
                        .FederationConfiguration
                        .IdentityConfiguration
                        .ClaimsAuthenticationManager
                };

                // You can setup authentication against membership:
                //authConfig.AddBasicAuthentication((username, password) =>
                //    Membership.ValidateUser(username, password));
                authConfig.AddBasicAuthentication((username, password) =>
                    username == Helpers.__ && password == Helpers.__);

                config.MessageHandlers.Add(new AuthenticationHandler(authConfig));

                client.DefaultRequestHeaders.Authorization =
                    new BasicAuthenticationHeaderValue("happy", "holidays");
                using (var response = client.GetAsync("http://go.com/api/authenticationkoan").Result)
                    Helpers.AssertEquality(HttpStatusCode.OK, response.StatusCode);
            }
        }
        public void ByProjectShouldReturnCorrectResponse()
        {
            // Required by the HttpServer to find controller in another assembly
            var controller = typeof(CommitsController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var httpServer = new HttpServer(config);
            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/Commits/ByProject/1"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;

                Assert.IsNotNull(result);
                Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
            }
        }
Exemple #13
0
		public void Configuration(IAppBuilder owinAppBuilder)
        {
			ConfigureAuth(owinAppBuilder);

			// DependencyInjection config
			_container.RegisterModules(new ODataServiceModule(), new IocConfig());

			// Add Web API to the Owin pipeline
			HttpConfiguration webApiConfig = new HttpConfiguration();
#if DEBUG
			webApiConfig.EnableSystemDiagnosticsTracing();
#endif
			webApiConfig.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(_container);
			HttpServer webApiServer = new HttpServer(webApiConfig);
			EntityRepositoryConfig.ConfigureODataService(webApiServer);

			// Map routes using class attributes
			webApiConfig.MapHttpAttributeRoutes();

			owinAppBuilder.UseWebApi(webApiServer);

			// Verify that DI config is valid; and initialize everything
			_container.Verify();

        }
        public static void RunTest(string controllerName, string routeSuffix, HttpRequestMessage request,
            Action<HttpResponseMessage> assert, Action<HttpConfiguration> configurer = null)
        {
            // Arrange
            HttpConfiguration config = new HttpConfiguration() { IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always };

            config.Routes.MapHttpRoute("Default", "{controller}" + routeSuffix, new { controller = controllerName });
            if (configurer != null)
            {
                configurer(config);
            }
            HttpServer server = new HttpServer(config);
            HttpMessageInvoker invoker = new HttpMessageInvoker(server);
            HttpResponseMessage response = null;
            try
            {
                // Act
                response = invoker.SendAsync(request, CancellationToken.None).Result;

                // Assert
                assert(response);
            }
            finally
            {
                request.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
        public async Task WriteToStreamAsync_TestExpectations(string requestUri, string acceptMediaType, string expectedMediaType, string expectedValue)
        {
            var config = new HttpConfiguration();
            config.Formatters.Add(CreateFormatter(config.Formatters.JsonFormatter));
            config.Routes.MapHttpRoute("Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

            using (var server = new HttpServer(config))
            using (var client = new HttpClient(server))
            {
                client.BaseAddress = new Uri("http://test.org/");

                var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
                if (!string.IsNullOrEmpty(acceptMediaType))
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptMediaType));

                try
                {
                    var response = await client.SendAsync(request);
                    var content = response.Content;
                    Assert.AreEqual(expectedMediaType, content.Headers.ContentType.MediaType);

                    var text = await content.ReadAsStringAsync();
                    Assert.AreEqual(expectedValue, text);
                }
                catch (InvalidOperationException ex)
                {
                    Assert.AreEqual(expectedValue, ex.Message);
                }
            }
        }
        public void ChatHistoryShouldReturnNotFoundIfNoUsername()
        {
            var controller = typeof(MessageController);

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
               name: "DefaultApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
            );

            var httpServer = new HttpServer(config);

            var httpInvoker = new HttpMessageInvoker(httpServer);

            using (httpInvoker)
            {
                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri("http://test.com/api/Message/History"),
                    Method = HttpMethod.Get
                };

                var result = httpInvoker.SendAsync(request, CancellationToken.None).Result;
                Assert.AreEqual(HttpStatusCode.NotFound, result.StatusCode);
            }
        }
Exemple #17
0
 public static async void RegisterNorthwind(
     HttpConfiguration config, HttpServer server)
 {
     await config.MapODataDomainRoute<NorthwindController>(
         "NorthwindApi", "api/Northwind",
         new ODataDomainBatchHandler(server));
 }
        public void WindsorResolver_Resolves_Registered_ContactRepository_Through_ContactsController_Test()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default",
                "api/{controller}/{id}", new { id = RouteParameter.Optional });

            using (var container = new WindsorContainer())
            {
                container.Register(
                    Component.For<IContactRepository>().Instance(new InMemoryContactRepository()),
                    Component.For<ContactsController>().ImplementedBy<ContactsController>());

                config.DependencyResolver = new WindsorResolver(container);

                var server = new HttpServer(config);
                var client = new HttpClient(server);

				client.GetAsync("http://anything/api/contacts").ContinueWith(task =>
				{
					var response = task.Result.Content.ReadAsAsync<List<Contact>>().Result;
					Assert.IsNotNull(response[1]);


				});
            }
        }
        public void Post_Lots_Of_Contacts_Using_EncodingHandler_Test()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            config.MessageHandlers.Add(new EncodingHandler());

            var server = new HttpServer(config);
            var client = new HttpClient(new EncodingHandler(server));
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));

            var content = new List<Contact>();
            for (int i = 0; i < 1000; i++)
            {
                var c = new Contact { Id = i };
                content.Add(c);
            }

            var request = new HttpRequestMessage();
            request.Content = new ObjectContent(typeof(List<Contact>), content, config.Formatters.JsonFormatter);
            client.PostAsync("http://anything/api/contacts", request.Content).ContinueWith(task =>
            {
                var response = task.Result;
                Assert.IsNotNull(response);
                Assert.IsTrue(response.StatusCode == HttpStatusCode.Created);
            });
        }
 public ODataSingletonQueryOptionTest()
 {
     _configuration = new HttpConfiguration();
     _configuration.Routes.MapODataServiceRoute("odata", "odata", GetEdmModel());
     HttpServer server = new HttpServer(_configuration);
     _client = new HttpClient(server);
 }
        public static IAppBuilder UseWebApi(this IAppBuilder builder, HttpConfiguration configuration)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            HttpServer server = new HttpServer(configuration);

            try
            {
                HttpMessageHandlerOptions options = CreateOptions(builder, server, configuration);
                return UseMessageHandler(builder, options);
            }
            catch
            {
                server.Dispose();
                throw;
            }
        }
        public async Task http_post()
        {
            //arrange
            var httpConfig = new HttpConfiguration();
            WebApiConfig.Register(httpConfig);
            var url = "http://localhost/api/default";

            //act
            using (var httpServer = new HttpServer(httpConfig))
            using (var client = new HttpMessageInvoker(httpServer))
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                {
                    request.Content = new ObjectContent<string>("Johnny", new JsonMediaTypeFormatter());
                    using (var response = await client.SendAsync(request, CancellationToken.None))
                    {
                        var output = await response.Content.ReadAsAsync<string>();

                        //assert
                        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                        Assert.AreEqual("Hello Johnny!", output);
                    }
                }
            }
            
        }
Exemple #23
0
 public static void RegisterNorthwind(
     HttpConfiguration config, HttpServer server)
 {
     config.MapRestierRoute<NorthwindApi>(
         "NorthwindApi", "api/Northwind",
         new RestierBatchHandler(server));
 }
        public SelectExpandTest()
        {
            _configuration =
                new[]
                {
                    typeof(SelectExpandTestCustomersController), typeof(SelectExpandTestCustomersAliasController),
                    typeof(PlayersController), typeof(NonODataSelectExpandTestCustomersController),
                    typeof(AttributedSelectExpandCustomersController), typeof(SelectExpandTestCustomer),
                    typeof(SelectExpandTestSpecialCustomer), typeof(SelectExpandTestCustomerWithAlias),
                    typeof(SelectExpandTestOrder), typeof(SelectExpandTestSpecialOrder),
                    typeof(SelectExpandTestSpecialOrderWithAlias)
                }.GetHttpConfiguration();
            _configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            _configuration.MapODataServiceRoute("odata", "odata", GetModel());
            _configuration.MapODataServiceRoute("odata-inheritance", "odata-inheritance", GetModelWithInheritance());
            _configuration.MapODataServiceRoute("odata-alias", "odata-alias", GetModelWithCustomerAlias());
            _configuration.MapODataServiceRoute(
                "odata-alias2-inheritance",
                "odata-alias2-inheritance",
                GetModelWithCustomerAliasAndInheritance());
            _configuration.MapODataServiceRoute("odata2", "odata2", GetModelWithProcedures());
            _configuration.Routes.MapHttpRoute("api", "api/{controller}", new { controller = "NonODataSelectExpandTestCustomers" });

            HttpServer server = new HttpServer(_configuration);
            _client = new HttpClient(server);
        }
 public static async void RegisterSpatial(
     HttpConfiguration config, HttpServer server)
 {
     await config.MapRestierRoute<SpatialApi>(
         "SpatialApi", "api/spatial2",
         new RestierBatchHandler(server));
 }
        public static void SimpleHelloWorldController()
        {
            using (var config = new HttpConfiguration())
            using (var server = new HttpServer(config))
            using (var client = new HttpClient(server))
            {
                TraceConfig.Register(config);

                // Controllers are identified through the routing mechanism.
                // Web API includes a convenient extension method to the
                // HttpRouteCollection type, which is exposed as the
                // HttpConfiguration.Routes property. We will use the default
                // uri template and map it using the `MapHttpRoute` extension method.
                // If you have worked with MVC, this will be very familiar.
                // In a larger project, this would most likely be defined in
                // your Global.asax or WebApiConfig.cs file.
                config.Routes.MapHttpRoute(
                    name: "Api",
                    routeTemplate: "api/{controller}"
                );

                using (var response = client.GetAsync("http://example.org/api/helloworld").Result)
                {
                    var body = response.Content.ReadAsStringAsync().Result;
                    Helpers.AssertEquality("\"Hello, ApiController!\"", body);
                }
            }
        }
Exemple #27
0
        public void SetUp()
        {
            var httpConfiguration = new HttpConfiguration();
            httpConfiguration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}",
                                                  new { id = RouteConfig.GetOptional() });
            server = new HttpServer(httpConfiguration);
            client = new HttpClient(server);

            for (int i = 0; i < 10; ++i)
            {
                var id = MorceauRobotRepo.GetNextId();
                MorceauRobotRepo.MorceauxRobot[id] = new MorceauRobot
                                                     	{
                                                     		Id = id,
                                                     		Description = i.ToString(CultureInfo.InvariantCulture),
                                                     		Longueur = ((double) i)/2
                                                     	};
            }

            result = client.PostAsJsonAsync("http://localhost/api/morceaurobotapi",
                                            new MorceauRobot
                                                {
                                                    Description = "patate",
                                                    Longueur = 1394,
                                                    Nom = "flugelhorn"
                                                }).Result;
        }
        public async Task AttributeRouting_QueryProperty_AfterCallBoundFunction()
        {
            // Arrange
            const string RequestUri = @"http://localhost/Customers(12)/NS.GetOrder(orderId=4)/Amount";
            CustomersModelWithInheritance model = new CustomersModelWithInheritance();

            HttpConfiguration config = new[] { typeof(CustomersController) }.GetHttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.MapODataServiceRoute("odata", "", model.Model);

            HttpServer server = new HttpServer(config);
            config.EnsureInitialized();

            HttpClient client = new HttpClient(server);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, RequestUri);

            // Act
            HttpResponseMessage response = await client.SendAsync(request);
            string responseString = await response.Content.ReadAsStringAsync();

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.Equal("{\r\n  \"@odata.context\":\"http://localhost/$metadata#Edm.Int32\",\"value\":56\r\n}",
                responseString);
        }
        public void Log_Simple_Request_Test_Should_Log_Request_And_Response()
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("default", "api/{controller}/{id}", new { id = RouteParameter.Optional });

            var dummyRepository = new DummyLoggingRepository();
            config.MessageHandlers.Add(new LoggingHandler(dummyRepository));
            config.MessageHandlers.Add(new EncodingHandler());

            var server = new HttpServer(config);
            var client = new HttpClient(new EncodingHandler(server));
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var content = new List<Contact>();
            var c = new Contact { Id = 1, Birthday = DateTime.Now.AddYears(-20) };
            content.Add(c);

            var request = new HttpRequestMessage();
            request.Content = new ObjectContent(typeof(List<Contact>), content, config.Formatters.JsonFormatter);
            client.PostAsync("http://anything/api/contacts", request.Content).ContinueWith(task =>
            {
                var response = task.Result;
                Assert.IsNotNull(response);
                Assert.AreEqual(2, dummyRepository.LogMessageCount);
                Assert.IsTrue(dummyRepository.HasRequestMessageTypeBeenReceived, "No request message has been logged");
                Assert.IsTrue(dummyRepository.HasResponseMessageTypeBeenReceived, "No Response message has been received");
            });
        }
        public void cache_singleton_in_pipeline()
        {
            _cache = new Mock<IApiOutputCache>();

            var conf = new HttpConfiguration();
            conf.CacheOutputConfiguration().RegisterCacheOutputProvider(() => _cache.Object);

            conf.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            _server = new HttpServer(conf);

            var client = new HttpClient(_server);
            var result = client.GetAsync(_url + "Get_c100_s100").Result;

            _cache.Verify(s => s.Contains(It.Is<string>(x => x == "webapi.outputcache.v2.tests.testcontrollers.samplecontroller-get_c100_s100:application/json; charset=utf-8")), Times.Exactly(2));

            var result2 = client.GetAsync(_url + "Get_c100_s100").Result;
            _cache.Verify(s => s.Contains(It.Is<string>(x => x == "webapi.outputcache.v2.tests.testcontrollers.samplecontroller-get_c100_s100:application/json; charset=utf-8")), Times.Exactly(4));

            _server.Dispose();
        }
Exemple #31
0
        public static void MyClassInitialize(TestContext testContext)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("capture", "v1/{controller}/{id}/capture",
                                       defaults: new { id = RouteParameter.Optional });
            config.Routes.MapHttpRoute("Default", "v1/{controller}/{id}",
                                       defaults: new { id = RouteParameter.Optional });

            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.MessageHandlers.Add(new WebApiKeyHandler());
            config.Formatters.Insert(0, new JsonNetFormatter());

            _server = new HttpServer(config);
            //setting the handler to in memory http server instead of live http handler
            MessageHandlerProvider.Handler = _server;
        }
Exemple #32
0
 private static HttpBatchHandler CreateProductUnderTest(HttpServer httpServer, IExceptionLogger exceptionLogger,
                                                        IExceptionHandler exceptionHanlder)
 {
     return(new MockHttpBatchHandler(httpServer, exceptionLogger, exceptionHanlder));
 }
        /// <summary>
        /// Instructs WebApi to map one or more of the registered Restier APIs to the specified Routes, each with it's own isolated Dependency Injection container.
        /// </summary>
        /// <param name="config">The <see cref="HttpConfiguration"/> instance to enhance.</param>
        /// <param name="configureRoutesAction"></param>
        /// <param name="httpServer"></param>
        /// <returns>The <see cref="HttpConfiguration"/> instance to allow for fluent method chaining.</returns>
        /// <example>
        /// <code>
        /// config.MapRestier(builder =>
        ///     builder
        ///         .MapApiRoute<SomeApi>("SomeApiV1", "someapi/")
        ///         .MapApiRoute<AnotherApi>("AnotherApiV1", "anotherapi/")
        /// );
        /// </code>
        /// </example>
        public static HttpConfiguration MapRestier(this HttpConfiguration config, Action <RestierRouteBuilder> configureRoutesAction, HttpServer httpServer)
        {
            Ensure.NotNull(configureRoutesAction, nameof(configureRoutesAction));

            var rrb = new RestierRouteBuilder();

            configureRoutesAction.Invoke(rrb);

            foreach (var route in rrb.Routes)
            {
                ODataBatchHandler batchHandler = null;
                var conventions = CreateRestierRoutingConventions(config, route.Key);

                if (route.Value.AllowBatching)
                {
                    if (httpServer == null)
                    {
                        throw new ArgumentNullException(nameof(httpServer), owinException);
                    }

#pragma warning disable IDE0067 // Dispose objects before losing scope
                    batchHandler = new RestierBatchHandler(httpServer)
                    {
                        ODataRouteName = route.Key
                    };
#pragma warning restore IDE0067 // Dispose objects before losing scope
                }

                var odataRoute = config.MapODataServiceRoute(route.Key, route.Value.RoutePrefix, (containerBuilder, routeName) =>
                {
                    var rcb          = containerBuilder as RestierContainerBuilder;
                    rcb.routeBuilder = rrb;
                    rcb.RouteName    = routeName;

                    containerBuilder.AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp => conventions);
                    if (batchHandler != null)
                    {
                        //RWM: DO NOT simplify this generic signature. It HAS to stay this way, otherwise the code breaks.
                        containerBuilder.AddService <ODataBatchHandler>(ServiceLifetime.Singleton, sp => batchHandler);
                    }
                });
            }

            return(config);
        }
Exemple #34
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="TApi"></typeparam>
        /// <param name="config"></param>
        /// <param name="routeName"></param>
        /// <param name="routePrefix"></param>
        /// <param name="allowBatching"></param>
        /// <param name="httpServer"></param>
        /// <returns></returns>
        public static HttpConfiguration MapRestier <TApi>(this HttpConfiguration config, string routeName, string routePrefix, bool allowBatching, HttpServer httpServer)
        {
            ODataBatchHandler batchHandler = null;
            var conventions = CreateRestierRoutingConventions(config, routeName);

            if (allowBatching)
            {
                if (httpServer == null)
                {
                    throw new ArgumentNullException(nameof(httpServer), owinException);
                }

#pragma warning disable IDE0067 // Dispose objects before losing scope
                batchHandler = new RestierBatchHandler(httpServer)
                {
                    ODataRouteName = routeName
                };
#pragma warning restore IDE0067 // Dispose objects before losing scope
            }

            config.MapODataServiceRoute(routeName, routePrefix, (builder) =>
            {
                builder.AddService <IEnumerable <IODataRoutingConvention> >(ServiceLifetime.Singleton, sp => conventions);
                if (batchHandler != null)
                {
                    //RWM: DO NOT simplify this generic signature. It HAS to stay this way, otherwise the code breaks.
                    builder.AddService <ODataBatchHandler>(ServiceLifetime.Singleton, sp => batchHandler);
                }
            });

            return(config);
        }
Exemple #35
0
 public MockHttpBatchHandler(HttpServer server) : base(server)
 {
 }
Exemple #36
0
 private static HttpBatchHandler CreateProductUnderTest(HttpServer httpServer)
 {
     return(new MockHttpBatchHandler(httpServer));
 }