IReadOnlyList<RouteEntry> IDirectRouteProvider.GetDirectRoutes(HttpControllerDescriptor controllerDescriptor, IReadOnlyList<HttpActionDescriptor> actionDescriptors,
     IInlineConstraintResolver constraintResolver)
 {
     var routes = _provider.GetDirectRoutes(controllerDescriptor, actionDescriptors, constraintResolver);
     var list = new List<RouteEntry>();
     foreach (var route in routes)
     {
         var newRoute = new RouteEntry(route.Name ?? Guid.NewGuid().ToString(), route.Route);
         list.Add(newRoute);
         var descs = route.Route.GetTargetActionDescriptors();
         if (descs.Length == 0)
         {
             continue;
         }
         foreach (var desc in descs)
         {
             var reflDesc = desc as ReflectedHttpActionDescriptor;
             if (reflDesc == null)
             {
                 continue;
             }
             var method = reflDesc.MethodInfo;
             RouteEntry prevEntry;
             if (_map.TryGetValue(method, out prevEntry))
             {
                 throw new MultipleRoutesForSameMethodException(reflDesc, prevEntry, newRoute);
             }
             _map.Add(method, newRoute);
         }
     }
     return list;
 }
        public void CompareTo_RespectsOrder(int order1, int order2, int expectedValue)
        {
            var x = new RouteEntry();
            var y = new RouteEntry();

            x.Order = order1;
            y.Order = order2;

            Assert.Equal(expectedValue, x.CompareTo(y));
        }
        RouteEntry IDirectRouteFactory.CreateRoute(DirectRouteFactoryContext context)
        {
            var result = ((IDirectRouteFactory)InnerAttribute).CreateRoute(context);

            var writeableResult = new RouteEntry(result.Name, new WriteableRoute(result.Route));

            //need to add this here so we can retrieve it later
            writeableResult.Route.DataTokens.Add("Umb_RouteName", Name);
            return writeableResult;
        }
        public void CompareTo_RespectsOrder(int order1, int order2, int expectedValue)
        {
#if ASPNETWEBAPI
            var x = new HttpRouteEntry();
            var y = new HttpRouteEntry();
#else
            var x = new RouteEntry();
            var y = new RouteEntry();
#endif

            x.Order = order1;
            y.Order = order2;

            Assert.Equal(expectedValue, x.CompareTo(y));
        }
Exemple #5
0
        public override void RouteRemove(RouteEntry r)
        {
            string cmd = "/sbin/route del";

            cmd += " -host " + r.Address.Value;
            cmd += " gw " + r.Gateway.Value;
            cmd += " netmask " + r.Mask.Value;
            if (r.Metrics != "")
            {
                cmd += " metric " + r.Metrics;
            }
            if (r.Interface != "")
            {
                cmd += " dev " + r.Interface;
            }

            ShellCmd(cmd);
        }
Exemple #6
0
        public RequirementContentType GenerateRequirementClassificationForJobProfile(RouteEntryType routeEntryType, JobProfileContentType jobProfile)
        {
            RouteEntry routeEntry = jobProfile.HowToBecomeData.RouteEntries.Where(re => re.RouteName.Equals((int)routeEntryType)).FirstOrDefault();

            if (routeEntry == null)
            {
                throw new Exception($"Unable to find the route entry with route name {(int)routeEntryType}");
            }

            return(new RequirementContentType()
            {
                Id = routeEntry.EntryRequirements[0].Id,
                Info = "This is updated requirement info",
                Title = "This is an updated requirement title",
                JobProfileId = jobProfile.JobProfileId,
                JobProfileTitle = jobProfile.Title,
            });
        }
        public void CreateRoute_DelegatesToContextCreateBuilderBuild()
        {
            // Arrange
            string expectedTemplate     = "RouteTemplate";
            IDirectRouteFactory product = CreateProductUnderTest(expectedTemplate);

            RouteEntry expectedEntry = CreateEntry();

            IDirectRouteBuilder       builder = CreateBuilder(() => expectedEntry);
            DirectRouteFactoryContext context = CreateContext((template) => template == expectedTemplate ? builder :
                                                              new DirectRouteBuilder(new TActionDescriptor[0], targetIsAction: true));

            // Act
            RouteEntry entry = product.CreateRoute(context);

            // Assert
            Assert.Same(expectedEntry, entry);
        }
Exemple #8
0
        public override List <RouteEntry> RouteList()
        {
            List <RouteEntry> entryList = new List <RouteEntry>();

            string result = ShellCmd("route -n -ee");

            string[] lines = result.Split('\n');
            foreach (string line in lines)
            {
                string[] fields = Utils.StringCleanSpace(line).Split(' ');

                if (fields.Length == 11)
                {
                    RouteEntry e = new RouteEntry();
                    e.Address = fields[0];
                    e.Gateway = fields[1];
                    e.Mask    = fields[2];
                    e.Flags   = fields[3].ToUpperInvariant();
                    e.Metrics = fields[4];
                    // Ref, Use ignored
                    e.Interface = fields[7];
                    e.Mss       = fields[8];
                    e.Window    = fields[9];
                    e.Irtt      = fields[10];

                    if (e.Address.Valid == false)
                    {
                        continue;
                    }
                    if (e.Gateway.Valid == false)
                    {
                        continue;
                    }
                    if (e.Mask.Valid == false)
                    {
                        continue;
                    }

                    entryList.Add(e);
                }
            }

            return(entryList);
        }
Exemple #9
0
        protected HTTPResponse HandleRequest(HTTPRequest request)
        {
            var url = StringUtils.FixUrl(request.path);

            if (url.Equals("/favicon.ico"))
            {
                return(null);
            }

            DataNode result;
            var      query = request.args;

            RouteEntry route = null;// router.Find(url, query);

            if (route != null)
            {
                var handler = route.Handlers.First().Handler; // TODO fixme

                try
                {
                    result = (DataNode)handler(request);
                }
                catch (Exception ex)
                {
                    result = OperationResult(ex.Message);
                }
            }
            else
            {
                result = DataNode.CreateObject("result");
                result.AddField("error", "invalid route");
            }

            var response = new HTTPResponse();


            var content = DataFormats.SaveToString(format, result);

            response.bytes = System.Text.Encoding.UTF8.GetBytes(content);

            response.headers["Content-Type"] = mimeType + "; charset=UTF-8";

            return(response);
        }
Exemple #10
0
        public override void RouteRemove(RouteEntry r)
        {
            string cmd = "route del";

            cmd += " -net " + r.Address.Value;
            cmd += " gw " + r.Gateway.Value;
            cmd += " netmask " + r.Mask.Value;

            /*
             * if(r.Metrics != "")
             *      cmd += " metric " + r.Metrics;
             */
            if (r.Interface != "")
            {
                cmd += " dev " + r.Interface;
            }

            ShellCmd(cmd);             // IJTF2 // TOCHECK
        }
Exemple #11
0
        public LinksContentType GenerateLinksContentTypeForJobProfile(RouteEntryType routeEntryType, JobProfileContentType jobProfile)
        {
            RouteEntry routeEntry = jobProfile.HowToBecomeData.RouteEntries.Where(re => re.RouteName.Equals((int)routeEntryType)).FirstOrDefault();

            if (routeEntry == null)
            {
                throw new Exception($"Unable to find the route entry with route name {(int)routeEntryType}");
            }

            return(new LinksContentType()
            {
                Id = routeEntry.MoreInformationLinks[0].Id,
                Text = "This is updated link text",
                Title = "This is an updated link title",
                Url = $"https://{this.RandomString(10)}.com/",
                JobProfileId = jobProfile.JobProfileId,
                JobProfileTitle = jobProfile.Title,
            });
        }
        public void CreateRouteEntry_IfDirectRouteProviderReturnsRouteWithoutActionDescriptors_Throws()
        {
            // Arrange
            string areaPrefix       = null;
            string controllerPrefix = null;
            Route  route            = new Route(url: null, routeHandler: null);

            Assert.Null(route.GetTargetActionDescriptors()); // 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
                );
        }
Exemple #13
0
        public void GetControllerDirectRoutes_IfDirectRouteProviderReturnsRouteWithoutActionDescriptors_Throws()
        {
            // Arrange
            IHttpRoute route     = new Mock <IHttpRoute>().Object;
            RouteEntry entry     = new RouteEntry(name: null, route: route);
            var        factories = new[] { CreateStubRouteFactory(entry) };

            var action             = CreateStubActionDescriptor("IgnoreAction");
            var constraintResolver = new Mock <IInlineConstraintResolver>(MockBehavior.Strict).Object;

            var provider = new AccessibleDirectRouteProvider();

            // 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>(
                () => provider.GetControllerDirectRoutes(action.ControllerDescriptor, new[] { action }, factories, constraintResolver),
                expectedMessage);
        }
    protected override IReadOnlyList <RouteEntry> GetActionDirectRoutes(HttpActionDescriptor actionDescriptor, IReadOnlyList <IDirectRouteFactory> factories, IInlineConstraintResolver constraintResolver)
    {
        var result = base.GetActionDirectRoutes(actionDescriptor, factories, constraintResolver).ToList();
        var list   = new List <RouteEntry>();

        foreach (var route in result.Where(r => r.Route.RouteTemplate.Contains("[ApiGroup]")))
        {
            var attribute   = ((ReflectedHttpActionDescriptor)actionDescriptor).GetCustomAttributes <ApiGroupAttribute>().First();
            var newTemplate = route.Route.RouteTemplate.Replace("[ApiGroup]", attribute.GroupName);
            if (!result.Any(r => r.Route.RouteTemplate == newTemplate))
            {
                var entry = new RouteEntry(null, new HttpRoute(newTemplate,
                                                               new HttpRouteValueDictionary(route.Route.Defaults),
                                                               new HttpRouteValueDictionary(route.Route.Constraints),
                                                               new HttpRouteValueDictionary(route.Route.DataTokens)));
                list.Add(entry);
            }
        }
        return(list.AsReadOnly());
    }
Exemple #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress dest, mask, hop;

            if (!IPAddress.TryParse(tbDest.Text, out dest))
            {
                MessageBox.Show("Не корреткное значение IP адреса. Корректный формат xxx.xxx.xxx.xxx");
                tbDest.Focus();
                return;
            }
            else
            if (!IPAddress.TryParse(tbMask.Text, out mask))
            {
                MessageBox.Show("Не корреткное значение IP адреса. Корректный формат xxx.xxx.xxx.xxx");
                tbMask.Focus();
                return;
            }
            else
            if (!IPAddress.TryParse(tbHop.Text, out hop))
            {
                MessageBox.Show("Не корректное значение IP адреса. Корректный формат xxx.xxx.xxx.xxx");
                tbHop.Focus();
                return;
            }
            else
            if (cbInterfaces.Text == "")
            {
                MessageBox.Show("необходимо выбрать интерфейс");
                cbInterfaces.Focus();
                return;
            }


            RouteEntry routeTmp = new RouteEntry((uint)dest.Address, (uint)mask.Address, 0, (uint)hop.Address, Helper.interfaceInfo[cbInterfaces.SelectedIndex].RelatedInterface, NetworkPortsLib.Type.ForwardType.Direct, NetworkPortsLib.Type.ForwardProtocol.Static, 0, 0, Convert.ToInt32(nMetric.Value), 0, 0, 0, 0, indexArray[cbInterfaces.SelectedIndex]);
            int        iret     = Helper.iph.AddRouteEntry(routeTmp);

            if (iret != 0)
            {
                MessageBox.Show("Ошибка - " + Convert.ToString(iret));
            }
        }
        /// <summary>
        /// Override of <c>GetActionDirectRoutes</c> which extracts the version range and creates route entries
        /// for each version.
        /// </summary>
        /// <param name="actionDescriptor">action descriptor</param>
        /// <param name="factories">a list of factories</param>
        /// <param name="constraintResolver">constraint resolver</param>
        /// <returns>a list of route entries</returns>
        protected override IReadOnlyList <RouteEntry> GetActionDirectRoutes(
            HttpActionDescriptor actionDescriptor,
            IReadOnlyList <IDirectRouteFactory> factories,
            IInlineConstraintResolver constraintResolver)
        {
            List <RouteEntry> entries = new List <RouteEntry>();

            // extract the version range associate with the controller
            List <string> validVersions = this.GetVersionListForController(actionDescriptor);

            if (validVersions != null)
            {
                foreach (string vers in validVersions)
                {
                    string prefix = vers + "/" + this.GetRoutePrefix(actionDescriptor.ControllerDescriptor);

                    var actions = new HttpActionDescriptor[] { actionDescriptor };

                    foreach (IDirectRouteFactory factory in factories)
                    {
                        RouteEntry entry = CreateActionRouteEntry(prefix, factory, actions, constraintResolver);
                        entries.Add(entry);
                    }
                }
            }
            else
            {
                string prefix = this.GetRoutePrefix(actionDescriptor.ControllerDescriptor);

                var actions = new HttpActionDescriptor[] { actionDescriptor };

                foreach (IDirectRouteFactory factory in factories)
                {
                    RouteEntry entry = CreateActionRouteEntry(prefix, factory, actions, constraintResolver);
                    entries.Add(entry);
                }
            }

            return(entries);
        }
Exemple #17
0
        private void SaveClicked(object sender, System.EventArgs e)
        {
            Unfocus();

            if (Uri.IsWellFormedUriString(BridgeEntry.Text, UriKind.Absolute) &&
                Uri.IsWellFormedUriString(RouteEntry.Text, UriKind.Absolute) &&
                Uri.IsWellFormedUriString(FundEntry.Text, UriKind.Absolute))
            {
                Config.BridgeServerUrl   = BridgeEntry.Text;
                Config.RouteServerUrl    = RouteEntry.Text;
                Config.IdentityServerUrl = FundEntry.Text;

                Application.Current.Properties[Config.BridgeService]   = Config.BridgeServerUrl;
                Application.Current.Properties[Config.IdentityService] = Config.IdentityServerUrl;
                Application.Current.Properties[Config.RouteService]    = Config.RouteServerUrl;
                Application.Current.SavePropertiesAsync();

                ShowErrorMessage(AppResources.SettingsChanged);
            }
            else
            {
                EventHandler handleHandler = (sv, ev) => {
                    if (!Uri.IsWellFormedUriString(BridgeEntry.Text, UriKind.Absolute))
                    {
                        BridgeEntry.Focus();
                    }
                    else if (!Uri.IsWellFormedUriString(RouteEntry.Text, UriKind.Absolute))
                    {
                        RouteEntry.Focus();
                    }
                    else if (!Uri.IsWellFormedUriString(FundEntry.Text, UriKind.Absolute))
                    {
                        FundEntry.Focus();
                    }
                };

                ShowErrorMessage(AppResources.InvalidUrl, false, handleHandler);
            }
        }
Exemple #18
0
        public void RouteRemove(IpAddress address, IpAddress mask)
        {
            lock (this)
            {
                string key = RouteEntry.ToKey(address, mask);
                if (EntryAdded.ContainsKey(key))
                {
                    RouteEntry entry = EntryAdded[key];
                    entry.RefCount--;
                    if (entry.RefCount > 0)
                    {
                    }
                    else
                    {
                        entry.Remove();
                        EntryAdded.Remove(key);
                    }
                }

                Recovery.Save();
            }
        }
        internal static RouteTable Create(IEnumerable <Type> componentTypes)
        {
            var routes = new List <RouteEntry>();

            foreach (var type in componentTypes)
            {
                // We're deliberately using inherit = false here.
                //
                // RouteAttribute is defined as non-inherited, because inheriting a route attribute always causes an
                // ambiguity. You end up with two components (base class and derived class) with the same route.
                var routeAttributes = type.GetCustomAttributes <RouteAttribute>(inherit: false);

                foreach (var routeAttribute in routeAttributes)
                {
                    var template = TemplateParser.ParseTemplate(routeAttribute.Template);
                    var entry    = new RouteEntry(template, type);
                    routes.Add(entry);
                }
            }

            return(new RouteTable(routes.OrderBy(id => id, RoutePrecedence).ToArray()));
        }
        /// <summary>
        /// Uses the factory to create a route entry for the specific actions
        /// </summary>
        /// <param name="prefix">the route prefix</param>
        /// <param name="factory">the factory used to create a route entry</param>
        /// <param name="actions">the actions</param>
        /// <param name="constraintResolver">constraint resolver</param>
        /// <returns>the route entry</returns>
        private static RouteEntry CreateActionRouteEntry(
            string prefix,
            IDirectRouteFactory factory,
            IReadOnlyCollection <HttpActionDescriptor> actions,
            IInlineConstraintResolver constraintResolver)
        {
            Contract.Assert(factory != null);

            DirectRouteFactoryContext context = new DirectRouteFactoryContext(prefix, actions, constraintResolver, true);
            RouteEntry entry = factory.CreateRoute(context);

            if (entry == null)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Method {0}.{1} must not return null.",
                                                        typeof(IDirectRouteFactory).Name,
                                                        "CreateRoute"));
            }

            ValidateRouteEntry(entry);
            return(entry);
        }
        private static RouteEntry CreateRouteEntry(
            string prefix,
            IDirectRouteFactory factory,
            IReadOnlyCollection <HttpActionDescriptor> actions,
            IInlineConstraintResolver constraintResolver,
            bool targetIsAction)
        {
            Contract.Assert(factory != null);

            DirectRouteFactoryContext context = new DirectRouteFactoryContext(prefix, actions, constraintResolver, targetIsAction);
            RouteEntry entry = factory.CreateRoute(context);

            if (entry == null)
            {
                throw Error.InvalidOperation(SRResources.TypeMethodMustNotReturnNull,
                                             typeof(IDirectRouteFactory).Name, "CreateRoute");
            }

            DirectRouteBuilder.ValidateRouteEntry(entry);

            return(entry);
        }
Exemple #22
0
 private void удалитьМаршрутToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (!admin)
     {
         return;
     }
     if (grid.SelectedRows.Count > 0)
     {
         if (MessageBox.Show("Маршрут будет удален. Вы уверены?", "Внимание", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
         {
             RouteEntry routeTmp = Helper.GetRoute(Convert.ToInt32(grid.SelectedRows[0].Cells[12].Value) - 1);
             int        iret     = Helper.iph.DeleteRouteTableEntry(routeTmp);
             if (iret != 0)
             {
                 MessageBox.Show("Ошибка при удалении. Код ошибки - " + Convert.ToString(iret), "Информация", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             else
             {
                 Helper.FillRouteTable();
             }
         }
     }
 }
Exemple #23
0
        private static RouteEntry CreateRouteEntry(string routeTemplate)
        {
            var methodInfo           = typeof(TestController).GetMethod("Action");
            var controllerDescriptor = new ReflectedControllerDescriptor(typeof(TestController));
            var actionDescriptor     = new ReflectedActionDescriptor(
                methodInfo,
                "Action",
                controllerDescriptor);

            var route = new RouteBuilder2().BuildDirectRoute(
                routeTemplate,
                new RouteAttribute(),
                controllerDescriptor,
                actionDescriptor);

            var entry = new RouteEntry()
            {
                Route    = route,
                Template = routeTemplate,
            };

            return(entry);
        }
Exemple #24
0
        IReadOnlyList <RouteEntry> IDirectRouteProvider.GetDirectRoutes(HttpControllerDescriptor controllerDescriptor, IReadOnlyList <HttpActionDescriptor> actionDescriptors,
                                                                        IInlineConstraintResolver constraintResolver)
        {
            var routes = _provider.GetDirectRoutes(controllerDescriptor, actionDescriptors, constraintResolver);
            var list   = new List <RouteEntry>();

            foreach (var route in routes)
            {
                var newRoute = new RouteEntry(route.Name ?? Guid.NewGuid().ToString(), route.Route);
                list.Add(newRoute);
                var descs = route.Route.GetTargetActionDescriptors();
                if (descs.Length == 0)
                {
                    continue;
                }
                foreach (var desc in descs)
                {
                    var reflDesc = desc as ReflectedHttpActionDescriptor;
                    if (reflDesc == null)
                    {
                        continue;
                    }
                    var           method = reflDesc.MethodInfo;
                    MethodHandler prevEntry;
                    if (_map.TryGetValue(method, out prevEntry))
                    {
                        prevEntry.RouteEntries.Add(newRoute);
                        //throw new MultipleRoutesForSameMethodException(reflDesc, prevEntry.RouteEntry, newRoute);
                    }
                    else
                    {
                        _map.Add(method, new MethodHandler(method, newRoute, _routeSelector));
                    }
                }
            }
            return(list);
        }
Exemple #25
0
        private static IReadOnlyList <RouteEntry> CreateRouteEntries(
            string prefix,
            IReadOnlyCollection <IDirectRouteFactory> factories,
            IReadOnlyCollection <HttpActionDescriptor> actions,
            IInlineConstraintResolver constraintResolver,
            bool targetIsAction
            )
        {
            List <RouteEntry> entries = new List <RouteEntry>();

            foreach (IDirectRouteFactory factory in factories)
            {
                RouteEntry entry = CreateRouteEntry(
                    prefix,
                    factory,
                    actions,
                    constraintResolver,
                    targetIsAction
                    );
                entries.Add(entry);
            }

            return(entries);
        }
        internal static RouteEntry CreateRouteEntry(
            string prefix,
            IDirectRouteFactory factory,
            IReadOnlyCollection <HttpActionDescriptor> actions,
            IInlineConstraintResolver constraintResolver,
            bool targetIsAction)
        {
            Contract.Assert(factory != null);

            DirectRouteFactoryContext context = new DirectRouteFactoryContext(prefix, actions, constraintResolver, targetIsAction);
            RouteEntry entry = factory.CreateRoute(context);

            if (entry == null)
            {
                throw Error.InvalidOperation(SRResources.TypeMethodMustNotReturnNull,
                                             typeof(IDirectRouteFactory).Name, "CreateRoute");
            }

            IHttpRoute route = entry.Route;

            Contract.Assert(route != null);

            HttpActionDescriptor[] targetActions = GetTargetActionDescriptors(route);

            if (targetActions == null || targetActions.Length == 0)
            {
                throw new InvalidOperationException(SRResources.DirectRoute_MissingActionDescriptors);
            }

            if (route.Handler != null)
            {
                throw new InvalidOperationException(SRResources.DirectRoute_HandlerNotSupported);
            }

            return(entry);
        }
Exemple #27
0
        public void RouteAdd(IpAddress address, IpAddress mask, IpAddress gateway, string iface)
        {
            lock (this)
            {
                string key = RouteEntry.ToKey(address, mask);
                if (EntryAdded.ContainsKey(key))
                {
                    RouteEntry entry = EntryAdded[key];
                    entry.RefCount++;
                }
                else
                {
                    RouteEntry entry = new RouteEntry();
                    entry.Address   = address;
                    entry.Mask      = mask;
                    entry.Gateway   = gateway;
                    entry.Interface = iface;
                    EntryAdded[key] = entry;
                    entry.Add();
                }

                Recovery.Save();
            }
        }
Exemple #28
0
        internal static RouteTable Create(Dictionary <Type, string[]> templatesByHandler)
        {
            var routes = new List <RouteEntry>();

            foreach (var keyValuePair in templatesByHandler)
            {
                var parsedTemplates        = keyValuePair.Value.Select(v => TemplateParser.ParseTemplate(v)).ToArray();
                var allRouteParameterNames = parsedTemplates
                                             .SelectMany(GetParameterNames)
                                             .Distinct(StringComparer.OrdinalIgnoreCase)
                                             .ToArray();

                foreach (var parsedTemplate in parsedTemplates)
                {
                    var unusedRouteParameterNames = allRouteParameterNames
                                                    .Except(GetParameterNames(parsedTemplate), StringComparer.OrdinalIgnoreCase)
                                                    .ToArray();
                    var entry = new RouteEntry(parsedTemplate, keyValuePair.Key, unusedRouteParameterNames);
                    routes.Add(entry);
                }
            }

            return(new RouteTable(routes.OrderBy(id => id, RoutePrecedence).ToArray()));
        }
        public void CreateRoute_UsesOrderPropertyWhenBuilding()
        {
            // Arrange
            int expectedOrder             = 123;
            RouteFactoryAttribute product = CreateProductUnderTest();

            product.Order = expectedOrder;

            int order = 0;
            IDirectRouteBuilder builder = null;

            builder = CreateBuilder(() =>
            {
                order = builder.Order;
                return(null);
            });
            DirectRouteFactoryContext context = CreateContext((i) => builder);

            // Act
            RouteEntry ignore = product.CreateRoute(context);

            // Assert
            Assert.Equal(expectedOrder, order);
        }
Exemple #30
0
    private bool IsDuplicateTemplate(RouteEntry entry, List <RouteEntry> others)
    {
        for (var j = 0; j < others.Count; j++)
        {
            // This is another route with the same precedence. It is guaranteed to have the same number of segments
            // of the same kinds and in the same order. We just need to check the literals.
            var other = others[j];

            var isSame = true;
            for (var k = 0; k < entry.Template.Segments.Count; k++)
            {
                if (!string.Equals(
                        entry.Template.Segments[k].Parts[0].Text,
                        other.Template.Segments[k].Parts[0].Text,
                        StringComparison.OrdinalIgnoreCase))
                {
                    isSame = false;
                    break;
                }

                if (HttpMethods.HasValue() &&
                    !string.Equals(entry.Method, other.Method, StringComparison.OrdinalIgnoreCase))
                {
                    isSame = false;
                    break;
                }
            }

            if (isSame)
            {
                return(true);
            }
        }

        return(false);
    }
        public void CreateRoute_UsesNamePropertyWhenBuilding()
        {
            // Arrange
            string expectedName           = "RouteName";
            RouteFactoryAttribute product = CreateProductUnderTest();

            product.Name = expectedName;

            string name = null;
            IDirectRouteBuilder builder = null;

            builder = CreateBuilder(() =>
            {
                name = builder.Name;
                return(null);
            });
            DirectRouteFactoryContext context = CreateContext((i) => builder);

            // Act
            RouteEntry ignore = product.CreateRoute(context);

            // Assert
            Assert.Same(expectedName, name);
        }
 public MultipleRoutesForSameMethodException(ReflectedHttpActionDescriptor action, RouteEntry prevRoute, RouteEntry newRoute)
 {
     Action = action;
     PrevRoute = prevRoute;
     NewRoute = newRoute;
 }
Exemple #33
0
        /// <summary>
        /// Route precedence algorithm.
        /// We collect all the routes and sort them from most specific to
        /// less specific. The specificity of a route is given by the specificity
        /// of its segments and the position of those segments in the route.
        /// * A literal segment is more specific than a parameter segment.
        /// * A parameter segment with more constraints is more specific than one with fewer constraints
        /// * Segment earlier in the route are evaluated before segments later in the route.
        /// For example:
        /// /Literal is more specific than /Parameter
        /// /Route/With/{parameter} is more specific than /{multiple}/With/{parameters}
        /// /Product/{id:int} is more specific than /Product/{id}
        ///
        /// Routes can be ambiguous if:
        /// They are composed of literals and those literals have the same values (case insensitive)
        /// They are composed of a mix of literals and parameters, in the same relative order and the
        /// literals have the same values.
        /// For example:
        /// * /literal and /Literal
        /// /{parameter}/literal and /{something}/literal
        /// /{parameter:constraint}/literal and /{something:constraint}/literal
        ///
        /// To calculate the precedence we sort the list of routes as follows:
        /// * Shorter routes go first.
        /// * A literal wins over a parameter in precedence.
        /// * For literals with different values (case insensitive) we choose the lexical order
        /// * For parameters with different numbers of constraints, the one with more wins
        /// If we get to the end of the comparison routing we've detected an ambiguous pair of routes.
        /// </summary>
        internal static int RouteComparison(RouteEntry x, RouteEntry y)
        {
            if (ReferenceEquals(x, y))
            {
                return(0);
            }

            var xTemplate = x.Template;
            var yTemplate = y.Template;

            if (xTemplate.Segments.Length != y.Template.Segments.Length)
            {
                return(xTemplate.Segments.Length < y.Template.Segments.Length ? -1 : 1);
            }
            else
            {
                for (var i = 0; i < xTemplate.Segments.Length; i++)
                {
                    var xSegment = xTemplate.Segments[i];
                    var ySegment = yTemplate.Segments[i];
                    if (!xSegment.IsParameter && ySegment.IsParameter)
                    {
                        return(-1);
                    }
                    if (xSegment.IsParameter && !ySegment.IsParameter)
                    {
                        return(1);
                    }

                    if (xSegment.IsParameter)
                    {
                        // Always favor non-optional parameters over optional ones
                        if (!xSegment.IsOptional && ySegment.IsOptional)
                        {
                            return(-1);
                        }

                        if (xSegment.IsOptional && !ySegment.IsOptional)
                        {
                            return(1);
                        }

                        if (xSegment.Constraints.Length > ySegment.Constraints.Length)
                        {
                            return(-1);
                        }
                        else if (xSegment.Constraints.Length < ySegment.Constraints.Length)
                        {
                            return(1);
                        }
                    }
                    else
                    {
                        var comparison = string.Compare(xSegment.Value, ySegment.Value, StringComparison.OrdinalIgnoreCase);
                        if (comparison != 0)
                        {
                            return(comparison);
                        }
                    }
                }

                throw new InvalidOperationException($@"The following routes are ambiguous:
'{x.Template.TemplateText}' in '{x.Handler.FullName}'
'{y.Template.TemplateText}' in '{y.Handler.FullName}'
");
            }
        }
Exemple #34
0
        public override void OnRecoveryLoad(XmlElement root)
        {
            base.OnRecoveryLoad(root);

            DefaultGateway = root.GetAttribute("gateway");
            DefaultInterface = root.GetAttribute("interface");

            XmlElement nodeAdded = root.GetElementsByTagName("added")[0] as XmlElement;
            foreach (XmlElement nodeEntry in nodeAdded.ChildNodes)
            {
                RouteEntry entry = new RouteEntry();
                entry.ReadXML(nodeEntry);
                EntryAdded[entry.Key] = entry;
            }

            XmlElement nodeRemoved = root.GetElementsByTagName("removed")[0] as XmlElement;
            foreach (XmlElement nodeEntry in nodeRemoved.ChildNodes)
            {
                RouteEntry entry = new RouteEntry();
                entry.ReadXML(nodeEntry);
                EntryRemoved[entry.Key] = entry;
            }
        }
Exemple #35
0
        public override List <RouteEntry> RouteList()
        {
            List <RouteEntry> entryList = new List <RouteEntry>();

            // 'route print' show IP in Interface fields, but 'route add' need the interface ID. We use a map.
            Dictionary <string, string> InterfacesIp2Id = new Dictionary <string, string>();

            ManagementClass            objMC  = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection objMOC = objMC.GetInstances();

            foreach (ManagementObject objMO in objMOC)
            {
                if (!((bool)objMO["IPEnabled"]))
                {
                    continue;
                }

                string[] ips = Conversions.ToString(objMO["IPAddress"]).Trim().Split(',');
                string   id  = Conversions.ToString(objMO["InterfaceIndex"]).Trim();

                foreach (string ip in ips)
                {
                    InterfacesIp2Id[ip.Trim()] = id;
                }
            }

            // Loopback interface it's not in the enumeration below.
            InterfacesIp2Id["127.0.0.1"] = "1";

            string cmd    = "route PRINT";
            string result = ShellCmd(cmd);

            string[] lines = result.Split('\n');
            foreach (string line in lines)
            {
                string[] fields = Utils.StringCleanSpace(line).Split(' ');

                if (fields.Length == 5)
                {
                    // Route line.
                    RouteEntry e = new RouteEntry();
                    e.Address   = fields[0];
                    e.Mask      = fields[1];
                    e.Gateway   = fields[2];
                    e.Interface = fields[3];
                    e.Metrics   = fields[4];

                    if (e.Address.Valid == false)
                    {
                        continue;
                    }
                    if (e.Mask.Valid == false)
                    {
                        continue;
                    }

                    if (e.Gateway.Value != "On-link")
                    {
                        if (e.Gateway.Valid == false)
                        {
                            continue;
                        }
                    }

                    if (InterfacesIp2Id.ContainsKey(e.Interface))
                    {
                        e.Interface = InterfacesIp2Id[e.Interface];
                        entryList.Add(e);
                    }
                    else
                    {
                        Engine.Instance.LogDebug("Unexpected.");
                    }
                }
            }

            return(entryList);
        }
Exemple #36
0
        public override void RouteRemove(RouteEntry r)
        {
            string cmd = "route delete " + r.Address.Value + " mask " + r.Mask.Value + " " + r.Gateway.Value;

            ShellCmd(cmd);
        }
 public MethodHandler(MethodInfo method, RouteEntry newRoute, Func<HttpRequestMessage, ICollection<RouteEntry>, RouteEntry> routeSelector)
 {
     _routeSelector = routeSelector ?? ((req, coll) => coll.First());
     RouteEntries = new Collection<RouteEntry> { newRoute };
     ParameterHandlers = method.GetParameters().Select(p => new ParameterHandler(p)).ToList();
 }
Exemple #38
0
        public void RouteAdd(IpAddress address, IpAddress mask, IpAddress gateway, string iface)
        {
            lock (this)
            {
                string key = RouteEntry.ToKey(address, mask);
                if (EntryAdded.ContainsKey(key))
                {
                    RouteEntry entry = EntryAdded[key];
                    entry.RefCount++;
                }
                else
                {
                    RouteEntry entry = new RouteEntry();
                    entry.Address = address;
                    entry.Mask = mask;
                    entry.Gateway = gateway;
                    entry.Interface = iface;
                    EntryAdded[key] = entry;
                    entry.Add();
                }

                Recovery.Save();
            }
        }
        internal static void ValidateRouteEntry(RouteEntry entry)
        {
            Contract.Assert(entry != null);

            IHttpRoute route = entry.Route;
            Contract.Assert(route != null);

            HttpActionDescriptor[] targetActions = route.GetTargetActionDescriptors();

            if (targetActions == null || targetActions.Length == 0)
            {
                throw new InvalidOperationException(SRResources.DirectRoute_MissingActionDescriptors);
            }

            if (route.Handler != null)
            {
                throw new InvalidOperationException(SRResources.DirectRoute_HandlerNotSupported);
            }
        }
        internal static void ValidateRouteEntry(RouteEntry entry)
        {
            Contract.Assert(entry != null);

            TRoute route = entry.Route;
            Contract.Assert(route != null);

            TActionDescriptor[] targetActions = route.GetTargetActionDescriptors();

            if (targetActions == null || targetActions.Length == 0)
            {
                throw new InvalidOperationException(TResources.DirectRoute_MissingActionDescriptors);
            }
#if ASPNETWEBAPI
            if (route.Handler != null)
            {
                throw new InvalidOperationException(TResources.DirectRoute_HandlerNotSupported);
            }
#else
            if (route.RouteHandler != null)
            {
                throw new InvalidOperationException(TResources.DirectRoute_RouteHandlerNotSupported);
            }
#endif
        }