Ejemplo n.º 1
0
        private void RouteProvider_RoutingCompleted(object sender, RoutingCompletedEventArgs e)
        {
            this.findRouteButton.IsEnabled = true;

            RouteResponse routeResponse = e.Response as RouteResponse;

            if (routeResponse != null &&
                routeResponse.Error == null)
            {
                if (routeResponse.Result != null &&
                    routeResponse.Result.RoutePath != null)
                {
                    PolylineData routeLine = new PolylineData()
                    {
                        Points    = routeResponse.Result.RoutePath.Points,
                        ShapeFill = new MapShapeFill()
                        {
                            Stroke          = new SolidColorBrush(Colors.Red),
                            StrokeThickness = 2
                        }
                    };

                    this.routeLayer.Items.Add(routeLine);
                }
            }
        }
Ejemplo n.º 2
0
        private void CreateTripRoute(Wycieczka newTrip, RouteResponse route)
        {
            var tripRoute = new Odcinek()
            {
                WycieczkaId = newTrip.Id
            };

            if (route.IsCustomRoute())
            {
                var start         = route.Start.ToModel();
                var end           = route.End.ToModel();
                var mountainGroup = _context.GrupaGorska.FirstOrDefault(m => m.Nazwa == route.MountainGroup);
                _context.Update(start);
                _context.Update(end);
                _context.SaveChanges();
                OdcinekWłasny customRoute = new OdcinekWłasny()
                {
                    Punkty      = route.Points,
                    PoczatekId  = start.Id,
                    KoniecId    = end.Id,
                    GrupaGorska = mountainGroup
                };
                _context.OdcinekWłasny.Add(customRoute);
                _context.SaveChanges();
                tripRoute.OdcinekWłasnyId = customRoute.Id;
            }
            else
            {
                tripRoute.OdcinekPunktowanyId = route.Id;
            }

            newTrip.Odcinek.Add(tripRoute);
        }
        private RouteResponse TryRequestRouteResponse()
        {
            Osrm5x        osrm     = new Osrm5x(OsrmServerBaseUrl);
            RouteResponse response = null;

            try
            {
                RouteRequest request = new RouteRequest()
                {
                    Coordinates = OsrmConverter.ConvertGeocoordinatesToLocations(Coordinates).ToArray(),
                    Steps       = true,
                    Alternative = CalculateAlternativeRoutes
                };
                response = osrm.Route(request);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (response != null)
                {
                    Console.WriteLine("Status Code of RouteRequest: " + response.Code);
                }
            }

            return(response);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Draws the walkable route to the spear, if the spear is unavailable
        /// </summary>
        public async void DrawWalkableRouteToSpear(Location playerLocation, Location spearLocation)
        {
            if (DirManager == null)
            {
                DirManager = Map.DirectionsManager;
            }
            DirManager.Waypoints.Clear();

            DirManager.Waypoints.Add(new Waypoint(playerLocation));
            DirManager.Waypoints.Add(new Waypoint(spearLocation));


            DirManager.RequestOptions.RouteMode = RouteModeOption.Walking;
            DirManager.RequestOptions.Optimize  = OptimizeOption.Walking;

            //Do something with the distance

            RouteResponse response = await DirManager.CalculateDirectionsAsync();

            // not sure if merge conflict or not
            DirManager.RenderOptions.WaypointPushpinOptions.Visible = false;


            SpearHandler.Score.Distance = response.Routes[0].TravelDistance * 1000;
            SpearHandler.PropertyChanged(); //Manual f*** you to binding.

            if (response.HasError)
            {
                await SatanController.ShowMessageAsync("Route error", "The route could not be calculated.");
            }
            DirManager.ShowRoutePath(DirManager.ActiveRoute);
        }
Ejemplo n.º 5
0
        public async Task <RouteResponse> PatchRouteByIdentiferAsync(RouteIdentifier identifier, IDictionary <string, object> values)
        {
            // We'll get the intersection of known valid property names, to the incoming property
            // names, as this will get us a list of only valid incoming property keys.
            var userId = User.GetUserId();
            var route  = await _routeRepository.GetRouteByIdentifierAsync(identifier, userId);

            var validProperties = new List <string> {
                "owner", "uri", "title", "type", "code", "isOnline"
            };

            // Allow the IsDefault property to be set if the user is an admin.
            if (User.IsAdmin())
            {
                validProperties.Add("isDefault");
            }

            var selectedProperties = values.Keys.Intersect(validProperties);

            // Only set allowed properties using reflection and type coersion. We proper-case the
            // name because our serializer automatically camel-cases json property names.
            foreach (var property in selectedProperties)
            {
                route.SetProperty(property.ToProperCase(), values[property]);
            }

            // Update server properties.
            route.IsCurrent = false;
            route           = await _routeRepository.UpdateRouteAsync(route, userId);

            return(RouteResponse.Map(route));
        }
        public async Task <IHttpActionResult> PostPublishAsync(RouteIdentifier identifier)
        {
            // Load route to get source code.
            var route = await _routeRepository.GetRouteByIdentifierAsync(identifier);

            var code = route.Code;

            // Compile code and get assembly as byte array.
            var compilationResult = _compilationService.Compile(code);

            // We'll save the assembly and mark the route as published if the compilation was successful.
            if (compilationResult.Success)
            {
                route.Assembly    = compilationResult.Assembly;
                route.IsCurrent   = true;
                route.IsOnline    = true;
                route.PublishedOn = DateTimeOffset.UtcNow;

                route = await _routeRepository.UpdateRouteAsync(route);
            }

            var result = new PublishResponse
            {
                Compilation = compilationResult,
                Route       = RouteResponse.Map(route)
            };

            // Return an error response if compile was unsuccessful, otherwise the response was successful.
            return(Content(compilationResult.Success ? HttpStatusCode.OK : HttpStatusCode.InternalServerError, result));
        }
Ejemplo n.º 7
0
        public async Task <RouteResponse> GetRouteByIdentiferAsync(RouteIdentifier identifier)
        {
            var userId = User.GetUserId();
            var route  = await _routeRepository.GetRouteByIdentifierAsync(identifier, userId);

            return(RouteResponse.Map(route));
        }
        public void GenerateUsefulRouteResponse_MultipleRoutes_AllRoutesConvertedCorrectly()
        {
            // Arrange
            RouteResponse OldRouteFormat = new RouteResponse {
                Routes = new List <Route> {
                    GetRoute1(), GetRoute2()
                }
            };

            // Act
            List <UsefulRouteResponse> actualResult = RoutingController.GenerateUsefulRouteResponse(OldRouteFormat);

            // Assert
            Assert.Equal(2, actualResult.Count);

            for (int focusedResponseIndex = 0; focusedResponseIndex < Route1And2ExpectedOutcome.Count; focusedResponseIndex++)
            {
                Assert.Equal(Route1And2ExpectedOutcome[focusedResponseIndex].TravelTimeInSeconds, actualResult[focusedResponseIndex].TravelTimeInSeconds);
                Assert.Equal(Route1And2ExpectedOutcome[focusedResponseIndex].Distance, actualResult[focusedResponseIndex].Distance);

                for (int focusedPointIndex = 0; focusedPointIndex < actualResult[0].Points.Count; focusedPointIndex++)
                {
                    Assert.Equal(Route1And2ExpectedOutcome[focusedResponseIndex].Points[focusedPointIndex].Latitude, actualResult[focusedResponseIndex].Points[focusedPointIndex].Latitude);
                    Assert.Equal(Route1And2ExpectedOutcome[focusedResponseIndex].Points[focusedPointIndex].Longitude, actualResult[focusedResponseIndex].Points[focusedPointIndex].Longitude);
                }
            }
        }
Ejemplo n.º 9
0
        public RouteResponse CC(ControlCommand command)
        {
            //serialize message
            string serialized = JsonConvert.SerializeObject(command, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            });
            JObject asJO = JObject.Parse(serialized);



            //create peristed message
            BusMessage msg = new BusMessage()
            {
                PayLoad = serialized, MessageType = asJO["$type"].ToString()
            };


            RouteResponse toReturn = new RouteResponse()
            {
                Status = false
            };

            try {
                toReturn = Bus.ReceiveMessage(msg);
            } catch {
                throw;
            }

            return(toReturn);
        }
Ejemplo n.º 10
0
        public List <MyWaypoint> CreateRoute(MyWaypoint startPoint, MyWaypoint endPoint)
        {
            // create route from waypointString
            RouteRequest routeRequest = new RouteRequest();

            // Set the credentials using a valid Bing Maps key
            routeRequest.Credentials = new BingRouteService.Credentials();
            routeRequest.Credentials.ApplicationId = m_bingMapKey;

            // tell them that we want points along the route
            routeRequest.Options = new RouteOptions();
            routeRequest.Options.RoutePathType = RoutePathType.Points;

            //Parse user data to create array of waypoints
            BingRouteService.Waypoint[] waypoints = new BingRouteService.Waypoint[2];

            BingRouteService.Waypoint point1    = new BingRouteService.Waypoint();
            BingRouteService.Location location1 = new BingRouteService.Location();
            location1.Latitude  = startPoint.Latitude;
            location1.Longitude = startPoint.Longitude;
            point1.Location     = location1;
            point1.Description  = "Start";
            waypoints[0]        = point1;

            BingRouteService.Waypoint point2    = new BingRouteService.Waypoint();
            BingRouteService.Location location2 = new BingRouteService.Location();
            location2.Latitude  = endPoint.Latitude;
            location2.Longitude = endPoint.Longitude;
            point2.Location     = location2;
            point2.Description  = "End";
            waypoints[1]        = point2;

            routeRequest.Waypoints = waypoints;

            // Make the calculate route request
            RouteServiceClient routeService  = new RouteServiceClient("BasicHttpBinding_IRouteService");
            RouteResponse      routeResponse = routeService.CalculateRoute(routeRequest);

            // pull out the lat/lon values
            List <MyWaypoint> returnPoints = new List <MyWaypoint>();

            if (routeResponse.Result.Legs.Length > 0)
            {
                //MessageBox.Show("Distance: " + routeResponse.Result.Summary.Distance.ToString()
                //    + " Time: " + routeResponse.Result.Summary.TimeInSeconds.ToString());
                foreach (BingRouteService.Location thisPt in routeResponse.Result.RoutePath.Points)
                {
                    MyWaypoint thisPoint = new MyWaypoint();

                    thisPoint.Latitude  = thisPt.Latitude;
                    thisPoint.Longitude = thisPt.Longitude;
                    //thisPoint.Altitude = GetAltitude(thisPoint.Latitude, thisPoint.Longitude);
                    thisPoint.Altitude = 0.0;

                    returnPoints.Add(thisPoint);
                }
            }

            return(returnPoints);
        }
Ejemplo n.º 11
0
 private static void InitializeRouter()
 {
     router = new Router();
     router.AddRoute <LoadStore>("GET", "/load", Load, false);
     router.AddRoute <SaveStore>("POST", "/Save", Save, false);
     router.AddRoute <AuditLog>("POST", "/SaveLogEntry", SaveLogEntry, false);
     router.AddRoute("GET", "/", () => RouteResponse.Page("Hello World", "text/html"), false);
 }
Ejemplo n.º 12
0
        private static IRouteResponse BeginTransaction(RequestCommon req)
        {
            var conn        = OpenConnection();
            var transaction = conn.BeginTransaction();

            transactions[req.UserId] = new Transaction(transaction, conn);

            return(RouteResponse.OK());
        }
Ejemplo n.º 13
0
        private static IRouteResponse SaveLogEntry(AuditLog entry)
        {
            using (var conn = OpenConnection())
            {
                CreateLogEntry(conn, entry);
            }

            return(RouteResponse.OK());
        }
Ejemplo n.º 14
0
 public static Models.Route MapToRoute(this RouteResponse response)
 {
     return(new Models.Route
     {
         TravelTime = response.Routes.First().Duration,
         Distance = response.Routes.First().Distance,
         GeoJson = response.Routes.First().Geometry.Coordinates.Select(x => new Coordinates(x[0], x[1])).ToList()
     });
 }
Ejemplo n.º 15
0
 public void queRouteRequest(RouteResponse response)
 {
     if (!responseQueue.Contains(response))
     {
         //if (response.route == null)
         //System.Diagnostics.Debug.WriteLine("wtf is happening right now?");
         response.rdy = false;
         lock (lck) responseQueue.Add(response);
     }
 }
        public void TryExecuteRequest()
        {
            RouteResponse response = TryRequestRouteResponse();

            if (response != null && response.Code == AcceptingStatusCode)
            {
                RequestSuccessful = true;
                RequestedResponse = OsrmConverter.ConvertRouteResponseToRouteInfoResponse(response);
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Checks if destenation is reached
 /// </summary>
 /// <param name="routeResponse">graphhopper route object</param>
 /// <returns>true if destenation is reached, false otherwise</returns>
 private bool DestenationReached(RouteResponse routeResponse)
 {
     if (routeResponse != null)
     {
         return((routeResponse.Paths.Count > 0 && routeResponse.Paths[0].Instructions.Count == 0) ||
                (routeResponse.Paths[0].Instructions.Count > 0 && routeResponse.Paths[0].Instructions[0].Sign == 4) ||
                routeResponse.Paths[0].Distance < 2);
     }
     return(false);
 }
Ejemplo n.º 18
0
        private static IRouteResponse ImportEntity(EntityData entity)
        {
            IRouteResponse resp = RouteResponse.OK();

            // Evil!
            // Lock the whole process in case another async call fails and the client calls abort which gets
            // processed and then more import calls are received.
            lock (schemaLocker)
            {
                // We assume there's data!
                using (var tconn = OpenConnection())
                {
                    CheckForTable(tconn, entity.StoreName);

                    // Somewhat annoyingly we actually have to check all the records for any new field.
                    entity.StoreData.ForEach(d =>
                    {
                        foreach (var prop in d.Properties())
                        {
                            CheckForField(tconn, entity.StoreName, prop.Name);
                        }
                    });
                }
            }

            var tinfo       = transactions[entity.UserId];
            var transaction = tinfo.t;
            var conn        = tinfo.c;

            try
            {
                Interlocked.Increment(ref tinfo.transactionCount);
                Console.WriteLine($"{tinfo.transactionCount} {tinfo.rollbackCount} {tinfo.c.State}");

                for (int n = 0; n < entity.StoreData.Count && Interlocked.Read(ref tinfo.rollbackCount) == 0; ++n)
                {
                    lock (schemaLocker)
                    {
                        InsertRecord(conn, transaction, entity.UserId, entity.StoreName, entity.StoreData[n]);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                resp = RouteResponse.ServerError(new { Error = ex.Message });
            }
            finally
            {
                Interlocked.Decrement(ref tinfo.transactionCount);
            }


            return(resp);
        }
Ejemplo n.º 19
0
        public bool CreateCustomRoute(CustomRouteRequest route, out IList <RouteResponse> result)
        {
            var routes = _context.GradedRoutesWithIncludedRelatedData();
            var places = FindPlacesFromRoutes(routes);

            PlaceResponse start = route.Start;
            PlaceResponse end   = route.End;

            double distanceFromStart = FindClosestPlace(start, places, out Miejsce closestToStart);
            double distanceFromEnd   = FindClosestPlace(end, places, out Miejsce closestToEnd);

            if (distanceFromStart <= MAXIMUM_DISTANCE && distanceFromEnd <= MAXIMUM_DISTANCE)
            {
                var mountainGroup     = FindMountainGroup(closestToStart);
                var mountainGroupName = _context.GrupaGorska.First(m => m.Id == mountainGroup).Nazwa;
                routes = routes.Where(r => r.GrupaGorskaId == mountainGroup).ToList();
                places = FindPlacesFromRoutes(routes);

                //create graph from locations in a mountain group
                var graph = new BidirectionalGraph <PlaceVertex, Edge <PlaceVertex> >();
                var edgeCostDictionary = new Dictionary <Edge <PlaceVertex>, int>();
                PopulateGraph(graph, edgeCostDictionary, places, routes);

                //find path between start location and end location using A* Algorithm
                AStarShortestPathAlgorithm <PlaceVertex, Edge <PlaceVertex> > astar = new AStarShortestPathAlgorithm <PlaceVertex, Edge <PlaceVertex> >(graph, x => edgeCostDictionary[x], x => 0);
                var startVertex = new PlaceVertex(closestToStart.Id);
                var endVertex   = new PlaceVertex(closestToEnd.Id);

                if (astar.ComputeDistanceBetween(startVertex, endVertex, out var path))
                {
                    result = new List <RouteResponse>();
                    if (distanceFromStart >= MINIMUM_DISTANCE)
                    {
                        result.Add(RouteResponse.CreateCustomRoute(start, PlaceResponse.BuildFromModel(closestToStart), mountainGroupName, distanceFromStart));
                    }
                    result = result.Concat(CreateResponseListFromPath(path)).ToList();
                    if (distanceFromEnd >= MINIMUM_DISTANCE)
                    {
                        result.Add(RouteResponse.CreateCustomRoute(PlaceResponse.BuildFromModel(closestToEnd), end, mountainGroupName, distanceFromEnd));
                    }
                    return(true);
                }
                else
                {
                    result = new List <RouteResponse>();
                    return(false);
                }
            }
            else
            {
                result = new List <RouteResponse>();
                return(false);
            }
        }
Ejemplo n.º 20
0
        public override async Task <RouteResponse> PlanRoute(RouteRequest request, ServerCallContext context)
        {
            var response = new RouteResponse();

            response.Miles = new Random().Next(15, 200);
            response.Steps.Add("Go the traffic light");
            response.Steps.Add("Turn Left");
            response.Steps.Add("You have arrived");
            response.DrivingTime = Timestamp.FromDateTime(DateTime.Now.AddMinutes(response.Miles).ToUniversalTime());
            return(response);
        }
Ejemplo n.º 21
0
        private static string ExtractFullDescriptionFromRoute(RouteResponse routeResponse)
        {
            string description = routeResponse.Paths[0].Instructions[0].Text;

            description += $" for : {routeResponse.Paths[0].Instructions[0].Time / 1000}[sec]";
            if (routeResponse.Paths[0].Instructions.Count > 1)
            {
                description += $",\nand then {routeResponse.Paths[0].Instructions[1].Text}";
            }
            return(description);
        }
Ejemplo n.º 22
0
 private void UpdateCurrentTimeDuration(RouteResponse routeResponse)
 {
     if (routeResponse.Paths.Count > 0 && routeResponse.Paths[0].Instructions.Count > 0 && routeResponse.Paths[0].Instructions[0].Time != null)
     {
         currentTimeDuration = (int)routeResponse.Paths[0].Instructions[0].Time;
     }
     else
     {
         currentTimeDuration = NAVIGATION_MAX_SAMPLING_MILLIS;
     }
 }
Ejemplo n.º 23
0
        private IList <RouteResponse> CreateResponseListFromPath(IEnumerable <IEdge <PlaceVertex> > path)
        {
            List <OdcinekPunktowany> routes    = _context.GradedRoutesWithIncludedRelatedData().ToList();
            List <RouteResponse>     responses = new List <RouteResponse>();

            foreach (var edge in path)
            {
                var route = routes.First(r => r.Id == edge.Source.RouteId);
                responses.Add(RouteResponse.BuildFromModel(route));
            }
            return(responses);
        }
Ejemplo n.º 24
0
        private static IRouteResponse Load(LoadStore store)
        {
            Console.WriteLine($"Load store {store.StoreName} for user {store.UserId}");

            using (var conn = OpenConnection())
            {
                CheckForTable(conn, store.StoreName);
                var data = LoadStore(conn, store.StoreName, store.UserId);

                return(RouteResponse.OK(data));
            }
        }
Ejemplo n.º 25
0
        public ActionResult Route(RouteRequest routeRequest)
        {
            RouteResponse routeResponse = new RouteResponse();

            try
            {
            }
            catch (Exception ex) {
                return(BadRequest());
            }
            return(Ok(routeResponse));
        }
Ejemplo n.º 26
0
        private static IRouteResponse CommitTransaction(RequestCommon req)
        {
            Console.WriteLine("Committing transactions...");
            var tinfo = transactions[req.UserId];

            Console.WriteLine($"{tinfo.transactionCount} {tinfo.rollbackCount} {tinfo.c.State}");
            tinfo.t.Commit();
            tinfo.c.Close();
            transactions.Remove(req.UserId, out _);

            return(RouteResponse.OK());
        }
Ejemplo n.º 27
0
        public async Task <RouteResponse> PostCreateRouteAsync(RouteRequest routeRequest)
        {
            // We'll use the patch method to set the properties values from the request to a new internal Route class.
            var userId = User.GetUserId();
            var route  = new Route();

            routeRequest.Patch(route);

            route = await _routeRepository.CreateRouteAsync(route, userId);

            return(RouteResponse.Map(route));
        }
Ejemplo n.º 28
0
        public override Task <RouteResponse> PlanRoute(RouteRequest request, ServerCallContext context)
        {
            var response = new RouteResponse();

            response.Miles = new Random().Next(15, 200);
            response.Steps.Add("At the end of your driveway, go left");
            response.Steps.Add("Turn right at Darrow");
            response.Steps.Add("Keep going until you get to the pacific");
            response.Steps.Add("You missed it  - " + request.Street);
            response.ArrivalTime = Timestamp.FromDateTime(DateTime.Now.AddHours(12).ToUniversalTime());
            return(Task.FromResult(response));
        }
Ejemplo n.º 29
0
 private static void InitializeRouter()
 {
     router = new Router();
     router.AddRoute <RequestCommon>("GET", "/Load", Load, false);
     router.AddRoute <RequestCommon>("POST", "/BeginTransaction", BeginTransaction, false);
     router.AddRoute <RequestCommon>("POST", "/CommitTransaction", CommitTransaction, false);
     router.AddRoute <RequestCommon>("POST", "/RollbackTransaction", RollbackTransaction, false);
     router.AddRoute <AuditLogEntries>("POST", "/ImportChanges", ImportAuditLog, false);
     router.AddRoute <EntityData>("POST", "/ImportEntity", ImportEntity, false);
     router.AddRoute <AuditLog>("POST", "/SaveLogEntry", SaveLogEntry, false);
     router.AddRoute("GET", "/", () => RouteResponse.Page("Hello World", "text/html"), false);
 }
Ejemplo n.º 30
0
        private async Task StartRouteSpeech(RouteResponse routeResponse)
        {
            await textToSpeechService.SpeakAsync("We're ready, let's go!");

            await Task.Delay(2000);

            string description = ExtractFullDescriptionFromRoute(routeResponse);

            if (!string.IsNullOrEmpty(description))
            {
                textToSpeechService.Speak(description);
            }
        }
Ejemplo n.º 31
0
            /// <summary>
            /// Calculates a route based on the distance between points.
            /// </summary>
            /// <param name="request">The request to calculate a route for..</param>
            /// <returns>A response with the calculated distance.</returns>
            /// <seealso cref="IRouteService.CalculateRouteAsync"/>
            public Task<RouteResponse> CalculateRouteAsync(RouteRequest request)
            {
                if (request == null)
                {
                    throw new ArgumentNullException("request");
                }

                const double secondsPerUnitDistance = 60 * 60;

                Location start = request.Waypoints[0].Location;
                Location end = request.Waypoints[0].Location;

                double northSouth = start.Latitude - end.Latitude;
                double eastWest = start.Longitude - end.Longitude;
                double approximateDistance = Math.Sqrt(Math.Pow(northSouth, 2) + Math.Pow(eastWest, 2));
                int travelTimeSeconds = (int)(approximateDistance * secondsPerUnitDistance);

                RouteResponse response = new RouteResponse
                {
                    ResponseSummary = new ResponseSummary
                    {
                        StatusCode = ResponseStatusCode.Success,
                    },
                    Result = new RouteResult
                    {
                        Summary = new RouteSummary
                        {
                            TimeInSeconds = travelTimeSeconds,
                        },
                    },
                };
                return TaskExt.WrapInTask(() => response);
            }