Наследование: System.Web.Routing.RouteBase
        protected override bool IsMatch(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {

            if (!base.IsMatch(httpContext, route, parameterName, values, routeDirection))
            {
                return false;
            }

            if (routeDirection == RouteDirection.UrlGeneration)
            {
                return true;
            }

            var encoded = values[parameterName].ToString();
            var decoded = SettingsHelper.SeoDecode(encoded, SeoUrlKeywordTypes.Category, 
                values.ContainsKey(Constants.Language) ? values[Constants.Language].ToString() : null);

            var childCategryId = decoded.Split(Separator.ToCharArray()).Last();

            var category = CartHelper.CatalogClient.GetCategoryById(childCategryId);

            if (category == null)
            {
                return false;
            }

            var outline = new BrowsingOutline(CartHelper.CatalogOutlineBuilder.BuildCategoryOutline(StoreHelper.CustomerSession.CatalogId, category));

            return ValidateCategoryPath(outline.ToString(), decoded);
        }
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (routeDirection == RouteDirection.UrlGeneration)
            {
                return true;
            }

            object versionValue;
            if (!values.TryGetValue(parameterName, out versionValue))
            {
                return true;
            }

            if (versionValue == null || versionValue == UrlParameter.Optional)
            {
                return true;
            }

            string versionText = versionValue.ToString();
            if (versionText.Length == 0)
            {
                return true;
            }
            SemanticVersion ignored;
            return SemanticVersion.TryParse(versionText, out ignored);
        }
Пример #3
0
        public void FactoryMethodWillCreateShellRoutes() {
            var settings = new ShellSettings { Name = "Alpha" };
            var builder = new ContainerBuilder();
            builder.RegisterType<ShellRoute>().InstancePerDependency();
            builder.RegisterAutoMocking();
            builder.Register(ctx => settings);

            var container = builder.Build();
            var buildShellRoute = container.Resolve<Func<RouteBase, ShellRoute>>();

            var routeA = new Route("foo", new MvcRouteHandler());
            var route1 = buildShellRoute(routeA);

            var routeB = new Route("bar", new MvcRouteHandler()) {
                DataTokens = new RouteValueDictionary { { "area", "Beta" } }
            };
            var route2 = buildShellRoute(routeB);

            Assert.That(route1, Is.Not.SameAs(route2));

            Assert.That(route1.ShellSettingsName, Is.EqualTo("Alpha"));
            Assert.That(route1.Area, Is.Null);

            Assert.That(route2.ShellSettingsName, Is.EqualTo("Alpha"));
            Assert.That(route2.Area, Is.EqualTo("Beta"));
        }
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, 
     RouteValueDictionary values, RouteDirection routeDirection)
 {
     Debug.WriteLine(httpContext.Request.HttpMethod == "GET");
     return httpContext.Request.UserAgent != null &&
         httpContext.Request.UserAgent.Contains(requiredUserAgent);
 }
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
#endif
        {
            if (parameterName == null)
            {
                throw Error.ArgumentNull("parameterName");
            }

            if (values == null)
            {
                throw Error.ArgumentNull("values");
            }

            object value;
            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                int length = valueString.Length;
                if (Length.HasValue)
                {
                    return length == Length.Value;
                }
                else
                {
                    return length >= MinLength.Value && length <= MaxLength.Value;
                }
            }
            return false;
        }
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (httpContext == null || !httpContext.Request.IsLocal )
                return false;

            return true;
        }
 protected override bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     var methodOverride = httpContext.Request.Unvalidated().Form["X-HTTP-Method-Override"];
     if (methodOverride == null) return base.Match(httpContext, route, parameterName, values, routeDirection);
     return AllowedMethods.Any(m => string.Equals(m, httpContext.Request.HttpMethod, StringComparison.OrdinalIgnoreCase))
         && AllowedMethods.Any(m => string.Equals(m, methodOverride, StringComparison.OrdinalIgnoreCase));
 }
Пример #8
0
		internal static void RegisterRoutes()
		{
			var urls = new[] 
		    { 
		        "ssr-jquip.all", 
		        "ssr-includes.js", 
		        "ssr-includes.css", 
		        "ssr-includes.tmpl", 
		        "ssr-results"
		    };
			var routes = RouteTable.Routes;
			var handler = new MiniProfilerRouteHandler(new MiniProfilerHandler());
			var prefix = (Profiler.Settings.RouteBasePath ?? "").Replace("~/", "").WithTrailingSlash();

			using (routes.GetWriteLock())
			{
				foreach (var url in urls)
				{
					var route = new Route(prefix + url, handler) {
						// we have to specify these, so no MVC route helpers will match, e.g. @Html.ActionLink("Home", "Index", "Home")
						Defaults = new RouteValueDictionary(new { controller = "MiniProfilerHandler", action = "ProcessRequest" })
					};

					// put our routes at the beginning, like a boss
					routes.Insert(0, route);
				}
			}
		}
Пример #9
0
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {

            object value;
            if (values.TryGetValue(parameterName, out value)) {
                var parameterValue = Convert.ToString(value);

                var path = FindPath(parameterValue);
                if (path == null) {
                    return false;
                }

                var archiveData = FindArchiveData(parameterValue);
                if (archiveData == null) {
                    return false;
                }

                try {
                    // is this a valid date ?
                    archiveData.ToDateTime();
                }
                catch {
                    return false;
                }

                var autoroute = _pathResolutionService.GetPath(path);

                return autoroute != null && autoroute.Is<BlogPart>();
            }

            return false;
        }
Пример #10
0
        public LocaleRoute(
                    string pattern, 
                    RouteValueDictionary defaults, 
                    RouteValueDictionary constraints,
                    RouteValueDictionary tokens,
                    string[] namespaces,
                    IRouteHandler routeHandler)
        {
            var localeConstraints = new RouteValueDictionary(constraints);
            localeConstraints.Add("locale", @"[a-zA-Z]{2}");

            _routeWithLocale = new Route(
                                    @"{locale}/" + pattern,
                                    defaults,
                                    localeConstraints,
                                    tokens,
                                    new LocaleRouteHandler(routeHandler));

            _routeWithoutLocale = new Route(
                                        pattern,
                                        defaults,
                                        constraints,
                                        tokens,
                                        new LocaleRouteHandler(routeHandler));

            if(namespaces != null && namespaces.Any()) {
                _routeWithLocale.DataTokens["Namespaces"] = namespaces;
                _routeWithoutLocale.DataTokens["Namespaces"] = namespaces;
            }
        }
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, 
                   RouteValueDictionary values, RouteDirection routeDirection)
 {
     bool result = httpContext.Request.UserAgent != null &&
         httpContext.Request.UserAgent.Contains(requiredUserAgent);
     return result;
 }
Пример #12
0
		public void SetNullUrl ()
		{
			var r = new Route (null, null);
			r.Url = "urn:foo";
			r.Url = null;
			Assert.AreEqual (String.Empty, r.Url);
		}
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var blogRepo = DependencyResolver.Current.GetService<IRepository<Data.Blog>>();
            var httpContextService = DependencyResolver.Current.GetService<IHttpContextService>();

            return DependencyResolver.Current.GetService<IRepository<Redirect>>().GetRedirectFor(httpContext.Request.Url.LocalPath.TrimStart('/'), blogRepo.GetCurrentBlog(httpContextService).Id) != null;
        }
        protected override bool IsMatch(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (routeDirection == RouteDirection.UrlGeneration)
            {
                return true;
            }

            if (!base.IsMatch(httpContext, route, parameterName, values, routeDirection))
            {
                return false;
            }

            //First check that language matches regex pattern
            object parameterValue; 
            values.TryGetValue(parameterName, out parameterValue);
            var parameterValueString = Convert.ToString(parameterValue, CultureInfo.InvariantCulture);
            var constraintsRegEx = string.Format("^({0})$", Constants.LanguageRegex);
            if (!Regex.IsMatch(parameterValueString, constraintsRegEx, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Compiled))
            {
                return false;
            }

            try
            {
                var culture = CultureInfo.CreateSpecificCulture(parameterValueString);
                //If culture is created then it is correct
            }
            catch
            {
                //Language is not valid
                return false;
            }

            return true;
        }
Пример #15
0
		protected virtual bool Match (HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
		{
			if (httpContext == null)
				throw new ArgumentNullException ("httpContext");
			if (route == null)
				throw new ArgumentNullException ("route");
			if (parameterName == null)
				throw new ArgumentNullException ("parameterName");
			if (values == null)
				throw new ArgumentNullException ("values");

			switch (routeDirection) {
			case RouteDirection.IncomingRequest:
				// LAMESPEC: .NET allows case-insensitive comparison, which violates RFC 2616
				return AllowedMethods.Contains (httpContext.Request.HttpMethod);

			case RouteDirection.UrlGeneration:
				// See: aspnetwebstack's WebAPI equivalent for details.
				object method;

				if (!values.TryGetValue (parameterName, out method))
					return true;

				// LAMESPEC: .NET allows case-insensitive comparison, which violates RFC 2616
				return AllowedMethods.Contains (Convert.ToString (method));

			default:
				throw new ArgumentException ("Invalid routeDirection: " + routeDirection);
			}
		}
Пример #16
0
            public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                if (routeDirection == RouteDirection.IncomingRequest)
                {
                    if (_alreadyProcessed.ContainsKey(httpContext.Request.Url.AbsolutePath))
                    {
                        return _alreadyProcessed[httpContext.Request.Url.AbsolutePath];
                    }
                    var pathParts = httpContext.Request.Url.AbsolutePath.Split('/').ToList();
                    var backOfficePart = pathParts.IndexOf(_appContext.Settings.RebelPaths.BackOfficePath);
                    //ensure there's enough parts to match
                    if (backOfficePart == -1 || ((pathParts.Count - 1) < backOfficePart + 2))
                    {
                        _alreadyProcessed.AddOrUpdate(httpContext.Request.Url.AbsolutePath, false, (k, v) => false);
                        return false;
                    }
                    //ensure were matching the correct area
                    if (pathParts[backOfficePart + 1] != _areaName)
                    {
                        _alreadyProcessed.AddOrUpdate(httpContext.Request.Url.AbsolutePath, false, (k, v) => false);
                        return false;
                    }
                    //+2 because the area name comes after the back office path
                    var controller = pathParts[backOfficePart + 2];
                    if (_toIgnore.InvariantContains(controller))
                    {
                        _alreadyProcessed.AddOrUpdate(httpContext.Request.Url.AbsolutePath, true, (k, v) => true);
                        return true;
                    }
                }

                return false;

            }
 // To only allow *supported* cultures as the first part of the route, instead of  anything in the format xx or xx-xx comment the lower method
 // and uncomment this one, and make CultureManager.CultureIsSupported public.
 //public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 //{
 //    if (!values.ContainsKey(parameterName))
 //        return false;
 //    string potentialCultureName = (string)values[parameterName];
 //    return CultureManager.CultureIsSupported(potentialCultureName);
 //}
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     if (!values.ContainsKey(parameterName))
         return false;
     string potentialCultureName = (string)values[parameterName];
     return CultureFormatChecker.FormattedAsCulture(potentialCultureName);
 }
Пример #18
0
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var sid = values["id"];
            //Check sid exist in Student Table!

            return true; //
        }
Пример #19
0
        public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults,
            object constraints, string[] namespaces)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            var route = new Route(url, new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(defaults),
                Constraints = new RouteValueDictionary(constraints),
                DataTokens = new RouteValueDictionary()
            };

            if ((namespaces != null) && (namespaces.Length > 0))
            {
                route.DataTokens["Namespaces"] = namespaces;
            }

            routes.Add(name, route);

            return route;
        
        }
Пример #20
0
        public static void MapWebPageRoute(this RouteCollection routeCollection, string routeUrl, string virtualPath, object defaultValues = null, object constraints = null, string routeName = null)
        {
            routeName = routeName ?? routeUrl;

            var item = new Route(routeUrl, new RouteValueDictionary(defaultValues), new RouteValueDictionary(constraints), new WebPagesRouteHandler(virtualPath));
            routeCollection.Add(routeName, item);
        }
Пример #21
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="httpContext"></param>
 /// <param name="route"></param>
 /// <param name="parameterName"></param>
 /// <param name="values"></param>
 /// <param name="routeDirection"></param>
 /// <returns></returns>
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     if (values[parameterName].ToString().ToLower() == "rqitems")
         return true;
     else
         return false;
 }
Пример #22
0
 /// <summary>
 /// Adds the page route.
 /// </summary>
 /// <param name="routes">The routes.</param>
 /// <param name="routeName">Name of the route.</param>
 /// <param name="pageAndRouteIds">The page and route ids.</param>
 public static void AddPageRoute( this Collection<RouteBase> routes, string routeName, List<Rock.Web.PageAndRouteId> pageAndRouteIds)
 {
     Route route = new Route( routeName, new Rock.Web.RockRouteHandler() );
     route.DataTokens = new RouteValueDictionary();
     route.DataTokens.Add( "PageRoutes", pageAndRouteIds );
     routes.Add( route );
 }
Пример #23
0
 public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     if (RequireAnonymous)
         return !httpContext.Request.IsAuthenticated;
     else
         return httpContext.Request.IsAuthenticated;
 }
Пример #24
0
        public bool Match(HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            object obj;

            values.TryGetValue(parameterName, out obj);
            return(Regex.IsMatch(Convert.ToString(obj, (IFormatProvider)CultureInfo.InvariantCulture), "^(" + Constraint + ")$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant));
        }
Пример #25
0
 public static void MapRootArea(this RouteCollection routes, string url, string rootNamespace, object defaults)
 {
     Route route = new Route(url, new MvcRouteHandler());
         route.DataTokens = new RouteValueDictionary(new { namespaces = new string[] { rootNamespace + ".Controllers" } });
         route.Defaults = new RouteValueDictionary(new { area = "root", action = "Index", controller = "Home", id = "" });
         routes.Add(route);
 }
Пример #26
0
        bool IRouteConstraint.Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            var Controllers = CoreConfiguration.Instance.IgnorableControllers.Split(',');
            var Actions = CoreConfiguration.Instance.IgnorableActions.Split(',');

            return !Controllers.Any(Controller => Controller == values["controller"].ToString()) && !Actions.Any(Action => Action == values["action"].ToString());
        }
        public void CreateRouteEntry_IfDirectRouteProviderReturnsRouteWithEmptyActionDescriptors_Throws()
        {
            // Arrange
            string areaPrefix = null;
            string controllerPrefix = null;
            Route route = new Route(url: null, routeHandler: null);
            route.DataTokens = new RouteValueDictionary();
            route.DataTokens.Add(RouteDataTokenKeys.Actions, new ActionDescriptor[0]);
            ActionDescriptor[] originalActions = route.GetTargetActionDescriptors();
            Assert.NotNull(originalActions); // Guard
            Assert.Equal(0, originalActions.Length); // Guard
            RouteEntry entry = new RouteEntry(name: null, route: route);
            IDirectRouteFactory factory = CreateStubRouteFactory(entry);
            ControllerDescriptor controllerDescriptor = CreateStubControllerDescriptor("IgnoreController");
            ActionDescriptor actionDescriptor = CreateStubActionDescriptor(controllerDescriptor, "IgnoreAction");
            IReadOnlyCollection<ActionDescriptor> actions = new ActionDescriptor[] { actionDescriptor };
            IInlineConstraintResolver constraintResolver =
                new Mock<IInlineConstraintResolver>(MockBehavior.Strict).Object;

            // Act & Assert
            string expectedMessage = "The route does not have any associated action descriptors. Routing requires " +
                "that each direct route map to a non-empty set of actions.";
            Assert.Throws<InvalidOperationException>(() => DefaultDirectRouteProvider.CreateRouteEntry(areaPrefix,
                controllerPrefix, factory, actions, constraintResolver, targetIsAction: false), expectedMessage);
        }
        protected override bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            switch (routeDirection)
            {
                case RouteDirection.IncomingRequest:
                    foreach (var method in AllowedMethods)
                    {
                        if (String.Equals(method, httpContext.Request.HttpMethod, StringComparison.OrdinalIgnoreCase))
                            return true;

                        if (httpContext.Request.Unvalidated().Form == null)
                            continue;

                        var overridden = httpContext.Request.Unvalidated().Form["_method"] ?? httpContext.Request.Unvalidated().Form["X-HTTP-Method-Override"];
                        if (String.Equals(method, overridden, StringComparison.OrdinalIgnoreCase))
                        {
                            return true;
                        }

                    }
                    break;
            }

            return base.Match(httpContext, route, parameterName, values, routeDirection);
        }
 bool IRouteConstraint.Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     if (!values.ContainsKey(parameterName))
         return false;
     var parameterValue = values[parameterName];
     return parameterValue != null && Enum.GetNames(EnumType).Contains(parameterValue.ToString(), StringComparer.OrdinalIgnoreCase);
 }
Пример #30
0
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
#endif
        {
            if (parameterName == null)
            {
                throw Error.ArgumentNull("parameterName");
            }

            if (values == null)
            {
                throw Error.ArgumentNull("values");
            }

            object value;
            if (values.TryGetValue(parameterName, out value) && value != null)
            {
                if (value is bool)
                {
                    return true;
                }

                bool result;
                string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
                return Boolean.TryParse(valueString, out result);
            }
            return false;
        }
Пример #31
0
 public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     object val;
     values.TryGetValue(parameterName, out val);
     string input = Convert.ToString(val, CultureInfo.InvariantCulture);
     return regex.IsMatch(input);
 }
        public bool Match(HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            ///^Admin(.)+/
            var pattern        = "^Admin";
            var controllerName = values["controller"].ToString();
            var result         = Regex.IsMatch(controllerName, pattern);

            return(result);
        }
Пример #33
0
        /// <summary>
        /// 给 ASP.NET RouteTable 注册路由规则
        /// </summary>
        private static void InitRouting()
        {
            string filePath = MvcRuntime.Instance.GetPhysicalPath("ClownFish.Mvc.RouteTable.config");

            if (File.Exists(filePath) == false)
            {
                throw new FileNotFoundException("未能找到文件:" + filePath + " ,如果要启用 MvcRoutingModule,必须配置这个文件。");
            }


            ClownFish.Mvc.Config.RouteTableConfig config
                = XmlHelper.XmlDeserializeFromFile <ClownFish.Mvc.Config.RouteTableConfig>(filePath, Encoding.UTF8);

            if (config.Routes != null)
            {
                foreach (var route in config.Routes)
                {
                    if (string.IsNullOrEmpty(route.Url))
                    {
                        throw new System.Configuration.ConfigurationErrorsException("路由规则配置,必须要指定URL属性。");
                    }

                    RouteValueDictionary values = new RouteValueDictionary();

                    if (string.IsNullOrEmpty(route.Namespace) == false)
                    {
                        values.Add("namespace", route.Namespace);
                    }

                    if (string.IsNullOrEmpty(route.Controller) == false)
                    {
                        values.Add("controller", route.Controller);
                    }

                    if (string.IsNullOrEmpty(route.Action) == false)
                    {
                        values.Add("action", route.Action);
                    }


                    System.Web.Routing.Route routeRule = new System.Web.Routing.Route(route.Url, new MvcRouteHandler());
                    if (values.Count > 0)
                    {
                        routeRule.DataTokens = values;
                    }

                    if (string.IsNullOrEmpty(route.Name))
                    {
                        RouteTable.Routes.Add(routeRule);
                    }
                    else
                    {
                        RouteTable.Routes.Add(route.Name, routeRule);
                    }
                }
            }
        }
Пример #34
0
        public bool Match(HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            object value;

            if (values.TryGetValue(parameterName, out value))
            {
                var requestedController = Convert.ToString(value);
                if (s_knownControllers.Contains(requestedController))
                {
                    return(true);
                }
            }
            return(false);
        }
Пример #35
0
        private static void MapRoute(MobiChat.Data.Route route, List <RouteParameter> parameters)
        {
            RouteValueDictionary defaults    = new RouteValueDictionary();
            RouteValueDictionary constraints = new RouteValueDictionary();

            if (!defaults.ContainsKey("controller"))
            {
                defaults.Add("controller", route.Controller);
            }
            if (!defaults.ContainsKey("action"))
            {
                defaults.Add("action", route.Action);
            }

            if (parameters != null)
            {
                foreach (RouteParameter parameter in parameters)
                {
                    if (!defaults.ContainsKey(parameter.Key))
                    {
                        if (parameter.IsOptional)
                        {
                            defaults.Add(parameter.Key, UrlParameter.Optional);
                        }
                        else
                        {
                            defaults.Add(parameter.Key, !string.IsNullOrEmpty(parameter.Value) ? parameter.Value : (object)UrlParameter.Optional);
                        }
                    }
                    if (parameter.Constraint != null)
                    {
                        constraints.Add(parameter.Key, parameter.Constraint);
                    }
                }
            }

            string pattern = route.Pattern;

            System.Web.Routing.Route routeTemp = null;
            if (route.IsSessionRoute)
            {
                constraints.Add("dynamicParameters", string.Format(@"((/?{0}/{3})|(/?{1}/{3})|(/?{2}/{3}))*", MobiChat.Constants.SessionID, MobiChat.Constants.LookupID, MobiChat.Constants.PaymentID, MobiChat.Constants.RegexGuid));
                pattern += "/{*dynamicParameters}";
                RouteTable.Routes.Add(route.Name, new SessionRoute(pattern, defaults, constraints, new MvcRouteHandler()));
            }
            else
            {
                RouteTable.Routes.Add(route.Name, new System.Web.Routing.Route(pattern, defaults, constraints, new MvcRouteHandler()));
            }
        }
        public bool Match(HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            if (parameterName == "path")
            {
                string path       = values[parameterName].ToString();
                int    postId     = 0;
                int    categoryId = 0;
                int    page       = 0;
                if (CustomRegex.PageRegex.IsMatch(path))
                {
                    path = CustomRegex.PageRegex.Replace(path, evaluator =>
                    {
                        int.TryParse(evaluator.Groups[1].Value, out page);
                        return("");
                    });
                    values.Add(StringKeys.RouteValue_Page, page);
                }

                if (CustomRegex.PostIdRegex.IsMatch(path))
                {
                    path = CustomRegex.PostIdRegex.Replace(path, evaluator =>
                    {
                        int.TryParse(evaluator.Groups[1].Value, out postId);
                        return("");
                    });
                }
                else if (CustomRegex.CategoryIdRegex.IsMatch(path))
                {
                    path = CustomRegex.CategoryIdRegex.Replace(path, evaluator =>
                    {
                        int.TryParse(evaluator.Groups[1].Value, out categoryId);
                        return("");
                    });
                }
                values[parameterName] = path;
                if (postId > 0)
                {
                    values.Add(StringKeys.RouteValue_Post, postId);
                }
                if (categoryId > 0)
                {
                    values.Add(StringKeys.RouteValue_Category, categoryId);
                }
            }
            return(true);
        }
Пример #37
0
            public bool Match(HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
            {
                if (values[parameterName] != null)
                {
                    var permalink = values[parameterName].ToString();
                    if (!permalink.StartsWith("/"))
                    {
                        permalink = "/" + permalink;
                    }

                    var r = db.GetRouteByPath(permalink);
                    if (r != null && !String.IsNullOrWhiteSpace(r.RoutePath))
                    {
                        httpContext.Items["route"] = r;
                        return(true);
                    }
                }
                return(false);
            }
Пример #38
0
        private RouteModel GetRouteModelForRoute(ITabContext context, MvcRouteBase routeBase,
                                                 Dictionary <int, List <RouteDataMessage> > routeMessages,
                                                 Dictionary <int, Dictionary <int, List <ProcessConstraintMessage> > > constraintMessages)
        {
            RouteModel routeModel = new RouteModel();

            RouteDataMessage routeMessage = SafeFirstOrDefault(routeMessages.GetValueOrDefault(routeBase.GetHashCode()));

            if (routeMessage != null)
            {
                routeModel.Duration = routeMessage.Duration;
                routeModel.IsMatch  = routeMessage.IsMatch;
            }

            MvcRoute route = routeBase as MvcRoute;

            if (route != null)
            {
                routeModel.Area = (route.DataTokens != null && route.DataTokens.ContainsKey("area"))
                                        ? route.DataTokens["area"].ToString() : null;
                routeModel.Url = route.Url;

                // Append localizations if possible
                LocalizationCollectionRoute localizationCollectionRoute = null;
                FieldInfo fieldInfo = route.GetType().GetField("__target");

                if (fieldInfo != null)
                {
                    localizationCollectionRoute = fieldInfo.GetValue(route) as LocalizationCollectionRoute;
                }

                if (localizationCollectionRoute != null)
                {
                    routeModel.Url += " (LocalizationRoute)";
                    routeModel.Url += Environment.NewLine;

                    foreach (LocalizationRoute localizationRoute in
                             localizationCollectionRoute.LocalizedRoutes.OrderBy(x => x.Culture))
                    {
                        routeModel.Url += string.Format(Environment.NewLine + "{0} ({1})", localizationRoute.Url(),
                                                        !string.IsNullOrEmpty(localizationRoute.Culture) ? localizationRoute.Culture : "neutral");
                    }

                    if (!localizationCollectionRoute.LocalizedRoutes.Any())
                    {
                        routeModel.Url += Environment.NewLine + "! No translations exists - this route will not be accessible !";
                    }
                }

                routeModel.RouteData   = ProcessRouteData(route.Defaults, routeMessage);
                routeModel.Constraints = ProcessConstraints(context, route, constraintMessages);
                routeModel.DataTokens  = ProcessDataTokens(route.DataTokens);
            }
            else
            {
                routeModel.Url = routeBase.ToString();
            }

            IRouteNameMixin routeName = routeBase as IRouteNameMixin;

            if (routeName != null)
            {
                routeModel.Name = routeName.Name;
            }

            return(routeModel);
        }
Пример #39
0
        private IEnumerable <RouteConstraintModel> ProcessConstraints(ITabContext context, MvcRoute route,
                                                                      Dictionary <int, Dictionary <int, List <ProcessConstraintMessage> > > constraintMessages)
        {
            if (route.Constraints == null || route.Constraints.Count == 0)
            {
                return(null);
            }

            Dictionary <int, List <ProcessConstraintMessage> > counstraintRouteMessages =
                constraintMessages.GetValueOrDefault(route.GetHashCode());

            List <RouteConstraintModel> result = new List <RouteConstraintModel>();

            foreach (KeyValuePair <string, object> constraint in route.Constraints)
            {
                RouteConstraintModel model = new RouteConstraintModel();
                model.ParameterName = constraint.Key;
                model.Constraint    = constraint.Value.ToString();

                if (counstraintRouteMessages != null)
                {
                    ProcessConstraintMessage counstraintMessage =
                        SafeFirstOrDefault(counstraintRouteMessages.GetValueOrDefault(constraint.Value.GetHashCode()));
                    model.IsMatch = false;

                    if (counstraintMessage != null)
                    {
                        model.IsMatch = counstraintMessage.IsMatch;
                    }
                }

                result.Add(model);
            }

            return(result);
        }
Пример #40
0
        public void ExtendsRouteConstraintConstraints(RoutesInspector sut, IInspectorContext context, NewRoute route, System.Web.Routing.Route newRoute, IRouteConstraint routeConstraint, IRouteConstraint newRouteConstraint)
        {
            route.Constraints = new RouteValueDictionary {
                { "controller", routeConstraint }
            };

            RouteTable.Routes.Clear();
            RouteTable.Routes.Add("Test", route);

            context.ProxyFactory.Setup(x => x.IsWrapClassEligible(typeof(System.Web.Routing.Route))).Returns(true).Verifiable();
            context.ProxyFactory.Setup(x => x.WrapClass((System.Web.Routing.Route)route, It.IsAny <IEnumerable <IAlternateMethod> >(), It.IsAny <IEnumerable <object> >(), It.IsAny <object[]>())).Returns(newRoute).Verifiable();
            context.ProxyFactory.Setup(x => x.IsWrapInterfaceEligible <IRouteConstraint>(typeof(IRouteConstraint))).Returns(true).Verifiable();
            context.ProxyFactory.Setup(x => x.WrapInterface(routeConstraint, It.IsAny <IEnumerable <IAlternateMethod> >(), It.IsAny <IEnumerable <object> >())).Returns(newRouteConstraint).Verifiable();

            sut.Setup(context);

            context.ProxyFactory.VerifyAll();
            Assert.Same(newRouteConstraint, route.Constraints["controller"]);
        }
Пример #41
0
        public void ExtendsMvcRoutes(System.Web.Routing.IRouteHandler routeHandler, RoutesInspector sut, IInspectorContext context, System.Web.Routing.Route newRoute)
        {
            RouteTable.Routes.Clear();
            RouteTable.Routes.Add("Test", new System.Web.Routing.Route("Test", routeHandler));

            context.ProxyFactory.Setup(x => x.ExtendClass <System.Web.Routing.Route>(It.IsAny <IEnumerable <IAlternateMethod> >(), It.IsAny <IEnumerable <object> >(), It.IsAny <object[]>())).Returns(newRoute).Verifiable();

            sut.Setup(context);

            context.ProxyFactory.VerifyAll();
            Assert.Same(newRoute, RouteTable.Routes[0]);
        }
Пример #42
0
        public void WrapsMvcRouteDerivedTypes(RoutesInspector sut, System.Web.Routing.IRouteHandler routeHandler, IInspectorContext context, NewRoute route, System.Web.Routing.Route newRoute)
        {
            RouteTable.Routes.Clear();
            RouteTable.Routes.Add("Test", route);

            context.ProxyFactory.Setup(x => x.IsWrapClassEligible(typeof(System.Web.Routing.Route))).Returns(true).Verifiable();
            context.ProxyFactory.Setup(x => x.WrapClass((System.Web.Routing.Route)route, It.IsAny <IEnumerable <IAlternateMethod> >(), It.IsAny <IEnumerable <object> >(), It.IsAny <object[]>())).Returns(newRoute).Verifiable();

            sut.Setup(context);

            context.ProxyFactory.VerifyAll();
            Assert.Same(newRoute, RouteTable.Routes[0]);
        }
Пример #43
0
 public bool Match(HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     throw new NotImplementedException();
 }
Пример #44
0
        public bool Match(System.Web.HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, System.Web.Routing.RouteValueDictionary values, System.Web.Routing.RouteDirection routeDirection)
        {
            var inMethod = httpContext.Request.HttpMethod.ToUpperInvariant();

            return(_verbs.Contains(inMethod));
        }
Пример #45
0
 bool IRouteConstraint.Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     return(Match(httpContext, route, parameterName, values, routeDirection));
 }
Пример #46
0
        public string BuildUrl(Route route, RequestContext requestContext, RouteValueDictionary userValues, RouteValueDictionary constraints, out RouteValueDictionary usedValues)
        {
            usedValues = null;

            if (requestContext == null)
            {
                return(null);
            }

            RouteData            routeData     = requestContext.RouteData;
            RouteValueDictionary defaultValues = route != null ? route.Defaults : null;
            RouteValueDictionary ambientValues = routeData.Values;

            if (defaultValues != null && defaultValues.Count == 0)
            {
                defaultValues = null;
            }
            if (ambientValues != null && ambientValues.Count == 0)
            {
                ambientValues = null;
            }
            if (userValues != null && userValues.Count == 0)
            {
                userValues = null;
            }

            // Check URL parameters
            // It is allowed to take ambient values for required parameters if:
            //
            //   - there are no default values provided
            //   - the default values dictionary contains at least one required
            //     parameter value
            //
            bool canTakeFromAmbient;

            if (defaultValues == null)
            {
                canTakeFromAmbient = true;
            }
            else
            {
                canTakeFromAmbient = false;
                foreach (KeyValuePair <string, bool> de in parameterNames)
                {
                    if (defaultValues.ContainsKey(de.Key))
                    {
                        canTakeFromAmbient = true;
                        break;
                    }
                }
            }

            bool allMustBeInUserValues = false;

            foreach (KeyValuePair <string, bool> de in parameterNames)
            {
                string parameterName = de.Key;
                // Is the parameter required?
                if (defaultValues == null || !defaultValues.ContainsKey(parameterName))
                {
                    // Yes, it is required (no value in defaults)
                    // Has the user provided value for it?
                    if (userValues == null || !userValues.ContainsKey(parameterName))
                    {
                        if (allMustBeInUserValues)
                        {
                            return(null);                            // partial override => no match
                        }
                        if (!canTakeFromAmbient || ambientValues == null || !ambientValues.ContainsKey(parameterName))
                        {
                            return(null);                            // no value provided => no match
                        }
                    }
                    else if (canTakeFromAmbient)
                    {
                        allMustBeInUserValues = true;
                    }
                }
            }

            // Check for non-url parameters
            if (defaultValues != null)
            {
                foreach (var de in defaultValues)
                {
                    string parameterName = de.Key;

                    if (parameterNames.ContainsKey(parameterName))
                    {
                        continue;
                    }

                    object parameterValue = null;
                    // Has the user specified value for this parameter and, if
                    // yes, is it the same as the one in defaults?
                    if (userValues != null && userValues.TryGetValue(parameterName, out parameterValue))
                    {
                        object defaultValue = de.Value;
                        if (defaultValue is string && parameterValue is string)
                        {
                            if (String.Compare((string)defaultValue, (string)parameterValue, StringComparison.Ordinal) != 0)
                            {
                                return(null);                                // different value => no match
                            }
                        }
                        else if (defaultValue != parameterValue)
                        {
                            return(null);                            // different value => no match
                        }
                    }
                }
            }

            // We're a match, generate the URL
            var ret = new StringBuilder();

            usedValues = new RouteValueDictionary();
            bool canTrim = true;

            // Going in reverse order, so that we can trim without much ado
            int tokensCount = tokens.Length - 1;

            for (int i = tokensCount; i >= 0; i--)
            {
                PatternToken token = tokens [i];
                if (token == null)
                {
                    if (i < tokensCount && ret.Length > 0 && ret [0] != '/')
                    {
                        ret.Insert(0, '/');
                    }
                    continue;
                }

                if (token.Type == PatternTokenType.Literal)
                {
                    ret.Insert(0, token.Name);
                    continue;
                }

                string parameterName = token.Name;
                object tokenValue;

#if SYSTEMCORE_DEP
                if (userValues.GetValue(parameterName, out tokenValue))
                {
                    if (tokenValue != null)
                    {
                        usedValues.Add(parameterName, tokenValue.ToString());
                    }

                    if (!defaultValues.Has(parameterName, tokenValue))
                    {
                        canTrim = false;
                        if (tokenValue != null)
                        {
                            ret.Insert(0, tokenValue.ToString());
                        }
                        continue;
                    }

                    if (!canTrim && tokenValue != null)
                    {
                        ret.Insert(0, tokenValue.ToString());
                    }

                    continue;
                }

                if (defaultValues.GetValue(parameterName, out tokenValue))
                {
                    object ambientTokenValue;
                    if (ambientValues.GetValue(parameterName, out ambientTokenValue))
                    {
                        tokenValue = ambientTokenValue;
                    }

                    if (!canTrim && tokenValue != null)
                    {
                        ret.Insert(0, tokenValue.ToString());
                    }

                    usedValues.Add(parameterName, tokenValue.ToString());
                    continue;
                }

                canTrim = false;
                if (ambientValues.GetValue(parameterName, out tokenValue))
                {
                    if (tokenValue != null)
                    {
                        ret.Insert(0, tokenValue.ToString());
                        usedValues.Add(parameterName, tokenValue.ToString());
                    }
                    continue;
                }
#endif
            }

            // All the values specified in userValues that aren't part of the original
            // URL, the constraints or defaults collections are treated as overflow
            // values - they are appended as query parameters to the URL
            if (userValues != null)
            {
                bool first = true;
                foreach (var de in userValues)
                {
                    string parameterName = de.Key;

#if SYSTEMCORE_DEP
                    if (parameterNames.ContainsKey(parameterName) || defaultValues.Has(parameterName) || constraints.Has(parameterName))
                    {
                        continue;
                    }
#endif

                    object parameterValue = de.Value;
                    if (parameterValue == null)
                    {
                        continue;
                    }

                    var parameterValueAsString = parameterValue as string;
                    if (parameterValueAsString != null && parameterValueAsString.Length == 0)
                    {
                        continue;
                    }

                    if (first)
                    {
                        ret.Append('?');
                        first = false;
                    }
                    else
                    {
                        ret.Append('&');
                    }


                    ret.Append(Uri.EscapeDataString(parameterName));
                    ret.Append('=');
                    if (parameterValue != null)
                    {
                        ret.Append(Uri.EscapeDataString(de.Value.ToString()));
                    }

                    usedValues.Add(parameterName, de.Value.ToString());
                }
            }

            return(ret.ToString());
        }
Пример #47
0
 public bool Match(System.Web.HttpContextBase httpContext, System.Web.Routing.Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
 {
     return(true);
 }
Пример #48
0
        private bool ProcessConstraintInternal(HttpContextBase httpContext, Route route, object constraint, string parameterName,
                                               RouteValueDictionary values, RouteDirection routeDirection, RequestContext reqContext,
                                               out bool invalidConstraint)
        {
            invalidConstraint = false;
            IRouteConstraint irc = constraint as IRouteConstraint;

            if (irc != null)
            {
                return(irc.Match(httpContext, route, parameterName, values, routeDirection));
            }

            string s = constraint as string;

            if (s != null)
            {
                string v = null;
                object o;

                // NOTE: If constraint was not an IRouteConstraint, is is asumed
                // to be an object 'convertible' to string, or at least this is how
                // ASP.NET seems to work by the tests i've done latelly. (pruiz)

                if (values != null && values.TryGetValue(parameterName, out o))
                {
                    v = Convert.ToString(o, CultureInfo.InvariantCulture);
                }

                if (!String.IsNullOrEmpty(v))
                {
                    return(MatchConstraintRegex(v, s));
                }
                else if (reqContext != null)
                {
                    RouteData            rd       = reqContext != null ? reqContext.RouteData : null;
                    RouteValueDictionary rdValues = rd != null ? rd.Values : null;

                    if (rdValues == null || rdValues.Count == 0)
                    {
                        return(false);
                    }

                    if (!rdValues.TryGetValue(parameterName, out o))
                    {
                        return(false);
                    }

                    v = Convert.ToString(o, CultureInfo.InvariantCulture);
                    if (String.IsNullOrEmpty(v))
                    {
                        return(false);
                    }

                    return(MatchConstraintRegex(v, s));
                }
                return(false);
            }

            invalidConstraint = true;
            return(false);
        }