Пример #1
0
        public void Should_map_one_to_many_realtions()
        {
            var persons = new List <Person>
            {
                new Person {
                    Firstname = "Robin", Lastname = "Ridderholt", Id = 1
                },
                new Person {
                    Firstname = "Micke", Lastname = "Larsson", Id = 2, Email = new List <Email> {
                        new Email {
                            Address = "*****@*****.**"
                        }
                    }
                },
                new Person {
                    Firstname = "Micke", Lastname = "Larsson", Id = 2, Email = new List <Email> {
                        new Email {
                            Address = "*****@*****.**"
                        }
                    }
                }
            };

            var transformer = new CustomTransformer <Person>(person => person.Id);

            transformer.TransformTuple(new object[] { "Micke", "Larsson", 2, "*****@*****.**" }, new[] { "Firstname", "Lastname", "Id", "Email.Address" });

            var list = transformer.TransformList(persons) as List <Person>;

            list.Should().HaveCount(2);
            list.Single(x => x.Id == 2).Email.Should().HaveCount(2);
            list.Single(x => x.Id == 1).Email.Should().BeNull();
        }
Пример #2
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHttpProxy httpProxy)
        {
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            // Copy all request headers except Host
            var transformer    = new CustomTransformer(); // or HttpTransformer.Default;
            var requestOptions = new RequestProxyOptions(TimeSpan.FromSeconds(100), null);

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    await httpProxy.ProxyAsync(httpContext, "https://localhost:10000/", httpClient, requestOptions, transformer);
                    var errorFeature = httpContext.Features.Get <IProxyErrorFeature>();
                    if (errorFeature != null)
                    {
                        var error     = errorFeature.Error;
                        var exception = errorFeature.Exception;
                    }
                });
            });
        }
Пример #3
0
        public void Should_map_basic_properties(object[] tuple, string[] aliases, Person expected)
        {
            var transfomer = new CustomTransformer <Person>();

            var result = transfomer.TransformTuple(tuple, aliases);
            var actual = result as Person;

            actual.Firstname.Should().Be(expected.Firstname);
            actual.Lastname.Should().Be(expected.Lastname);
            actual.Id.Should().Be(expected.Id);
        }
        public void Should_map_basic_properties(object[] tuple, string[] aliases, Person expected)
        {
            var transfomer = new CustomTransformer<Person>();

            var result = transfomer.TransformTuple(tuple, aliases);
            var actual = result as Person;

            actual.Firstname.Should().Be(expected.Firstname);
            actual.Lastname.Should().Be(expected.Lastname);
            actual.Id.Should().Be(expected.Id);
        }
Пример #5
0
        public void Should_map_one_to_one_relation(object[] tuple, string[] aliases, Person expected)
        {
            var transfomer = new CustomTransformer <Person>();

            var result = transfomer.TransformTuple(tuple, aliases);
            var actual = result as Person;

            actual.Firstname.Should().Be(expected.Firstname);
            actual.Lastname.Should().Be(expected.Lastname);
            actual.Id.Should().Be(expected.Id);

            actual.Address.Should().NotBeNull();

            actual.Address.City.Should().Be(expected.Address.City);
            actual.Address.Street.Should().Be(expected.Address.Street);
            actual.Address.Zipcode.Should().Be(expected.Address.Zipcode);
        }
        public void Should_map_one_to_many_realtions()
        {
            var persons = new List<Person>
            {
                new Person{Firstname = "Robin", Lastname = "Ridderholt", Id = 1},
                new Person{Firstname = "Micke", Lastname = "Larsson", Id = 2, Email = new List<Email>{new Email{Address = "*****@*****.**"}}},
                new Person{Firstname = "Micke", Lastname = "Larsson", Id = 2, Email = new List<Email>{new Email{Address = "*****@*****.**"}}}
            };

            var transformer = new CustomTransformer<Person>(person => person.Id);

            transformer.TransformTuple(new object[] {"Micke", "Larsson", 2, "*****@*****.**"}, new[] {"Firstname", "Lastname", "Id", "Email.Address"});

            var list = transformer.TransformList(persons) as List<Person>;

            list.Should().HaveCount(2);
            list.Single(x => x.Id == 2).Email.Should().HaveCount(2);
            list.Single(x => x.Id == 1).Email.Should().BeNull();
        }
Пример #7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHttpProxy httpProxy)
        {
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = System.Net.DecompressionMethods.None,
                UseCookies             = false
            });

            var transformer    = new CustomTransformer();
            var requestOptions = new RequestProxyOptions();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    var urls  = getUrls();
                    var teste = httpContext.Request.Headers.FirstOrDefault(c => c.Key == "teste").Value;
                    var url   = urls.FirstOrDefault(x => x.key == "1").url;
                    if (teste.Count != 0)
                    {
                        url = urls?.FirstOrDefault(x => x.key == teste.ToString()).url;
                    }

                    await httpProxy.ProxyAsync(httpContext, url, httpClient, requestOptions);
                    var errorFeature = httpContext.GetProxyErrorFeature();
                    if (errorFeature != null)
                    {
                        var error     = errorFeature.Error;
                        var exception = errorFeature.Exception;
                    }
                });
            });
        }
Пример #8
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHttpProxy httpProxy)
        {
            // Configure our own HttpMessageInvoker for outbound calls for proxy operations
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            // Setup our own request transform class
            var transformer    = new CustomTransformer(); // or HttpTransformer.Default;
            var requestOptions = new RequestProxyOptions {
                Timeout = TimeSpan.FromSeconds(100)
            };

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                // When using IHttpProxy for direct proxying you are responsible for routing, destination discovery, load balancing, affinity, etc..
                // For an alternate example that includes those features see BasicYarpSample.
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    await httpProxy.ProxyAsync(httpContext, "https://example.com", httpClient, requestOptions, transformer);
                    var errorFeature = httpContext.Features.Get <IProxyErrorFeature>();

                    // Check if the proxy operation was successful
                    if (errorFeature != null)
                    {
                        var error     = errorFeature.Error;
                        var exception = errorFeature.Exception;
                    }
                });
            });
        }
Пример #9
0
        public async Task SimpleProjectionsAsync()
        {
            var transformer = new CustomTransformer();

            await(Sfi.EvictQueriesAsync());
            Sfi.Statistics.Clear();

            const string queryString = "select i.Name, i.Description from AnotherItem i where i.Name='widget'";

            object savedId;

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    var i = new AnotherItem {
                        Name = "widget"
                    };
                    savedId = await(s.SaveAsync(i));
                    await(tx.CommitAsync());
                }

            QueryStatistics  qs = Sfi.Statistics.GetQueryStatistics(queryString);
            EntityStatistics es = Sfi.Statistics.GetEntityStatistics(typeof(AnotherItem).FullName);

            Thread.Sleep(200);

            IList result;

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(0));

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(1));

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).SetResultTransformer(transformer).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(2), "hit count should go up since the cache contains the result before the possible application of a resulttransformer");

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).SetResultTransformer(transformer).ListAsync());
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(3), "hit count should go up since we are using the same resulttransformer");
            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    result = await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());
                    Assert.That(result.Count, Is.EqualTo(1));
                    var i = await(s.GetAsync <AnotherItem>(savedId));
                    i.Name = "Widget";
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(4));
            Assert.That(qs.CacheMissCount, Is.EqualTo(2));

            Thread.Sleep(200);

            using (ISession s = OpenSession())
                using (ITransaction tx = s.BeginTransaction())
                {
                    await(s.CreateQuery(queryString).SetCacheable(true).ListAsync());

                    var i = await(s.GetAsync <AnotherItem>(savedId));
                    Assert.That(i.Name, Is.EqualTo("Widget"));

                    await(s.DeleteAsync(i));
                    await(tx.CommitAsync());
                }

            Assert.That(qs.CacheHitCount, Is.EqualTo(4));
            Assert.That(qs.CacheMissCount, Is.EqualTo(3));
            Assert.That(qs.CachePutCount, Is.EqualTo(3));
            Assert.That(qs.ExecutionCount, Is.EqualTo(3));
            Assert.That(es.FetchCount, Is.EqualTo(0));             //check that it was being cached
        }
Пример #10
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        public void Configure(IApplicationBuilder app, IHttpForwarder forwarder)
        {
            // Configure our own HttpMessageInvoker for outbound calls for proxy operations
            var httpClient = new HttpMessageInvoker(new SocketsHttpHandler()
            {
                UseProxy               = false,
                AllowAutoRedirect      = false,
                AutomaticDecompression = DecompressionMethods.None,
                UseCookies             = false
            });

            // Setup our own request transform class
            var transformer    = new CustomTransformer(); // or HttpTransformer.Default;
            var requestOptions = new ForwarderRequestConfig {
                Timeout = TimeSpan.FromSeconds(100)
            };

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.Map("/test/{**catch-all}", async httpContext =>
                {
                    var error = await forwarder.SendAsync(httpContext, "https://example.com", httpClient, requestOptions,
                                                          (context, proxyRequest) =>
                    {
                        // Customize the query string:
                        var queryContext = new QueryTransformContext(context.Request);
                        queryContext.Collection.Remove("param1");
                        queryContext.Collection["area"] = "xx2";

                        // Assign the custom uri. Be careful about extra slashes when concatenating here.
                        proxyRequest.RequestUri = new Uri("https://example.com" + context.Request.Path + queryContext.QueryString);

                        // Suppress the original request header, use the one from the destination Uri.
                        proxyRequest.Headers.Host = null;

                        return(default);
                    });

                    // Check if the proxy operation was successful
                    if (error != ForwarderError.None)
                    {
                        var errorFeature = httpContext.Features.Get <IForwarderErrorFeature>();
                        var exception    = errorFeature.Exception;
                    }
                });


                // When using IHttpForwarder for direct forwarding you are responsible for routing, destination discovery, load balancing, affinity, etc..
                // For an alternate example that includes those features see BasicYarpSample.
                endpoints.Map("/{**catch-all}", async httpContext =>
                {
                    var error = await forwarder.SendAsync(httpContext, "https://example.com", httpClient, requestOptions, transformer);
                    // Check if the proxy operation was successful
                    if (error != ForwarderError.None)
                    {
                        var errorFeature = httpContext.Features.Get <IForwarderErrorFeature>();
                        var exception    = errorFeature.Exception;
                    }
                });
            });
        public DynamicPageEndpointMatcherPolicyTest()
        {
            var actions = new ActionDescriptor[]
            {
                new PageActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["page"] = "/Index",
                    },
                    DisplayName = "/Index",
                },
                new PageActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["page"] = "/About",
                    },
                    DisplayName = "/About"
                },
            };

            PageEndpoints = new[]
            {
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[0]), "Test1"),
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[1]), "Test2"),
            };

            DynamicEndpoint = new Endpoint(
                _ => Task.CompletedTask,
                new EndpointMetadataCollection(new object[]
            {
                new DynamicPageRouteValueTransformerMetadata(typeof(CustomTransformer), State),
                new PageEndpointDataSourceIdMetadata(1),
            }),
                "dynamic");

            DataSource = new DefaultEndpointDataSource(PageEndpoints);

            SelectorCache = new TestDynamicPageEndpointSelectorCache(DataSource);

            var services = new ServiceCollection();

            services.AddRouting();
            services.AddTransient <CustomTransformer>(s =>
            {
                var transformer       = new CustomTransformer();
                transformer.Transform = (c, values, state) => Transform(c, values, state);
                transformer.Filter    = (c, values, state, endpoints) => Filter(c, values, state, endpoints);
                return(transformer);
            });
            Services = services.BuildServiceProvider();

            Comparer = Services.GetRequiredService <EndpointMetadataComparer>();

            LoadedEndpoints = new[]
            {
                new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "Test1"),
                new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "Test2"),
                new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "ReplacedLoaded")
            };

            var loader = new Mock <PageLoader>();

            loader
            .Setup(l => l.LoadAsync(It.IsAny <PageActionDescriptor>(), It.IsAny <EndpointMetadataCollection>()))
            .Returns((PageActionDescriptor descriptor, EndpointMetadataCollection endpoint) => Task.FromResult(new CompiledPageActionDescriptor
            {
                Endpoint = descriptor.DisplayName switch
                {
                    "/Index" => LoadedEndpoints[0],
                    "/About" => LoadedEndpoints[1],
                    "/ReplacedEndpoint" => LoadedEndpoints[2],
                    _ => throw new InvalidOperationException($"Invalid endpoint '{descriptor.DisplayName}'.")
                }
            }));
		public void SimpleProjections()
		{
			var transformer = new CustomTransformer();
			sessions.EvictQueries();
			sessions.Statistics.Clear();

			const string queryString = "select i.Name, i.Description from AnotherItem i where i.Name='widget'";

			object savedId;
			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.CreateQuery(queryString).SetCacheable(true).List();
				var i = new AnotherItem { Name = "widget" };
				savedId = s.Save(i);
				tx.Commit();
			}

			QueryStatistics qs = sessions.Statistics.GetQueryStatistics(queryString);
			EntityStatistics es = sessions.Statistics.GetEntityStatistics(typeof(AnotherItem).FullName);

			Thread.Sleep(200);

			IList result;
			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.CreateQuery(queryString).SetCacheable(true).List();
				tx.Commit();
			}

			Assert.That(qs.CacheHitCount, Is.EqualTo(0));

			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.CreateQuery(queryString).SetCacheable(true).List();
				tx.Commit();
			}

			Assert.That(qs.CacheHitCount, Is.EqualTo(1));

			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.CreateQuery(queryString).SetCacheable(true).SetResultTransformer(transformer).List();
				tx.Commit();
			}

			Assert.That(qs.CacheHitCount, Is.EqualTo(2), "hit count should go up since the cache contains the result before the possible application of a resulttransformer");

			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.CreateQuery(queryString).SetCacheable(true).SetResultTransformer(transformer).List();
				tx.Commit();
			}

			Assert.That(qs.CacheHitCount, Is.EqualTo(3), "hit count should go up since we are using the same resulttransformer");
			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				result = s.CreateQuery(queryString).SetCacheable(true).List();
				Assert.That(result.Count, Is.EqualTo(1));
				var i = s.Get<AnotherItem>(savedId);
				i.Name = "Widget";
				tx.Commit();
			}

			Assert.That(qs.CacheHitCount, Is.EqualTo(4));
			Assert.That(qs.CacheMissCount, Is.EqualTo(2));

			Thread.Sleep(200);

			using (ISession s = OpenSession())
			using (ITransaction tx = s.BeginTransaction())
			{
				s.CreateQuery(queryString).SetCacheable(true).List();

				var i = s.Get<AnotherItem>(savedId);
				Assert.That(i.Name, Is.EqualTo("Widget"));

				s.Delete(i);
				tx.Commit();
			}

			Assert.That(qs.CacheHitCount, Is.EqualTo(4));
			Assert.That(qs.CacheMissCount, Is.EqualTo(3));
			Assert.That(qs.CachePutCount, Is.EqualTo(3));
			Assert.That(qs.ExecutionCount, Is.EqualTo(3));
			Assert.That(es.FetchCount, Is.EqualTo(0)); //check that it was being cached
		}
        public DynamicControllerEndpointMatcherPolicyTest()
        {
            var dataSourceKey = new ControllerEndpointDataSourceIdMetadata(1);
            var actions       = new ActionDescriptor[]
            {
                new ControllerActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["action"]     = "Index",
                        ["controller"] = "Home",
                    },
                },
                new ControllerActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["action"]     = "About",
                        ["controller"] = "Home",
                    },
                },
                new ControllerActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["action"]     = "Index",
                        ["controller"] = "Blog",
                    },
                }
            };

            ControllerEndpoints = new[]
            {
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[0]), "Test1"),
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[1]), "Test2"),
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[2]), "Test3"),
            };

            DynamicEndpoint = new Endpoint(
                _ => Task.CompletedTask,
                new EndpointMetadataCollection(new object[]
            {
                new DynamicControllerRouteValueTransformerMetadata(typeof(CustomTransformer), State),
                dataSourceKey
            }),
                "dynamic");

            DataSource = new DefaultEndpointDataSource(ControllerEndpoints);

            SelectorCache = new TestDynamicControllerEndpointSelectorCache(DataSource, 1);

            var services = new ServiceCollection();

            services.AddRouting();
            services.AddTransient <CustomTransformer>(s =>
            {
                var transformer       = new CustomTransformer();
                transformer.Transform = (c, values, state) => Transform(c, values, state);
                transformer.Filter    = (c, values, state, candidates) => Filter(c, values, state, candidates);
                return(transformer);
            });
            Services = services.BuildServiceProvider();

            Comparer = Services.GetRequiredService <EndpointMetadataComparer>();
        }
        public void Should_map_one_to_one_relation(object[] tuple, string[] aliases, Person expected)
        {
            var transfomer = new CustomTransformer<Person>();

            var result = transfomer.TransformTuple(tuple, aliases);
            var actual = result as Person;

            actual.Firstname.Should().Be(expected.Firstname);
            actual.Lastname.Should().Be(expected.Lastname);
            actual.Id.Should().Be(expected.Id);

            actual.Address.Should().NotBeNull();

            actual.Address.City.Should().Be(expected.Address.City);
            actual.Address.Street.Should().Be(expected.Address.Street);
            actual.Address.Zipcode.Should().Be(expected.Address.Zipcode);
        }
        public DynamicPageEndpointMatcherPolicyTest()
        {
            var actions = new ActionDescriptor[]
            {
                new PageActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["page"] = "/Index",
                    },
                },
                new PageActionDescriptor()
                {
                    RouteValues = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase)
                    {
                        ["page"] = "/About",
                    },
                },
            };

            PageEndpoints = new[]
            {
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[0]), "Test1"),
                new Endpoint(_ => Task.CompletedTask, new EndpointMetadataCollection(actions[1]), "Test2"),
            };

            DynamicEndpoint = new Endpoint(
                _ => Task.CompletedTask,
                new EndpointMetadataCollection(new object[]
            {
                new DynamicPageRouteValueTransformerMetadata(typeof(CustomTransformer)),
            }),
                "dynamic");

            DataSource = new DefaultEndpointDataSource(PageEndpoints);

            Selector = new TestDynamicPageEndpointSelector(DataSource);

            var services = new ServiceCollection();

            services.AddRouting();
            services.AddScoped <CustomTransformer>(s =>
            {
                var transformer       = new CustomTransformer();
                transformer.Transform = (c, values) => Transform(c, values);
                return(transformer);
            });
            Services = services.BuildServiceProvider();

            Comparer = Services.GetRequiredService <EndpointMetadataComparer>();

            LoadedEndpoint = new Endpoint(_ => Task.CompletedTask, EndpointMetadataCollection.Empty, "Loaded");

            var loader = new Mock <PageLoader>();

            loader
            .Setup(l => l.LoadAsync(It.IsAny <PageActionDescriptor>()))
            .Returns(Task.FromResult(new CompiledPageActionDescriptor()
            {
                Endpoint = LoadedEndpoint,
            }));
            Loader = loader.Object;
        }