Esempio n. 1
0
        public DefaultRouteResolverFixture()
        {
            this.moduleBuilder = A.Fake <INancyModuleBuilder>();
            A.CallTo(() => this.moduleBuilder.BuildModule(A <NancyModule> .Ignored, A <NancyContext> .Ignored)).
            ReturnsLazily(r => r.Arguments[0] as NancyModule);

            this.catalog = A.Fake <INancyModuleCatalog>();
            A.CallTo(() => this.catalog.GetModuleByKey(A <string> .Ignored, A <NancyContext> .Ignored)).Returns(expectedModule);

            this.expectedAction = x => HttpStatusCode.OK;
            this.expectedModule = new FakeNancyModule(x =>
            {
                x.AddGetRoute("/foo/bar", this.expectedAction);
            });

            A.CallTo(() => this.catalog.GetModuleByKey(A <string> .Ignored, A <NancyContext> .Ignored)).ReturnsLazily(() => this.expectedModule);

            this.matcher = A.Fake <IRoutePatternMatcher>();
            A.CallTo(() => this.matcher.Match(A <string> .Ignored, A <string> .Ignored)).ReturnsLazily(x =>
                                                                                                       new FakeRoutePatternMatchResult(c =>
            {
                c.IsMatch(((string)x.Arguments[0]).Equals(((string)x.Arguments[1])));
                c.AddParameter("foo", "bar");
            }));

            this.resolver = new DefaultRouteResolver(this.catalog, this.matcher, this.moduleBuilder);
        }
Esempio n. 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UriTemplateRouteResolver"/> class.
 /// </summary>
 /// <param name="inner">The inner.</param>
 /// <param name="moduleCatalog">The module catalog.</param>
 /// <param name="builder">The builder.</param>
 /// <param name="environment">The environment.</param>
 public UriTemplateRouteResolver(DefaultRouteResolver inner, INancyModuleCatalog moduleCatalog, INancyModuleBuilder builder, INancyEnvironment environment)
 {
     this.inner                     = inner;
     this.moduleCatalog             = moduleCatalog;
     this.builder                   = builder;
     this.globalizationConfiguraton = environment.GetValue <GlobalizationConfiguration>();
 }
Esempio n. 3
0
        public static void Enable(DiagnosticsConfiguration diagnosticsConfiguration, IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IEnumerable<ISerializer> serializers, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, ICultureService cultureService)
        {
            var keyGenerator = new DefaultModuleKeyGenerator();
            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(keyGenerator, providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);

            var diagnosticsRouteCache = new RouteCache(diagnosticsModuleCatalog, keyGenerator, new DefaultNancyContextFactory(cultureService), new DefaultRouteSegmentExtractor(), new DefaultRouteDescriptionProvider(), cultureService);

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DefaultRoutePatternMatcher(),
                new DiagnosticsModuleBuilder(rootPathProvider, serializers, modelBinderLocator),
                diagnosticsRouteCache,
                responseProcessors);

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem<Func<NancyContext, Response>>(
                    PipelineKey,
                    ctx =>
                    {
                        if (!ctx.ControlPanelEnabled)
                        {
                            return null;
                        }

                        if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
                        {
                            return null;
                        }

                        ctx.Items[ItemsKey] = true;

                        var resourcePrefix =
                            string.Concat(diagnosticsConfiguration.Path, "/Resources/");

                        if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
                        {
                            var resourceNamespace = "Nancy.Diagnostics.Resources";

                            var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
                            if (!string.IsNullOrEmpty(path))
                            {
                                resourceNamespace += string.Format(".{0}", path.Replace('\\', '.'));
                            }

                            return new EmbeddedFileResponse(
                                typeof(DiagnosticsHook).Assembly,
                                resourceNamespace,
                                Path.GetFileName(ctx.Request.Url.Path));
                        }

                        RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);

                        return diagnosticsConfiguration.Valid
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
                                   : GetDiagnosticsHelpView(ctx);
                    }));
        }
Esempio n. 4
0
        public static void Enable(DiagnosticsConfiguration diagnosticsConfiguration, IPipelines pipelines, IEnumerable <IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable <IResponseProcessor> responseProcessors, ICultureService cultureService)
        {
            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);

            var diagnosticsRouteCache = new RouteCache(diagnosticsModuleCatalog, new DefaultNancyContextFactory(cultureService), new DefaultRouteSegmentExtractor(), new DefaultRouteDescriptionProvider(), cultureService);

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator),
                diagnosticsRouteCache,
                new RouteResolverTrie(new TrieNodeFactory()));

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem <Func <NancyContext, Response> >(
                    PipelineKey,
                    ctx =>
            {
                if (!ctx.ControlPanelEnabled)
                {
                    return(null);
                }

                if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                ctx.Items[ItemsKey] = true;

                var resourcePrefix =
                    string.Concat(diagnosticsConfiguration.Path, "/Resources/");

                if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
                {
                    var resourceNamespace = "Nancy.Diagnostics.Resources";

                    var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
                    if (!string.IsNullOrEmpty(path))
                    {
                        resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
                    }

                    return(new EmbeddedFileResponse(
                               typeof(DiagnosticsHook).Assembly,
                               resourceNamespace,
                               Path.GetFileName(ctx.Request.Url.Path)));
                }

                RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);

                return(diagnosticsConfiguration.Valid
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
                                   : GetDiagnosticsHelpView(ctx));
            }));
        }
Esempio n. 5
0
        public static void Enable(DiagnosticsConfiguration diagnosticsConfiguration, IPipelines pipelines, IEnumerable <IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IEnumerable <ISerializer> serializers, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable <IResponseProcessor> responseProcessors)
        {
            var keyGenerator             = new DefaultModuleKeyGenerator();
            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(keyGenerator, providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);

            var diagnosticsRouteCache = new RouteCache(diagnosticsModuleCatalog, keyGenerator, new DefaultNancyContextFactory());

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DefaultRoutePatternMatcher(),
                new DiagnosticsModuleBuilder(rootPathProvider, serializers, modelBinderLocator),
                diagnosticsRouteCache,
                responseProcessors);

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem <Func <NancyContext, Response> >(
                    PipelineKey,
                    ctx =>
            {
                if (!ctx.ControlPanelEnabled)
                {
                    return(null);
                }

                if (!ctx.Request.Path.StartsWith(ControlPanelPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                if (ctx.Request.Path.StartsWith(ResourcePrefix, StringComparison.OrdinalIgnoreCase))
                {
                    var resourceNamespace = "Nancy.Diagnostics.Resources";

                    var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(ResourcePrefix, string.Empty)) ?? string.Empty;
                    if (!string.IsNullOrEmpty(path))
                    {
                        resourceNamespace += string.Format(".{0}", path.Replace('\\', '.'));
                    }

                    return(new EmbeddedFileResponse(
                               typeof(DiagnosticsHook).Assembly,
                               resourceNamespace,
                               Path.GetFileName(ctx.Request.Url.Path)));
                }

                return(diagnosticsConfiguration.Valid
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
                                   : GetDiagnosticsHelpView(ctx));
            }));
        }
Esempio n. 6
0
            public void Can_Resolve_Home_Page_With_Default_Action(string path)
            {
                // Given

                //var store = this.SetupContext();
                var routeResolverTrie = A.Fake <IRouteResolverTrie>();
                //var mapper = A.Fake<IControllerMapper>();



                //A.CallTo(() => mapper.GetControllerName(typeof (FakeController))).Returns("FakeController");
                //A.CallTo(() => mapper.ControllerHasAction("FakeController", "index")).Returns(true);

                // When

                ResolveResult data;

                using (var store = this.SetupContext())
                {
                    using (var session = store.OpenSession())
                    {
                        var node = new TrieNode
                        {
                            PageId = "pages/1"
                        };

                        var page = new FakePage {
                            Id = "pages/1"
                        };
                        var structureInfo = new Trie
                        {
                            Id       = DefaultBrickPileBootstrapper.TrieId,
                            RootNode = node
                        };
                        session.Store(structureInfo);
                        session.Store(page);
                        session.SaveChanges();

                        var resolver = new DefaultRouteResolver(routeResolverTrie);

                        A.CallTo(() => routeResolverTrie.LoadTrie()).Returns(structureInfo);

                        data = resolver.Resolve(path);
                    }

                    //Then

                    Assert.NotNull(data);
                    Assert.Equal(data.TrieNode.PageId, "pages/1");
                    Assert.Equal("index", data.Action);
                }
            }
Esempio n. 7
0
        public void Should_return_route_whos_filter_returns_true_when_there_is_also_a_matching_route_with_a_failing_filter()
        {
            // Given
            var moduleCatalog    = new FakeModuleCatalog();
            var routeCache       = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>());
            var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder);
            var request          = new FakeRequest("GET", "/filt");
            var context          = new NancyContext {
                Request = request
            };

            // When
            var route = specificResolver.Resolve(context, routeCache).Item1;

            // Then
            route.Description.Condition(context).ShouldBeTrue();
        }
Esempio n. 8
0
        public void Should_return_a_route_if_matching_and_the_filter_returns_true()
        {
            // Given
            var moduleCatalog    = new FakeModuleCatalog();
            var routeCache       = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>());
            var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder);
            var request          = new FakeRequest("GET", "/notfiltered");
            var context          = new NancyContext {
                Request = request
            };

            // When
            var route = specificResolver.Resolve(context, routeCache).Item1;

            // Then
            route.ShouldBeOfType(typeof(Route));
        }
        public void Should_not_return_a_route_if_matching_and_the_filter_returns_false()
        {
            // Given
            var moduleCatalog    = new FakeModuleCatalog();
            var routeCache       = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>(), A.Fake <IRouteSegmentExtractor>(), this.routeDescriptionProvider);
            var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder, routeCache, null);
            var request          = new FakeRequest("GET", "/filtered");
            var context          = new NancyContext {
                Request = request
            };

            // When
            var route = specificResolver.Resolve(context).Item1;

            // Then
            route.ShouldBeOfType(typeof(NotFoundRoute));
        }
Esempio n. 10
0
        public void Should_return_prereq_and_postreq_from_module()
        {
            // Given
            var moduleCatalog = A.Fake <INancyModuleCatalog>();

            A.CallTo(() => moduleCatalog.GetAllModules(A <NancyContext> .Ignored)).Returns(new[] { new FakeNancyModuleWithPreAndPostHooks() });
            A.CallTo(() => moduleCatalog.GetModuleByKey(A <string> .Ignored, A <NancyContext> .Ignored)).Returns(
                new FakeNancyModuleWithPreAndPostHooks());

            var routeCache       = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>());
            var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder);
            var request          = new FakeRequest("GET", "/PrePost");
            var context          = new NancyContext {
                Request = request
            };

            // When
            var result = specificResolver.Resolve(context, routeCache);

            // Then
            result.Item3.ShouldNotBeNull();
            result.Item4.ShouldNotBeNull();
        }
Esempio n. 11
0
        /// <summary>
        /// Enables the diagnostics dashboard and will intercept all requests that are passed to
        /// the condigured paths.
        /// </summary>
        public static void Enable(IPipelines pipelines, IEnumerable <IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable <IResponseProcessor> responseProcessors, IEnumerable <IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable <IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, ITypeCatalog typeCatalog, IAssemblyCatalog assemblyCatalog)
        {
            var diagnosticsConfiguration =
                environment.GetValue <DiagnosticsConfiguration>();

            var diagnosticsEnvironment =
                GetDiagnosticsEnvironment();

            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog, assemblyCatalog);

            var diagnosticsRouteCache = new RouteCache(
                diagnosticsModuleCatalog,
                new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource, environment),
                new DefaultRouteSegmentExtractor(),
                new DefaultRouteDescriptionProvider(),
                cultureService,
                routeMetadataProviders);

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment),
                diagnosticsRouteCache,
                new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)),
                environment);

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem <Func <NancyContext, Response> >(
                    PipelineKey,
                    ctx =>
            {
                if (!ctx.ControlPanelEnabled)
                {
                    return(null);
                }

                if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                if (!diagnosticsConfiguration.Enabled)
                {
                    return(HttpStatusCode.NotFound);
                }

                ctx.Items[ItemsKey] = true;

                var resourcePrefix =
                    string.Concat(diagnosticsConfiguration.Path, "/Resources/");

                if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
                {
                    var resourceNamespace = "Nancy.Diagnostics.Resources";

                    var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
                    if (!string.IsNullOrEmpty(path))
                    {
                        resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
                    }

                    return(new EmbeddedFileResponse(
                               typeof(DiagnosticsHook).GetTypeInfo().Assembly,
                               resourceNamespace,
                               Path.GetFileName(ctx.Request.Url.Path)));
                }

                RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);

                return(ValidateConfiguration(diagnosticsConfiguration)
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer, diagnosticsEnvironment)
                                   : new DiagnosticsViewRenderer(ctx, environment)["help"]);
            }));
        }