private bool CalculateRoute(RoutePath path, string httpMethod, RouteBuilder route, RouteNode node) { using (path.Pin()) using (var pin = route.Pin()) { if (node.Part.AcceptPath(path, httpMethod)) { route.Add(node.Part); if (node.Children.Any()) { foreach (var child in node.Children) { if (CalculateRoute(path, httpMethod, route, child)) { pin.Accept(); return true; } } } else if (!path.Any()) { pin.Accept(); return true; } } return false; } }
/// <summary> /// The run. /// </summary> /// <param name="requestId"> /// The request identifier. /// </param> /// <param name="routePath"> /// The route path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="postData"> /// The post data. /// </param> /// <param name="requestData"> /// Raw json request data. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> /// <exception cref="Exception"> /// Generic exception - Route path not valid. /// </exception> public static ChromelyResponse Run(string requestId, RoutePath routePath, object parameters, object postData, string requestData) { var response = new ChromelyResponse(requestId); if (string.IsNullOrEmpty(routePath.Path)) { response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.BadRequest; response.StatusText = "Bad Request"; return(response); } if (routePath.Path.ToLower().Equals("/info")) { response = GetInfo(); return(response); } var route = ServiceRouteProvider.GetRoute(routePath); if (route == null) { throw new Exception($"Route for path = {routePath} is null or invalid."); } return(ExcuteRoute(requestId, routePath, parameters, postData, requestData)); }
public static List<RoutePath> LoadAllRoutes() { var routeFiles = new List<RoutePath>(); var fileList = Directory.GetFiles(Options.workingDirectory + "\\Routes"); foreach (string filename in fileList) { // Reasds the CSV using the method in this class. // The 'false' argument prevents readCSV from adding the directory path, // as it is already in the filename string. var splitCsv = readCSV(filename, true); // Splitting the name of the route file to get the two parts to process var routeNameParts = Path.GetFileName(filename).Split('.'); // Initialise a new route RoutePath thisRoute = new RoutePath(); // Setting the route name and sub-route from the filename thisRoute.routeName = routeNameParts[0]; thisRoute.subRoute = routeNameParts[1]; foreach (var line in splitCsv) { var point = new PointF(); point.Y = float.Parse(line[0]); point.X = float.Parse(line[1]); thisRoute.points.Add(Geometry.CoordsToMapPoint(point)); } routeFiles.Add(thisRoute); } return routeFiles; }
public bool AcceptPath(RoutePath path, string httpMethod) { var requiredHttpMethod = RequiredHttpMethod; if (requiredHttpMethod != null && httpMethod != (string)requiredHttpMethod) return false; return Accept(path); }
/// <summary> /// The run. /// </summary> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> /// <exception cref="Exception"> /// Generic exception - Route path not valid. /// </exception> public static ChromelyResponse Run(CefRequest request) { var uri = new Uri(request.Url); string path = uri.LocalPath; var response = new ChromelyResponse(); if (string.IsNullOrEmpty(path)) { response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.BadRequest; response.StatusText = "Bad Request"; return(response); } if (path.ToLower().Equals("/info")) { response = GetInfo(); return(response); } var routePath = new RoutePath(request.Method, path); var route = ServiceRouteProvider.GetRoute(routePath); if (route == null) { throw new Exception($"Route for path = {path} is null or invalid."); } var parameters = request.Url.GetParameters(); var postData = GetPostData(request); return(ExcuteRoute(string.Empty, routePath, parameters, postData, string.Empty)); }
public virtual void ProcessData(RoutePath path, RouteData data) { ConsumePath(path); foreach (var item in RouteData) { data[item.Key] = item.Value; } }
/// <summary> /// The post json. /// </summary> /// <param name="path"> /// The route path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="postData"> /// The post data. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public string PostJson(string path, object parameters, object postData) { var routePath = new RoutePath(Method.POST, path); var chromelyResponse = RequestTaskRunner.Run(string.Empty, routePath, parameters, postData); string jsonResponse = chromelyResponse.EnsureJson(); return(jsonResponse); }
/// <summary> /// The get json. /// </summary> /// <param name="path"> /// The route path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <returns> /// The <see cref="string"/>. /// </returns> public string GetJson(string path, object parameters) { var routePath = new RoutePath(Method.GET, path); var chromelyResponse = RequestTaskRunner.Run(string.Empty, routePath, parameters, null); string jsonResponse = chromelyResponse.EnsureJson(); return(jsonResponse); }
private IEnumerator WaitForPassengers(float waitTime) { yield return(new WaitForSeconds(waitTime)); _currentTarget.BoardPassengers(); _currentTarget = _airportQueue.Dequeue(); _currentRoute = new RoutePath(_previousTarget.Location, _currentTarget.Location, Speed); }
private void Route_Complete(object sender, CalculateRouteCompletedEventArgs args) { myDrawObject.IsEnabled = true; routeResultsGraphicsLayer.ClearGraphics(); waypointGraphicsLayer.ClearGraphics(); StringBuilder directions = new StringBuilder(); ObservableCollection <RouteLeg> routeLegs = args.Result.Result.Legs; int numLegs = routeLegs.Count; int instructionCount = 0; for (int n = 0; n < numLegs; n++) { if ((n % 2) == 0) { AddStopPoint(mercator.FromGeographic(new MapPoint(routeLegs[n].ActualStart.Longitude, routeLegs[n].ActualStart.Latitude)) as MapPoint); AddStopPoint(mercator.FromGeographic(new MapPoint(routeLegs[n].ActualEnd.Longitude, routeLegs[n].ActualEnd.Latitude)) as MapPoint); } else if (n == (numLegs - 1)) { AddStopPoint(mercator.FromGeographic(new MapPoint(routeLegs[n].ActualEnd.Longitude, routeLegs[n].ActualEnd.Latitude)) as MapPoint); } directions.Append(string.Format("--Leg #{0}--\n", n + 1)); foreach (ItineraryItem item in routeLegs[n].Itinerary) { instructionCount++; directions.Append(string.Format("{0}. {1}\n", instructionCount, item.Text)); } } Regex regex = new Regex("<[/a-zA-Z:]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline); DirectionsContentTextBlock.Text = regex.Replace(directions.ToString(), string.Empty); DirectionsGrid.Visibility = Visibility.Visible; RoutePath routePath = args.Result.Result.RoutePath; Polyline line = new Polyline(); line.Paths.Add(new PointCollection()); foreach (ESRI.ArcGIS.Client.Bing.RouteService.Location location in routePath.Points) { line.Paths[0].Add(mercator.FromGeographic(new MapPoint(location.Longitude, location.Latitude)) as MapPoint); } Graphic graphic = new Graphic() { Geometry = line, Symbol = LayoutRoot.Resources["RoutePathSymbol"] as Symbol }; routeResultsGraphicsLayer.Graphics.Add(graphic); }
protected override bool Accept(RoutePath path) { if (path.Current != null && path.Current.Equals(Literal, StringComparison.OrdinalIgnoreCase)) { path.Consume(); return true; } return false; }
protected override bool Accept(RoutePath path) { if (path.Current != null) { path.ConsumeAll(); return true; } return false; }
public override void ProcessData(RoutePath path, RouteData data) { base.ProcessData(path, data); var part = path.Consume(); part = HttpUtility.UrlDecode(part); var value = Convert.ChangeType(part, Parameter.ParameterType); data[Parameter.Name] = value; }
public Task <ChromelyResponse> RunAsync(string requestId, RoutePath routePath, IDictionary <string, string> parameters, object postData, string requestData) { if (routePath == null || string.IsNullOrWhiteSpace(routePath?.Path)) { return(Task.FromResult(GetBadRequestResponse(null))); } return(ExcuteRouteAsync(routePath, parameters, postData, requestId)); }
public static ActionRoute GetActionRoute(IChromelyContainer container, RoutePath routePath) { object routeObj = container.GetInstance(typeof(ActionRoute), routePath.Key); if ((routeObj == null) || !(routeObj is ActionRoute)) { throw new Exception($"No route found for method:{routePath.Method} route path:{routePath.Path}."); } return (ActionRoute)routeObj; }
public static ActionRoute GetActionRoute(IChromelyContainer container, RoutePath routePath) { var route = container.GetInstance(typeof(ActionRoute), routePath.Key) as ActionRoute; if (route == null) { throw new Exception($"No route found for method:{routePath.Method} route path:{routePath.Path}."); } return(route); }
public static bool IsActionRouteAsync(IChromelyContainer container, RoutePath routePath) { try { var route = container.GetInstance(typeof(ActionRoute), routePath.Key) as ActionRoute; return(route == null ? false : route.IsAsync); } catch {} return(false); }
/// <summary> /// The get route. /// </summary> /// <param name="routePath"> /// The route path. /// </param> /// <returns> /// The <see cref="Route"/>. /// </returns> /// <exception cref="Exception"> /// Generic exception - Route Not found. /// </exception> public static Route GetRoute(RoutePath routePath) { object routeObj = IoC.GetInstance(typeof(Route), routePath.Key); if ((routeObj == null) || !(routeObj is Route)) { throw new Exception($"No route found for method:{routePath.Method} route path:{routePath.Path}."); } return((Route)routeObj); }
public ChromelyResponse Run(string method, string path, IDictionary <string, string> parameters, object postData) { var routePath = new RoutePath(method, path); if (string.IsNullOrWhiteSpace(routePath?.Path)) { return(GetBadRequestResponse(null)); } return(ExcuteRoute(routePath, parameters, postData)); }
public async Task <TResult> DispatchAsync <TResult>(MethodInfo method, object[] args) { ServiceAttribute attribute = method.DeclaringType.GetCustomAttribute <ServiceAttribute>(); OwinRequest request = new OwinRequest() { Path = RoutePath.Parse(method), Parameters = args, Group = string.IsNullOrWhiteSpace(attribute.Group) ? method.DeclaringType.Assembly.GetName().Name : attribute.Group }; return(await this.SendAsync <TResult>(request)); }
/// <summary> /// Dispatches the plane on a flight (if not dispatched already) /// </summary> public void Dispatch() { if (!IsDispatched) { IsDispatched = true; FillQueue(); _previousTarget = _flightPlan[0]; _currentTarget = _airportQueue.Dequeue(); transform.position = _flightPlan[0].Location.ToSphericalCartesian(); _currentRoute = new RoutePath(_previousTarget.Location, _currentTarget.Location, Speed); gameObject.SetActive(true); } }
public override bool OnQuery(CefBrowser browser, CefFrame frame, long queryId, string request, bool persistent, CefMessageRouterBrowserSide.Callback callback) { var options = new JsonSerializerOptions(); options.ReadCommentHandling = JsonCommentHandling.Skip; options.AllowTrailingCommas = true; var requestData = JsonSerializer.Deserialize <request>(request, options); var method = requestData.method ?? string.Empty; if (RoutePath.ValidMethod(method)) { var id = requestData.id ?? string.Empty; var path = requestData.url ?? string.Empty; var routePath = new RoutePath(method, path); bool isRequestAsync = ServiceRouteProvider.IsActionRouteAsync(_container, routePath); if (isRequestAsync) { Task.Run(async() => { var parameters = requestData.parameters; var postData = requestData.postData; var response = await _requestTaskRunner.RunAsync(id, routePath, parameters, postData, request); var jsonResponse = response.ToJson(); callback.Success(jsonResponse); }); } else { Task.Run(() => { var parameters = requestData.parameters; var postData = requestData.postData; var response = _requestTaskRunner.Run(id, routePath, parameters, postData, request); var jsonResponse = response.ToJson(); callback.Success(jsonResponse); }); } return(true); } callback.Failure(100, "Request is not valid."); return(false); }
/// <summary> /// The get json. /// </summary> /// <param name="path"> /// The route path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="javascriptCallback"> /// The javascript callback. /// </param> public void GetJson(string path, object parameters, IJavascriptCallback javascriptCallback) { Task.Run(async() => { using (javascriptCallback) { var routePath = new RoutePath(Method.GET, path); var chromelyResponse = await RequestTaskRunner.RunAsync(string.Empty, routePath, parameters, null); string jsonResponse = chromelyResponse.EnsureJson(); var response = new CallbackResponseStruct(jsonResponse); await javascriptCallback.ExecuteAsync(response); } }); }
protected override bool Accept(RoutePath path) { foreach (var constraint in Constraints) { if (!constraint.Accept(path)) return false; } if (path.Current != null) { path.Consume(); return true; } return false; }
public void GenerateRoutesForController(RouteTree routeTree, Type controllerType) { var routeAttributes = controllerType.GetCustomAttributes(typeof(RouteAttribute), true); var routeAttribute = routeAttributes.Length > 0 ? (RouteAttribute)routeAttributes[0] : null; string route; if (routeAttribute == null) route = GenerateDefaultRouteForController(controllerType); else route = routeAttribute.Value; var routePath = new RoutePath(route); var currentNode = (IRouteNode)routeTree; var leafNodes = new List<RouteNode>(); do { RouteNode nextNode = null; if (routePath.Current != null) { var routePart = routePath.Consume(); var part = new RouteLiteral(routePart, true); nextNode = new RouteNode(part); AddNode(currentNode, nextNode); if (routePath.Current == null) { part.RouteData[RouteData.ControllerKey] = controllerType; leafNodes.Add(nextNode); } } // If defined as a default route, then we don't require the last path part if (routePath.Current == null) { var defaultAttributes = controllerType.GetCustomAttributes(typeof(DefaultAttribute), true); if (defaultAttributes.Length > 0) { var defaultNode = new RouteNode(new RouteDefault(RouteData.ControllerKey, controllerType)); AddNode(currentNode, defaultNode); leafNodes.Add(defaultNode); } } currentNode = nextNode; } while (routePath.Current != null); foreach (var method in controllerType.GetMethods().Where(x => x.IsPublic && !x.IsStatic && (typeof(ActionResult).IsAssignableFrom(x.ReturnType) || typeof(Task<ActionResult>).IsAssignableFrom(x.ReturnType)))) { GenerateRoutesForAction(routeTree, controllerType, leafNodes, method); } }
public void Clear() { if (RoutePath != null) { RoutePath.Clear(); } Helpers.Clear(); RoutePushpins.Clear(); ItineraryItems.Clear(); DrivePathDistance = 0.0; waypoints.Clear(); waypointIndex = 0; RaiseSearchPushpinsChanged(0); RaisePropertyChanged("Waypoints"); }
private IRoutePart[] CalculateRoute(string path, string httpMethod) { var routePath = new RoutePath(path); var route = new RouteBuilder(); foreach (var node in RootPaths) { if (CalculateRoute(routePath, httpMethod, route, node)) { return route.ToArray(); } } return null; }
private async Task <ChromelyResponse> ExcuteRouteAsync(RoutePath routePath, object parameters, object postData, string requestId = null) { object result = null; var status = 200; var statusText = "OK"; try { var requestContext = GetRequestContext(routePath.Method, routePath.Path, requestId); var action = _actionBuilder.BuildAction(requestContext); var arguments = BindParameters(action, requestContext, parameters, postData); if (action.IsAsync) { result = await action.InvokeAsync(arguments); if (result != null) { var resultType = result.GetType(); if (resultType.Name == "VoidTaskResult") { result = null; } } } else { result = action.Invoke(arguments); } } catch (Exception e) { result = e.Message; status = 500; statusText = "Server Error"; } return(new ChromelyResponse() { ReadyState = (int)ReadyState.ResponseIsReady, Status = status, StatusText = (string.IsNullOrWhiteSpace(statusText) && (status == (int)HttpStatusCode.OK)) ? "OK" : statusText, Data = result }); }
private void ArriveAtTarget() { _previousTarget = _currentTarget; _currentRoute = null; if (_currentTarget == null) { Debug.Log("Can't arrive at null."); return; } if (_airportQueue.Count == 0) { FillQueue(); } StartCoroutine(WaitForPassengers(1)); }
public IActionResult setRoutePath([FromBody] RoutePath newRoutePath) { string errorString = null; try { newRoutePath.CreatedByUserId = Int32.Parse(User.Claims.FirstOrDefault(x => x.Type.Equals("UserId")).Value); RoutePathModel RoutePathModel = new RoutePathModel(); newRoutePath.RoutePathId = RoutePathModel.AddNewRoutePath(newRoutePath, out errorString); return(new JsonResult(newRoutePath.RoutePathId)); } catch (Exception e) { return(Ok(e + "\n" + errorString)); } }
private ChromelyResponse ExecuteRoute(string requestId, RoutePath routePath, IDictionary <string, string> parameters, object postData, string requestData) { var route = ServiceRouteProvider.GetActionRoute(_container, routePath); if (route == null) { throw new Exception($"Route for path = {routePath} is null or invalid."); } var response = route.Invoke(requestId: requestId, routePath: routePath, parameters: parameters, postData: postData, rawJson: requestData); response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.OK; response.StatusText = "OK"; return(response); }
/// <summary> /// The excute route. /// </summary> /// <param name="requestId"> /// The request identifier. /// </param> /// <param name="routePath"> /// The route path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="postData"> /// The post data. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> /// <exception cref="Exception"> /// Generic exception - Route path not valid. /// </exception> private static ChromelyResponse ExcuteRoute(string requestId, RoutePath routePath, object parameters, object postData) { var route = ServiceRouteProvider.GetRoute(routePath); if (route == null) { throw new Exception($"Route for path = {routePath} is null or invalid."); } var response = route.Invoke(requestId, routePath, parameters?.ToObjectDictionary(), postData); response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.OK; response.StatusText = "OK"; return(response); }
public IActionResult GetHeritageAnalysisBestRoute(long id) { //filter contact records by contact id var item = _context.HeritageGameAnalyses .FirstOrDefault(t => t.Id == id); if (item == null) { return(NotFound()); } var itemDto = _mapper.Map <HeritageGameAnalysisDto> (item); RoutePath bestRoute = CalculateBestRoute(itemDto); return(Ok(bestRoute)); }
public IActionResult UpdateRoutePath([FromBody] RoutePath newRoutePath) { string errorString = null; try { newRoutePath.UpdatedByUserId = Int32.Parse(User.Claims.FirstOrDefault(x => x.Type.Equals("UserId")).Value); RoutePathModel routePathModel = new RoutePathModel(); newRoutePath.Updated = DateTime.Now; newRoutePath.RoutePathId = routePathModel.UpdateRoutePathByRoutePathId(newRoutePath, out errorString); return(new JsonResult(newRoutePath)); } catch (Exception e) { return(Ok(e + "\n" + errorString)); } }
/// <summary> /// The run. /// </summary> /// <param name="request"> /// The request. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> /// <exception cref="Exception"> /// Generic exception - Route path not valid. /// </exception> public static ChromelyResponse Run(IRequest request) { var isCustomScheme = UrlSchemeProvider.IsUrlOfRegisteredCustomScheme(request.Url); if (!isCustomScheme) { throw new Exception($"Url {request.Url} is not of a registered custom scheme."); } var uri = new Uri(request.Url); var path = uri.LocalPath; var parameters = request.Url.GetParameters(); var postData = GetPostData(request); var routePath = new RoutePath(request.Method, path); return(Run(string.Empty, routePath, parameters, postData)); }
public void AddRoute(GeoPoint a, GeoPoint b) { int r = _routes; SetRoutes(_routes + 1); List <Vector3> vertices = new List <Vector3>(); float distance = 0.0f; RoutePath.BuildPath(a, b, _iterations, ref vertices, ref distance); _totalDistance += distance; for (int i = 0; i < vertices.Count; i++) { _lineRenderer.SetPosition(r * (_iterations + 1) + i, vertices[i]); } }
public void ApplyRoutePath(BlockGroup blockGroup, RoutePath routePath) { Vector3i[] offsets = { new Vector3i(0, 0, 1), new Vector3i(0, 0, -1), new Vector3i(1, 0, 0), new Vector3i(-1, 0, 0), }; foreach (var panel in this.panels) { panel.paths = new List <FieldPanel>(); for (int i = 0; i < 4; i++) { Vector3i key = panel.position + offsets[i]; // 隣接のセルを探す var neighbourPanels = this.panels.FindAll(delegate(FieldPanel a) { return(a.position.x == key.x && a.position.z == key.z); }); foreach (var target in neighbourPanels) { if (panel.CanMoveTo(target, blockGroup)) { panel.paths.Add(target); } } } var paths = routePath.FindPaths(panel.originalPosition); foreach (var path in paths) { foreach (var target in this.panels) { if (target.originalPosition == path) { panel.paths.Add(target); } } } } }
public RouteData Apply(string path, string method) { path = path.ChopEnd("/"); var routePath = new RoutePath(path.ToLower()); var route = CalculateRoute(path, method); if (route == null) { throw new InvalidOperationException("Could not apply the URL path '" + path + "'. No route supports this path."); } var routeData = new RouteData(); routePath = new RoutePath(path); foreach (var part in route) { part.ProcessData(routePath, routeData); } return routeData; }
/// <summary> /// The run. /// </summary> /// <param name="requestId"> /// The request identifier. /// </param> /// <param name="routePath"> /// The route path. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="postData"> /// The post data. /// </param> /// <returns> /// The <see cref="ChromelyResponse"/>. /// </returns> public static ChromelyResponse Run(string requestId, RoutePath routePath, object parameters, object postData) { var response = new ChromelyResponse(requestId); if (string.IsNullOrEmpty(routePath.Path)) { response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.BadRequest; response.StatusText = "Bad Request"; return(response); } if (routePath.Path.ToLower().Equals("/info")) { return(GetInfo()); } return(ExcuteRoute(requestId, routePath, parameters, postData)); }
public ChromelyResponse Run(string requestId, RoutePath routePath, IDictionary <string, string> parameters, object postData, string requestData) { if (string.IsNullOrEmpty(routePath.Path)) { return(GetBadRequestResponse(requestId)); } if (routePath.Path.ToLower().Equals("/info")) { return(GetInfo(requestId)); } var route = ServiceRouteProvider.GetActionRoute(_container, routePath); if (route == null) { throw new Exception($"Route for path = {routePath} is null or invalid."); } return(ExecuteRoute(requestId, routePath, parameters, postData, requestData)); }
/// <summary> /// The run async. /// </summary> /// <param name="routePath"> /// The route routePath. /// </param> /// <param name="parameters"> /// The parameters. /// </param> /// <param name="postData"> /// The post data. /// </param> /// <returns> /// The <see cref="Task"/>. /// </returns> public static Task <ChromelyResponse> RunAsync(RoutePath routePath, object parameters, object postData) { var response = new ChromelyResponse(); if (string.IsNullOrEmpty(routePath.Path)) { response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.BadRequest; response.StatusText = "Bad Request"; return(Task.FromResult(response)); } if (routePath.Path.ToLower().Equals("/info")) { response = GetInfo(); return(Task.FromResult(response)); } response = ExcuteRoute(routePath, parameters, postData); return(Task.FromResult(response)); }
protected override void ConsumePath(RoutePath path) { }
public bool Accept(RoutePath path) { int result; return int.TryParse(path.Current, out result); }
protected virtual void ConsumePath(RoutePath path) { path.Consume(); }
protected abstract bool Accept(RoutePath path);
private void GenerateRoutesForAction(RouteTree routeTree, Type controllerType, List<RouteNode> parentNodes, MethodInfo actionMethod) { var routeAttributes = actionMethod.GetCustomAttributes(typeof(RouteAttribute), true); var routeAttribute = routeAttributes.Length > 0 ? (RouteAttribute)routeAttributes[0] : null; string route; if (routeAttribute == null) route = GenerateDefaultRouteForAction(actionMethod); else route = routeAttribute.Value; string httpMethod = null; if (actionMethod.IsDefined(typeof(HttpPostAttribute), false)) { httpMethod = "POST"; } bool addToRoot = false; if (route.StartsWith("/")) { addToRoot = true; } var effectiveNodes = addToRoot ? new[] { (IRouteNode)routeTree } : parentNodes.ToArray(); foreach (var node in effectiveNodes) { var routePath = new RoutePath(route); var currentNode = node; do { RouteNode nextNode = null; if (routePath.Current != null) { var part = routePath.Consume(); if (part == "@") { part = GenerateDefaultRouteForAction(actionMethod); } RoutePart routePart; if (part == "*") { var parameter = actionMethod.GetParameters().Single(); routePart = new RouteWildcard(parameter); } else if (part.StartsWith("{") && part.EndsWith("}")) { var pieces = part.ChopStart("{").ChopEnd("}").Split(':'); var id = pieces[0]; var parameter = actionMethod.GetParameters().Single(x => x.Name == id); var variable = new RouteVariable(routePath.Current == null, parameter); var constraints = pieces.Skip(1).ToArray(); foreach (var name in constraints) { var constraint = RouteConstraints.GetConstraint(name); variable.Constraints.Add(constraint); } routePart = variable; } else { routePart = new RouteLiteral(part, routePath.Current == null); } nextNode = new RouteNode(routePart); if (routePath.Current == null) { routePart.RouteData[RouteData.ActionKey] = actionMethod; routePart.RouteData[RouteData.ControllerKey] = controllerType; if (httpMethod != null) routePart.RouteData[RouteData.RequiredHttpMethodKey] = httpMethod; } nextNode = AddNode(currentNode, nextNode); } if (routePath.Current == null) { if (actionMethod.IsDefined(typeof(DefaultAttribute), false)) AddNode(currentNode, new RouteNode(new RouteDefault(RouteData.ActionKey, actionMethod))); } currentNode = nextNode; } while (routePath.Current != null); } }
protected override void ConsumePath(RoutePath path) { // Prevent default consume since we're going to consume it ourselves below }
// Adds indexes of where the last and next stops are relative to the routes // Also adds distances private void AddPathInfo(List<RoutePath> routes, List<Bus> buses, List<Stop> stops, List<Route> routeInfo) { foreach (Bus bus in buses) { RoutePath route = new RoutePath(); bool foundRoute = false; int i = 0; do { if (routes[i].subRoute==bus.subRoute && routes[i].routeName==bus.routeName) { foundRoute = true; route = routes[i]; bus.routeIndex = i; } i++; } while (!foundRoute && i < routes.Count); // Find the locations of the last and next stops from the stops file Point lastLoc = stopLocation(stops, bus.lastStop.stopID).location; Point nextLoc = stopLocation(stops, bus.nextStop.stopID).location; // Get the index of the point on the path closest to the last stop bus.lastStopIndex = indexOfClosest(route.points, lastLoc, bus.lastStopIndex); // Repeat for the next stop. Note that a 'begin at' index is passed. // This is so that, for circular routes, an earlier stop isn't used. bus.nextStopIndex = indexOfClosest(route.points, nextLoc, bus.lastStopIndex); double legDistance = 0; // Every line between points of the indexes just calculated for (int j = bus.lastStopIndex; j < bus.nextStopIndex; j++) { // Add the distance of the line to the running total legDistance += Geometry.Distance(route.points[j], route.points[j + 1]); } bus.lengthOfLeg = legDistance; // Get the colour of the route foreach (Route r in routeInfo) { if (r.routeName == bus.routeName) { bus.colour = r.colour; } } } }
/* protected override bool IsDuplicate(IRoutePart part) { return part is RouteDefault; } */ protected override bool Accept(RoutePath path) { // We only want to apply default routes if there's nothing left in the path return path.Current == null; }
public override void ProcessData(RoutePath path, RouteData data) { base.ProcessData(path, data); var s = path.ConsumeAll(); data[parameter.Name] = Convert.ChangeType(s, parameter.ParameterType); }