[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);
        }
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var reqLog = new
            {
                Method = request.Method,
                Url = request.RequestUri.AbsoluteUri,
                Headers = request.Headers,
                Body = await request.Content.ReadAsStringAsync()
            };

            Logger.DebugFormat("HTTP Request\n{0}", LogSerializer.Serialize(reqLog));

            var response = await base.SendAsync(request, cancellationToken);

            string body = "";

            if (response.Content != null)
            {
                body = await response.Content.ReadAsStringAsync();
            }

            var respLog = new
            {
                StatusCode = response.StatusCode,
                Headers = response.Headers,
                Body = body
            };

            Logger.DebugFormat("HTTP Response\n{0}", LogSerializer.Serialize(respLog));

            return response;
        }
        public async Task SupportsPrereleaseParameter()
        {
            // Arrange
            var packages = new[]
            {
                new PackageVersion("Antlr", "3.1.3.42154"),
                new PackageVersion("Antlr", "3.4.1.9004-pre"),
                new PackageVersion("angularjs", "1.2.0-RC1"),
                new PackageVersion("WebGrease", "1.6.0")
            };

            using (var app = await StartedWebApp.StartAsync(packages))
            {
                string query = "Id:angularjs Id:Antlr Id:WebGrease";

                // Act
                var withPrereleaseResponse = await app.Client.GetAsync(new V2SearchBuilder { Query = query, Prerelease = true }.RequestUri);
                var withPrerelease = await withPrereleaseResponse.Content.ReadAsAsync<V2SearchResult>();

                var withoutPrereleaseResponse = await app.Client.GetAsync(new V2SearchBuilder { Query = query, Prerelease = false }.RequestUri);
                var withoutPrerelease = await withoutPrereleaseResponse.Content.ReadAsAsync<V2SearchResult>();

                // Assert
                Assert.Equal("1.2.0-RC1", withPrerelease.GetPackageVersion("angularjs"));  // the only version available is prerelease
                Assert.Equal("3.4.1.9004-pre", withPrerelease.GetPackageVersion("Antlr")); // the latest version is prerelease
                Assert.Equal("1.6.0", withPrerelease.GetPackageVersion("WebGrease"));      // the only version available is non-prerelease

                Assert.False(withoutPrerelease.ContainsPackage("angularjs"));              // the only version available is prerelease and is therefore excluded
                Assert.Equal("3.1.3.42154", withoutPrerelease.GetPackageVersion("Antlr")); // this is the latest non-release version
                Assert.Equal("1.6.0", withoutPrerelease.GetPackageVersion("WebGrease"));   // the only version available is non-prerelease
            }
        }
        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 HttpResponseMessage GetSettings()
        {
            var response = new
                            {
                                results = new SettingsViewModel(ActiveModule)
                            };

            return Request.CreateResponse(response);
        }
		public void TestHasApiRouteToCorrectController()
		{
			var expectations = new
			{
				controller = "WithObject",
				action = "Get"
			};
			RouteAssert.HasApiRoute(config, "/api/withobject/123/fred", HttpMethod.Get, expectations);
		}
		public void TestHasApiRoute()
		{
			var expectations = new
				{
					controller = "FromBody",
					action = "CreateSomething",
					id = "123"
				};
			RouteAssert.HasApiRoute(config, "/api/frombody/123", HttpMethod.Post, expectations);
		}
		public void TestHasApiRoute()
		{
			var expectations = new
				{
					controller = "FromUri",
					action = "DoSomething"
				};

			RouteAssert.HasApiRoute(config, "/api/fromuri/123", HttpMethod.Get, expectations);
		}
        public static void UpdateConfiguration(HttpConfiguration config)
        {
            var controllers = new[] { typeof(UnqualifiedCarsController) };
            TestAssemblyResolver resolver = new TestAssemblyResolver(new TypesInjectionAssembly(controllers));

            config.Services.Replace(typeof(IAssembliesResolver), resolver);
            config.Routes.Clear();
            config.EnableUnqualifiedNameCall(true);
            config.MapODataServiceRoute("odata", "odata", GetModel());
        }
        public void ShouldReturnHotel()
        {
            // Arrange
            var hotel = new Hotel
                            {
                                Name = "Taj Mahal",
                                ImageUrl = "http://www.fake.com/image.jpg",
                                Grade = 4.5m,
                                Html = "<blink>AWESOME</blink>",
                                Id = "1",
                                Url = "http://fake.com"
                            };

            var offerRepo = new Mock<ITravelOffersRepository>();
            offerRepo.Setup(repository => repository.GetHotel(It.Is<string>(s => s == "10")))
                     .Returns(hotel);

            var bootstrapper = new TestBootstrapper(with =>
            {
                with.Module<OfferHotelModule>();
                with.Dependency<ITravelOffersRepository>(offerRepo.Object);
            });

            var browser = new Browser(bootstrapper);

            // Act
            var result = browser.Get(
                "/offer/hotel/10",
                with =>
                {
                    with.HttpRequest();
                    with.Accept("application/json");
                });

            // Assert
            result.StatusCode.Should().Be(HttpStatusCode.OK);

            var hotelModel =
                new
                {
                    html = string.Empty,
                    grade = 0.0m,
                    name = string.Empty,
                    url = string.Empty,
                    hasImage = false
                };

            var jsonObject = JsonConvert.DeserializeAnonymousType(result.Body.AsString(), hotelModel);

            jsonObject.name.Should().Be(hotel.Name);
            jsonObject.hasImage.Should().BeTrue();
            jsonObject.grade.Should().Be(hotel.Grade);
            jsonObject.html.Should().Be(hotel.Html);
            jsonObject.url.Should().Be(hotel.Url);
        }
        public async Task<string> CreateAuthorization(string userName, string password, string[] scopes)
        {
            var createAuthorizationMessage = new {scopes, note = _appName};
            string json = JsonConvert.SerializeObject( createAuthorizationMessage );
            var client = new HttpClient(new UserAgentHandler("GitHubVsIntegrator", new BasicAuthHandler(userName, password)));            
            var res = await client.PostAsync(_apiHost+"/authorizations", new StringContent(json));
            var resContent = await res.Content.ReadAsStringAsync();
            var obj = JsonConvert.DeserializeObject<Authorization>(resContent);

            return obj.token;
        }
		public void TestHasApiRouteParams()
		{
			var expectations = new
				{
					controller = "WithSimpleObject",
					action = "Get",
					data = "1-2"
				};

			RouteAssert.HasApiRoute(config, "/api/withsimpleobject/1-2", HttpMethod.Get, expectations);
		}
        public IndexModule()
        {
            Get["/"] = parameters => View["Index"];

            Post["/", true] = async (x, ct) =>
            {
                var link = await GetQrCode(ct);
                var model = new { QrPath = link };
                return View["Index", model];
            };
        }
        public HttpResponseMessage SaveSettings(SettingsViewModel settings)
        {
            settings.Save(ActiveModule);

            var response = new
                            {
                                success = true
                            };

            return Request.CreateResponse(response);
        }
		public void ShouldHaveRouteWithOptionalParamNotSupplied()
		{
			var expectations = new
			{
				controller = "WithOptionalParam",
				action = "Get",
				paramA = 42,
			};

			RouteAssert.HasApiRoute(config, "/api/WithOptionalParam/42/", HttpMethod.Get, expectations);
		}
		public void TestHasApiRouteParams()
		{
			var expectations = new
				{
					controller = "WithObject",
					action = "Get",
					id = "123",
					name = "fred"
				};

			RouteAssert.HasApiRoute(config, "/api/withobject/123/fred", HttpMethod.Get, expectations);
		}
		public void TestHasApiRouteValuesFromUri()
		{
			var expectations = new
			{
				controller = "FromUri",
				action = "DoSomething",
				name = "Fred",
				number = 42
			};

			RouteAssert.HasApiRoute(config, "/api/fromuri?name=Fred&number=42", HttpMethod.Get, expectations);
		}
		public void TestHasNullablePropertyValue()
		{
			var expectations = new
			{
				controller = "FromUri",
				action = "DoSomething",
				name = "Fred",
				otherNumber = 31
			};

			RouteAssert.HasApiRoute(config, "/api/fromuri?name=Fred&otherNumber=31", HttpMethod.Get, expectations);
		}
		public void ShouldHaveRouteWithOptionalParamSupplied()
		{
			var expectations = new
				{
					controller = "WithOptionalParamAttr",
					action = "Get",
					paramA = 42,
					paramB = 34
				};

			RouteAssert.HasApiRoute(config, "/someapi/withoptionalparam/42?paramB=34", HttpMethod.Get, expectations);
		}
		public void ShouldHaveRouteWithOptionalParamNotSuppliedAndExpectationOfNull()
		{
			var expectations = new
				{
					controller = "WithOptionalParamAttr",
					action = "Get",
					paramA = 42,
					paramB = (int?)null
				};

			RouteAssert.HasApiRoute(config, "/someapi/withoptionalparam/42/", HttpMethod.Get, expectations);
		}
		public void TestHasApiRouteValuesFromBody()
		{
			const string PostBody = "{ Name: 'Fred Bloggers', Number: 42 }";
			var expectations = new
				{
					controller = "FromBody",
					action = "CreateSomething",
					id = "123",
					name = "Fred Bloggers",
					number = 42
				};
			RouteAssert.HasApiRoute(config, "/api/frombody/123", HttpMethod.Post, PostBody, BodyFormat.Json, expectations);
		}
 public void TailComUmElemento()
 {
     using (var cliente = new HttpClient(servidor))
     {
         var conteudo = new[] {1};
         using (var request = CriarRequest("api/Conjuntos/Tail", HttpMethod.Get, conteudo))
         {
             using (var response = cliente.SendAsync(request, new CancellationTokenSource().Token).Result)
             {
                 response.Content.ReadAsStringAsync().Result.Should().Be(JsonConvert.SerializeObject(new int[] {}));
             }
         }
     }
 }
		public void MismatchFailsValuesFromBody()
		{
			var expectations = new
			{
				controller = "FromUri",
				action = "DoSomething",
				name = "Jim",
				number = 42
			};

			var assertEngine = new FakeAssertEngine();
			RouteAssert.UseAssertEngine(assertEngine);

			RouteAssert.HasApiRoute(config, "/api/fromuri?name=Fred&number=42", HttpMethod.Get, expectations);

			Assert.That(assertEngine.StringMismatchCount, Is.EqualTo(1));
			Assert.That(assertEngine.Messages[0], Is.EqualTo("Expected 'Jim', not 'Fred' for 'name' at url '/api/fromuri?name=Fred&number=42'."));
		}
		public void MismatchFailsValuesFromBody()
		{
			const string PostBody = "{ Name: 'Fred Bloggers', Number: 42 }";
			var expectations = new
				{
					controller = "FromBody",
					action = "CreateSomething",
					id = "123",
					name = "Jim Spriggs",
					number = 42
				};

			var assertEngine = new FakeAssertEngine();
			RouteAssert.UseAssertEngine(assertEngine);

			RouteAssert.HasApiRoute(config, "/api/frombody/123", HttpMethod.Post, PostBody, BodyFormat.Json, expectations);

			Assert.That(assertEngine.StringMismatchCount, Is.EqualTo(1));
			Assert.That(assertEngine.Messages[0], Is.EqualTo("Expected 'Jim Spriggs', not 'Fred Bloggers' for 'name' at url '/api/frombody/123'."));
		}
        public async Task CanReturnEmptyResult()
        {
            // Arrange
            var packages = new[]
            {
                new PackageVersion("Newtonsoft.Json", "7.0.1")
            };

            using (var app = await StartedWebApp.StartAsync(packages))
            {
                // Act
                var response = await app.Client.GetAsync(new V2SearchBuilder { Query = "something else" }.RequestUri);
                var s = await response.Content.ReadAsStringAsync();
                var result = await response.Content.ReadAsAsync<V2SearchResult>(Serialization.MediaTypeFormatters);

                // Assert
                Assert.Equal(0, result.TotalHits);
                Assert.Empty(result.Data);
            }
        }
        public object GetHotel(dynamic parameters)
        {
            Hotel hotel = this.TravelOffersRepository.GetHotel(parameters.hotelid);

            if (hotel == null)
            {
                return new Response { StatusCode = HttpStatusCode.NotFound };
            }

            var hotelModel =
                new
                    {
                        html = hotel.Html,
                        grade = hotel.Grade,
                        name = hotel.Name,
                        url = hotel.Url,
                        hasImage = !string.IsNullOrEmpty(hotel.ImageUrl)
                    };

            return hotelModel;
        }
        public async Task DollarFormat_Applies_IfPresent(string path, string mediaTypeFormat)
        {
            // Arrange
            MediaTypeHeaderValue expected = MediaTypeHeaderValue.Parse(mediaTypeFormat);
            string url = string.Format("http://localhost/{0}?$format={1}", path, mediaTypeFormat);
            IEdmModel model = GetEdmModel();
            var configuration =
                new[] { typeof(FormatCustomersController), typeof(ThisController) }.GetHttpConfiguration();
            HttpServer server = new HttpServer(configuration);
            HttpClient client = new HttpClient(server);
            configuration.MapODataServiceRoute("odata", routePrefix: null, model: model);

            // Act
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
            request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
            HttpResponseMessage response = await client.SendAsync(request);

            // Assert
            response.EnsureSuccessStatusCode();
            Assert.Equal(expected, response.Content.Headers.ContentType);
        }
        public async Task SortsResultsByDownload()
        {
            // Arrange
            var packages = new[]
            {
                new PackageVersion("Newtonsoft.Json", "7.0.1", 10),
                new PackageVersion("EntityFramework", "6.1.3", 20),
                new PackageVersion("bootstrap", "3.3.6", 5)
            };

            using (var app = await StartedWebApp.StartAsync(packages))
            {
                // Act
                var response = await app.Client.GetAsync(new V2SearchBuilder().RequestUri);
                var result = await response.Content.ReadAsAsync<V2SearchResult>(Serialization.MediaTypeFormatters);

                // Assert
                Assert.Equal("EntityFramework", result.Data[0].PackageRegistration.Id);
                Assert.Equal("Newtonsoft.Json", result.Data[1].PackageRegistration.Id);
                Assert.Equal("bootstrap", result.Data[2].PackageRegistration.Id);
            }
        }
 public void WorksWithoutIdTested()
 {
     var expectedRoute = new { controller = "WithNullable", action = "Get" };
     RouteAssert.HasApiRoute(config, "/api/WithNullable", HttpMethod.Get, expectedRoute);
 }
 public void NullValueIsCaptured()
 {
     var expectedRoute = new { controller = "WithNullable", action = "Get", id = (int?)null };
     RouteAssert.HasApiRoute(config, "/api/WithNullable", HttpMethod.Get, expectedRoute);
 }