Ejemplo n.º 1
0
        public Api(WebServer server)
        {
            server.Add("/login", Login);
            server.Add("/register", Register);
            server.Add("/signout", SignOut);

            Router apiRouter = server.AddRouter("/api");

            apiRouter.Add("/kids", Kids)
            .Add("/user", User)
            .Add("/events", Events)
            .Add("/event", Event)
            .Add("/email_available", EmailAvailable)
            .Add("/add_kid", AddKid)
            .Add("/create_event", CreateEvent)
            .Add("/schedule_event", ScheduleEvent)
            .Add("/own_events", OwnEvents)
            .Add("/own_event", OwnEvent)
            .Add("/book_event", BookEvent)
            .Add("/categories", Categories)
            .Add("/user_update", UserUpdate)
            .Add("/pay", Pay);

            /*
             * Admin APIs
             */
            apiRouter.Add("/users", Users)
            .Add("/ban_user", BanUser);
        }
        public async Task Ok_should_return_200_Ok()
        {
            Router.Add("/", c => Task.Delay(0));

            var response = new Mock <IOwinResponse>();

            response.Setup(r => r.WriteAsync(It.IsAny <string>())).Returns(Task.Factory.StartNew(() => { }));
            response.SetupProperty(r => r.StatusCode);

            var request = new Mock <IOwinRequest>();

            request.Setup(r => r.Uri).Returns(new Uri("http://localhost/"));
            request.Setup(r => r.Method).Returns("GET");

            var context = new Mock <IOwinContext>();

            context.Setup(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response).Returns(response.Object);

            await Router.Invoke(context.Object).ConfigureAwait(false);

            await Task.Delay(10);

            Assert.AreEqual(200, context.Object.Response.StatusCode);
        }
        public async Task Ok_with_UnauthorizedAccessException_should_return_401_Error()
        {
            Router.Add("/", c => c.OkJson(() => {
                throw new UnauthorizedAccessException();
                return("Hello world!"); //Needed for function type inference
            }));
            var response = new Mock <IOwinResponse>();

            response.Setup(r => r.WriteAsync(It.IsAny <string>())).Returns(Task.Factory.StartNew(() => { }));
            response.SetupProperty(r => r.StatusCode);

            var request = new Mock <IOwinRequest>();

            request.Setup(r => r.Uri).Returns(new Uri("http://localhost/"));
            request.Setup(r => r.Method).Returns("GET");

            var context = new Mock <IOwinContext>();

            context.Setup(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response).Returns(response.Object);


            await Router.Invoke(context.Object).ConfigureAwait(false);

            Assert.AreEqual(401, context.Object.Response.StatusCode);
        }
Ejemplo n.º 4
0
    protected override void SetupRouter()
    {
        Router.Clear();

        // HTML Routes
        Router.Add("student-test", "StaticViews/views/student-test.html");
    }
Ejemplo n.º 5
0
 public void RoutesAre([SelectionValues("GET", "POST", "DELETE", "PUT", "HEAD")] string HttpMethod, string Pattern)
 {
     _router.Add(HttpMethod, Pattern, env =>
     {
         env.Response.ContentType("text/plain");
         return(env.Response.WriteAsync($"{HttpMethod}: /{Pattern}"));
     });
 }
Ejemplo n.º 6
0
 public void RoutesAre([SelectionValues("GET", "POST", "DELETE", "PUT", "HEAD")] string HttpMethod, string Pattern)
 {
     _router.Add(HttpMethod, Pattern, env =>
     {
         env.Write($"{HttpMethod}: /{Pattern}", "text/plain");
         return(Task.CompletedTask);
     });
 }
Ejemplo n.º 7
0
 public Navigator()
 {
     r.Add(this);
     r.Add(Navigation.Instance);
     r.Add(ObjectManager.Instance);
     r.Add(new Loader());
     r.Add(new ProfileLoader(r.Get <Loader>()));
     r.Add(new Pather(r.Get <Navigation>(), r.Get <ObjectManager>(), r.Get <ProfileLoader>()));
     r.Add(new Manager(r.Get <Pather>()));
     r.Add(new CMD(r.Get <Navigator>(), r.Get <ProfileLoader>()));
 }
Ejemplo n.º 8
0
        public void BuildRoutingTree(ConnegRules rules, JasperGenerationRules generation, JasperRuntime runtime)
        {
            Router.HandlerBuilder = new RouteHandlerBuilder(runtime.Container, rules, generation);
            assertNoDuplicateRoutes();

            foreach (var route in _chains.Select(x => x.Route))
            {
                Router.Add(route);
            }
        }
Ejemplo n.º 9
0
        public void BuildRoutingTree(IGenerationConfig generation, IContainer container)
        {
            var handlers = CompileAndBuildAll(generation, container);

            foreach (var handler in handlers)
            {
                var route = handler.Chain.Route;
                route.Handler = handler;
                Router.Add(route);
            }
        }
Ejemplo n.º 10
0
        public void BuildRoutingTree(JasperGenerationRules generation, IContainer container)
        {
            var rules = container.QuickBuild <ConnegRules>();

            Router.HandlerBuilder = new RouteHandlerBuilder(container, rules, generation);
            assertNoDuplicateRoutes();

            foreach (var route in _chains.Select(x => x.Route))
            {
                Router.Add(route);
            }
        }
Ejemplo n.º 11
0
    protected override void SetupRouter()
    {
        Router.Clear();

        Router.Add("", "RestrictedViews/views/admin.html");
        Router.Add("home", "RestrictedViews/views/admin.html");
        Router.Add("system", "RestrictedViews/views/settings.html");

        AddFolderToRouter("error", "StaticViews/views/error");
        AddFolderToRouter("", "RestrictedViews/views");
        AddFolderToRouter("img", "RestrictedViews/img");
        AddFolderToRouter("js", "RestrictedViews/js");
        AddFolderToRouter("css", "RestrictedViews/css");
    }
Ejemplo n.º 12
0
        public async Task TestConditionalRouting(int input, int expectedResult, int expectedEligible)
        {
            const int incrementRoutes = 3;

            var router = new Router <BasicRoutingContext <IntWrapper> >();

            Times(incrementRoutes, () => router.Add(new IncrementRoute()));

            var context = new BasicRoutingContext <IntWrapper>(new IntWrapper(input));
            var routed  = await router.RouteAsync(context);

            Assert.Equal(expectedEligible, routed);
            Assert.Equal(expectedResult, context.Data.Int);
        }
Ejemplo n.º 13
0
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            Router.Add("/", context => context.OkJson(() => HelloWorld.SayHello()));
            Router.Add("/exception", context => { throw new Exception(); });
            Router.Add("/:id", context => context.OkJson(() => context.Param <int>(":id")));

            int iterations = 0;

            using (WebApp.Start <Startup>("http://localhost:8002"))
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    ServiceEventSource.Current.ServiceMessage(this, "Working-{0}", iterations++);
                    await Task.Delay(TimeSpan.FromHours(1), cancellationToken);
                }
            }
        }
Ejemplo n.º 14
0
        public void BuildRoutingTree(ConnegRules rules, GenerationRules generation, JasperRuntime runtime)
        {
            assertNoDuplicateRoutes();

            foreach (var chain in _chains)
            {
                rules.Apply(chain);
            }

            var handlers = CompileAndBuildAll(generation, runtime.Get);

            foreach (var handler in handlers)
            {
                var route = handler.Chain.Route;
                route.Handler = handler;
                Router.Add(route);
            }
        }
Ejemplo n.º 15
0
        protected override void SetupRouter()
        {
            Router.Clear();

            Router.Add("", "StaticViews/views/index.html");
            Router.Add("home", "StaticViews/views/index.html");
            Router.Add("aboutme", "StaticViews/views/aboutme.html");
            Router.Add("resources", "StaticViews/views/resources.html");
            Router.Add("projects", "StaticViews/views/projects.html");

            AddFolderToRouter("", "StaticViews/img");

            // All other files
            AddFolderToRouter("", "StaticViews/views");
            AddFolderToRouter("img", "StaticViews/img");
            AddFolderToRouter("js", "StaticViews/js");
            AddFolderToRouter("css", "StaticViews/css");
        }
        public async Task Simple_routes_are_routed()
        {
            var success = false;

            Router.Add("/", c => Task.Factory.StartNew(() => { success = true; }));
            var request = new Mock <IOwinRequest>();

            request.Setup(r => r.Uri).Returns(new Uri("http://localhost/"));
            request.Setup(r => r.Method).Returns("GET");

            var context = new Mock <IOwinContext>();

            context.Setup(c => c.Request).Returns(request.Object);

            await Router.Invoke(context.Object).ConfigureAwait(false);

            Assert.IsTrue(success);
        }
Ejemplo n.º 17
0
    protected override void SetupRouter()
    {
        // So why not serve static? Because I need a way to serve my own routes.
        // Even though ASP.NET Core can do that too. Oh well.
        Router.Clear();

        // HTML Routes
        Router.Add("", "StaticViews/views/index.html");
        Router.Add("home", "StaticViews/views/index.html");

        // Holy crap icon stuff
        AddFolderToRouter("", "StaticViews/img");

        // All other files
        // Do not include StaticViews/views as that picks up student-test
        AddFolderToRouter("img", "StaticViews/img");
        AddFolderToRouter("js", "StaticViews/js");
        AddFolderToRouter("css", "StaticViews/css");
    }
        public async Task Thrown_exceptions_are_caught()
        {
            Router.Add("/", c => { throw new Exception(); });
            var response = new Mock <IOwinResponse>();

            response.Setup(r => r.WriteAsync(It.IsAny <string>())).Returns(Task.Factory.StartNew(() => { }));
            response.SetupProperty(r => r.StatusCode);

            var request = new Mock <IOwinRequest>();

            request.Setup(r => r.Uri).Returns(new Uri("http://localhost/"));
            request.Setup(r => r.Method).Returns("GET");

            var context = new Mock <IOwinContext>();

            context.Setup(c => c.Request).Returns(request.Object);
            context.Setup(c => c.Response).Returns(response.Object);

            await Router.Invoke(context.Object).ConfigureAwait(false);

            Assert.AreEqual(500, context.Object.Response.StatusCode);
        }
        public async Task Routes_are_executed_in_correct_order()
        {
            var success = false;

            Router.Add("/", c => Task.Factory.StartNew(() => Assert.Fail()));
            Router.Add("/:id", c => Task.Factory.StartNew(() =>
            {
                Assert.AreEqual(1, c.Param <int>(":id"));
                success = true;
            }));
            var request = new Mock <IOwinRequest>();

            request.Setup(r => r.Uri).Returns(new Uri("http://localhost/1"));
            request.Setup(r => r.Method).Returns("GET");

            var context = new Mock <IOwinContext>();

            context.Setup(c => c.Request).Returns(request.Object);

            await Router.Invoke(context.Object).ConfigureAwait(false);

            Assert.IsTrue(success);
        }
        public async Task Complex_routes_with_ints_and_guids_are_routed()
        {
            var guid    = Guid.Empty;
            var success = false;

            Router.Add("/:id/:someguid", c => Task.Factory.StartNew(() =>
            {
                Assert.AreEqual(1, c.Param <int>(":id"));
                Assert.AreEqual(guid, c.Param <Guid>(":someguid"));
                success = true;
            }));
            var request = new Mock <IOwinRequest>();

            request.Setup(r => r.Uri).Returns(new Uri("http://localhost/1/{00000000-0000-0000-0000-000000000000}"));
            request.Setup(r => r.Method).Returns("GET");

            var context = new Mock <IOwinContext>();

            context.Setup(c => c.Request).Returns(request.Object);

            await Router.Invoke(context.Object).ConfigureAwait(false);

            Assert.IsTrue(success);
        }
Ejemplo n.º 21
0
            public IRouter BuildRoutes(IList <RouterComponent> routerComponents)
            {
                // Create a root level router as a container for everythinng that's not on a route.
                // When the application does not use routing everything ends up in here
                IRouter rootRouter = new Router(_dependencyGraphFactory);

                // Add a root segment called with a pass everything filter
                rootRouter.Add("root", owinContext => true);
                var rootRoutingSegment = rootRouter.Segments[0];

                // Wrap the root router in a component, this is equivalent to registering the router
                // with the builder.
                var rootRouterComponent = new RouterComponent
                {
                    Middleware     = rootRouter,
                    MiddlewareType = typeof(IRoute),
                };

                routerComponents.Add(rootRouterComponent);

                // For each router component figure out it's parents and children in the routing graph
                var defaultParents = new List <string> {
                    rootRoutingSegment.Name
                };

                foreach (var routerComponent in routerComponents)
                {
                    var router = (IRouter)routerComponent.Middleware;

                    routerComponent.ChildRouteNames = router.Segments
                                                      .Select(s => s.Name)
                                                      .ToList();

                    routerComponent.ParentRouteNames = router.Dependencies
                                                       .Where(d => d.DependentType == typeof(IRoute) && !string.IsNullOrEmpty(d.Name))
                                                       .Select(s => s.Name)
                                                       .ToList();

                    if (routerComponent.ParentRouteNames.Count == 0 && !ReferenceEquals(routerComponent, rootRouterComponent))
                    {
                        routerComponent.ParentRouteNames = defaultParents;
                    }
                }

                // Create Segment objects for each IRoutingSegment configured by the application
                // We will use the segmenter later to fill in the list of components on each segment
                foreach (var routerComponent in routerComponents)
                {
                    var router = (IRouter)routerComponent.Middleware;
                    routerComponent.RouterSegments = router
                                                     .Segments
                                                     .Select(s => new Segment
                    {
                        Name           = s.Name,
                        RoutingSegment = s
                    })
                                                     .ToList();
                }
                var rootSegment = rootRouterComponent.RouterSegments[0];

                // Connect the routers together by assiging each one to its parents
                var allSegments = routerComponents.SelectMany(r => r.RouterSegments).ToList();

                foreach (var routerComponent in routerComponents)
                {
                    if (routerComponent == rootRouterComponent)
                    {
                        continue;
                    }

                    var router          = (IRouter)routerComponent.Middleware;
                    var dependentRoutes = router
                                          .Dependencies
                                          .Where(dep => dep.DependentType == typeof(IRoute))
                                          .ToList();
                    if (dependentRoutes.Count == 0)
                    {
                        rootSegment.Components.Add(routerComponent);
                        routerComponent.SegmentAssignments.Add(rootSegment);
                    }
                    else
                    {
                        foreach (var routeDependency in dependentRoutes)
                        {
                            var dependentSegment = allSegments.FirstOrDefault(
                                s => string.Equals(s.Name, routeDependency.Name, StringComparison.OrdinalIgnoreCase));
                            if (dependentSegment == null)
                            {
                                if (routeDependency.Required)
                                {
                                    throw new MissingDependencyException(
                                              "Route '"
                                              + routerComponent.Middleware.Name
                                              + "' depends on route '"
                                              + routeDependency.Name
                                              + "' which is not configured");
                                }
                            }
                            else
                            {
                                dependentSegment.Components.Add(routerComponent);
                                routerComponent.SegmentAssignments.Add(dependentSegment);
                            }
                        }
                    }
                }

                return(rootRouter);
            }
Ejemplo n.º 22
0
 public void Complex_routes_are_added_to_collection()
 {
     Router.Add("/awdawdad/:id", context => Task.Factory.StartNew(id => { }, context.Param <int>(":id")));
     Assert.AreEqual(1, Router.Routes.Count());
 }
Ejemplo n.º 23
0
 internal void RegisterRoute(string route)
 {
     _router.Add(route);
 }
Ejemplo n.º 24
0
 public void RoutesAre([SelectionValues("GET", "POST", "DELETE", "PUT", "HEAD")]
                       string HttpMethod, string Pattern)
 {
     _router.Add(HttpMethod, Pattern);
 }
Ejemplo n.º 25
0
        public async Task Router_ShouldCallHandlerFunc()
        {
            _sut.Add("GET", "home", "/", _handlerFunc.Handle);

            var request = PrepareRequest("GET", "/");
            await _sut.HandleAsync(request, Substitute.For <IResponse>());

            await _handlerFunc.Received().Handle(Arg.Any <Context>());
        }
Ejemplo n.º 26
0
 public Merchant()
 {
     r.Add(this);
     r.Add(Inventory.Instance);
     r.Add(Navigation.Instance);
     r.Add(ObjectManager.Instance);
     r.Add(new Loader());
     r.Add(new ProfileLoader(r.Get <Loader>()));
     r.Add(new Pather(r.Get <Navigation>(), r.Get <ObjectManager>(), r.Get <ProfileLoader>()));
     r.Add(new ChoreBoy(r.Get <Inventory>(), r.Get <ObjectManager>(), r.Get <Pather>()));
     r.Add(new Controller(r.Get <ChoreBoy>(), r.Get <ObjectManager>(), r.Get <Pather>()));
     r.Add(new Manager(r.Get <Controller>(), r.Get <ObjectManager>(), r.Get <ProfileLoader>()));
     r.Add(new CMD(r.Get <Merchant>(), r.Get <ProfileLoader>()));
 }
Ejemplo n.º 27
0
 public void Simple_routes_are_added_to_collection()
 {
     Router.Add("/", context => Task.Factory.StartNew(() => {}));
     Assert.AreEqual(1, Router.Routes.Count());
 }
Ejemplo n.º 28
0
 /// <summary>
 ///     Adds a responder, and detects on what requests to respond.
 /// </summary>
 /// <param name="router">
 ///     A <see cref="Router" /> to add the responder to.
 /// </param>
 /// <param name="responder">
 ///     A <see cref="Action" /> to respond with.
 /// </param>
 /// <returns>
 ///     A <see cref="Router" /> to add more responders in flow.
 /// </returns>
 public static Router AddRest(this Router router, Delegate responder)
 {
     router.Add(responder);
     return(router);
 }
Ejemplo n.º 29
0
 public Harvester()
 {
     r.Add(this);
     r.Add(CustomClasses.Instance);
     r.Add(Inventory.Instance);
     r.Add(Lua.Instance);
     r.Add(Navigation.Instance);
     r.Add(ObjectManager.Instance);
     r.Add(Skills.Instance);
     r.Add(Spell.Instance);
     r.Add(new Loader());
     r.Add(new CCLoader(r.Get <CustomClasses>()));
     r.Add(new ProfileLoader(r.Get <Loader>()));
     r.Add(new CMD(r.Get <ProfileLoader>()));
     r.Add(new ConsumablesModule(r.Get <Inventory>(), r.Get <ObjectManager>()));
     r.Add(new PathModule(r.Get <Navigation>(), r.Get <ObjectManager>(), r.Get <ProfileLoader>()));
     r.Add(new CombatModule(r.Get <CustomClasses>(), r.Get <ObjectManager>(), r.Get <PathModule>()));
     r.Add(new NodeScanModule(r.Get <CMD>(), r.Get <ObjectManager>(), r.Get <Skills>()));
     r.Add(new Flow(r.Get <CMD>(), r.Get <CombatModule>(), r.Get <ConsumablesModule>(),
                    r.Get <Inventory>(), r.Get <Lua>(), r.Get <NodeScanModule>(),
                    r.Get <ObjectManager>(), r.Get <PathModule>(), r.Get <Spell>()));
     r.Add(new Controller(r.Get <Flow>(), r.Get <Inventory>(), r.Get <ObjectManager>(),
                          r.Get <PathModule>()));
     r.Add(new Manager(r.Get <CCLoader>(), r.Get <Controller>(), r.Get <ObjectManager>(),
                       r.Get <ProfileLoader>()));
 }
Ejemplo n.º 30
0
 /// <summary>
 ///     Adds a responder, and detects on what requests to respond.
 /// </summary>
 /// <param name="router">
 ///     A <see cref="Router" /> to add the responder to.
 /// </param>
 /// <param name="responder">
 ///     A <see cref="Action" /> to respond with.
 /// </param>
 /// <returns>
 ///     A <see cref="Router" /> to add more responders in flow.
 /// </returns>
 public static Router AddRest <T1>(this Router router, Action <Request, T1> responder)
 {
     router.Add(responder);
     return(router);
 }