public async Task ShouldReturnCorrectTaskForSignOutRequest()
        {
            _userSession = Substitute.For <IUserSession>();
            _userSession.GetUserAsync().Returns(Task.FromResult(
                                                    new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(JwtClaimTypes.Subject, "test"), new Claim(JwtClaimTypes.AuthenticationMethod, "test"), new Claim(JwtClaimTypes.Name, "test person") }))));
            _validator = new WsFederationRequestValidator(Substitute.For <ILogger <WsFederationRequestValidator> >(),
                                                          new InMemoryClientStore(new[]
            {
                new Client
                {
                    ClientId      = "http://sample-with-policyengine/",
                    ProtocolType  = IdentityServerConstants.ProtocolTypes.WsFederation,
                    RedirectUris  = new [] { "http://localhost" },
                    AllowedScopes = { "openid", "profile" }
                }
            }));

            var endpoint    = new WsFederationEndpoint(_logger, _validator, GetDefaultResponseGenerator(), _userSession);
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Method      = "GET";
            httpContext.Request.QueryString = QueryString.FromUriComponent("?wa=wsignout1.0&wtrealm=http%3a%2f%2fsample-with-policyengine%2f");
            var result = await endpoint.ProcessAsync(httpContext);

            Assert.IsInstanceOfType(result, typeof(WsFederationSignOutResult));
        }
        public ActionResult Authorize(AuthorizationCodeModel model)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCode(StatusCodes.Status417ExpectationFailed));
            }

            // TODO: do validation of the client id, scope, callback id, etc., and then let the user login

            return(RedirectToAction("Choose", "Home"));

            // ignore all this for now

            UriBuilder builder = new UriBuilder(model.redirect_uri);

            var qs = QueryString.FromUriComponent(builder.Query);

            //qs = qs.Add("code", Guid.NewGuid().ToString("N"));
            qs = qs.Add("code", "test123");
            qs = qs.Add("state", DateTime.UtcNow.Ticks.ToString());

            builder.Query = qs.ToUriComponent();


            return(Redirect(builder.ToString()));
        }
예제 #3
0
        async Task <HttpRequestFeature> CreateRequestAsync(Stream stream, CancellationToken cancellationToken)
        {
            var firstLine = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);

            var parts  = firstLine.Split(' ');
            var result = new HttpRequestFeature();

            result.Method = parts[0];
            var uri = new Uri(parts[1], UriKind.RelativeOrAbsolute);

            if (!uri.IsAbsoluteUri)
            {
                uri = new Uri(_localhostUri, uri);
            }
            result.Protocol = parts[2];
            for (; ;)
            {
                var line = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false);

                if (line.Length == 0)
                {
                    break;
                }
                (var name, var values) = HttpParser.ParseHeaderNameValues(line);
                result.Headers.Add(name, new Microsoft.Extensions.Primitives.StringValues(values.ToArray()));
            }
            result.Scheme      = uri.Scheme;
            result.Path        = PathString.FromUriComponent(uri);
            result.QueryString = QueryString.FromUriComponent(uri).Value;
            result.Body        = new BodyStream(stream, result.Headers.ContentLength);
            return(result);
        }
        private async Task <StringValues> CreateAuthorizationCode(ITokenManager tokenManager)
        {
            var httpContext = new DefaultHttpContext();

            httpContext.Request.QueryString = QueryString.FromUriComponent(@"?response_type=code&client_id=s6BhdRkqt3&redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb&scope=openid%20profile%20email%20offline_access&nonce=n-0S6_WzA2Mj&state=af0ifjsldkj");
            var requestParameters = httpContext.Request.Query.ToDictionary(kvp => kvp.Key, kvp => (string[])kvp.Value);

            var requestFactory = CreateAuthorizationRequestFactory();

            var user        = CreateUser("user");
            var application = CreateApplication("s6BhdRkqt");

            var queryExecutor = new QueryResponseGenerator();

            // Act
            var result = await requestFactory.CreateAuthorizationRequestAsync(requestParameters);

            var authorization = result.Message;

            var tokenContext = result.CreateTokenGeneratingContext(user, application);

            await tokenManager.IssueTokensAsync(tokenContext);

            return(tokenContext.AuthorizationCode.SerializedValue);
        }
        /// <inheritdoc />
        public IAndHttpRequestBuilder WithLocation(Uri location)
        {
            Uri uri;

            if (location.IsAbsoluteUri)
            {
                uri = new Uri(location.OriginalString, UriKind.Absolute);
            }
            else
            {
                uri = new Uri(new Uri("http://localhost"), location);
            }

            if (location.IsAbsoluteUri)
            {
                this
                .WithHost(HostString.FromUriComponent(uri))
                .WithScheme(uri.Scheme);
            }

            return(this
                   .WithPathBase(PathString.FromUriComponent(uri))
                   .WithPath(PathString.FromUriComponent(uri.AbsolutePath))
                   .WithQueryString(QueryString.FromUriComponent(uri.Query)));
        }
예제 #6
0
        private IDictionary <string, object> ConvertEventArgsIntoOwinEnvironment(RequestReceivedEventArgs args)
        {
            var result  = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase);
            var context = PipelineContext.GetOrCreate(result);

            result["owin.CallCancelled"] = new CancellationToken();
            result["owin.Version"]       = "1.0.0";

            var request = context.Request;

            result["owin.RequestHeaders"] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
            request.Body            = Stream.Null;
            request.Method          = "GET";
            request.Scheme          = "http";
            request.Headers["Host"] = args.Request.Url.Authority;
            request.Path            = new Microsoft.Owin.PathString(args.PathAndFile);
            request.PathBase        = new Microsoft.Owin.PathString(args.Root);
            request.Protocol        = "HTTP/1.1";
            request.QueryString     = QueryString.FromUriComponent(args.Request.Url);
            request.RemoteIpAddress = args.Request.RemoteEndPoint.Address.ToString();
            request.RemotePort      = args.Request.RemoteEndPoint.Port;

            var response = context.Response;

            result["owin.ResponseHeaders"] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
            response.Body = new MemoryStream();

            return(result);
        }
        async Task <HttpRequestFeature> CreateRequesteAsync(Stream stream)
        {
            var lineReader  = new ByLineReader(stream, 1024);
            var requestLine = await lineReader.NextLineAsync().ConfigureAwait(false);

            var firstLine = HttpParser.GetAsciiString(requestLine);
            var parts     = firstLine.Split(' ');
            var result    = new HttpRequestFeature();

            result.Method = parts[0];
            var uri = new Uri("http://localhost" + parts[1]);

            result.Protocol = parts[2];
            for (; ;)
            {
                var line = await lineReader.NextLineAsync().ConfigureAwait(false);

                if (line.Count == 0)
                {
                    break;
                }
                (var name, var values) = HttpParser.ParseHeaderNameValue(line);
                result.Headers.Add(name, new Microsoft.Extensions.Primitives.StringValues(values.ToArray()));
            }
            result.Scheme      = uri.Scheme;
            result.Path        = PathString.FromUriComponent(uri);
            result.QueryString = QueryString.FromUriComponent(uri).Value;
            result.Body        = new StreamWithPrefix(lineReader.Remaining, stream, result.Headers.ContentLength);
            return(result);
        }
예제 #8
0
        public void OnAuthorization_RedirectsToHttpsEndpoint_ForCustomSslPort(
            string url,
            int?sslPort,
            string expectedUrl)
        {
            // Arrange
            var options = Options.Create(new MvcOptions());
            var uri     = new Uri(url);

            var requestContext = new DefaultHttpContext();

            requestContext.RequestServices     = CreateServices(sslPort);
            requestContext.Request.Scheme      = "http";
            requestContext.Request.Method      = "GET";
            requestContext.Request.Host        = HostString.FromUriComponent(uri);
            requestContext.Request.Path        = PathString.FromUriComponent(uri);
            requestContext.Request.QueryString = QueryString.FromUriComponent(uri);

            var authContext = CreateAuthorizationContext(requestContext);
            var attr        = new RequireHttpsAttribute();

            // Act
            attr.OnAuthorization(authContext);

            // Assert
            Assert.NotNull(authContext.Result);
            var result = Assert.IsType <RedirectResult>(authContext.Result);

            Assert.Equal(expectedUrl, result.Url);
        }
예제 #9
0
        private static IHtmlHelper CreateHelper(HttpContext ctx = null, Action <IServiceCollection> configureServices = null)
        {
            var services = new ServiceCollection();

            services.AddSingleton(HtmlEncoder.Default);
            services.AddSingleton <IJSRuntime, UnsupportedJavaScriptRuntime>();
            services.AddSingleton <IUriHelper, HttpUriHelper>();
            services.AddSingleton <StaticComponentRenderer>();

            configureServices?.Invoke(services);

            var helper  = new Mock <IHtmlHelper>();
            var context = ctx ?? new DefaultHttpContext();

            context.RequestServices     = services.BuildServiceProvider();
            context.Request.Scheme      = "http";
            context.Request.Host        = new HostString("localhost");
            context.Request.PathBase    = "/base";
            context.Request.Path        = "/path";
            context.Request.QueryString = QueryString.FromUriComponent("?query=value");

            helper.Setup(h => h.ViewContext)
            .Returns(new ViewContext()
            {
                HttpContext = context
            });
            return(helper.Object);
        }
예제 #10
0
            internal RequestState(HttpRequestMessage request, PathString pathBase, CancellationToken cancellationToken)
            {
                _request     = request;
                _responseTcs = new TaskCompletionSource <HttpResponseMessage>();

                if (request.RequestUri.IsDefaultPort)
                {
                    request.Headers.Host = request.RequestUri.Host;
                }
                else
                {
                    request.Headers.Host = request.RequestUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
                }

                FeatureCollection = new FeatureCollection();
                HttpContext       = new DefaultHttpContext(FeatureCollection);
                HttpContext.SetFeature <IHttpRequestFeature>(new RequestFeature());
                _responseFeature = new ResponseFeature();
                HttpContext.SetFeature <IHttpResponseFeature>(_responseFeature);
                var serverRequest = HttpContext.Request;

                serverRequest.Protocol = "HTTP/" + request.Version.ToString(2);
                serverRequest.Scheme   = request.RequestUri.Scheme;
                serverRequest.Method   = request.Method.ToString();

                var        fullPath = PathString.FromUriComponent(request.RequestUri);
                PathString remainder;

                if (fullPath.StartsWithSegments(pathBase, out remainder))
                {
                    serverRequest.PathBase = pathBase;
                    serverRequest.Path     = remainder;
                }
                else
                {
                    serverRequest.PathBase = PathString.Empty;
                    serverRequest.Path     = fullPath;
                }

                serverRequest.QueryString = QueryString.FromUriComponent(request.RequestUri);
                // TODO: serverRequest.CallCancelled = cancellationToken;

                foreach (var header in request.Headers)
                {
                    serverRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
                }
                var requestContent = request.Content;

                if (requestContent != null)
                {
                    foreach (var header in request.Content.Headers)
                    {
                        serverRequest.Headers.AppendValues(header.Key, header.Value.ToArray());
                    }
                }

                _responseStream                 = new ResponseStream(CompleteResponse);
                HttpContext.Response.Body       = _responseStream;
                HttpContext.Response.StatusCode = 200;
            }
예제 #11
0
        private static IHtmlHelper CreateHelper(HttpContext ctx = null, Action <IServiceCollection> configureServices = null)
        {
            var services = new ServiceCollection();

            services.AddSingleton <IConfiguration>(new ConfigurationBuilder().Build());
            services.AddLogging();
            services.AddDataProtection();
            services.AddSingleton(HtmlEncoder.Default);
            configureServices = configureServices ?? (s => s.AddServerSideBlazor());
            configureServices?.Invoke(services);

            var helper  = new Mock <IHtmlHelper>();
            var context = ctx ?? new DefaultHttpContext();

            context.RequestServices     = services.BuildServiceProvider();
            context.Request.Scheme      = "http";
            context.Request.Host        = new HostString("localhost");
            context.Request.PathBase    = "/base";
            context.Request.Path        = "/path";
            context.Request.QueryString = QueryString.FromUriComponent("?query=value");

            helper.Setup(h => h.ViewContext)
            .Returns(new ViewContext()
            {
                HttpContext = context
            });
            return(helper.Object);
        }
        public async Task VerifyWebhookAsync_MissingHubChallenge_ReturnsBadRequest()
        {
            // Arrange
            var request  = new Mock <HttpRequest>();
            var response = new Mock <HttpResponse>();

            string webhookChallengeCode = "5af96abed0b2fc27a017bf5a7e961dd9";
            string webhookToken         = "abc123";

            request.Setup(x => x.QueryString).Returns(QueryString.FromUriComponent($"?hub.mode=subscribe&hub.verify_token={webhookToken}"));
            response.Setup(x => x.Body).Returns(new MemoryStream());

            var mockOptions = new RingCentralOptions()
            {
                RingCentralEngageApiAccessToken = "abc", RingCentralEngageApiUrl = "http://localhost", BotId = "testbot", RingCentralEngageWebhookValidationToken = "incorrect_token"
            };
            var sut = new RingCentralClientWrapper(OptionsHelper.GetOptionsMonitor(mockOptions), new StaticHandoffRequestRecognizer());

            // Act
            await sut.VerifyWebhookAsync(request.Object, response.Object, It.IsAny <CancellationToken>());

            response.Object.Body.Position = 0;
            using var sr = new StreamReader(response.Object.Body);
            var responseBody = sr.ReadToEnd();

            // Assert
            Assert.NotEqual(webhookChallengeCode, responseBody);
            response.VerifySet(x => x.StatusCode = StatusCodes.Status400BadRequest);
        }
예제 #13
0
 public static HttpRequest ParseRequest(IHttpRequestFeature _requestFeature)
 {
     return(new(QueryString.FromUriComponent(_requestFeature.QueryString),
                new HttpMethod(_requestFeature.Method),
                _requestFeature.Path,
                _requestFeature.Body));
 }
예제 #14
0
        /// <summary>
        /// Mock and send web request to api process
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <param name="method"></param>
        /// <param name="queryString"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        private T MockRequest <T>(string path, SignalsApiMethod method, string queryString = null, object body = null)
            where T : VoidResult
        {
            // build http context
            var context = new DefaultHttpContext();

            context.Response.Body  = new MemoryStream();
            context.Request.Path   = path;
            context.Request.Method = method.ToString();

            if (!queryString.IsNullOrEmpty())
            {
                context.Request.QueryString = QueryString.FromUriComponent(queryString);
            }

            if (!body.IsNull())
            {
                context.Request.Body = new MemoryStream(Encoding.Default.GetBytes(body.SerializeJson()));
            }

            // mock context accessor
            var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();

            mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context);
            var request = new HttpContextWrapper(mockHttpContextAccessor.Object);

            // dispatch mock web request
            WebMediator.Dispatch(request);

            // read response
            context.Response.Body.Position = 0;
            var response = new StreamReader(context.Response.Body).ReadToEnd();

            return(response.Deserialize <T>());
        }
예제 #15
0
        private async Task PopulateRequestAsync(Stream stream, IOwinRequest request)
        {
            var lineReader  = new ByLineReader(stream, 1024);
            var requestLine = await lineReader.NextLineAsync().ConfigureAwait(false);

            var firstLine = HttpParser.GetAsciiString(requestLine);
            var parts     = firstLine.Split(' ');

            request.Method   = parts[0];
            request.Protocol = parts[2];
            var uri = new Uri("http://localhost" + parts[1]);

            for (; ;)
            {
                var line = await lineReader.NextLineAsync().ConfigureAwait(false);

                if (line.Count == 0)
                {
                    break;
                }
                (var name, var values) = HttpParser.ParseHeaderNameValue(line);
                request.Headers.Add(name, values.ToArray());
            }
            request.Scheme      = uri.Scheme;
            request.Path        = PathString.FromUriComponent(uri);
            request.QueryString = QueryString.FromUriComponent(uri);
            request.Body        = new StreamWithPrefix(lineReader.Remaining, stream, null);
        }
예제 #16
0
 public UriHelper(Uri uri)
 {
     Scheme = uri.Scheme;
     Host   = HostString.FromUriComponent(uri);
     // Assume nothing is being put in PathBase
     Path     = PathString.FromUriComponent(uri);
     Query    = QueryString.FromUriComponent(uri);
     Fragment = FragmentString.FromUriComponent(uri);
 }
예제 #17
0
        public async Task <WebSocket> ConnectAsync(Uri uri, CancellationToken cancellationToken)
        {
            WebSocketFeature webSocketFeature = null;
            var contextBuilder = new HttpContextBuilder(_application, AllowSynchronousIO, PreserveExecutionContext);

            contextBuilder.Configure(context =>
            {
                var request    = context.Request;
                var scheme     = uri.Scheme;
                scheme         = (scheme == "ws") ? "http" : scheme;
                scheme         = (scheme == "wss") ? "https" : scheme;
                request.Scheme = scheme;
                if (!request.Host.HasValue)
                {
                    request.Host = uri.IsDefaultPort
                        ? new HostString(HostString.FromUriComponent(uri).Host)
                        : HostString.FromUriComponent(uri);
                }
                request.Path     = PathString.FromUriComponent(uri);
                request.PathBase = PathString.Empty;
                if (request.Path.StartsWithSegments(_pathBase, out var remainder))
                {
                    request.Path     = remainder;
                    request.PathBase = _pathBase;
                }
                request.QueryString = QueryString.FromUriComponent(uri);
                request.Headers.Add(HeaderNames.Connection, new string[] { "Upgrade" });
                request.Headers.Add(HeaderNames.Upgrade, new string[] { "websocket" });
                request.Headers.Add(HeaderNames.SecWebSocketVersion, new string[] { "13" });
                request.Headers.Add(HeaderNames.SecWebSocketKey, new string[] { CreateRequestKey() });
                if (SubProtocols.Any())
                {
                    request.Headers.Add(HeaderNames.SecWebSocketProtocol, SubProtocols.ToArray());
                }

                request.Body = Stream.Null;

                // WebSocket
                webSocketFeature = new WebSocketFeature(context);
                context.Features.Set <IHttpWebSocketFeature>(webSocketFeature);

                ConfigureRequest?.Invoke(context.Request);
            });

            var httpContext = await contextBuilder.SendAsync(cancellationToken);

            if (httpContext.Response.StatusCode != StatusCodes.Status101SwitchingProtocols)
            {
                throw new InvalidOperationException("Incomplete handshake, status code: " + httpContext.Response.StatusCode);
            }
            if (webSocketFeature.ClientWebSocket == null)
            {
                throw new InvalidOperationException("Incomplete handshake");
            }

            return(webSocketFeature.ClientWebSocket);
        }
예제 #18
0
        /// <summary>
        /// Builds the HTTP context.
        /// </summary>
        /// <param name="routeEndpoint">The route endpoint.</param>
        /// <param name="requestInfo">The request information.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The HTTP context to invoke a request delegate with</returns>
        private HttpContext BuildHttpContext(RouteEndpoint routeEndpoint, RequestInfo requestInfo, RouteValueDictionary routeValues)
        {
            DefaultHttpContext httpContext = new DefaultHttpContext();

            httpContext.Features.Set <IEndpointFeature>(new HttpContextFeatures.EndpointFeature(routeEndpoint));
            httpContext.Features.Set <IRoutingFeature>(new HttpContextFeatures.RoutingFeature(routeValues));
            httpContext.RequestServices = _serviceProvider;

            if (_httpContextAccessor.HttpContext != null)
            {
                httpContext.User = _httpContextAccessor.HttpContext.User;
            }

            string[] relativeUriComponents = requestInfo.RelativeUri.Split(QuerySeparator);
            Uri      requestUri            = new UriBuilder(_batchRequestOptions.RequestHost)
            {
                Path  = relativeUriComponents[0],
                Query = relativeUriComponents.Length > 1 ? relativeUriComponents[1] : string.Empty,
            }.Uri;

            httpContext.Request.Scheme      = requestUri.Scheme;
            httpContext.Request.Host        = HostString.FromUriComponent(requestUri);
            httpContext.Request.Path        = PathString.FromUriComponent(requestUri);
            httpContext.Request.QueryString = QueryString.FromUriComponent(requestUri);
            httpContext.Request.Query       = new QueryCollection(QueryHelpers.ParseQuery(requestUri.Query));
            httpContext.Request.ContentType = requestInfo.ContentType;
            httpContext.Request.Method      = requestInfo.Method.ToUpper();
            httpContext.Request.Protocol    = _batchRequestOptions.DefaultProtocol;
            httpContext.Request.IsHttps     = httpContext.Request.Scheme == Uri.UriSchemeHttps;

            httpContext.Response.Body = new MemoryStream();
            if (!string.IsNullOrEmpty(requestInfo.Body))
            {
                byte[] bodyData;
                if (requestInfo.Base64Encoded)
                {
                    try
                    {
                        bodyData = Convert.FromBase64String(requestInfo.Body);
                    }
                    catch (FormatException)
                    {
                        throw new Base64FormatException()
                              {
                                  Base64 = requestInfo.Body
                              };
                    }
                }
                else
                {
                    bodyData = Encoding.UTF8.GetBytes(requestInfo.Body);
                }
                httpContext.Request.Body = new MemoryStream(bodyData);
            }

            return(httpContext);
        }
예제 #19
0
        private static ODataQueryOptions GetODataQueryOptions(string oData)
        {
            const string baseUrl = "http://localhost/User?";

            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri($"{baseUrl}{oData}"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            return(oDataQueryOptions);
        }
예제 #20
0
        private async Task <HttpRequest> GetRequest(HttpContext context, HttpRequestMessage request)
        {
            var requestContent = request.Content ?? new StreamContent(Stream.Null);
            var body           = await requestContent.ReadAsStreamAsync();

            PathString pathBase = new PathString("");

            var req = context.Request;

            req.Protocol = "HTTP/" + request.Version.ToString(fieldCount: 2);
            req.Method   = request.Method.ToString();

            req.Scheme = request.RequestUri.Scheme;

            foreach (var header in request.Headers)
            {
                req.Headers.Append(header.Key, header.Value.ToArray());
            }

            if (req.Host == null || !req.Host.HasValue)
            {
                // If Host wasn't explicitly set as a header, let's infer it from the Uri
                req.Host = HostString.FromUriComponent(request.RequestUri);
                if (request.RequestUri.IsDefaultPort)
                {
                    req.Host = new HostString(req.Host.Host);
                }
            }

            req.Path     = PathString.FromUriComponent(request.RequestUri);
            req.PathBase = PathString.Empty;
            if (req.Path.StartsWithSegments(pathBase, out var remainder))
            {
                req.Path     = remainder;
                req.PathBase = pathBase;
            }
            req.QueryString = QueryString.FromUriComponent(request.RequestUri);

            if (requestContent != null)
            {
                foreach (var header in requestContent.Headers)
                {
                    req.Headers.Append(header.Key, header.Value.ToArray());
                }
            }

            if (body.CanSeek)
            {
                // This body may have been consumed before, rewind it.
                body.Seek(0, SeekOrigin.Begin);
            }
            req.Body = body;


            return(req);
        }
예제 #21
0
        public void TranslateAnyToJoin_WhenQueriedBasedOnChildPropertyDifferentLetter()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=products/any(j:j/name eq 'test')"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN j IN c.products WHERE j.name = 'test' ", sqlQuery);
        }
예제 #22
0
        public void TranslateAnyToJoin_WhenQueriedBasedOnMultipleChildProperty()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=products/any(p: p/name eq 'test') and locations/any(l: l/name eq 'test2')"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN p IN c.products JOIN l IN c.locations WHERE p.name = 'test' AND l.name = 'test2' ", sqlQuery);
        }
예제 #23
0
        public void TranslateAnyToJoin_WhenChildHasFieldId()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=competitors/any(p: p/id eq '6a7ad0aa-678e-40f9-8cdf-03e3ab4a4106')"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN p IN c.competitors WHERE p.id = '6a7ad0aa-678e-40f9-8cdf-03e3ab4a4106' ", sqlQuery);
        }
예제 #24
0
        public void TranslateAnyToJoin_WhenChildHasFieldIdBasedOnAnotherField()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=competitors/any(p: p/name eq 'test')"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN p IN c.competitors WHERE p.name = 'test' ", sqlQuery);
        }
예제 #25
0
        public void TranslateAnyToJoin_MixedLevelProperties()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=competitors/any(p: p/name eq 'test') and englishName eq 'test1'"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN p IN c.competitors WHERE p.name = 'test' AND c.englishName = 'test1' ", sqlQuery);
        }
예제 #26
0
        public void TranslateAnyToJoin_Works_WhenCollectionIsInThirdChildElement()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=competitor/competitor/competitor/locations/any(j:j/name eq 'test')"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN j IN c.competitor.competitor.competitor.locations WHERE j.name = 'test' ", sqlQuery);
        }
예제 #27
0
        public void TranslateAnyToJoin_QueryBasedOnCorrectOrder_WhenConditionIsBasedOnId()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=competitor/competitorTwo/locations/any(j:j/id eq 'test')"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN j IN c.competitor.competitorTwo.locations WHERE j.id = 'test' ", sqlQuery);
        }
예제 #28
0
        public void Translate_ReturnsCaseSensitiveStringFunction_WhenODataQueryDoesNotContainCaseInsensitiveStringQuery(string uriString, string expectedSqlQuery)
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri(uriString));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var actualSqlQuery       = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual(expectedSqlQuery, actualSqlQuery);
        }
예제 #29
0
        public void TranslateAnyToJoin_WhenThereIsOneNestedjoinWithComplexPath()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=payload/bet/legs/any(l: l/outcomes/any(o: o/id eq 'test'))"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN l IN c.payload.bet.legs JOIN o IN l.outcomes WHERE o.id = 'test' ", sqlQuery);
        }
예제 #30
0
        public void TranslateAnyToJoin_WhenThereIsOneNestedjoin()
        {
            HttpRequest.QueryString = QueryString.FromUriComponent(new Uri("http://localhost/User?$filter=competitor/locations/any(j:j/locations/any(l:l/id eq 'test'))"));
            var oDataQueryOptions = new ODataQueryOptions(ODataQueryContext, HttpRequest);

            var oDataToSqlTranslator = new ODataToSqlTranslator(new SQLQueryFormatter());
            var sqlQuery             = oDataToSqlTranslator.Translate(oDataQueryOptions, TranslateOptions.ALL & ~TranslateOptions.TOP_CLAUSE);

            Assert.AreEqual("SELECT VALUE c FROM c JOIN j IN c.competitor.locations JOIN l IN j.locations WHERE l.id = 'test' ", sqlQuery);
        }