/// <summary>
        /// Pendent
        /// </summary>
        /// <param name="area">The area.</param>
        /// <param name="controller">The controller.</param>
        /// <param name="action">The action.</param>
        /// <param name="metaDescriptor">The meta descriptor.</param>
        /// <param name="match">The routing match.</param>
        /// <returns></returns>
        public IControllerContext Create(string area, string controller, string action,
                                         ControllerMetaDescriptor metaDescriptor, RouteMatch match)
        {
            var context = new ControllerContext(controller, area, action, metaDescriptor)
            {
                RouteMatch = match
            };

            context.ViewFolder       = ResolveViewFolder(context, area, controller, action);
            context.SelectedViewName = ResolveDefaultViewSelection(context, area, controller, action);

            foreach (var pair in match.Parameters)
            {
                if (pair.Value == null || pair.Key == "controller" || pair.Key == "action" || pair.Key == "area")
                {
                    // We skip those only to avoid compatibility issues as
                    // customactionparameters have higher precedence on parameters matching
                    continue;
                }

                context.CustomActionParameters[pair.Key] = pair.Value;
            }

            return(context);
        }
Пример #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResponseAdapter"/> class.
 /// </summary>
 /// <param name="response">The response.</param>
 /// <param name="currentUrl">The current URL.</param>
 /// <param name="urlBuilder">The URL builder.</param>
 /// <param name="serverUtility">The server utility.</param>
 /// <param name="routeMatch">The route match.</param>
 /// <param name="referrer">The referrer.</param>
 public ResponseAdapter(HttpResponse response, UrlInfo currentUrl,
                        IUrlBuilder urlBuilder, IServerUtility serverUtility,
                        RouteMatch routeMatch, string referrer)
     : base(currentUrl, urlBuilder, serverUtility, routeMatch, referrer)
 {
     this.response = response;
 }
Пример #3
0
        public void ShouldMatchStatic()
        {
            var route = new PatternRoute("/some/path");
            var match = new RouteMatch();

            Assert.AreEqual(8000, route.Matches("/some/path", CreateGetContext(), match));
        }
Пример #4
0
        public void ShouldMatchHiphensAndUnderlines()
        {
            var route = new PatternRoute("/some/path_to-this");
            var match = new RouteMatch();

            Assert.AreEqual(8000, route.Matches("/some/path_to-this", CreateGetContext(), match));
        }
Пример #5
0
        public async Task FindRoutes(string method, string path, string aResult)
        {
            HorseMvc mvc = new HorseMvc();

            mvc.Init();
            mvc.CreateRoutes(Assembly.GetExecutingAssembly());
            mvc.Use();

            HttpRequest request = new HttpRequest();

            request.Method = method;
            request.Path   = path;

            HttpResponse response = new HttpResponse();

            RouteMatch match = mvc.RouteFinder.Find(mvc.Routes, request);

            Assert.NotNull(match);

            HorseController controller = mvc.ControllerFactory.CreateInstance(mvc,
                                                                              match.Route.ControllerType,
                                                                              request,
                                                                              response,
                                                                              mvc.ServiceProvider.CreateScope());

            MvcConnectionHandler handler = new MvcConnectionHandler(mvc, null);

            var parameters            = (await handler.FillParameters(request, match)).Select(x => x.Value).ToArray();
            Task <IActionResult> task = (Task <IActionResult>)match.Route.ActionType.Invoke(controller, parameters);

            IActionResult result = task.Result;
            string        url    = Encoding.UTF8.GetString(((MemoryStream)result.Stream).ToArray());

            url.Should().Be(aResult);
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="ResponseAdapter"/> class.
		/// </summary>
		/// <param name="response">The response.</param>
		/// <param name="currentUrl">The current URL.</param>
		/// <param name="urlBuilder">The URL builder.</param>
		/// <param name="serverUtility">The server utility.</param>
		/// <param name="routeMatch">The route match.</param>
		/// <param name="referrer">The referrer.</param>
		public ResponseAdapter(HttpResponse response, UrlInfo currentUrl, 
			IUrlBuilder urlBuilder, IServerUtility serverUtility,
			RouteMatch routeMatch, string referrer)
			: base(currentUrl, urlBuilder, serverUtility, routeMatch, referrer)
		{
			this.response = response;
		}
Пример #7
0
        private async Task ExecuteAction(RouteMatch match, FilterContext context, TwinoController controller, ActionDescriptor descriptor, HttpResponse response)
        {
            if (match.Route.IsAsyncMethod)
            {
                Task <IActionResult> task = (Task <IActionResult>)match.Route.ActionType.Invoke(controller, descriptor.Parameters.Select(x => x.Value).ToArray());
                await task;
                await CompleteActionExecution(match, context, response, controller, descriptor, task.Result);
            }
            else
            {
                TaskCompletionSource <bool> source = new TaskCompletionSource <bool>(TaskCreationOptions.RunContinuationsAsynchronously);
                ThreadPool.QueueUserWorkItem(async t =>
                {
                    try
                    {
                        IActionResult ar = (IActionResult)match.Route.ActionType.Invoke(controller, descriptor.Parameters.Select(x => x.Value).ToArray());
                        await CompleteActionExecution(match, context, response, controller, descriptor, ar);
                        source.SetResult(true);
                    }
                    catch (Exception e)
                    {
                        source.SetException(e.InnerException ?? e);
                    }
                });

                await source.Task;
            }
        }
Пример #8
0
        public void ShouldMatchStaticWithFileExtension()
        {
            var route = new PatternRoute("/default.aspx");
            var match = new RouteMatch();

            Assert.AreEqual(8000, route.Matches("/default.aspx", CreateGetContext(), match));
        }
Пример #9
0
        public void Request_CreatesSessionfulHandler()
        {
            StringWriter writer = new StringWriter();

            HttpResponse res = new HttpResponse(writer);
            HttpRequest  req = new HttpRequest(Path.Combine(
                                                   AppDomain.CurrentDomain.BaseDirectory, "Handlers/Files/simplerequest.txt"),
                                               "http://localhost:1333/home/something", "");
            RouteMatch  routeMatch = new RouteMatch();
            HttpContext httpCtx    = new HttpContext(req, res);

            httpCtx.Items[RouteMatch.RouteMatchKey] = routeMatch;

            using (_MockRepository.Record())
            {
                ControllerMetaDescriptor controllerDesc = new ControllerMetaDescriptor();
                controllerDesc.ControllerDescriptor = new ControllerDescriptor(typeof(Controller), "home", "", false);

                Expect.Call(_ControllerFactoryMock.CreateController("", "home")).IgnoreArguments().Return(_ControllerMock);
                Expect.Call(_ControllerDescriptorProviderMock.BuildDescriptor(_ControllerMock)).Return(controllerDesc);
                Expect.Call(_ControllerContextFactoryMock.Create("", "home", "something", controllerDesc, routeMatch)).
                Return(new ControllerContext());
            }

            using (_MockRepository.Playback())
            {
                IHttpHandler handler = _HandlerFactory.GetHandler(httpCtx, "GET", "", "");

                Assert.IsNotNull(handler);
                Assert.IsInstanceOfType(typeof(MonoRailHttpHandler), handler);
            }
        }
Пример #10
0
        private void SetupWizardController(bool useCurrentRouteForRedirects)
        {
            helper.WizardController = repository.DynamicMock <IWizardController>();
            SetupResult.For(helper.WizardController.UseCurrentRouteForRedirects).Return(useCurrentRouteForRedirects);
            repository.Replay(helper.WizardController);

            if (useCurrentRouteForRedirects)
            {
                repository.BackToRecord(controllerContext, BackToRecordOptions.None);
                var routeMatch = new RouteMatch();
                routeMatch.AddNamed("manufacturer", "Ford");
                routeMatch.AddNamed("model", "Falcon");
                SetupResult.For(controllerContext.RouteMatch).Return(routeMatch);
                SetupResult.For(controllerContext.AreaName).Return("Cars");
                repository.Replay(controllerContext);

                var routingEngine = new RoutingEngine();
                routingEngine.Add(
                    new PatternRoute("/<area>/<manufacturer>/AddOptionsWizard/<model>/[action]")
                    .DefaultForController().Is("AddOptionsWizardController")
                    .DefaultForAction().Is("start"));
                helper.UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), routingEngine);
                helper.CurrentUrl = new UrlInfo("Cars", "CarsController", "View", String.Empty, "rails");
                helper.UrlBuilder.UseExtensions = false;
            }
        }
Пример #11
0
        /// <summary>
        /// Calls controller and action executing filters
        /// </summary>
        private async Task <bool> CheckActionExecutingFilters(RouteMatch match, FilterContext context, HttpResponse response, IController controller, ActionDescriptor descriptor)
        {
            if (match.Route.HasControllerExecutingFilter)
            {
                //find controller filters
                IActionExecutingFilter[] filters = (IActionExecutingFilter[])match.Route.ControllerType.GetCustomAttributes(typeof(IActionExecutingFilter), true);

                //call BeforeCreated methods of controller attributes
                bool resume = await CallFilters(response, context, filters, async filter => await filter.OnExecuting(controller, descriptor, context));

                if (!resume)
                {
                    return(false);
                }
            }

            if (match.Route.HasActionExecutingFilter)
            {
                //find controller filters
                IActionExecutingFilter[] filters = (IActionExecutingFilter[])match.Route.ActionType.GetCustomAttributes(typeof(IActionExecutingFilter), true);

                //call BeforeCreated methods of controller attributes
                bool resume = await CallFilters(response, context, filters, async filter => await filter.OnExecuting(controller, descriptor, context));

                if (!resume)
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #12
0
        public void ShouldReturnZeroForMissingRequiredPart()
        {
            var route = new PatternRoute("/<controller>/[action]");

            var match = new RouteMatch();

            Assert.AreEqual(0, route.Matches("/", CreateGetContext(), match));
        }
Пример #13
0
		/// <summary>
		/// Initializes a new instance of the <see cref="BaseResponse"/> class.
		/// </summary>
		/// <param name="currentUrl">The current URL.</param>
		/// <param name="urlBuilder">The URL builder.</param>
		/// <param name="serverUtility">The server utility.</param>
		/// <param name="routeMatch">The route match.</param>
		/// <param name="referrer">The referrer.</param>
		protected BaseResponse(UrlInfo currentUrl, IUrlBuilder urlBuilder, IServerUtility serverUtility, RouteMatch routeMatch, string referrer)
		{
			this.currentUrl = currentUrl;
			this.urlBuilder = urlBuilder;
			this.serverUtility = serverUtility;
			this.routeMatch = routeMatch;
			this.referrer = referrer;
		}
Пример #14
0
		public void NamedRequiredParameters()
		{
			PatternRoute route = new PatternRoute("/<controller>/<action>");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(4000, route.Matches("/some/act", CreateGetContext(), match));
			Assert.AreEqual("some", match.Parameters["controller"]);
			Assert.AreEqual("act", match.Parameters["action"]);
		}
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseResponse"/> class.
 /// </summary>
 /// <param name="currentUrl">The current URL.</param>
 /// <param name="urlBuilder">The URL builder.</param>
 /// <param name="serverUtility">The server utility.</param>
 /// <param name="routeMatch">The route match.</param>
 /// <param name="referrer">The referrer.</param>
 protected BaseResponse(UrlInfo currentUrl, IUrlBuilder urlBuilder, IServerUtility serverUtility, RouteMatch routeMatch, string referrer)
 {
     this.currentUrl    = currentUrl;
     this.urlBuilder    = urlBuilder;
     this.serverUtility = serverUtility;
     this.routeMatch    = routeMatch;
     this.referrer      = referrer;
 }
        public void NavigatingToUnrecognizedPathThrows()
        {
            Resolver.Setup(x => x.MatchPathToRoute(It.IsAny <string>())).Returns(RouteMatch.Failure(null, "Boogedyboo"));

            var navigator = new Navigator(Factory.Object, null, "magellan", Resolver.Object, () => NavigationService.Object);

            Assert.Throws <UnroutableRequestException>(() => navigator.Navigate(new Uri("magellan://patients/list")));
        }
Пример #17
0
        private static void ProcessRequest(EndpointHandler endpointHandler, EndpointHandlerRegister handlerRegister, TcpClient client)
        {
            try
            {
                NetworkStream requestStream = client.GetStream();

                Console.WriteLine($"Nachricht erhalten um: {DateTime.Now} Client: {client.Client.RemoteEndPoint}");
                Console.WriteLine("-----------------------------------------------------------------------------");

                HttpRequestParser requestParser = new HttpRequestParser();
                RequestContext    context;

                context = requestParser.ParseRequestStream(requestStream);

                Console.WriteLine("-----------------------------------------------------------------------------");
                Console.WriteLine();

                RouteMatch match = handlerRegister.GetEndPointHandler(context);

                if (match != null)
                {
                    IActionResult result = endpointHandler.Invoke(match, client, context);
                    result.Execute();
                }
                else
                {
                    HttpStatusCodeResult.NotFound(client)
                    .Execute();
                }

                client.Close();
            }
            catch (HttpRequestParserException parserEx)
            {
                string parseErrorMessage = $"Ungültiger Request, parsen nicht möglich: {parserEx.Message}";

                Console.WriteLine(parseErrorMessage);
                HttpStatusCodeResult.BadRequest(client, parseErrorMessage)
                .Execute();
            }
            catch (Exception ex) when(ex is EndPointHandlerException || ex is EndpointHandlerRegisterException)
            {
                HttpStatusCodeResult.BadRequest(client, ex.GetFullMessage(verbose: true))
                .Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unerwarteter Fehler: {ex.Message}");

                HttpStatusCodeResult.InternalServerError(client)
                .Execute();
            }
            finally
            {
                client.Close();
            }
        }
Пример #18
0
		public override int Matches(string url, IRouteContext context, RouteMatch match)
		{
			var points = base.Matches(url, context, match);
			
			if ((points == 0) || (string.Compare(restVerbResolver.Resolve(context.Request), requiredVerb, true) != 0))
				return 0;
			
			return points;
		}
		public void NamedRequiredParametersForExtension()
		{
			var route = new PatternRoute("/<controller>/<action>.<format>");
			var match = new RouteMatch();
			Assert.AreEqual(6000, route.Matches("/some/act.xml", CreateGetContext(), match));
			Assert.AreEqual("some", match.Parameters["controller"]);
			Assert.AreEqual("act", match.Parameters["action"]);
			Assert.AreEqual("xml", match.Parameters["format"]);
		}
Пример #20
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var serverRequest        = new TestRequest(Validate.NotNull(nameof(request), request));
            var cookiesFromContainer = CookieContainer.GetCookieHeader(serverRequest.Url);

            if (!string.IsNullOrEmpty(cookiesFromContainer))
            {
                serverRequest.Headers.Add(HttpHeaderNames.Cookie, cookiesFromContainer);
            }

            var context = new TestContext(serverRequest)
            {
                CancellationToken = cancellationToken,
                Route             = RouteMatch.UnsafeFromRoot(UrlPath.Normalize(serverRequest.Url.AbsolutePath, false)),
            };

            await _handler.HandleContextAsync(context).ConfigureAwait(false);

            var serverResponse  = context.TestResponse;
            var responseCookies = serverResponse.Headers.Get(HttpHeaderNames.SetCookie);

            if (!string.IsNullOrEmpty(responseCookies))
            {
                CookieContainer.SetCookies(serverRequest.Url, responseCookies);
            }

            var response = new HttpResponseMessage((HttpStatusCode)serverResponse.StatusCode)
            {
                RequestMessage = request,
                Version        = serverResponse.ProtocolVersion,
                ReasonPhrase   = serverResponse.StatusDescription,
                Content        = serverResponse.Body == null ? null : new ByteArrayContent(serverResponse.Body),
            };

            foreach (var key in serverResponse.Headers.AllKeys)
            {
                var responseHeaderType = GetResponseHeaderType(key);
                switch (responseHeaderType)
                {
                case ResponseHeaderType.Content:
                    response.Content?.Headers.Add(key, serverResponse.Headers.GetValues(key));
                    break;

                case ResponseHeaderType.Response:
                    response.Headers.Add(key, serverResponse.Headers.GetValues(key));
                    break;

                case ResponseHeaderType.None:
                    break;

                default:
                    throw SelfCheck.Failure("Unexpected response header type {responseHeaderType}.");
                }
            }

            return(response);
        }
Пример #21
0
        public void NamedRequiredParameters()
        {
            var route = new PatternRoute("/<controller>/<action>");
            var match = new RouteMatch();

            Assert.AreEqual(4000, route.Matches("/some/act", CreateGetContext(), match));
            Assert.AreEqual("some", match.Parameters["controller"]);
            Assert.AreEqual("act", match.Parameters["action"]);
        }
Пример #22
0
        public void ShouldMatchWhenRestrictingWithMatchingMultipleVerb()
        {
            var route = new PatternRoute("/simple")
                        .RestrictTo(Verb.Get | Verb.Post);

            var match = new RouteMatch();

            Assert.Less(0, route.Matches("/simple", CreateGetContext(), match));
        }
Пример #23
0
        public void ShouldNotMatchWhenRestrictingMultipleVerbs()
        {
            var route = new PatternRoute("/simple")
                        .RestrictTo(Verb.Post | Verb.Put);

            var match = new RouteMatch();

            Assert.AreEqual(0, route.Matches("/simple", CreateGetContext(), match));
        }
Пример #24
0
		public void ShouldMatchSimplesSlash()
		{
			PatternRoute route = new PatternRoute("/");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(1, route.Matches("/", CreateGetContext(), match));
			Assert.AreEqual(1, route.Matches("", CreateGetContext(), match));
			Assert.AreEqual(0, route.Matches("some", CreateGetContext(), match));
			Assert.AreEqual(0, route.Matches("/some", CreateGetContext(), match));
		}
Пример #25
0
        public void NamedParametersCanHaveUnderlines()
        {
            var route = new PatternRoute("/<controller>/<action>");
            var match = new RouteMatch();

            route.Matches("/some/act_name", CreateGetContext(), match);
            Assert.AreEqual("some", match.Parameters["controller"]);
            Assert.AreEqual("act_name", match.Parameters["action"]);
        }
Пример #26
0
        public void ShouldReturnNonZeroForMatchedDefaults()
        {
            var route = new PatternRoute("/[controller]/[action]");

            var match = new RouteMatch();

            Assert.AreEqual(2, route.Matches("/", CreateGetContext(), match));
            Assert.IsTrue(match.Parameters.ContainsKey("controller"));
            Assert.IsTrue(match.Parameters.ContainsKey("action"));
        }
Пример #27
0
        public void ShouldMatchEmptyUrl()
        {
            var route = new PatternRoute("/[controller]/[action]");

            var match = new RouteMatch();

            Assert.AreEqual(2, route.Matches("", CreateGetContext(), match));
            Assert.IsTrue(match.Parameters.ContainsKey("controller"));
            Assert.IsTrue(match.Parameters.ContainsKey("action"));
        }
Пример #28
0
        public void ShouldMatchSimplesSlash()
        {
            var route = new PatternRoute("/");
            var match = new RouteMatch();

            Assert.AreEqual(1, route.Matches("/", CreateGetContext(), match));
            Assert.AreEqual(1, route.Matches("", CreateGetContext(), match));
            Assert.AreEqual(0, route.Matches("some", CreateGetContext(), match));
            Assert.AreEqual(0, route.Matches("/some", CreateGetContext(), match));
        }
Пример #29
0
		public void ShouldMatchStaticCaseInsensitive()
		{
			PatternRoute route = new PatternRoute("/default.aspx");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(8000, route.Matches("/DEFAULT.ASPX", CreateGetContext(), match));

			route = new PatternRoute("/some/path");
			match = new RouteMatch();
			Assert.AreEqual(8000, route.Matches("/SOME/Path", CreateGetContext(), match));
		}
Пример #30
0
        void InitUrlInfo(string areaName, string controllerName, string actionName)
        {
            var urlInfo = new UrlInfo(areaName, controllerName, actionName, "/", "castle");

            SetupResult.For(engineContext.UrlInfo).Return(urlInfo);

            var routeMatch = new RouteMatch();

            SetupResult.For(controllerContext.RouteMatch).Return(routeMatch);
        }
Пример #31
0
        public override int Matches(string url, IRouteContext context, RouteMatch match)
        {
            var points = base.Matches(url, context, match);

            if ((points == 0) || (string.Compare(restVerbResolver.Resolve(context.Request), requiredVerb, true) != 0))
            {
                return(0);
            }

            return(points);
        }
Пример #32
0
        public void ShouldMatchStaticCaseInsensitive()
        {
            var route = new PatternRoute("/default.aspx");
            var match = new RouteMatch();

            Assert.AreEqual(8000, route.Matches("/DEFAULT.ASPX", CreateGetContext(), match));

            route = new PatternRoute("/some/path");
            match = new RouteMatch();
            Assert.AreEqual(8000, route.Matches("/SOME/Path", CreateGetContext(), match));
        }
Пример #33
0
        public void NamedOptionalParametersWithDefaults()
        {
            var route = new PatternRoute("/<controller>/[action]/[id]")
                        .DefaultFor("action").Is("index").DefaultFor("id").Is("0");
            var match = new RouteMatch();

            Assert.AreEqual(2002, route.Matches("/some", CreateGetContext(), match));
            Assert.AreEqual("some", match.Parameters["controller"]);
            Assert.AreEqual("index", match.Parameters["action"]);
            Assert.AreEqual("0", match.Parameters["id"]);
        }
Пример #34
0
        public void RedirectUsingRoute_SpecifyingParameters()
        {
            engine.Add(new PatternRoute("/something/<param1>/admin/[controller]/[action]/[id]"));

            var match = new RouteMatch();

            var url      = new UrlInfo("area", "home", "index", "", ".castle");
            var response = new StubResponse(url, urlBuilder, urlBuilder.ServerUtil, match);

            response.RedirectUsingRoute("cart", "checkout", DictHelper.Create("param1=Marge"));
            Assert.AreEqual("/something/Marge/admin/cart/checkout", response.RedirectedTo);
        }
        public static void AssertRoute(this RouteMatch match, params Func <string, string>[] parameters)
        {
            Assert.IsTrue(match.Success, match.FailReason);
            foreach (var parameter in parameters)
            {
                var key   = parameter.Method.GetParameters()[0].Name;
                var value = parameter(null);

                Assert.IsTrue(match.Values.ContainsKey(key), "The matched route does not contain a value for '{0}'", key);
                Assert.AreEqual(value, match.Values[key], "Error when matching parameter {0}", key);
            }
        }
Пример #36
0
        public void AnythingBut_Restriction()
        {
            var route = new PatternRoute("/<controller>/[action]/[id]")
                        .Restrict("controller").AnythingBut("dummy")
                        .Restrict("id").ValidInteger;

            var match = new RouteMatch();

            Assert.AreEqual(0, route.Matches("/dummy/index", CreateGetContext(), match));
            Assert.AreEqual(0, route.Matches("/DUMMY/list", CreateGetContext(), match));
            Assert.AreEqual(4001, route.Matches("/some/new", CreateGetContext(), match));
            Assert.AreEqual(6000, route.Matches("/some/list/1", CreateGetContext(), match));
        }
Пример #37
0
        /// <summary>
        /// Executes after controller filters. Returns true, if execution can resume.
        /// </summary>
        private async Task <bool> ExecuteAfterControllerFilters(RouteMatch match, FilterContext context, HttpResponse response, IController controller)
        {
            if (!match.Route.HasControllerAfterFilter)
            {
                return(true);
            }

            //find controller filters
            IAfterControllerFilter[] filters = (IAfterControllerFilter[])match.Route.ControllerType.GetCustomAttributes(typeof(IAfterControllerFilter), true);

            //call AfterCreated methods of controller attributes
            return(await CallFilters(response, context, filters, async filter => await filter.OnAfter(controller, context)));
        }
Пример #38
0
        public override RouteMatch Match(string path)
        {
            var match = _regex.Match(path);
            if (match.Success == false)
                return new RouteMatch { Score = int.MinValue, Route = this };

            var routeMatch = new RouteMatch {Route = this, Score = _staticPartsCount*100};
            foreach (var routeParameterName in _routeParameterNames)
            {
                routeMatch.RouteParameters.Add(routeParameterName, new[] {match.Groups[routeParameterName].Value});
                routeMatch.Score++;
            }

            return routeMatch;
        }
        public void Init()
        {
            executorProvider = new Mock<ControllerExecutorProvider>();
            executor = new Mock<ControllerExecutor>();
            controllerProvider = new Mock<ControllerProvider>();
            context = new Mock<HttpContextBase>();

            routeMatch = new RouteMatch(null, null);
            prototype = new ControllerPrototype(new object());

            runner = new PipelineRunner
                     	{
                            ControllerProviders = new[] { new Lazy<ControllerProvider, IComponentOrder>(() => controllerProvider.Object, new FakeOrderMeta()) },
                            ControllerExecutorProviders = new[] { new Lazy<ControllerExecutorProvider, IComponentOrder>(() => executorProvider.Object, new FakeOrderMeta()) }
                     	};
        }
		/// <summary>
		/// Pendent.
		/// </summary>
		/// <param name="container"></param>
		/// <param name="urlInfo"></param>
		/// <param name="context"></param>
		/// <param name="routeMatch"></param>
		/// <returns></returns>
		public IEngineContext Create(IMonoRailContainer container, UrlInfo urlInfo, HttpContext context, RouteMatch routeMatch)
		{
			var session = ResolveRequestSession(container, urlInfo, context);

			var urlBuilder = container.UrlBuilder;

			var serverUtility = new ServerUtilityAdapter(context.Server);

			var referrer = context.Request.Headers["Referer"];

			return new DefaultEngineContext(container, urlInfo, context,
			                                serverUtility,
			                                new RequestAdapter(context.Request),
											new ResponseAdapter(context.Response, urlInfo, urlBuilder, serverUtility, routeMatch, referrer),
											new TraceAdapter(context.Trace), session);
		}
Пример #41
0
		public int Matches(string url, IRouteContext context, RouteMatch match)
		{
			var parts = GetParts(url);

			if (parts.Length != routeParts.Length)
				return 0;
			
			for (var i = 0; i < parts.Length; i++)
				if (string.Compare(parts[i], routeParts[i], true) != 0)
					return 0;
			
			match.Parameters.Add("area", area);
			match.Parameters.Add("controller", controller);
			match.Parameters.Add("action", action);

			return 100;
		}
		/// <summary>
		/// Pendent
		/// </summary>
		/// <param name="area">The area.</param>
		/// <param name="controller">The controller.</param>
		/// <param name="action">The action.</param>
		/// <param name="metaDescriptor">The meta descriptor.</param>
		/// <param name="match">The routing match.</param>
		/// <returns></returns>
		public IControllerContext Create(string area, string controller, string action,
										 ControllerMetaDescriptor metaDescriptor, RouteMatch match)
		{
			ControllerContext context = new ControllerContext(controller, area, action, metaDescriptor);
			context.RouteMatch = match;
			context.ViewFolder = ResolveViewFolder(context, area, controller, action);
			context.SelectedViewName = ResolveDefaultViewSelection(context, area, controller, action);

			foreach(KeyValuePair<string, string> pair in match.Parameters)
			{
				if (pair.Value == null || pair.Key == "controller" || pair.Key == "action" || pair.Key == "area")
				{
					// We skip those only to avoid compatibility issues as 
					// customactionparameters have higher precedence on parameters matching
					continue;
				}

				context.CustomActionParameters[pair.Key] = pair.Value;
			}

			return context;
		}
Пример #43
0
        internal static RouteMatch Match(string path)
        {
            var toReturn = new RouteMatch {Success = false};

            if (matchCache.ContainsKey(path))
            {
                toReturn = matchCache[path];
            }
            else
            {
                foreach (var route in routes)
                {
                    var match = route.PatternRegex.Match(path);

                    if (match.Success)
                    {
                        var controller = match.Groups["controller"].Value != "" ? match.Groups["controller"].Value : route.Controller;
                        var action = match.Groups["action"].Value != "" ? match.Groups["action"].Value : route.Action;

                        toReturn.Success = true;
                        toReturn.Controller = controller;
                        toReturn.Action = action;

                        toReturn.PathParameters = new Dictionary<string, string>();

                        foreach (var name in route.PatternRegex.GetGroupNames())
                            if (null != match.Groups[name])
                                toReturn.PathParameters.Add(name, match.Groups[name].Value);

                        matchCache.Add(path, toReturn);

                        break;
                    }
                }
            }

            return toReturn;
        }
Пример #44
0
		private void SetupWizardController(bool useCurrentRouteForRedirects)
		{
			helper.WizardController = repository.DynamicMock<IWizardController>();
			SetupResult.For(helper.WizardController.UseCurrentRouteForRedirects).Return(useCurrentRouteForRedirects);
			repository.Replay(helper.WizardController);

			if (useCurrentRouteForRedirects)
			{
				repository.BackToRecord(controllerContext, BackToRecordOptions.None);
				var routeMatch = new RouteMatch();
				routeMatch.AddNamed("manufacturer", "Ford");
				routeMatch.AddNamed("model", "Falcon");
				SetupResult.For(controllerContext.RouteMatch).Return(routeMatch);
				SetupResult.For(controllerContext.AreaName).Return("Cars");
				repository.Replay(controllerContext);

				var routingEngine = new RoutingEngine();
				routingEngine.Add(
					new PatternRoute("/<area>/<manufacturer>/AddOptionsWizard/<model>/[action]")
						.DefaultForController().Is("AddOptionsWizardController")
						.DefaultForAction().Is("start"));
				helper.UrlBuilder = new DefaultUrlBuilder(new StubServerUtility(), routingEngine);
				helper.CurrentUrl = new UrlInfo("Cars", "CarsController", "View", String.Empty, "rails");
				helper.UrlBuilder.UseExtensions = false;
			}
		}
Пример #45
0
		public void NamedOptionalParametersWithDefaults()
		{
			PatternRoute route = new PatternRoute("/<controller>/[action]/[id]")
				.DefaultFor("action").Is("index").DefaultFor("id").Is("0");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(2002, route.Matches("/some", CreateGetContext(), match));
			Assert.AreEqual("some", match.Parameters["controller"]);
			Assert.AreEqual("index", match.Parameters["action"]);
			Assert.AreEqual("0", match.Parameters["id"]);
		}
Пример #46
0
		public void NamedOptionalParametersWithRestrictions()
		{
			PatternRoute route = new PatternRoute("/<controller>/[action]/[id]")
				.Restrict("action").AnyOf("index", "list")
				.Restrict("id").ValidInteger;

			RouteMatch match = new RouteMatch();
			Assert.AreEqual(4001, route.Matches("/some/index", CreateGetContext(), match));
			Assert.AreEqual(4001, route.Matches("/some/list", CreateGetContext(), match));
			Assert.AreEqual(0, route.Matches("/some/new", CreateGetContext(), match));
			Assert.AreEqual(0, route.Matches("/some/index/foo", CreateGetContext(), match));
			Assert.AreEqual(0, route.Matches("/some/list/bar", CreateGetContext(), match));
			Assert.AreEqual(6000, route.Matches("/some/list/1", CreateGetContext(), match));
		}
Пример #47
0
 public IHttpHandler GetHandler(HttpRequest request, RouteMatch routeData)
 {
     throw new NotImplementedException();
 }
Пример #48
0
		public void AnythingBut_Restriction()
		{
			PatternRoute route = new PatternRoute("/<controller>/[action]/[id]")
				.Restrict("controller").AnythingBut("dummy")
				.Restrict("id").ValidInteger;

			RouteMatch match = new RouteMatch();
			Assert.AreEqual(0, route.Matches("/dummy/index", CreateGetContext(), match));
			Assert.AreEqual(0, route.Matches("/DUMMY/list", CreateGetContext(), match));
			Assert.AreEqual(4001, route.Matches("/some/new", CreateGetContext(), match));
			Assert.AreEqual(6000, route.Matches("/some/list/1", CreateGetContext(), match));
		}
Пример #49
0
		public void NamedRequiredParametersWithRestrictions()
		{
			string matchGuid = 
				"[A-Fa-f0-9]{32}|" +
				"({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?|" +
				"({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})";

			PatternRoute route = new PatternRoute("/<param>/<key>")
				.Restrict("key").ValidRegex(matchGuid);

			RouteMatch match = new RouteMatch();
			Assert.AreEqual(0, route.Matches("/something/zzzzzzzz-c123-11dc-95ff-0800200c9a66", CreateGetContext(), match));
			Assert.AreEqual(4000, route.Matches("/something/173e0970-c123-11dc-95ff-0800200c9a66", CreateGetContext(), match));
			Assert.AreEqual("something", match.Parameters["param"]);
			Assert.AreEqual("173e0970-c123-11dc-95ff-0800200c9a66", match.Parameters["key"]);
		}
Пример #50
0
		/// <summary>
		/// Sets the route match.
		/// </summary>
		/// <param name="useCurrentRouteParams">if set to <c>true</c> [use current route params].</param>
		/// <param name="routeMatch">The route match.</param>
		/// <returns></returns>
		public UrlBuilderParameters SetRouteMatch(bool useCurrentRouteParams, RouteMatch routeMatch)
		{
			this.useCurrentRouteParams = useCurrentRouteParams;
			this.routeMatch = routeMatch;
			return this;
		}
Пример #51
0
		public void ShouldMatchHiphensAndUnderlines()
		{
			PatternRoute route = new PatternRoute("/some/path_to-this");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(8000, route.Matches("/some/path_to-this", CreateGetContext(), match)); 
		}
Пример #52
0
		public void ShouldMatchEmptyUrl()
		{
			PatternRoute route = new PatternRoute("/[controller]/[action]");

			RouteMatch match = new RouteMatch();
			Assert.AreEqual(2, route.Matches("", CreateGetContext(), match));
			Assert.IsTrue(match.Parameters.ContainsKey("controller"));
			Assert.IsTrue(match.Parameters.ContainsKey("action"));
		}
Пример #53
0
		public void ShouldReturnNonZeroForMatchedDefaults()
		{
			PatternRoute route = new PatternRoute("/[controller]/[action]");

			RouteMatch match = new RouteMatch();
			Assert.AreEqual(2, route.Matches("/", CreateGetContext(), match));
			Assert.IsTrue(match.Parameters.ContainsKey("controller"));
			Assert.IsTrue(match.Parameters.ContainsKey("action"));
		}
Пример #54
0
		public void ShouldReturnZeroForMissingRequiredPart()
		{
			PatternRoute route = new PatternRoute("/<controller>/[action]");

			RouteMatch match = new RouteMatch();
			Assert.AreEqual(0, route.Matches("/", CreateGetContext(), match));
		}
Пример #55
0
		public void NamedParametersCanHaveUnderlines()
		{
			PatternRoute route = new PatternRoute("/<controller>/<action>");
			RouteMatch match = new RouteMatch();
			route.Matches("/some/act_name", CreateGetContext(), match);
			Assert.AreEqual("some", match.Parameters["controller"]);
			Assert.AreEqual("act_name", match.Parameters["action"]);
		}
Пример #56
0
		public void ShouldMatchStatic()
		{
			PatternRoute route = new PatternRoute("/some/path");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(8000, route.Matches("/some/path", CreateGetContext(), match));
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="StubResponse"/> class.
		/// </summary>
		/// <param name="currentUrl">The current URL.</param>
		/// <param name="urlBuilder">The URL builder.</param>
		/// <param name="serverUtility">The server utility.</param>
		/// <param name="routeMatch">The route match.</param>
		/// <param name="referrer">The referrer.</param>
		public StubResponse(UrlInfo currentUrl, IUrlBuilder urlBuilder, IServerUtility serverUtility, RouteMatch routeMatch, string referrer)
			: base(currentUrl, urlBuilder, serverUtility, routeMatch, referrer)
		{
		}
Пример #58
0
		/// <summary>
		/// Sets the route match.
		/// </summary>
		/// <param name="routeMatch">The route match.</param>
		/// <returns></returns>
		public UrlBuilderParameters SetRouteMatch(RouteMatch routeMatch)
		{
			this.routeMatch = routeMatch;
			return this;
		}
		/// <summary>
		/// Initializes a new instance of the <see cref="StubResponse"/> class.
		/// </summary>
		/// <param name="currentUrl">The current URL.</param>
		/// <param name="urlBuilder">The URL builder.</param>
		/// <param name="serverUtility">The server utility.</param>
		/// <param name="routeMatch">The route match.</param>
		public StubResponse(UrlInfo currentUrl, IUrlBuilder urlBuilder, IServerUtility serverUtility, RouteMatch routeMatch)
			: this(currentUrl, urlBuilder, serverUtility, routeMatch, null)
		{
		}
Пример #60
0
		public void ShouldMatchStaticWithFileExtension()
		{
			PatternRoute route = new PatternRoute("/default.aspx");
			RouteMatch match = new RouteMatch();
			Assert.AreEqual(8000, route.Matches("/default.aspx", CreateGetContext(), match));
		}