示例#1
0
        public static ApiRouter Search(Type rootType, Uri baseUri)
        {
            var typename = GetSegmentFromControllerType(rootType);
            var router = new ApiRouter("", baseUri).To(rootType);

            // Find controllers in the namespaces below type
            var controllers = rootType.Assembly.GetTypes()
                .Where(t => typeof(IHttpController).IsAssignableFrom(t) && t.Namespace.StartsWith(rootType.Namespace) && t != rootType)
                .Select(t => new ControllerEntry() { ControllerType = t, Path = t.Namespace.Replace(rootType.Namespace, "").Replace('.', '/') + "/" + GetSegmentFromControllerType(t) })
                .ToList();

            foreach (var controllerEntry in controllers) {
                Type localController = controllerEntry.ControllerType;
                router.AddWithPath(controllerEntry.Path,
                           (r) => {
                              var parameterAttributes = (PathParameterAttribute[])Attribute.GetCustomAttributes(controllerEntry.ControllerType, typeof (PathParameterAttribute));
                               foreach (var pathParameterAttribute in parameterAttributes) {
                                   r.Add(pathParameterAttribute.PathTemplate, (cr) => cr.To(localController));
                               }

                               // If no path parameters or any are optional then connect the controller to the router
                               if (parameterAttributes.Count() == 0 ||
                                   parameterAttributes.Any(pa => pa.Required == false)) {
                                   r.To(localController);
                               }

                           });

            }
            return router;
        }
示例#2
0
    private static void Main(string[] args)
    {
        var baseAddress   = new Uri("http://oak:8700/");
        var configuration = new HttpSelfHostConfiguration(baseAddress);
        var router        = new ApiRouter("api", baseAddress);

        // /api/Contacts
        router.Add("Contacts", rcs => rcs.To <ContactsController>());
        // /api/Contact/{contactid}
        router.Add("Contact", rc =>
                   rc.Add("{contactid}", rci => rci.To <ContactController>()));
        // /api/Group/{groupid}
        // /api/Group/{groupid}/Contacts
        router.Add("Group", rg =>
                   rg.Add("{groupid}", rgi => rgi.To <GroupController>()
                          .Add("Contacts", rgc => rgc.To <GroupContactsController>())));

        configuration.MessageHandlers.Add(router);
        var host = new HttpSelfHostServer(configuration);

        host.OpenAsync().Wait();
        Console.WriteLine("Host open.  Hit enter to exit...");
        Console.Read();
        host.CloseAsync().Wait();
    }
示例#3
0
        public MainAnswerHelper(BotUserRequest _thisRequest, object _Bot, SocialNetworkType _type, BotUser _botUser, List <MallBotContext> _dbContextes, List <VKApiRequestModel> _Requests = null)
        {
            botUser     = _botUser;
            dbContextes = _dbContextes;
            Requests    = _Requests;
            Bot         = _Bot;
            type        = _type;
            thisRequest = _thisRequest;

            #region Кэшируем
            string CachedItemKey = "MallBotData";
            var    datafromCache = cacher.Get(CachedItemKey);
            if (datafromCache == null)
            {
                datasOfBot = cacher.Update(CachedItemKey, dbContextes);
            }
            else
            {
                datasOfBot = (List <CachedDataModel>)datafromCache;
            }
            #endregion

            texter     = new BotTextHelper(botUser.Locale, type, datasOfBot[0].Texts);
            sender     = new ApiRouter(type, Bot, botUser, Requests);
            dataGetter = new GetDataHelper(datasOfBot);

            if (botUser.NowIs != MallBotWhatIsHappeningNow.SettingCustomer)
            {
                char usersdbID  = botUser.CustomerCompositeID[0];
                var  customerID = int.Parse(botUser.CustomerCompositeID.Remove(0, 1));
                currentCustomer = dataGetter.GetStructuredCustomers(true).FirstOrDefault(x => x.DBaseID == usersdbID).Customers.FirstOrDefault(x => x.CustomerID == customerID); //дает возможность работы в тц не из тестового режима
            }
        }
示例#4
0
        public void SegementWithTwoParameters()
        {
            var root = new ApiRouter("foo{a} and {b}");

            var match = root.Matches(null, "foo21 and boo");

            Assert.True(match);
        }
示例#5
0
        public void GetUrlOfController()
        {
            var router = new ApiRouter("foo", new Uri("http://localhost/api/")).To<FakeController>();

            var url = router.GetUrlForController(typeof (FakeController));

            Assert.Equal("http://localhost/api/foo", url.AbsoluteUri);
        }
示例#6
0
        public void GetUrlOfController()
        {
            var router = new ApiRouter("foo", new Uri("http://localhost/api/")).To <FakeController>();


            var url = router.GetUrlForController(typeof(FakeController));

            Assert.Equal("http://localhost/api/foo", url.AbsoluteUri);
        }
示例#7
0
 public AnswerWithPhotoHelper(SocialNetworkType _type, FindedInformation _answer, ApiRouter _sender, BotUser _botUser, BotTextHelper _texter, CachedDataModel _dataOfBot)
 {
     answer    = _answer;
     sender    = _sender;
     botUser   = _botUser;
     texter    = _texter;
     type      = _type;
     dataOfBot = _dataOfBot;
 }
示例#8
0
        public void GraftRouterAtRootB()
        {
            var router = new ApiRouter("", new Uri("http://localhost/api/")).To <FakeController>();

            var httpClient = new HttpClient(new FakeServer(router));

            var response = httpClient.GetAsync("http://localhost/api").Result;

            Assert.True(FakeController.WasInstantiated);
        }
示例#9
0
        public void GraftRouterAtSubTree()
        {
            var router = new ApiRouter("foo", new Uri("http://localhost/blah/")).To<FakeController>();

            var httpClient = new HttpClient(router);

            var response = httpClient.GetAsync("http://localhost/blah/foo").Result;

            Assert.True(FakeController.WasInstantiated);
        }
示例#10
0
        public void RouteRootPath()
        {
            var root = new ApiRouter("").To<FakeController>(new { ControllerId = "Root" });

            var httpClient = new HttpClient(root);

            var response = httpClient.GetAsync("http://localhost").Result;

            Assert.True(FakeController.WasInstantiated);
            Assert.Equal("Root", FakeController.ControllerId);
        }
示例#11
0
        public void RouteRootPath()
        {
            var root = new ApiRouter("").To <FakeController>(new { ControllerId = "Root" });

            var httpClient = new HttpClient(new FakeServer(root));

            var response = httpClient.GetAsync("http://localhost").Result;

            Assert.True(FakeController.WasInstantiated);
            Assert.Equal("Root", FakeController.ControllerId);
        }
示例#12
0
 private void RenderRouterHierarchy(StringBuilder sb, ApiRouter router, int depth = 0)
 {
     sb.Append("".PadLeft(depth));
     sb.Append('\\');
     sb.Append(router.SegmentTemplate);
     sb.Append(Environment.NewLine);
     foreach (var childrouter in router.ChildRouters.Values)
     {
         RenderRouterHierarchy(sb, childrouter, depth + 2);
     }
 }
示例#13
0
        public void BuildTreeFromPath()
        {
            var router = new ApiRouter("", new Uri("http://localhost/"));

            router.AddWithPath("foo/bar/baz", (r) => r.To<FakeController>() );

            var httpClient = new HttpClient(new FakeServer(router));

            var response = httpClient.GetAsync("http://localhost/foo/bar/baz").Result;

            Assert.True(FakeController.WasInstantiated);
        }
示例#14
0
        public void gamesRoutes2()
        {
            var router = new ApiRouter("games", new Uri("http://localhost/"));
            router.AddWithPath("{gametitle}/Setup/{gamesid}", apiRouter => apiRouter.To<SetupController>());
            router.AddWithPath("{gametitle}/Resources/{resourcetype}/{resourceid}", apiRouter => apiRouter.To<ResourceController>());
            router.AddWithPath("{gametitle}/{gameid}/Chat/{chatid}", apiRouter => apiRouter.To<ChatController>());
            router.AddWithPath("{gametitle}/{gameid}/State/{stateid}", apiRouter => apiRouter.To<StateController>());

            var url = router.GetUrlForController(typeof(ChatController));

            Assert.Equal("http://localhost/games/{gametitle}/{gameid}/Chat/{chatid}", url.OriginalString);
        }
示例#15
0
        public void RouteStaticPath()
        {
            var root = new ApiRouter("")
                       .Add(new ApiRouter("Desktop").To <FakeController>(new { ControllerId = "Desktop" }));

            var httpClient = new HttpClient(new FakeServer(root));

            var response = httpClient.GetAsync("http://localhost/Desktop").Result;

            Assert.NotNull(response);
            Assert.Equal("Desktop", FakeController.ControllerId);
        }
示例#16
0
        public void RouteStaticPath()
        {
            var root = new ApiRouter("")
                        .Add(new ApiRouter("Desktop").To<FakeController>(new { ControllerId = "Desktop" }));

            var httpClient = new HttpClient(root);

            var response = httpClient.GetAsync("http://localhost/Desktop").Result;

            Assert.NotNull(response);
            Assert.Equal("Desktop", FakeController.ControllerId);
        }
示例#17
0
        public void RouteWithMessageHandler()
        {
            var fakeHandler = new FakeHandler();

            var root = new ApiRouter("").WithHandler(fakeHandler).To <FakeController>();

            var httpClient = new HttpClient(new FakeServer(root));

            var response = httpClient.GetAsync("http://localhost/").Result;

            Assert.True(fakeHandler.WasCalled);
        }
示例#18
0
        public void BuildTreeFromPath()
        {
            var router = new ApiRouter("", new Uri("http://localhost/"));

            router.AddWithPath("foo/bar/baz", (r) => r.To <FakeController>());

            var httpClient = new HttpClient(new FakeServer(router));

            var response = httpClient.GetAsync("http://localhost/foo/bar/baz").Result;

            Assert.True(FakeController.WasInstantiated);
        }
示例#19
0
        public HttpServer(
            IOptionsService optionsService,
            IBellService bellService,
            ITalkTimerService timerService,
            ITalkScheduleService talksService)
        {
            _optionsService = optionsService;

            _apiThrottler = new ApiThrottler(optionsService);

            _apiRouter = new ApiRouter(_apiThrottler, _optionsService, bellService, timerService, talksService);
        }
示例#20
0
        public void GetLinkByTypeBetweenRouters()
        {
            var router = new ApiRouter("foo", new Uri("http://localhost/api/")).To<FakeController>()
                    .Add("child", cr => {
                                      cr.To<FakeChildController>();
                                      cr.RegisterLink<ParentLink, FakeController>();
                                  });

            var link = router.ChildRouters["child"].GetLink<ParentLink>();

            Assert.Equal("http://localhost/api/foo", link.Target.AbsoluteUri);
            Assert.IsType(typeof (ParentLink), link);
        }
示例#21
0
        public HttpServer(
            IOptionsService optionsService,
            IBellService bellService,
            ITalkTimerService timerService,
            ITalkScheduleService talksService)
        {
            _optionsService = optionsService;

            _clock24Hour  = new DateTime(1, 1, 1, 23, 1, 1).ToShortTimeString().Contains("23");
            _apiThrottler = new ApiThrottler(optionsService);

            _apiRouter = new ApiRouter(_apiThrottler, _optionsService, bellService, timerService, talksService);
        }
示例#22
0
        public void gamesRoutes2()
        {
            var router = new ApiRouter("games", new Uri("http://localhost/"));

            router.AddWithPath("{gametitle}/Setup/{gamesid}", apiRouter => apiRouter.To <SetupController>());
            router.AddWithPath("{gametitle}/Resources/{resourcetype}/{resourceid}", apiRouter => apiRouter.To <ResourceController>());
            router.AddWithPath("{gametitle}/{gameid}/Chat/{chatid}", apiRouter => apiRouter.To <ChatController>());
            router.AddWithPath("{gametitle}/{gameid}/State/{stateid}", apiRouter => apiRouter.To <StateController>());

            var url = router.GetUrlForController(typeof(ChatController));

            Assert.Equal("http://localhost/games/{gametitle}/{gameid}/Chat/{chatid}", url.OriginalString);
        }
示例#23
0
        public void GetLinkByTypeBetweenRouters()
        {
            var router = new ApiRouter("foo", new Uri("http://localhost/api/")).To <FakeController>()
                         .Add("child", cr => {
                cr.To <FakeChildController>();
                cr.RegisterLink <ParentLink, FakeController>();
            });


            var link = router.ChildRouters["child"].GetLink <ParentLink>();

            Assert.Equal("http://localhost/api/foo", link.Target.AbsoluteUri);
            Assert.IsType(typeof(ParentLink), link);
        }
示例#24
0
        public void RouteWithParameterSegement()
        {
            var root = new ApiRouter("")
                       .Add(new ApiRouter("Contact")
                            .Add(new ApiRouter("{id}").To <FakeController>(new { ControllerId = "Contact" })));

            var httpClient = new HttpClient(new FakeServer(root));

            var response = httpClient.GetAsync("http://localhost/Contact/23").Result;

            var pathparser = (PathRouteData)response.RequestMessage.Properties[HttpPropertyKeys.HttpRouteDataKey];

            Assert.Equal("23", pathparser.GetParameter("id"));
            Assert.Equal("Contact", FakeController.ControllerId);
        }
示例#25
0
        public void gamesRoutes()
        {
            var router =
                new ApiRouter("games", new Uri("http://localhost/"))
                    .Add("{gametitle}", rg => rg
                             .Add("Setup", rs => rs.Add("{gameid}", rgi => rgi.To<SetupController>()))
                             .Add("Resources", rr => rr.Add("{resourcetype}", rt => rt.Add("{resourceId}", ri => ri.To<ResourceController>())))
                             .Add("{gameid}", rgi => rgi
                                      .Add("Chat", rc => rc.Add("{chatid}", rci => rci.To<ChatController>()))
                                      .Add("State", rs => rs.Add("{stateid}", rsi => rsi.To<StateController>()))
                             ));

            var url = router.GetUrlForController(typeof(ChatController));

            Assert.Equal("http://localhost/games/{gametitle}/{gameid}/Chat/{chatid}", url.OriginalString);
        }
示例#26
0
        public void gamesRoutes()
        {
            var router =
                new ApiRouter("games", new Uri("http://localhost/"))
                .Add("{gametitle}", rg => rg
                     .Add("Setup", rs => rs.Add("{gameid}", rgi => rgi.To <SetupController>()))
                     .Add("Resources", rr => rr.Add("{resourcetype}", rt => rt.Add("{resourceId}", ri => ri.To <ResourceController>())))
                     .Add("{gameid}", rgi => rgi
                          .Add("Chat", rc => rc.Add("{chatid}", rci => rci.To <ChatController>()))
                          .Add("State", rs => rs.Add("{stateid}", rsi => rsi.To <StateController>()))
                          ));

            var url = router.GetUrlForController(typeof(ChatController));

            Assert.Equal("http://localhost/games/{gametitle}/{gameid}/Chat/{chatid}", url.OriginalString);
        }
示例#27
0
        public void RouteWithinLargeStaticPath()
        {
            var root = new ApiRouter("")
                       .Add(new ApiRouter("Mobile").To <FakeController>(new { ControllerId = "Mobile" }))
                       .Add(new ApiRouter("Admin")
                            .Add(new ApiRouter("Backups"))
                            .Add(new ApiRouter("Hotfixes").To <FakeController>(new { ControllerId = "Hotfixes" })))
                       .Add(new ApiRouter("Desktop").To <FakeController>(new { ControllerId = "Desktop" }));

            var httpClient = new HttpClient(new FakeServer(root));

            var response = httpClient.GetAsync("http://localhost/Admin/Hotfixes").Result;

            Assert.NotNull(response);
            Assert.True(FakeController.WasInstantiated);
            Assert.Equal("Hotfixes", FakeController.ControllerId);
        }
示例#28
0
        public void RouteWithinLargeStaticPath()
        {
            var root = new ApiRouter("")
                        .Add(new ApiRouter("Mobile").To<FakeController>(new { ControllerId = "Mobile" }))
                        .Add(new ApiRouter("Admin")
                                .Add(new ApiRouter("Backups"))
                                .Add(new ApiRouter("Hotfixes").To<FakeController>(new { ControllerId = "Hotfixes" })))
                        .Add(new ApiRouter("Desktop").To<FakeController>(new { ControllerId = "Desktop" }));

            var httpClient = new HttpClient(root);

            var response = httpClient.GetAsync("http://localhost/Admin/Hotfixes").Result;

            Assert.NotNull(response);
            Assert.True(FakeController.WasInstantiated);
            Assert.Equal("Hotfixes", FakeController.ControllerId);
        }
示例#29
0
        public MainAnswerHelper(DBHelpers.Models.MFCModels.BotUser _botUser, MFCBotContext _context, BotUserRequest _thisRequest, List <VKApiRequestModel> _requests)
        {
            context     = _context;
            botUser     = _botUser;
            thisRequest = _thisRequest;
            requests    = _requests;

            string key           = "MFCDATAOFBOT";
            var    datafromCache = cacheHelper.Get(key);

            if (datafromCache == null)
            {
                mfcDataOfBot = cacheHelper.Update(key, context);
            }
            else
            {
                mfcDataOfBot = (MFCBotModel)datafromCache;
            }

            if (botUser.NowIs != MFCBotWhatIsHappeningNow.SettingOffice)
            {
                var usersOffice = mfcDataOfBot.Offices.FirstOrDefault(x => x.AisMFCID == botUser.OfficeID);
                if (usersOffice.Name == "Ярмарка")
                {
                    usersOffice.OfficeID = 326;
                }
                //получаем все секции, которые относятся к выбранному филиалу
                mfcDataOfBot.Sections = mfcDataOfBot.AllSections.
                                        Where(x => mfcDataOfBot.SectionOffices.
                                              Where(z => z.OfficeID == usersOffice.OfficeID).
                                              Select(y => y.SectionID).Contains(x.SectionID)).DistinctBy(x => x.Name).ToList();
                //сохраняем из них только листья
                mfcDataOfBot.RetainLeafs();
            }

            sendHelper = new ApiRouter(SocialNetworkType.VK, null, botUser, requests);
            textHelper = new BotTextHelper(botUser.Locale, SocialNetworkType.VK, mfcDataOfBot.Texts);
        }
示例#30
0
        public async Task <int> AnalyseBadRequest(BotUser botUser, SocialNetworkType type, object bot, List <BotText> botTexts, List <VKApiRequestModel> Requests = null)
        {
            var texter = new BotTextHelper(botUser.Locale, type, botTexts);
            var sender = new ApiRouter(type, bot, botUser, Requests);

            switch (botUser.NowIs)
            {
            case MallBotWhatIsHappeningNow.SettingCustomer:
                return(await sender.SendText(texter.GetMessage("%badrequest1%")));

            case MallBotWhatIsHappeningNow.SearchingOrganization:
                return(await sender.SendText(texter.GetMessage("%badrequest2%")));

            case MallBotWhatIsHappeningNow.SearchingWay:
                return(await sender.SendText(texter.GetMessage("%badrequest3%")));

            case MallBotWhatIsHappeningNow.GettingAllOrganizations:
                return(await sender.SendText(texter.GetMessage("%badrequest4%")));

            default:
                return(0);
            }
        }
示例#31
0
        public void UseUriParamToResolveLink()
        {
            var router = new ApiRouter("", new Uri("http://localhost/"))
                         .Add("Customer", rc => rc
                              .Add("{customerid}", rci => rci.To <CustomerController>()
                                   .RegisterLink <InvoicesLink, InvoicesController>()
                                   .Add("Invoices", ri => ri.To <InvoicesController>())
                                   )
                              )
                         .Add("Invoice", ri => ri
                              .Add("{invoiceid}", rii => rii.To <InvoiceController>()
                                   .RegisterLink <CustomerLink, CustomerController>()
                                   )
                              );

            var httpClient = new HttpClient(new FakeServer(router));

            var response = httpClient.GetAsync("http://localhost/Customer/23/").Result;



            Assert.Equal("http://localhost/Customer/23/Invoices", response.Content.ReadAsStringAsync().Result);
        }
示例#32
0
 public FakeServer(ApiRouter router)
 {
     InnerHandler = router;
 }
示例#33
0
 public void AddRouter(ApiRouter router)
 {
     _SegmentRoutes.Add(router);
 }
示例#34
0
        public void UseUriParamToResolveLink()
        {
            var router = new ApiRouter("", new Uri("http://localhost/"))
                            .Add("Customer", rc => rc
                                .Add("{customerid}",rci => rci.To<CustomerController>()
                                                    .RegisterLink<InvoicesLink,InvoicesController>()
                                                    .Add("Invoices",ri => ri.To<InvoicesController>())
                                    )
                                )
                            .Add("Invoice", ri => ri
                                    .Add("{invoiceid}", rii => rii.To<InvoiceController>()
                                                        .RegisterLink<CustomerLink,CustomerController>()
                                    )
                                );

            var httpClient = new HttpClient(new FakeServer(router));

            var response = httpClient.GetAsync("http://localhost/Customer/23/").Result;

            Assert.Equal("http://localhost/Customer/23/Invoices", response.Content.ReadAsStringAsync().Result);
        }
示例#35
0
        public void RouteWithMessageHandler()
        {
            var fakeHandler = new FakeHandler();

            var root = new ApiRouter("").WithHandler(fakeHandler).To<FakeController>();

            var httpClient = new HttpClient(root);

            var response = httpClient.GetAsync("http://localhost/").Result;

            Assert.True(fakeHandler.WasCalled);
        }
示例#36
0
 private void RenderRouterHierarchy(StringBuilder sb,  ApiRouter router, int depth = 0 )
 {
     sb.Append("".PadLeft(depth));
         sb.Append('\\');
         sb.Append(router.SegmentTemplate);
         sb.Append(Environment.NewLine);
     foreach (var childrouter in router.ChildRouters.Values)
     {
         RenderRouterHierarchy(sb, childrouter, depth + 2);
     }
 }
 public InstanceWatcher(ApiRouter routerInstance)
 {
     this.routerInstance = routerInstance;
 }
示例#38
0
 public FakeServer(ApiRouter router)
 {
     InnerHandler = router;
 }
示例#39
0
        public void SegementWithTwoParameters()
        {
            var root = new ApiRouter("foo{a} and {b}");

            var match = root.Matches(null, "foo21 and boo");

            Assert.True(match);
        }
示例#40
0
        public void GraftRouterAtRoot()
        {
            var router = new ApiRouter("", new Uri("http://localhost/")).To<FakeController>();

            var httpClient = new HttpClient(new FakeServer(router));

            var response = httpClient.GetAsync("http://localhost/").Result;

            Assert.True(FakeController.WasInstantiated);
        }
示例#41
0
        public void RouteWithParameterSegement()
        {
            var root = new ApiRouter("")
                        .Add(new ApiRouter("Contact")
                                .Add(new ApiRouter("{id}").To<FakeController>(new { ControllerId = "Contact" })));

            var httpClient = new HttpClient(root);

            var response = httpClient.GetAsync("http://localhost/Contact/23").Result;

            var pathparser = (PathRouteData)response.RequestMessage.Properties[HttpPropertyKeys.HttpRouteDataKey];
            Assert.Equal("23", pathparser.GetParameter("id"));
            Assert.Equal("Contact", FakeController.ControllerId);
        }
示例#42
0
        public DiscoveryTests()
        {
            _router = RouteDiscovery.Search(typeof(Discovery.RootController), new Uri("http://localhost/"));

            _httpClient = new HttpClient(new FakeServer(_router));
        }
示例#43
0
        public DiscoveryTests()
        {
            _router = RouteDiscovery.Search(typeof(Discovery.RootController), new Uri("http://localhost/"));

            _httpClient = new HttpClient(new FakeServer(_router));
        }