public void add_http_method_constraint_multiple_times() { var route = new RouteDefinition("something"); route.AddHttpMethodConstraint("get"); route.AddHttpMethodConstraint("Get"); route.GetHttpMethodConstraints().ShouldHaveTheSameElementsAs("GET"); }
public void add_a_route_alias() { var chain = new RoutedChain("something/else"); var alias = new RouteDefinition("something/else"); chain.AddRouteAlias(alias); chain.AdditionalRoutes.ShouldHaveTheSameElementsAs(alias); }
public void adding_a_route_adds_a_RouteDefined_event() { var chain = new BehaviorChain(); var route = new RouteDefinition("something"); chain.Route = route; chain.As <ITracedModel>().StagedEvents.Last().ShouldEqual(new RouteDetermined(route)); }
private static void addBasicRouteInputs(ActionCall call, RouteDefinition route) { call.InputType() .GetProperties() .Where(x => x.HasAttribute <RouteInputAttribute>()) .Each(prop => route.Append("{" + prop.Name + "}")); route.ApplyInputType(call.InputType()); }
public void create_url_with_null_input_model_and_no_default_value_specified_for_optional_input() { var url = new RouteDefinition <SampleViewModelWithInputs>("test/edit/{OptionalInput}"); url.AddRouteInput(x => x.OptionalInput); url .CreateUrlFromInput(null) .ShouldEndWith("test/edit/default"); }
public void add_constraint_to_route_with_model() { var url = new RouteDefinition <SampleViewModel>("my/sample"); var constraintToAdd = new HttpMethodConstraint("POST"); url.AddRouteConstraint("httpMethod", constraintToAdd); Route route = url.ToRoute(); route.Constraints["httpMethod"].ShouldEqual(constraintToAdd); }
public void default_value_syntax_for_urlpattern_produces_correct_route() { var parent = new RouteDefinition("my/sample/{InPath:hello}/{AlsoInPath:world}"); parent.Input = new RouteInput <SampleViewModel>(parent); var route = parent.ToRoute(); Assert.IsFalse(Regex.Match(route.Url, @":\w+").Success); }
public void create_default_value_for_a_route() { var url = new RouteDefinition <SampleViewModel>("my/sample"); url.AddRouteInput(x => x.InPath); url.RouteInputFor("InPath").DefaultValue = "something"; Route route = url.ToRoute(); route.Defaults["InPath"].ShouldEqual("something"); }
public void create_route_with_http_constraints() { var route = new RouteDefinition("something"); route.AddHttpMethodConstraint("Get"); route.AddHttpMethodConstraint("POST"); route.ToRoute().Constraints.Single().Value.ShouldBeOfType <HttpMethodConstraint>() .AllowedMethods.ShouldHaveTheSameElementsAs("GET", "POST"); }
public void create_url_will_escape_the_url() { var url = new RouteDefinition <SampleViewModel>("test/edit/{InPath}"); url.AddRouteInput(x => x.InPath); url.CreateUrlFromInput(new SampleViewModel { InPath = "some text" }).ShouldEqual("test/edit/some%20text"); }
public void should_have_one_default_value_for_route() { var url = new RouteDefinition <SampleViewModel>("my/sample"); url.AddRouteInput(x => x.InPath); url.AddRouteInput(x => x.AlsoInPath); url.RouteInputFor("InPath").DefaultValue = "something"; Route route = url.ToRoute(); route.Defaults.Count().ShouldEqual(1); }
public void create_url_with_input_model() { var url = new RouteDefinition <SampleViewModel>("test/edit/{InPath}"); url.AddRouteInput(x => x.InPath); url.CreateUrlFromInput(new SampleViewModel { InPath = "5" }).ShouldEqual("test/edit/5"); }
public void create_url_with_variables_in_querystring() { var url = new RouteDefinition <SampleViewModel>("/my/sample/path"); url.AddQueryInput(x => x.InQueryString); url.CreateUrlFromInput(new SampleViewModel { InQueryString = "query" }).ShouldEqual("/my/sample/path?InQueryString=query"); }
public void BasicCurrentUserTest() { var routeData = new RouteData(); var mockUser = new Mock <IUser>(); var mockWebSerc = new Mock <WebSecurity>(null, null); mockWebSerc.Setup(s => s.CurrentUser).Returns(mockUser.Object); var appCtx = ApplicationContext.EnsureContext( new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })), new ServiceContext(), CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger( Mock.Of <ILogger>(), Mock.Of <IProfiler>()), true); var ctx = UmbracoContext.EnsureContext( Mock.Of <HttpContextBase>(), appCtx, mockWebSerc.Object, Mock.Of <IUmbracoSettingsSection>(), Enumerable.Empty <IUrlProvider>(), true); var content = new Mock <IPublishedContent>(); content.Setup(s => s.Name).Returns("test"); ctx.PublishedContentRequest = new PublishedContentRequest(new Uri("http://test.com"), ctx.RoutingContext, Mock.Of <IWebRoutingSection>(section => section.UrlProviderMode == UrlProviderMode.AutoLegacy.ToString()), s => new string[] { }) { PublishedContent = content.Object }; //The reoute definition will contain the current page request object and be passed into the route data var routeDefinition = new RouteDefinition { PublishedContentRequest = ctx.PublishedContentRequest }; //We create a route data object to be given to the Controller context routeData.DataTokens.Add(UmbConstants.Web.PublishedDocumentRequestDataToken, ctx.PublishedContentRequest); var controller = new BasicRenderMvcController(ctx, new UmbracoHelper(ctx)); //don't really care about the helper here controller.ControllerContext = new System.Web.Mvc.ControllerContext(ctx.HttpContext, routeData, controller); var res = controller.BasicGetSecurityAction() as PartialViewResult; var model = res.Model as IUser; Assert.IsNotNull(model); }
public async Task ImportRouteAsync() { var csvData = await FileInputService.ImportTextAsync(); var csvModel = CsvParser.ParseComplex <RouteDefinitionCsvModel>(csvData); var routeModel = RouteDefinition.FromCsvModel(csvModel); DbService.EditData(r => r.Add(new RouteDbModel { Id = Guid.NewGuid().ToString(), Definition = routeModel })); }
public void add_constraint_to_route_with_model() { var parent = new RouteDefinition("my/sample"); parent.Input = new RouteInput <SampleViewModel>(parent); var constraintToAdd = new HttpMethodConstraint("POST"); parent.AddRouteConstraint("httpMethod", constraintToAdd); Route route = parent.ToRoute(); route.Constraints["httpMethod"].ShouldEqual(constraintToAdd); }
public void should_have_one_default_value_for_a_route_and_does_not_include_querystring_in_route() { var url = new RouteDefinition <SampleViewModel>("my/sample"); url.AddRouteInput(x => x.InPath); url.AddQueryInput(x => x.InQueryString); url.RouteInputFor("InPath").DefaultValue = "something"; url.QueryInputFor("InQueryString").DefaultValue = "querysomething"; Route route = url.ToRoute(); route.Defaults.Count().ShouldEqual(1); }
public void create_url_with_variables_in_querystring_with_parameters() { var url = new RouteDefinition <SampleViewModel>("/my/sample/path"); url.AddQueryInput(x => x.InQueryString); var parameters = new RouteParameters <SampleViewModel>(); parameters[x => x.InQueryString] = "query"; url.CreateUrlFromParameters(parameters).ShouldEqual("/my/sample/path?InQueryString=query"); }
public void create_url_with_parameters() { var url = new RouteDefinition <SampleViewModel>("test/edit/{InPath}"); url.AddRouteInput(x => x.InPath); var parameters = new RouteParameters <SampleViewModel>(); parameters[x => x.InPath] = "5"; url.CreateUrlFromParameters(parameters).ShouldEqual("test/edit/5"); }
public void create_two_default_values_for_a_route() { var url = new RouteDefinition <SampleViewModel>("my/sample"); url.AddRouteInput(x => x.InPath); url.AddRouteInput(x => x.AlsoInPath); url.RouteInputFor("InPath").DefaultValue = "something"; url.RouteInputFor("AlsoInPath").DefaultValue = "something else"; Route route = url.ToRoute(); route.Defaults.Count().ShouldEqual(2); }
public void adds_the_route_aliases() { var route1 = new RouteDefinition("something/else"); var route2 = new RouteDefinition("again/something/else"); var chain = theGraph.BehaviorFor <RouteAliasController>(x => x.get_something()); var routes = chain.AdditionalRoutes; routes.ShouldHaveCount(2); routes.ShouldContain(route1); routes.ShouldContain(route2); }
public void BasicCurrentPageTest() { var appCtx = ApplicationContext.EnsureContext( new DatabaseContext(Mock.Of <IDatabaseFactory>(), Mock.Of <ILogger>(), new SqlSyntaxProviders(new[] { Mock.Of <ISqlSyntaxProvider>() })), new ServiceContext(), CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger( Mock.Of <ILogger>(), Mock.Of <IProfiler>()), true); var ctx = UmbracoContext.EnsureContext( Mock.Of <HttpContextBase>(), appCtx, new Mock <WebSecurity>(null, null).Object, Mock.Of <IUmbracoSettingsSection>(), Enumerable.Empty <IUrlProvider>(), true); var contentMock = new Mock <IPublishedContent>(); contentMock.Setup(s => s.Name).Returns("test"); var content = contentMock.Object; //setup published content request. This sets the current content on the Umbraco Context and will be used later ctx.PublishedContentRequest = new PublishedContentRequest(new Uri("http://test.com"), ctx.RoutingContext, Mock.Of <IWebRoutingSection>(section => section.UrlProviderMode == UrlProviderMode.AutoLegacy.ToString()), s => new string[] { }) { PublishedContent = content }; //The reoute definition will contain the current page request object and be passed into the route data var routeDefinition = new RouteDefinition { PublishedContentRequest = ctx.PublishedContentRequest }; //We create a route data object to be given to the Controller context var routeData = new RouteData(); routeData.DataTokens.Add("umbraco-route-def", routeDefinition); var controller = new BasicTestSurfaceController(); //Setting the controller context will provide the route data, route def, publushed content request, and current page to the surface controller controller.ControllerContext = new System.Web.Mvc.ControllerContext(ctx.HttpContext, routeData, controller); var res = controller.BasicCurrentPageAction(); var model = res.Model as string; Assert.AreEqual(content.Name, model); }
public void create_url_with_querystring_and_inputmodel() { var url = new RouteDefinition <SampleViewModel>("test/edit/{InPath}"); url.AddRouteInput(x => x.InPath); url.AddQueryInput(x => x.InQueryString); url.CreateUrlFromInput(new SampleViewModel { InPath = "5", InQueryString = "query" }).ShouldEqual("test/edit/5?InQueryString=query"); }
public static IEnumerable <object[]> GetTestRouteDefinitions() { RouteDefinition routeDefinition = TestData.CreateRouteDefinition(); yield return(new object[] { "normal case", routeDefinition }); routeDefinition.CarConsumption = null; yield return(new object[] { "car consumption is null", routeDefinition }); routeDefinition.CarConsumption = 6.7; routeDefinition.EngineStartEffort = null; yield return(new object[] { "engine start effort is null", routeDefinition }); }
public void create_url_with_input_model_and_default_value_for_required_input() { var url = new RouteDefinition <SampleViewModelWithInputs>("test/edit/{RequiredInput}"); url.AddRouteInput(x => x.RequiredInput); url .CreateUrlFromInput(new SampleViewModelWithInputs { RequiredInput = "a" }) .ShouldEndWith("test/edit/a"); }
public async Task AddRoute() { //Arrange RouteDefinition route = TestData.CreateRouteDefinition(); _routeModificationService.Setup(s => s.AddRouteAsync(route, _cancellationToken)).ReturnsAsync(TestData.CreateRoutModificationResult()); //Act await _applicationFacade.AddRouteAsync(route, _cancellationToken); //Assert _routeModificationService.VerifyAll(); }
public void create_url_with_multiple_variables_in_path() { var url = new RouteDefinition <SampleViewModel>("test/edit/{InPath}/{AlsoInPath}"); url.AddRouteInput(x => x.InPath); url.AddRouteInput(x => x.AlsoInPath); url.CreateUrlFromInput(new SampleViewModel { InPath = "5", AlsoInPath = "some text" }).ShouldEqual("test/edit/5/some%20text"); }
public Route(string routeKey, RouteDefinition routeDefinition, Dictionary <string, OutputModuleWrapper> outputs, YASLServer server) { Server = server; RouteKey = routeKey; AttachedQueue = Server.QueueFactory.GetMessageQueue(this); WorkCompleted = new ManualResetEvent(false); foreach (KeyValuePair <string, FilterDefinition> filterCfg in routeDefinition.Filters) { Filters.Add(filterCfg.Key, new Filter(filterCfg.Key, filterCfg.Value, outputs, server)); } FilterRuntime = Filters.Values.ToArray(); }
protected override string GetRouteUriString(RouteDefinition route) { var paramsBuilder = new StringBuilder("https://www.google.com/maps/dir/?api=1"); if (route.Origin != null) { paramsBuilder.Append($"&origin={route.Origin.Coordinates}"); } paramsBuilder.Append($"&destination={route.Destination.Coordinates}"); paramsBuilder.Append($"&waypoints={string.Join("|", route.Waypoints.Select(w => w.Coordinates.ToString()))}"); return(paramsBuilder.ToString()); }
public void describing_itself_session_state() { var route = new RouteDefinition("something"); route.SessionStateRequirement.ShouldBeNull(); Description.For(route).Properties["SessionStateRequirement"].ShouldEqual("Default"); route.SessionStateRequirement = SessionStateRequirement.RequiresSessionState; Description.For(route).Properties["SessionStateRequirement"].ShouldEqual( SessionStateRequirement.RequiresSessionState.ToString()); }
/// <summary> /// Returns a RouteDefinition object based on the current renderModel /// </summary> /// <param name="requestContext"></param> /// <param name="publishedContentRequest"></param> /// <returns></returns> internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest) { var defaultControllerName = ControllerExtensions.GetControllerName<RenderMvcController>(); //creates the default route definition which maps to the 'UmbracoController' controller var def = new RouteDefinition { ControllerName = defaultControllerName, Controller = new RenderMvcController(), PublishedContentRequest = publishedContentRequest, ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(), HasHijackedRoute = false }; //check if there's a custom controller assigned, base on the document type alias. var controller = _controllerFactory.CreateController(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias); //check if that controller exists if (controller != null) { //ensure the controller is of type 'RenderMvcController' if (controller is RenderMvcController) { //set the controller and name to the custom one def.Controller = (ControllerBase)controller; def.ControllerName = ControllerExtensions.GetControllerName(controller.GetType()); if (def.ControllerName != defaultControllerName) { def.HasHijackedRoute = true; } } else { LogHelper.Warn<RenderRouteHandler>( "The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must inherit from '{2}'.", () => publishedContentRequest.PublishedContent.DocumentTypeAlias, () => controller.GetType().FullName, () => typeof(RenderMvcController).FullName); //exit as we cannnot route to the custom controller, just route to the standard one. return def; } //check that a template is defined), if it doesn't and there is a hijacked route it will just route // to the index Action if (publishedContentRequest.HasTemplate) { //the template Alias should always be already saved with a safe name. //if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed // with the action name attribute. var templateName = global::umbraco.cms.helpers.Casing.SafeAlias(publishedContentRequest.Template.Alias.Split('.')[0]); def.ActionName = templateName; } } //store the route definition requestContext.RouteData.DataTokens["umbraco-route-def"] = def; return def; }
/// <summary> /// Handles a posted form to an Umbraco Url and ensures the correct controller is routed to and that /// the right DataTokens are set. /// </summary> /// <param name="requestContext"></param> /// <param name="postedInfo"></param> /// <param name="routeDefinition">The original route definition that would normally be used to route if it were not a POST</param> private IHttpHandler HandlePostedValues(RequestContext requestContext, PostedDataProxyInfo postedInfo, RouteDefinition routeDefinition) { var standardArea = Umbraco.Core.Configuration.GlobalSettings.UmbracoMvcArea; //set the standard route values/tokens requestContext.RouteData.Values["controller"] = postedInfo.ControllerName; requestContext.RouteData.Values["action"] = postedInfo.ActionName; requestContext.RouteData.DataTokens["area"] = postedInfo.Area; IHttpHandler handler = new MvcHandler(requestContext); //ensure the controllerType is set if found, meaning it is a plugin, not locally declared if (postedInfo.Area != standardArea) { //requestContext.RouteData.Values["controllerType"] = postedInfo.ControllerType; //find the other data tokens for this route and merge... things like Namespace will be included here using (RouteTable.Routes.GetReadLock()) { var surfaceRoute = RouteTable.Routes.OfType<Route>() .SingleOrDefault(x => x.Defaults != null && x.Defaults.ContainsKey("controller") && x.Defaults["controller"].ToString() == postedInfo.ControllerName && x.DataTokens.ContainsKey("area") && x.DataTokens["area"].ToString() == postedInfo.Area); if (surfaceRoute == null) throw new InvalidOperationException("Could not find a Surface controller route in the RouteTable for controller name " + postedInfo.ControllerName + " and within the area of " + postedInfo.Area); //set the 'Namespaces' token so the controller factory knows where to look to construct it if (surfaceRoute.DataTokens.ContainsKey("Namespaces")) { requestContext.RouteData.DataTokens["Namespaces"] = surfaceRoute.DataTokens["Namespaces"]; } handler = surfaceRoute.RouteHandler.GetHttpHandler(requestContext); } } //store the original URL this came in on requestContext.RouteData.DataTokens["umbraco-item-url"] = requestContext.HttpContext.Request.Url.AbsolutePath; //store the original route definition requestContext.RouteData.DataTokens["umbraco-route-def"] = routeDefinition; return handler; }
/// <summary> /// Returns a RouteDefinition object based on the current renderModel /// </summary> /// <param name="requestContext"></param> /// <param name="publishedContentRequest"></param> /// <returns></returns> internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest) { var defaultControllerName = ControllerExtensions.GetControllerName<RenderMvcController>(); //creates the default route definition which maps to the 'UmbracoController' controller var def = new RouteDefinition { ControllerName = defaultControllerName, Controller = new RenderMvcController(), PublishedContentRequest = publishedContentRequest, ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(), HasHijackedRoute = false }; //check if there's a custom controller assigned, base on the document type alias. var controller = _controllerFactory.CreateController(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias); //check if that controller exists if (controller != null) { //ensure the controller is of type 'RenderMvcController' if (controller is RenderMvcController) { //set the controller and name to the custom one def.Controller = (ControllerBase)controller; def.ControllerName = ControllerExtensions.GetControllerName(controller.GetType()); if (def.ControllerName != defaultControllerName) { def.HasHijackedRoute = true; } } else { LogHelper.Warn<RenderRouteHandler>("The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must inherit from '{2}'.", publishedContentRequest.PublishedContent.DocumentTypeAlias, controller.GetType().FullName, typeof(RenderMvcController).FullName); //exit as we cannnot route to the custom controller, just route to the standard one. return def; } //check that a template is defined), if it doesn't and there is a hijacked route it will just route // to the index Action if (publishedContentRequest.HasTemplate) { //check if the custom controller has an action with the same name as the template name (we convert ToUmbracoAlias since the template name might have invalid chars). //NOTE: This also means that all custom actions MUST be PascalCase.. but that should be standard. var templateName = publishedContentRequest.Template.Alias.Split('.')[0].ToUmbracoAlias(StringAliasCaseType.PascalCase); def.ActionName = templateName; } } return def; }
/// <summary> /// Returns a RouteDefinition object based on the current renderModel /// </summary> /// <param name="requestContext"></param> /// <param name="publishedContentRequest"></param> /// <returns></returns> internal virtual RouteDefinition GetUmbracoRouteDefinition(RequestContext requestContext, PublishedContentRequest publishedContentRequest) { if (requestContext == null) throw new ArgumentNullException("requestContext"); if (publishedContentRequest == null) throw new ArgumentNullException("publishedContentRequest"); var defaultControllerType = DefaultRenderMvcControllerResolver.Current.GetDefaultControllerType(); var defaultControllerName = ControllerExtensions.GetControllerName(defaultControllerType); //creates the default route definition which maps to the 'UmbracoController' controller var def = new RouteDefinition { ControllerName = defaultControllerName, ControllerType = defaultControllerType, PublishedContentRequest = publishedContentRequest, ActionName = ((Route)requestContext.RouteData.Route).Defaults["action"].ToString(), HasHijackedRoute = false }; //check that a template is defined), if it doesn't and there is a hijacked route it will just route // to the index Action if (publishedContentRequest.HasTemplate) { //the template Alias should always be already saved with a safe name. //if there are hyphens in the name and there is a hijacked route, then the Action will need to be attributed // with the action name attribute. var templateName = publishedContentRequest.TemplateAlias.Split('.')[0].ToSafeAlias(); def.ActionName = templateName; } //check if there's a custom controller assigned, base on the document type alias. var controllerType = _controllerFactory.GetControllerTypeInternal(requestContext, publishedContentRequest.PublishedContent.DocumentTypeAlias); //check if that controller exists if (controllerType != null) { //ensure the controller is of type 'IRenderMvcController' and ControllerBase if (TypeHelper.IsTypeAssignableFrom<IRenderMvcController>(controllerType) && TypeHelper.IsTypeAssignableFrom<ControllerBase>(controllerType)) { //set the controller and name to the custom one def.ControllerType = controllerType; def.ControllerName = ControllerExtensions.GetControllerName(controllerType); if (def.ControllerName != defaultControllerName) { def.HasHijackedRoute = true; } } else { LogHelper.Warn<RenderRouteHandler>( "The current Document Type {0} matches a locally declared controller of type {1}. Custom Controllers for Umbraco routing must implement '{2}' and inherit from '{3}'.", () => publishedContentRequest.PublishedContent.DocumentTypeAlias, () => controllerType.FullName, () => typeof(IRenderMvcController).FullName, () => typeof(ControllerBase).FullName); //we cannot route to this custom controller since it is not of the correct type so we'll continue with the defaults // that have already been set above. } } //store the route definition requestContext.RouteData.DataTokens["umbraco-route-def"] = def; return def; }