Ejemplo n.º 1
0
        /// <summary>
        /// Given a path, attempts to match the next part of it to the current segment.
        /// </summary>
        /// <param name="route">The route.</param>
        /// <param name="path">The path.</param>
        /// <returns>
        /// An object that indicates whether the path was successfully matched.
        /// </returns>
        public override SegmentPathMatch MatchPath(IRoute route, PathIterator path)
        {
            var values = new RouteValueDictionary();
            var next = path.Next();
            
            if (next.Length == 0)
            {
                if (defaultValue != UrlParameter.NotSpecified)
                {
                    values[parameterName] = defaultValue;
                }
                else
                {
                    return SegmentPathMatch.Failure(string.Format("The path does not contain a segment for parameter '{0}'", parameterName));   
                }
            }
            else
            {
                values[parameterName] = next;

                if (constraint != null && !constraint.IsValid(route, next, parameterName))
                {
                    return SegmentPathMatch.Failure(string.Format("Segment '{0}' did not match the constraint on parameter '{1}'", next, parameterName));
                }
            }
            return SegmentPathMatch.Successful(values);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Given a path, attempts to match the next part of it to the current segment.
 /// </summary>
 /// <param name="route">The route.</param>
 /// <param name="path">The path.</param>
 /// <returns>
 /// An object that indicates whether the path was successfully matched.
 /// </returns>
 public override SegmentPathMatch MatchPath(IRoute route, PathIterator path)
 {
     var next = path.Next();
     return String.Equals(next, literal, StringComparison.InvariantCultureIgnoreCase)
         ? SegmentPathMatch.Successful()
         : SegmentPathMatch.Failure(string.Format("Expected segment '{0}'; got '{1}'", literal, next));
 }
Ejemplo n.º 3
0
        //The constructor for the dispatch
        public Dispatch(ISimulationEnvironment env, string id, string time, string type, string color, string route)
        {
            //Store all incoming data to our global variables
            _environment = env;
            _dispatchTime = DateTime.Parse(time);
            _dispatchID = int.Parse(id);
            _routeType = int.Parse(type);
            _color = color;

            //Create our route object based on whether or not this is a custom route
            if (_routeType == 0)
            {
                var stops = new List<IBlock>();
                IBlock last = null;
                foreach (string blockID in route.Split('|'))
                {
                    stops.Add(_environment.TrackModel.requestBlockInfo(int.Parse(blockID), _color));
                    last = _environment.TrackModel.requestBlockInfo(int.Parse(blockID), _color);
                }
                _dispatchRoute = new Route(RouteTypes.PointRoute, last, -1, stops);
            }
            else
            {
                _dispatchRoute = new Route(RouteTypes.DefinedRoute, null, int.Parse(route), null);
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RouteMatch"/> class.
 /// </summary>
 /// <param name="success">if set to <c>true</c> [success].</param>
 /// <param name="route">The route.</param>
 /// <param name="parameterValues">The parameter values.</param>
 /// <param name="failReason">The fail reason.</param>
 private RouteMatch(bool success, IRoute route, IDictionary parameterValues, string failReason)
 {
     this.success = success;
     this.route = route;
     this.failReason = failReason;
     values = new RouteValueDictionary(parameterValues);
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Returns the customer that least increases the length of the given route.
        /// </summary>
        /// <param name="problem"></param>
        /// <param name="route"></param>
        /// <returns></returns>
        public static TwoOptResult CalculateBestPlacement(
            IProblemWeights problem,
            IRoute route)
        {
            //int previous1 = -1;
            //foreach (int customer1 in route)
            //{
            //    if (previous1 >= 0)
            //    {
            //        int previous2 = -1;
            //        foreach (int customer2 in route)
            //        {
            //            if (previous1 != previous2)
            //            {
            //                // test the two opt move.

            //            }

            //            previous2 = customer2;
            //        }
            //    }

            //    previous1 = customer1;
            //}
            throw new NotImplementedException();
        }
Ejemplo n.º 6
0
        public void Show(IRoute route, IEnumerable<IError> errors)
        {
            var view = route[KnownParameters.View] as UserControl;

            var adornerLayer = AdornerLayer.GetAdornerLayer(view);
            adornerLayer.Add(new ErrorsAdorner(view, errors));
        }
Ejemplo n.º 7
0
 public void Log(IRoute route)
 {
     _routeLog.Add(route);
     Routes = _routeLog
         .OrderByDescending(r => r.End)
         .ToList();
 }
        public bool Matches(IRoute route, IPath path)
        {
            var routePath = route.Path;
            if (!routePath.IsLiteral)
                return false;

            return routePath.LiteralPath.Equals(path.LiteralPath);
        }
Ejemplo n.º 9
0
        public NancyEngineFixture()
        {
            this.resolver = A.Fake<IRouteResolver>();
            this.route = A.Fake<IRoute>();

            A.CallTo(() => resolver.GetRoute(A<IRequest>.Ignored.Argument)).Returns(route);
            this.engine = new NancyEngine(resolver);
        }
Ejemplo n.º 10
0
        public object CreateView(IRoute route)
        {
            var type = GetTypeFor(route);

            if (type == null)
                return null;

            return Activator.CreateInstance(type);
        }
Ejemplo n.º 11
0
        public IRouteResult Process(IRoute route)
        {
            var listener = route[KnownParameters.Listener] as IListener;

            var result = listener.Execute(route)
                .AddParameter(KnownParameters.ProcessedByListener, true);

            return result as IRouteResult;
        }
Ejemplo n.º 12
0
        public static bool RouteEquals(this IRoute r1, IRoute r2)
        {
            if (r1.Resource != r2.Resource)
                return false;
            if (r1.Action != r2.Action)
                return false;

            return true;
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PathMatch"/> class.
 /// </summary>
 /// <param name="success">if set to <c>true</c> [success].</param>
 /// <param name="route">The route.</param>
 /// <param name="routeValues">The route values.</param>
 /// <param name="leftOver">The left over.</param>
 /// <param name="segmentValues">The segment values.</param>
 /// <param name="failReason">The fail reason.</param>
 private PathMatch(bool success, IRoute route, RouteValueDictionary routeValues, RouteValueDictionary leftOver, List<object> segmentValues, string failReason)
 {
     this.success = success;
     this.route = route;
     this.routeValues = routeValues;
     this.leftOver = leftOver;
     this.segmentValues = segmentValues;
     this.failReason = failReason;
 }
Ejemplo n.º 14
0
        public object CreateViewModel(IRoute route)
        {
            var type = GetTypeFor(route);

            if (type == null)
                return null;

            return IoC.Get(type);
        }
Ejemplo n.º 15
0
        private static object CheckParameter(IRoute route, ParameterInfo parameterInfo)
        {
            if (parameterInfo.ParameterType == typeof(int))
            {
                return int.Parse(route.Parameters[parameterInfo.Name]);
            }

            return route.Parameters[parameterInfo.Name];
        }
Ejemplo n.º 16
0
        private static object[] MapParameters(IRoute route, MethodInfo action)
        {
            var result = action
                .GetParameters()
                .Select(parameterInfo =>
                    CheckParameter(route, parameterInfo)).ToArray();

            return result;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Returns the customer that least increases the length of the given route.
        /// </summary>
        /// <param name="problem"></param>
        /// <param name="route"></param>
        /// <param name="customers"></param>
        /// <returns></returns>
        public static CheapestInsertionResult CalculateBestPlacement(
            IProblemWeights problem,
            IRoute route,
            ICollection<int> customers)
        {
            IInsertionCosts costs = new BinaryHeapInsertionCosts();

            return CheapestInsertionHelper.CalculateBestPlacement(problem, route, customers, costs);
        }
Ejemplo n.º 18
0
 public IRouteTable AddRoute(IRoute route)
 {
     if (route == null)
     {
         throw new ArgumentNullException("route");
     }
     
     routes.Add(route);
     return this;
 }
Ejemplo n.º 19
0
        public IRouteResult Execute(IRoute route)
        {
            var method = GetMethod(route);

            var parameters = GetParameters(route, method);

            object result = method.Invoke(this, parameters);

            return CreateRoute(result, route);
        }
Ejemplo n.º 20
0
        public IRouteResult Process(IRoute route)
        {
            var view = route[KnownParameters.View];
            var showAs = route[KnownParameters.ShowAs].ToString();

            var next = new Route("show", showAs)
                .AddParameter(KnownParameters.View, view);

            return new RouteResult(route).Next(next);
        }
 public void GetRouteReturnsCorrectRoute([Frozen]Mock<IRouteAlgorithmFactory> factoryStub, Mock<IRouteAlgorithm> routeAlgorithmStub, RouteSpecification specification, RouteType selectedAlgorithm, IRoute expectedResult, RouteController sut)
 {
     // Fixture setup
     factoryStub.Setup(f => f.CreateAlgorithm(selectedAlgorithm)).Returns(routeAlgorithmStub.Object);
     routeAlgorithmStub.Setup(a => a.CalculateRoute(specification)).Returns(expectedResult);
     // Exercise system
     var result = sut.GetRoute(specification, selectedAlgorithm);
     // Verify outcome
     Assert.Equal(expectedResult, result);
     // Teardown
 }
Ejemplo n.º 22
0
        void OnNext(IRoute route, IRouteProcessor processor)
        {
            if (route.IsEnd())
                return;

            route.Start = DateTime.Now.Ticks;
            var result = processor.Process(route);
            route.End = DateTime.Now.Ticks;

            Process(result);
        }
Ejemplo n.º 23
0
        public double Drive(ICar car, IRoute route)
        {
            double journeyDuration = 0;

            foreach (IPlace place in route.GetOrderedPlaces())
            {
                IDrivingStrategy drivingStrategy = SelectDrivingStrategy(place);
                journeyDuration += drivingStrategy.Execute(car, place, journeyDuration);
            }
            return journeyDuration;
        }
Ejemplo n.º 24
0
        public IRouteResult Process(IRoute route)
        {
            var controller = route[KnownParameters.Controller] as IController;

            var result = controller.Execute(route)
                .CopyParameterFrom(route, KnownParameters.ParentShowAs)
                .CopyParameterFrom(route, KnownParameters.ParentView)
                .AddParameter(KnownParameters.ProcessedByController, true)
                .AddParameter(KnownParameters.ParentController, controller);

            return result as IRouteResult;
        }
Ejemplo n.º 25
0
        public ViewModelRouteResult(IRoute route, object viewModel)
        {
            var result = route as IRouteResult ?? new RouteResult(route);
            CopyFrom(result);

            AddHistory(route);

            var nextRoute = new Route(route);
            nextRoute.AddParameter("ViewModel", viewModel);

            Next(nextRoute);
        }
Ejemplo n.º 26
0
 public void DeleteRoute(IRoute route)
 {
     if (RouteExists(route))
     {
         var routeToDelete = _routes.FirstOrDefault(r => r.Equals(route));
         _routes.Remove(routeToDelete);
     }
     else
     {
         throw new ArgumentException(string.Format(@"Route {0} -> {1} does not exist and cannot be deleted", route.From, route.To));
     }
 }
Ejemplo n.º 27
0
        public ControllerRouteResult(IRoute route, object controller)
        {
            var result = route as IRouteResult ?? new RouteResult(route);
            CopyFrom(result);

            AddHistory(route);

            var nextRoute = new Route(route);
            nextRoute.AddParameter(KnownParameters.Controller, controller);

            Next(nextRoute);
        }
Ejemplo n.º 28
0
 public void UpdateRoute(IRoute route)
 {
     if (RouteExists(route))
     {
         int routeIndex = _routes.FindIndex(r => r.Id == route.Id);
         _routes[routeIndex] = route;
     }
     else
     {
         throw new ArgumentException(string.Format(@"Route {0} -> {1} does not exist and cannot be updated", route.From, route.To));
     }
 }
Ejemplo n.º 29
0
        private static object[] MapParameters(IRoute route, MethodInfo action)
        {
            return action.GetParameters().Select<ParameterInfo, object>(
                parameter =>
                    {
                        if (parameter.ParameterType == typeof(int))
                        {
                            return int.Parse(route.ActionParameters[parameter.Name]);
                        }

                        return route.ActionParameters[parameter.Name];
                    }).ToArray();
        }
Ejemplo n.º 30
0
        public IRouteResult Process(IRoute route)
        {
            if (_presenter == null)
                return new EndRouteResult(route);

            if (!route.Contains(KnownParameters.Errors))
                throw new NoErrorsFoundToShowException(route);

            var errors = route[KnownParameters.Errors] as IEnumerable<IError>;
            _presenter.Show(route, errors);

            return new EndRouteResult(route);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// »нициализирует новый экземпл¤р класса <see cref="StaticRouteResolver"/>.
 /// </summary>
 /// <param name="exchange">
 /// The exchange.
 /// </param>
 /// <param name="routingKey">
 /// The routing key.
 /// </param>
 public StaticRouteResolver(string exchange, string routingKey = "")
 {
     this._route = new RabbitRoute(exchange, routingKey);
 }
Ejemplo n.º 32
0
 public virtual IRoute SetNext(IRoute route)
 {
     _next = route;
     return(route);
 }
 /// <summary>
 /// Verifies the constraint against the specified route information. Returns <c>false</c> when the
 /// constraint is violated.
 /// </summary>
 /// <param name="route">The route being matched.</param>
 /// <param name="value">The value of the route parameter to be matched.</param>
 /// <param name="parameterName">The name of the parameter being matched.</param>
 /// <returns>
 /// <c>true</c> if the value is valid according to this constraint, otherwise <c>false</c>.
 /// </returns>
 public bool IsValid(IRoute route, string value, string parameterName)
 {
     return(regex.Match(value).Success);
 }
Ejemplo n.º 34
0
 private TwoItemsKey <Line> GetKey(IRoute route)
 {
     return(new TwoItemsKey <Line>(route.From.Line, route.To.Line));
 }
Ejemplo n.º 35
0
 protected virtual void SetCurrentCulture(IRoute route)
 {
     Thread.CurrentThread.CurrentCulture   = route.Culture;
     Thread.CurrentThread.CurrentUICulture = route.Culture;
 }
Ejemplo n.º 36
0
 public PassengerManager(IRoute dataContext)
 {
     _dataContext = dataContext;
 }
Ejemplo n.º 37
0
 /// <summary>
 /// »нициализирует новый экземпл¤р класса <see cref="StaticRouteResolver"/>.
 /// </summary>
 /// <param name="route">
 /// The route.
 /// </param>
 public StaticRouteResolver(IRoute route)
 {
     this._route = route;
 }
Ejemplo n.º 38
0
 public override object Visit(IRoute entity, GridContext data)
 {
     return(new RouteSettings(entity, data));
 }
Ejemplo n.º 39
0
 public DriveReportService(IMailSender mailSender, IGenericRepository <DriveReport> driveReportRepository, IReimbursementCalculator calculator, IGenericRepository <OrgUnit> orgUnitRepository, IGenericRepository <Employment> employmentRepository, IGenericRepository <Substitute> substituteRepository, IAddressCoordinates coordinates, IRoute <RouteInformation> route, IGenericRepository <RateType> rateTypeRepo, IGenericRepository <Person> personRepo, ILogger logger)
 {
     _route                 = route;
     _rateTypeRepo          = rateTypeRepo;
     _coordinates           = coordinates;
     _calculator            = calculator;
     _orgUnitRepository     = orgUnitRepository;
     _employmentRepository  = employmentRepository;
     _substituteRepository  = substituteRepository;
     _mailSender            = mailSender;
     _driveReportRepository = driveReportRepository;
     _personRepository      = personRepo;
     _logger                = logger;
 }
Ejemplo n.º 40
0
 public FlightService(IRoute dataContext)
 {
     _route            = dataContext;
     _passengerManager = new PassengerManager(dataContext);
 }
Ejemplo n.º 41
0
 public IRouter InsertFirst(IRoute route)
 {
     InsertAt(0, route);
     return(this);
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Returns the customer that least increases the length of the given route.
        /// </summary>
        /// <param name="problem"></param>
        /// <param name="route"></param>
        /// <param name="customers"></param>
        /// <param name="seed_customer"></param>
        /// <param name="seed_customer_ratio"></param>
        /// <returns></returns>
        public static CheapestInsertionResult CalculateBestPlacement(
            IProblemWeights problem,
            IRoute route,
            ICollection <int> customers,
            int seed_customer,
            double seed_customer_ratio)
        {
            IInsertionCosts costs = new BinaryHeapInsertionCosts();

            // initialize the best placement result.
            CheapestInsertionResult best = new CheapestInsertionResult();

            best.Increase = float.MaxValue;

            // loop over all customers in the route.
            if (route.Count > 0)
            { // there have to be at least two customers.
                IEnumerator <int> route_enumerator = route.GetEnumerator();
                if (!route_enumerator.MoveNext())
                { // this route is empty
                    throw new ArgumentException("Route needs to be initialized with at least two customers!");
                }
                int customer_before = route_enumerator.Current;
                int customer_after  = -1;
                while (route_enumerator.MoveNext())
                { // keep moving!
                    customer_after = route_enumerator.Current;
                    InsertionCost cost  = costs.PopCheapest(customer_before, customer_after);
                    bool          found = false;
                    while (!found)
                    {     // test if the costs are empty.
                        if (cost == null)
                        { // re-initialize the costs with all customers under consideration.
                            foreach (int customer in customers)
                            {
                                float cost_quantity = (float)problem.WeightMatrix[customer_before][customer] +
                                                      (float)problem.WeightMatrix[customer][customer_after] -
                                                      (float)problem.WeightMatrix[customer_before][customer_after];
                                float seed_cost = (float)problem.WeightMatrix[seed_customer][customer] +
                                                  (float)problem.WeightMatrix[customer][seed_customer];
                                costs.Add(customer_before, customer_after, customer,
                                          (float)(cost_quantity + (seed_customer_ratio * seed_cost)));
                            }

                            // pop the cheapest again!
                            cost = costs.PopCheapest(customer_before, customer_after);
                        }
                        else if (customers.Contains(cost.Customer))
                        { // the customer is found!
                            found = true;
                        }
                        else
                        { // pop the cheapest again!
                            cost = costs.PopCheapest(customer_before, customer_after);
                        }
                    }

                    if (cost.Cost < best.Increase)
                    { // the costs is better than the current cost!
                        best = new CheapestInsertionResult()
                        {
                            Customer       = cost.Customer,
                            CustomerAfter  = customer_after,
                            CustomerBefore = customer_before,
                            Increase       = cost.Cost
                        };
                        if (best.Increase == 0)
                        { // immidiately return if smaller than epsilon.
                            return(best);
                        }
                    }

                    // set the after to the before.
                    customer_before = route_enumerator.Current;
                }

                // if the round is a round try first-last.
                if (route.IsRound)
                { // the route is a round!
                    customer_after = route.First;
                    InsertionCost cost  = costs.PopCheapest(customer_before, customer_after);
                    bool          found = false;
                    while (!found)
                    {     // test if the costs are empty.
                        if (cost == null)
                        { // re-initialize the costs with all customers under consideration.
                            foreach (int customer in customers)
                            {
                                float cost_quantity = (float)problem.WeightMatrix[customer_before][customer] +
                                                      (float)problem.WeightMatrix[customer][customer_after] -
                                                      (float)problem.WeightMatrix[customer_before][customer_after];
                                float seed_cost = (float)problem.WeightMatrix[seed_customer][customer] +
                                                  (float)problem.WeightMatrix[customer][seed_customer];
                                costs.Add(customer_before, customer_after, customer,
                                          (float)(cost_quantity + (seed_customer_ratio * seed_cost)));
                            }

                            // pop the cheapest again!
                            cost = costs.PopCheapest(customer_before, customer_after);
                        }
                        else if (customers.Contains(cost.Customer))
                        { // the customer is found!
                            found = true;
                        }
                        else
                        { // pop the cheapest again!
                            cost = costs.PopCheapest(customer_before, customer_after);
                        }
                    }

                    if (cost.Cost < best.Increase)
                    { // the costs is better than the current cost!
                        best = new CheapestInsertionResult()
                        {
                            Customer       = cost.Customer,
                            CustomerAfter  = customer_after,
                            CustomerBefore = customer_before,
                            Increase       = cost.Cost
                        };
                        if (best.Increase == 0)
                        { // immidiately return if smaller than epsilon.
                            return(best);
                        }
                    }
                }
            }
            else
            { // route needs to be initialized.
                throw new ArgumentException("Route needs to be initialized with at least two customers!");
            }

            // return result.
            return(best);
        }
Ejemplo n.º 43
0
        public long FindRoutes(IRoute <INode <T> > route, long count, long writtenToDisk, CancellationToken token)
        {
            const long queueLimit   = 1000000L;
            var        streamReader = (StreamReader)null;

            while (route != null)
            {
                foreach (var link in route.Value.Links.Except(route.AllValues))
                {
                    if (link is TerminalNode)
                    {
                        //Console.WriteLine(new Route<INode<T>>(link, route));
                        count++;

                        if (count % 100000 == 0)
                        {
                            Trace.WriteLine($"Route count: {count}, Queue count: {_workQueue.Count} in memory, {writtenToDisk} on disk");
                        }
                    }
                    else
                    {
                        _workQueue.Enqueue(new Route <INode <T> >(link, route));
                    }
                }

                if (_workQueue.Count >= queueLimit || token.IsCancellationRequested)
                {
                    var writtenCount = (long)0;
                    var tempFilePath = Path.GetTempFileName();
                    Trace.WriteLine($"Writing routes to file {tempFilePath}");

                    using (var sw = File.CreateText(tempFilePath))
                    {
                        while (_workQueue.Count > 0)
                        {
                            var queuedRoute = _workQueue.Dequeue();
                            if (!IsBlocked(queuedRoute))
                            {
                                sw.WriteLine(queuedRoute);
                                writtenCount++;
                            }
                        }
                    }

                    writtenToDisk += writtenCount;
                    Trace.WriteLine($"Wrote {writtenCount} routes to file {tempFilePath}, total routes written to file: {writtenToDisk}");
                    _tempFilePaths.Enqueue(tempFilePath);

                    if (token.IsCancellationRequested)
                    {
                        if (streamReader != null)
                        {
                            tempFilePath = Path.GetTempFileName();
                            using (var sw = File.CreateText(tempFilePath))
                            {
                                while (!streamReader.EndOfStream)
                                {
                                    sw.WriteLine(streamReader.ReadLine());
                                }
                            }

                            streamReader.Close();
                            _tempFilePaths.Enqueue(tempFilePath);
                        }

                        var resultFilePath = Path.Combine(Path.GetTempPath(), "InterimResult.txt");
                        using (var sw = File.CreateText(resultFilePath))
                        {
                            sw.WriteLine(count);
                            sw.WriteLine(writtenToDisk);
                            while (_tempFilePaths.Count > 0)
                            {
                                sw.WriteLine(_tempFilePaths.Dequeue());
                            }
                        }
                    }
                }

                if (_workQueue.Count > 0)
                {
                    route = _workQueue.Dequeue();
                    continue;
                }

                if (streamReader != null && streamReader.EndOfStream)
                {
                    streamReader.Close();
                    streamReader = null;
                }

                if (_tempFilePaths.Count > 0 && streamReader == null)
                {
                    streamReader = File.OpenText(_tempFilePaths.Dequeue());
                }

                if (streamReader != null && !streamReader.EndOfStream)
                {
                    route          = _routeParser.Parse(streamReader.ReadLine());
                    writtenToDisk -= 1;
                }
                else
                {
                    route = null;
                }
            }

            return(count);
        }
Ejemplo n.º 44
0
 /// <summary>
 /// 编译配置信息
 /// </summary>
 /// <param name="route"></param>
 /// <param name="routed"></param>
 protected void ComplieOptions(IRoute route, Routed routed)
 {
     ComplieOptionsGroup(route, routed);
     ComplieOptionsWhere(route, ComplieDirection(routed.Where));
     ComplieOptionsDefaults(route, ComplieDirection(routed.Defaults));
 }
Ejemplo n.º 45
0
 public MvcMiddleware(IRoute route)
 {
     this.route = route;
 }
Ejemplo n.º 46
0
 /// <summary>
 /// Disables the route, preventing it from being invoked during routing
 /// </summary>
 public static void Disable(this IRoute route)
 {
     route.Enabled = false;
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Does the actual solving.
        /// </summary>
        /// <param name="problem"></param>
        /// <returns></returns>
        protected override IRoute DoSolve(IProblem problem)
        {
            // convert to a symetric problem if needed.
            IProblem _problem = problem;

            if (!_problem.Symmetric)
            {
                _problem  = Convertor.ConvertToSymmetric(_problem);
                _was_asym = true;
            }

            // create the list of customers.
            _customers = new List <int>();
            for (int customer = 0; customer < _problem.Size; customer++)
            {
                _customers.Add(customer);
            }
            _sparse_set = SparseSetHelper.CreateNearestNeighourSet(_problem, _customers, _customers.Count / 10);
            //_sparse_set = SparseSetHelper.CreateNonSparseSet(_problem, _customers);
            // construct a route from the customers.
            //FixedSymmetricRoute init_route = new FixedSymmetricRoute(_customers);

            // construct a random route using best-placement.
            ArbitraryInsertionSolver bp_solver = new ArbitraryInsertionSolver();
            IRoute bp_route = bp_solver.Solve(_problem);
            FixedSymmetricRoute init_route = new FixedSymmetricRoute(bp_route);

            double     init_route_weight = LinKernighanSolver.Weight(_problem, init_route);
            RouteFound route             = new RouteFound()
            {
                Route       = init_route,
                RouteWeight = init_route_weight
            };

            OsmSharp.Logging.Log.TraceEvent("LinKernighanSolver", Logging.TraceEventType.Information, "Route {0}:{1}",
                                            route.Route.ToString(),
                                            route.RouteWeight);

            // step 2.
            EdgeSet     X           = new EdgeSet();
            EdgeSet     Y           = new EdgeSet();
            IList <int> untried_t_1 = new List <int>(route.Route);

            while (untried_t_1.Count > 0)
            {
                // select t1.
                int t_1 = untried_t_1[0];
                untried_t_1.RemoveAt(0);

                // search route with t_1.
                RouteFound t_1_route = this.AfterSelectt1(_problem, route, X, Y, t_1);

                // select the better route.
                if (t_1_route.RouteWeight < route.RouteWeight)
                {
                    untried_t_1 = new List <int>(route.Route);
                    route       = RouteFound.SelectBest(route, t_1_route);
                    X           = new EdgeSet();
                    Y           = new EdgeSet();
                }
            } // step 2 and step 12.

            // convert back to asym solution if needed.
            //result.RemoveAt(result.Count - 1);
            if (_was_asym)
            {
                return(this.ConvertToASymRoute(new List <int>(route.Route)));
            }
            return(route.Route);
        }
Ejemplo n.º 48
0
        public void TestDepotDynamicAsymmetricMultiRouteExchanges()
        {
            // create two routes.
            // 0->11->12->13->14->15->0
            // 0->21->22->23->24->25->0
            var    multiRoute = new MaxTimeSolution(0);
            IRoute route1     = multiRoute.Add();
            var    customers  = new List <int>(route1);

            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual(0, customers[0]);
            route1.InsertAfter(0, 11);
            Assert.AreEqual("0->11", route1.ToString());
            route1.InsertAfter(11, 12);
            route1.InsertAfter(12, 13);
            route1.InsertAfter(13, 14);
            route1.InsertAfter(14, 15);
            IRoute route2 = multiRoute.Add();

            customers = new List <int>(route2);
            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual(0, customers[0]);
            route2.InsertAfter(0, 21);
            Assert.AreEqual("0->21", route2.ToString());
            route2.InsertAfter(21, 22);
            route2.InsertAfter(22, 23);
            route2.InsertAfter(23, 24);
            route2.InsertAfter(24, 25);

            customers = new List <int>(route1);
            Assert.AreEqual(6, customers.Count);
            Assert.AreEqual(0, customers[0]);
            Assert.AreEqual(11, customers[1]);
            Assert.AreEqual(12, customers[2]);
            Assert.AreEqual(13, customers[3]);
            Assert.AreEqual(14, customers[4]);
            Assert.AreEqual(15, customers[5]);


            customers = new List <int>(route2);
            Assert.AreEqual(6, customers.Count);
            Assert.AreEqual(0, customers[0]);
            Assert.AreEqual(21, customers[1]);
            Assert.AreEqual(22, customers[2]);
            Assert.AreEqual(23, customers[3]);
            Assert.AreEqual(24, customers[4]);
            Assert.AreEqual(25, customers[5]);

            // replace the entire first route.
            route1.ReplaceEdgeFrom(0, 0);

            route2.ReplaceEdgeFrom(25, 11);
            route2.ReplaceEdgeFrom(11, 12);
            route2.ReplaceEdgeFrom(12, 13);
            route2.ReplaceEdgeFrom(13, 14);
            route2.ReplaceEdgeFrom(14, 15);

            Assert.IsTrue(multiRoute.IsValid());

            // create two routes.
            // 0->11->12->13->14->15->0
            // 0->21->22->23->24->25->0
            multiRoute = new MaxTimeSolution(0);
            route1     = multiRoute.Add();
            customers  = new List <int>(route1);
            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual(0, customers[0]);
            route1.InsertAfter(0, 11);
            Assert.AreEqual("0->11", route1.ToString());
            route1.InsertAfter(11, 12);
            route1.InsertAfter(12, 13);
            route1.InsertAfter(13, 14);
            route1.InsertAfter(14, 15);
            route2    = multiRoute.Add();
            customers = new List <int>(route2);
            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual(0, customers[0]);
            route2.InsertAfter(0, 21);
            Assert.AreEqual("0->21", route2.ToString());
            route2.InsertAfter(21, 22);
            route2.InsertAfter(22, 23);
            route2.InsertAfter(23, 24);
            route2.InsertAfter(24, 25);

            // exchange parts.
            var part1 = new List <int>(route1.Between(11, 13));
            var part2 = new List <int>(route2.Between(23, 25));

            route1.ReplaceEdgeFrom(0, 14);
            route2.ReplaceEdgeFrom(22, 0);

            int previous = 0;

            for (int idx = 0; idx < part2.Count; idx++)
            {
                route1.ReplaceEdgeFrom(previous, part2[idx]);
                previous = part2[idx];
            }
            route1.ReplaceEdgeFrom(previous, 14);

            previous = 22;
            for (int idx = 0; idx < part1.Count; idx++)
            {
                route2.ReplaceEdgeFrom(previous, part1[idx]);
                previous = part1[idx];
            }
            route2.ReplaceEdgeFrom(previous, 0);

            Assert.IsTrue(multiRoute.IsValid());

            customers = new List <int>(route1);
            Assert.AreEqual(6, customers.Count);
            Assert.AreEqual(0, customers[0]);
            Assert.AreEqual(23, customers[1]);
            Assert.AreEqual(24, customers[2]);
            Assert.AreEqual(25, customers[3]);
            Assert.AreEqual(14, customers[4]);
            Assert.AreEqual(15, customers[5]);

            customers = new List <int>(route2);
            Assert.AreEqual(6, customers.Count);
            Assert.AreEqual(0, customers[0]);
            Assert.AreEqual(21, customers[1]);
            Assert.AreEqual(22, customers[2]);
            Assert.AreEqual(11, customers[3]);
            Assert.AreEqual(12, customers[4]);
            Assert.AreEqual(13, customers[5]);

            // create two routes.
            // 0->11->12->13->14->15->0
            // 0->21->22->23->24->25->0
            multiRoute = new MaxTimeSolution(0);
            route1     = multiRoute.Add();
            customers  = new List <int>(route1);
            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual(0, customers[0]);
            route1.InsertAfter(0, 11);
            Assert.AreEqual("0->11", route1.ToString());
            route1.InsertAfter(11, 12);
            route1.InsertAfter(12, 13);
            route1.InsertAfter(13, 14);
            route1.InsertAfter(14, 15);
            route2    = multiRoute.Add();
            customers = new List <int>(route2);
            Assert.AreEqual(1, customers.Count);
            Assert.AreEqual(0, customers[0]);
            route2.InsertAfter(0, 21);
            Assert.AreEqual("0->21", route2.ToString());
            route2.InsertAfter(21, 22);
            route2.InsertAfter(22, 23);
            route2.InsertAfter(23, 24);
            route2.InsertAfter(24, 25);

            route1.ReplaceEdgeFrom(12, 15);
            route1.ReplaceEdgeFrom(14, 11);
            route1.ReplaceEdgeFrom(0, 13);

            customers = new List <int>(route1);
            Assert.AreEqual(6, customers.Count);
            Assert.AreEqual(0, customers[0]);
            Assert.AreEqual(13, customers[1]);
            Assert.AreEqual(14, customers[2]);
            Assert.AreEqual(11, customers[3]);
            Assert.AreEqual(12, customers[4]);
            Assert.AreEqual(15, customers[5]);

            route1.ToString();
        }
Ejemplo n.º 49
0
 public static RouteValues GetRouteValues(this IRoute route, IRequest request)
 {
     return(route.GetRouteValues(request.Url, request.HttpMethod, request.RequestType()));
 }
Ejemplo n.º 50
0
 /// <summary>
 /// 请求
 /// </summary>
 /// <param name="route">路由</param>
 /// <param name="request">请求</param>
 public DispatchEventArgs(IRoute route, IRequest request)
 {
     Route   = route;
     Request = request;
 }
Ejemplo n.º 51
0
 protected virtual void OnAddRoute(IRoute route)
 {
     Timespan += route.Timespan;
     Length   += route.Length - 1;
     Lines.UnionWith(route.GetLines());
 }
Ejemplo n.º 52
0
        public void TestRegisterResolveReleaseRoute()
        {
            IRoutingService <string> routingService = _erector.Container.Resolve <IRoutingService <string> >();
            string          destinationRoute        = "123.789";
            IRoute <string> iRoute = _erector.Container.Resolve <IRoute <string> >();

            iRoute.Route = destinationRoute;
            iRoute.RegisterRouteHandler = (message) => { };
            bool            registerRoute = false;
            Action <string> resolveRoute  = null;
            bool            releaseRoute  = false;

            //RoutingTable Exceptions
            routingService.RoutingTable = null;
            try
            {
                registerRoute = routingService.RegisterRoute(iRoute);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, routingService.ExceptionMessage_RoutingTableCannotBeNull);
            }
            try
            {
                resolveRoute = routingService.ResolveRoute(destinationRoute);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, routingService.ExceptionMessage_RoutingTableCannotBeNull);
            }
            try
            {
                releaseRoute = routingService.ReleaseRoute(iRoute);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, routingService.ExceptionMessage_RoutingTableCannotBeNull);
            }


            routingService.RoutingTable = GetMockedRoutingTable <string>();
            //Register
            try
            {
                registerRoute = routingService.RegisterRoute(null);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, routingService.ExceptionMessage_IRouteCannotBeNull);
            }
            registerRoute = routingService.RegisterRoute(iRoute);
            Assert.IsTrue(registerRoute);

            //Resolve
            try
            {
                resolveRoute = routingService.ResolveRoute(String.Empty);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, routingService.ExceptionMessage_RouteCannotBeNullOrEmpty);
            }
            resolveRoute = routingService.ResolveRoute(destinationRoute);
            Assert.IsNotNull(resolveRoute);

            //Release
            try
            {
                releaseRoute = routingService.ReleaseRoute(null);
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, routingService.ExceptionMessage_IRouteCannotBeNull);
            }
            releaseRoute = routingService.ReleaseRoute(iRoute);
            Assert.IsTrue(releaseRoute);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Clone ctor
 /// </summary>
 public PartialRoute(PartialRoute source, IRoute addition)
 {
     routes.AddRange(source.routes);
     routes.Add(addition);
 }
Ejemplo n.º 54
0
        public Individual <List <Genome>, Problem, Fitness> CrossOver(
            Solver <List <Genome>, Problem, Fitness> solver,
            Individual <List <Genome>, Problem, Fitness> parent1,
            Individual <List <Genome>, Problem, Fitness> parent2)
        {
            Genome route1 = parent1.Genomes[0];
            Genome route2 = parent2.Genomes[0];

            // get the minimum size of both routes.
            int size = route1.Sizes.Length;

            if (route2.Sizes.Length < size)
            {
                size = route2.Sizes.Length;
            }

            // select a random number of routes.
            HashSet <int> selected_first  = new HashSet <int>();
            HashSet <int> selected_second = new HashSet <int>();
            List <IRoute> selected_routes = new List <IRoute>();
            bool          first           = true;

            while (selected_routes.Count < size)
            {
                // select route.
                int selected_route = -1;
                if (first)
                {
                    selected_route = OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(route1.Sizes.Length);
                    while (selected_first.Contains(selected_route))
                    {
                        selected_route = OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(route1.Sizes.Length);
                    }

                    selected_first.Add(selected_route);
                    selected_routes.Add(route1.Route(selected_route));
                }
                else
                {
                    selected_route = OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(route2.Sizes.Length);
                    while (selected_second.Contains(selected_route))
                    {
                        selected_route = OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(route2.Sizes.Length);
                    }

                    selected_second.Add(selected_route);
                    selected_routes.Add(route2.Route(selected_route));
                }

                first = !first;
            }

            // generate the new customer genome.
            HashSet <int> selected_customers = new HashSet <int>();
            List <int>    customers          = new List <int>();
            List <int>    sizes = new List <int>();

            foreach (IRoute route in selected_routes)
            {
                int current_size = 0;
                foreach (int customer in route)
                {
                    if (!selected_customers.Contains(customer))
                    {
                        customers.Add(customer);
                        current_size++;
                        selected_customers.Add(customer);
                    }
                }
                sizes.Add(current_size);
            }
            while (sizes.Remove(0))
            {
            }

            Genome genome = new Genome();

            genome.Sizes     = sizes.ToArray();
            genome.Customers = customers.ToArray();

            // insert all non-placed customers in the order of the first route.
            foreach (int customer in route1.Customers)
            {
                if (!selected_customers.Contains(customer))
                {
                    // try reinsertion.
                    CheapestInsertionResult result = new CheapestInsertionResult();
                    result.Increase = float.MaxValue;

                    int target_idx = -1;
                    for (int idx = 0; idx < genome.Sizes.Length; idx++)
                    {
                        IRoute route = genome.Route(idx);

                        if (genome.Sizes[idx] > 0)
                        {
                            CheapestInsertionResult current_result =
                                CheapestInsertionHelper.CalculateBestPlacement(solver.Problem.Weights, route, customer);
                            if (current_result.Increase < result.Increase)
                            {
                                target_idx = idx;
                                result     = current_result;

                                if (result.Increase <= 0)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    // insert the customer.
                    for (int idx = 0; idx < customers.Count; idx++)
                    {
                        if (customers[idx] == result.CustomerBefore)
                        {
                            if (customers.Count - 1 == idx)
                            {
                                customers.Add(customer);
                            }
                            else
                            {
                                customers.Insert(idx + 1, customer);
                            }
                            break;
                        }
                    }

                    // set the mutated.
                    genome.Sizes[target_idx] = genome.Sizes[target_idx] + 1;
                    genome.Customers         = customers.ToArray();
                }
            }

            if (!genome.IsValid())
            {
                throw new Exception();
            }
            List <Genome> genomes = new List <Genome>();

            genomes.Add(genome);
            Individual <List <Genome>, Problem, Fitness> individual = new Individual <List <Genome>, Problem, Fitness>(genomes);

            //individual.Initialize();
            return(individual);
        }
Ejemplo n.º 55
0
 /// <summary>
 /// Enables the route, allowing it to be invoked during routing
 /// </summary>
 public static void Enable(this IRoute route)
 {
     route.Enabled = true;
 }
Ejemplo n.º 56
0
        /// <summary>
        /// Try and merge route2 into route1.
        /// </summary>
        /// <param name="problem"></param>
        /// <param name="solution"></param>
        /// <param name="route1_idx"></param>
        /// <param name="route2_idx"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        private MergeResult TryMerge(MaxTimeProblem problem, MaxTimeSolution solution,
                                     int route1_idx, int route2_idx, double max)
        {
            // get the route weights.
            double route1_weight = solution[route1_idx];
            double route2_weight = solution[route2_idx];

            // creates a result.
            MergeResult result = new MergeResult();

            result.Weight = double.MaxValue;

            // get the two routes.
            IRoute route1 = solution.Route(route1_idx);
            IRoute route2 = solution.Route(route2_idx);

            // just first do the case where both routes are of zero length.
            if (route1.Count == 1 && route2.Count == 1)
            { // calculate the increase when joining the two points.
                foreach (int customer1 in route1)
                {
                    foreach (int customer2 in route2)
                    {
                        double difference = problem.WeightMatrix[customer1][customer2] +
                                            problem.WeightMatrix[customer2][customer1];
                        double new_route_weight = route1_weight + difference + route2_weight;
                        if (new_route_weight < max)
                        {
                            result.Weight               = difference;
                            result.RouteSourceId        = route2_idx;
                            result.RouteTargetId        = route1_idx;
                            result.CustomerSourceSource = customer2;
                            result.CustomerSourceTarget = customer2;
                            result.CustomerTargetSource = customer1;

                            return(result);
                        }
                    }
                }
            }

            foreach (Edge route1_edge in route1.Edges())
            { // loop over all route1 edges.
                // calculate weight of the current edge.
                double route1_edge_weight  = problem.WeightMatrix[route1_edge.From][route1_edge.To];
                double route1_edge_without = route1_weight - route1_edge_weight;

                if (route2.Count == 1)
                { // there is only one customer.
                    foreach (int customer2 in route2)
                    {
                        //// calculate weight of the current edge.
                        //double route2_edge_weight = problem.WeightMatrix[route2_edge.From][route2_edge.To];
                        //double route2_edge_without = route2_weight - route2_edge_weight;

                        double new_edges_weight = problem.WeightMatrix[route1_edge.From][customer2] +
                                                  problem.WeightMatrix[customer2][route1_edge.To];

                        double difference = problem.WeightDifferenceAfterMerge(solution,
                                                                               new_edges_weight - (route1_edge_weight));

                        // check if the max bound is not violated.
                        double new_route_weight = route1_edge_without + difference + route2_weight; // the customer remain the same.
                        if (new_route_weight < max)
                        {
                            // the difference is smaller than the current result.
                            if (difference < result.Weight)
                            {
                                result.Weight               = difference;
                                result.RouteSourceId        = route2_idx;
                                result.RouteTargetId        = route1_idx;
                                result.CustomerSourceSource = customer2;
                                result.CustomerSourceTarget = customer2;
                                result.CustomerTargetSource = route1_edge.From;
                            }
                        }
                    }
                }
                else
                {     // there is at least one edge.
                    foreach (Edge route2_edge in route2.Edges())
                    { // loop over all route2 edges.
                        // calculate weight of the current edge.
                        double route2_edge_weight  = problem.WeightMatrix[route2_edge.From][route2_edge.To];
                        double route2_edge_without = route2_weight - route2_edge_weight;

                        double new_edges_weight = problem.WeightMatrix[route1_edge.From][route2_edge.To] +
                                                  problem.WeightMatrix[route2_edge.From][route1_edge.To];

                        double difference = problem.WeightDifferenceAfterMerge(solution,
                                                                               new_edges_weight - (route1_edge_weight + route2_edge_weight));

                        // check if the max bound is not violated.
                        double new_route_weight = route1_edge_weight + route2_edge_without + new_edges_weight; // the customer remain the same.
                        if (new_route_weight < max)
                        {
                            // the difference is smaller than the current result.
                            if (difference < result.Weight)
                            {
                                result.Weight               = difference;
                                result.RouteSourceId        = route2_idx;
                                result.RouteTargetId        = route1_idx;
                                result.CustomerSourceSource = route2_edge.To;
                                result.CustomerSourceTarget = route2_edge.From;
                                result.CustomerTargetSource = route1_edge.From;
                            }
                        }
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 57
0
        /// <summary>
        /// Calculates a solution.
        /// </summary>
        /// <param name="problem"></param>
        /// <returns></returns>
        internal override MaxTimeSolution Solve(MaxTimeProblem problem)
        {
            // create the calculator.
            MaxTimeCalculator calculator = new MaxTimeCalculator(problem);

            // create the solution.
            MaxTimeSolution solution = new MaxTimeSolution(problem.Size, true);

            double max = problem.Max.Value;

            // keep placing customer until none are left.
            List <int> customers = new List <int>(problem.Customers);

            // create n routes.
            for (int customer = 0; customer < customers.Count; customer++)
            {
                solution.Add(customer);
                solution[solution.Count - 1] = calculator.CalculateOneRouteIncrease(
                    0, 0);
            }

            // creates a result.
            MergeResult result = new MergeResult();

            result.Weight = double.MaxValue;

            // loop over all route pairs and merge the smallest merge.
            while (result != null)
            { // keep looping until there is no result anymore.
                result        = new MergeResult();
                result.Weight = double.MaxValue;

                for (int route1_idx = 1; route1_idx < solution.Count; route1_idx++)
                {         // keep looping over all routes.
                    for (int route2_idx = 0; route2_idx < solution.Count; route2_idx++)
                    {     // keep looping over all routes.
                        if (route1_idx == route2_idx)
                        { // only consider different routes.
                            break;
                        }

                        // calculate the merge result.
                        MergeResult current_result = this.TryMerge(problem, solution,
                                                                   route1_idx, route2_idx, problem.Max.Value);

                        // evaluate the current result.
                        if (current_result != null && current_result.Weight < result.Weight)
                        { // current result is best.
                            result = current_result;
                        }
                    }
                }

                // evaluate the result.
                if (result.Weight < double.MaxValue)
                { // there is a result; apply it!
                    IRoute source = solution.Route(result.RouteSourceId);
                    IRoute target = solution.Route(result.RouteTargetId);

                    //string source_string = source.ToString();
                    //string target_string = target.ToString();

                    if (target.Count > 1 && target.First == target.GetNeigbours(result.CustomerTargetSource)[0])
                    {
                        //throw new Exception();
                    }

                    // create an enumeration of all customers of source in the correct order.
                    IEnumerable <int> source_between = new List <int>(
                        source.Between(result.CustomerSourceSource, result.CustomerSourceTarget));

                    // insert after the complete source.
                    int previous = result.CustomerTargetSource;
                    int next     = target.GetNeigbours(result.CustomerTargetSource)[0];
                    foreach (int source_customer in source_between)
                    {
                        // insert.
                        target.ReplaceEdgeFrom(previous, source_customer);

                        previous = source_customer; // update previous.
                    }
                    target.ReplaceEdgeFrom(previous, next);

                    // remove the source route.
                    solution.Remove(result.RouteSourceId);
                    solution.RemoveWeight(result.RouteTargetId);

                    // calculate the weight of the new route.
                    solution[result.RouteTargetId] = solution[result.RouteTargetId] + result.Weight +
                                                     solution[result.RouteSourceId];

                    if (!solution.IsValid())
                    {
                        throw new Exception();
                    }
                }
                else
                { // set the result null.
                    result = null;
                }
            }

            return(solution);
        }
Ejemplo n.º 58
0
 public IRouter Register(IRoute route)
 {
     AppendRoutingTable(route);
     return(this);
 }
Ejemplo n.º 59
0
        public UpstreamPathTemplate Create(IRoute route)
        {
            var upstreamTemplate = route.UpstreamPathTemplate;

            var placeholders = new List <string>();

            for (var i = 0; i < upstreamTemplate.Length; i++)
            {
                if (IsPlaceHolder(upstreamTemplate, i))
                {
                    var postitionOfPlaceHolderClosingBracket = upstreamTemplate.IndexOf('}', i);
                    var difference      = postitionOfPlaceHolderClosingBracket - i + 1;
                    var placeHolderName = upstreamTemplate.Substring(i, difference);
                    placeholders.Add(placeHolderName);

                    //hack to handle /{url} case
                    if (ForwardSlashAndOnePlaceHolder(upstreamTemplate, placeholders, postitionOfPlaceHolderClosingBracket))
                    {
                        return(new UpstreamPathTemplate(RegExForwardSlashAndOnePlaceHolder, 0, false, route.UpstreamPathTemplate));
                    }
                }
            }

            var containsQueryString = false;

            if (upstreamTemplate.Contains("?"))
            {
                containsQueryString = true;
                upstreamTemplate    = upstreamTemplate.Replace("?", "\\?");
            }

            for (int i = 0; i < placeholders.Count; i++)
            {
                var indexOfPlaceholder      = upstreamTemplate.IndexOf(placeholders[i]);
                var indexOfNextForwardSlash = upstreamTemplate.IndexOf("/", indexOfPlaceholder);
                if (indexOfNextForwardSlash < indexOfPlaceholder || (containsQueryString && upstreamTemplate.IndexOf("?") < upstreamTemplate.IndexOf(placeholders[i])))
                {
                    if (upstreamTemplate[indexOfPlaceholder - 1] == '/')
                    {
                        upstreamTemplate = upstreamTemplate.Remove(indexOfPlaceholder - 1, 1);
                        upstreamTemplate = upstreamTemplate.Replace(placeholders[i], RegExMatchLastPlaceHolderZeroOrMoreOfEverything);
                    }
                    else
                    {
                        upstreamTemplate = upstreamTemplate.Replace(placeholders[i], RegExMatchOneOrMoreOfEverything);
                    }
                }
                else
                {
                    upstreamTemplate = upstreamTemplate.Replace(placeholders[i], RegExMatchOneOrMoreOfEverythingUntilNextForwardSlash);
                }
            }

            if (upstreamTemplate == "/")
            {
                return(new UpstreamPathTemplate(RegExForwardSlashOnly, route.Priority, containsQueryString, route.UpstreamPathTemplate));
            }

            if (upstreamTemplate.EndsWith("/"))
            {
                upstreamTemplate = upstreamTemplate.Remove(upstreamTemplate.Length - 1, 1) + "(/|)";
            }

            var template = route.RouteIsCaseSensitive
                ? $"^{upstreamTemplate}{RegExMatchEndString}"
                : $"^{RegExIgnoreCase}{upstreamTemplate}{RegExMatchEndString}";

            return(new UpstreamPathTemplate(template, route.Priority, containsQueryString, route.UpstreamPathTemplate));
        }
        public void SetUp()
        {
            _emplRepo               = NSubstitute.Substitute.For <IGenericRepository <Employment> >();
            _logger                 = NSubstitute.Substitute.For <ILogger>();
            _dmzRepoMock            = NSubstitute.Substitute.For <IGenericDmzRepository <Core.DmzModel.DriveReport> >();
            _coordinatesMock        = NSubstitute.Substitute.For <IAddressCoordinates>();
            _masterRepoMock         = NSubstitute.Substitute.For <IGenericRepository <Core.DomainModel.DriveReport> >();
            _driveReportServiceMock = NSubstitute.Substitute.For <IDriveReportService>();
            _rateRepoMock           = NSubstitute.Substitute.For <IGenericRepository <Rate> >();
            _licensePlateRepoMock   = NSubstitute.Substitute.For <IGenericRepository <LicensePlate> >();
            _routeMock              = NSubstitute.Substitute.For <IRoute <RouteInformation> >();
            _routeMock.GetRoute(DriveReportTransportType.Car, new List <Address>()).ReturnsForAnyArgs(new RouteInformation()
            {
                GeoPoints = "geogeo"
            });

            _coordinatesMock.GetAddressFromCoordinates(new Address()).ReturnsForAnyArgs(new Address()
            {
                Latitude     = "1",
                Longitude    = "1",
                StreetName   = "Katrinebjergvej",
                StreetNumber = "93B",
                ZipCode      = 8200,
                Town         = "Aarhus N"
            });

            _dmzRepoMock.WhenForAnyArgs(x => x.Delete(new Core.DmzModel.DriveReport())).Do(p => _dmzReportList.Remove(p.Arg <Core.DmzModel.DriveReport>()));

            _driveReportServiceMock.WhenForAnyArgs(x => x.Create(new Core.DomainModel.DriveReport())).Do(rep => _masterReportList.Add(rep.Arg <Core.DomainModel.DriveReport>()));

            _dmzRepoMock.WhenForAnyArgs(x => x.Insert(new Core.DmzModel.DriveReport())).Do(t => _dmzReportList.Add(t.Arg <Core.DmzModel.DriveReport>()));

            _rateRepoMock.AsQueryable().ReturnsForAnyArgs(new List <Rate>()
            {
                new Rate()
                {
                    Id     = 1,
                    KmRate = 12,
                    Active = true,
                    Year   = 2015,
                    Type   = new RateType()
                    {
                        Id = 1,
                        RequiresLicensePlate = true,
                        TFCode      = "1234",
                        Description = "TestDescription"
                    }
                }
            }.AsQueryable());

            _licensePlateRepoMock.AsQueryable().ReturnsForAnyArgs(new List <LicensePlate>()
            {
                new LicensePlate()
                {
                    Id          = 1,
                    PersonId    = 1,
                    Plate       = "TestPlate",
                    IsPrimary   = true,
                    Description = "TestDesc",
                }
            }.AsQueryable());

            _dmzReportList = new List <DriveReport>()
            {
                new DriveReport()
                {
                    Id                = 1,
                    Purpose           = "Test",
                    StartsAtHome      = false,
                    EndsAtHome        = false,
                    ManualEntryRemark = "ManualEntry",
                    Date              = "2015-05-27",
                    EmploymentId      = 1,
                    ProfileId         = 1,
                    RateId            = 1,
                    Profile           = new Profile()
                    {
                        FullName = "Test Testesen [TT]"
                    },
                    Route = new Route()
                    {
                        Id             = 1,
                        GPSCoordinates = new List <GPSCoordinate>()
                        {
                            new GPSCoordinate()
                            {
                                Latitude  = StringCipher.Encrypt("1", Encryptor.EncryptKey),
                                Longitude = StringCipher.Encrypt("1", Encryptor.EncryptKey),
                            },
                            new GPSCoordinate()
                            {
                                Latitude  = StringCipher.Encrypt("2", Encryptor.EncryptKey),
                                Longitude = StringCipher.Encrypt("2", Encryptor.EncryptKey),
                            }
                        }
                    }
                },
                new DriveReport()
                {
                    Id                = 2,
                    Purpose           = "Test2",
                    StartsAtHome      = true,
                    EndsAtHome        = true,
                    ManualEntryRemark = "ManualEntry",
                    Date              = "2015-05-26",
                    EmploymentId      = 1,
                    ProfileId         = 1,
                    RateId            = 1,
                    Profile           = new Profile()
                    {
                        FullName = "Test Testesen [TT]"
                    },
                    Route = new Route()
                    {
                        Id             = 2,
                        GPSCoordinates = new List <GPSCoordinate>()
                        {
                            new GPSCoordinate()
                            {
                                Latitude  = StringCipher.Encrypt("1", Encryptor.EncryptKey),
                                Longitude = StringCipher.Encrypt("1", Encryptor.EncryptKey),
                            },
                            new GPSCoordinate()
                            {
                                Latitude  = StringCipher.Encrypt("2", Encryptor.EncryptKey),
                                Longitude = StringCipher.Encrypt("2", Encryptor.EncryptKey),
                            }
                        }
                    }
                }
            };

            _masterRepoMock.AsQueryable().ReturnsForAnyArgs(_masterReportList.AsQueryable());
            _dmzRepoMock.AsQueryable().ReturnsForAnyArgs(_dmzReportList.AsQueryable());

            _uut = new DriveReportSyncService(_dmzRepoMock, _masterRepoMock, _rateRepoMock, _licensePlateRepoMock, _driveReportServiceMock, _routeMock, _coordinatesMock, _emplRepo, _logger);
        }