public static List <RouteScheduleSummary> GetSchedules()
        {
            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                var currentDateTime = UTCToLocalTime.LocalTimeFromUTC(DateTime.UtcNow);

                var fixedRouteSchedules = (from route in db.Routes
                                           from routeSchedule in db.RouteSchedules
                                           orderby routeSchedule.StartTime, routeSchedule.Route.ShortName
                                           where (routeSchedule.RouteID == route.ID)
                                           select routeSchedule).ToList <RouteSchedule>();

                var today = currentDateTime.Date;
                var routeScheduleOverrideList = (from rso in db.RouteScheduleOverrides
                                                 orderby rso.OverrideDate, rso.StartTime, rso.NewRoute.ShortName
                                                 select rso).ToList <RouteScheduleOverride>();

                var scheduleToDate = new Dictionary <RouteSchedule, DateTime>();
                var routeSchedules = BuildScheduleView.BuildEffectiveRouteSchedule(currentDateTime, 7, fixedRouteSchedules, scheduleToDate, routeScheduleOverrideList);

                var schedules = new List <RouteScheduleSummary>();
                foreach (var routeSchedule in routeSchedules)
                {
                    schedules.Add(new RouteScheduleSummary(routeSchedule));
                }
                return(schedules);
            }
        }
コード例 #2
0
        public ActionResult CreateConfirm(FormCollection collection)
        {
            var resultText = "Unknown error";
            var errorText  = "";

            try
            {
                using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
                {
                    var strRouteID = collection.Get("RouteID");
                    int routeID    = Convert.ToInt32(strRouteID);
                    var route      = db.Routes.Find(routeID);

                    resultText = "";

                    var jsonShapes = collection.Get("RouteShapeJSON");
                    if (jsonShapes != null && strRouteID != null)
                    {
                        RemoveOldShape(routeID, db);

                        SaveNewRouteShape(db, route, jsonShapes);

                        var jsonStops    = collection.Get("NewRouteStops");
                        var newStopCount = SaveNewRouteStops(db, jsonStops);

                        var assignStops = new AssignStopsToRoutes();
                        assignStops.UpdateStopsForRoute(db, routeID);

                        logger.Info($"Modified route shape of '{route.ShortName}' - '{route.LongName}, added {newStopCount} stops.'");
                        resultText = $"Route path for {route.ShortName} Saved, added {newStopCount} stops.";
                    }
                }
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        logger.Info("Property: {0} Error: {1}",
                                    validationError.PropertyName,
                                    validationError.ErrorMessage);
                    }
                }
                errorText = "Oops - Shape save exception.  This has been logged";
                logger.Error(dbEx, "Exception processing route shape");
            }
            catch (Exception ex)
            {
                // Unexpected error in parse or preview
                errorText = "Oops - Shape save exception.  This has been logged";
                logger.Error(ex, "Exception processing route shape");
            }

            ViewBag.RouteID      = GetRouteSelectList(null);
            ViewBag.ErrorMessage = errorText;
            ViewBag.Message      = resultText;

            return(View("Create"));
        }
コード例 #3
0
 public void UpdateStopsForAllRoutes()
 {
     using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
     {
         var routes = from Route in db.Routes
                      select Route;
         foreach (var route in routes)
         {
             UpdateStopsForRoute(db, route.ID);
         }
     }
 }
コード例 #4
0
 public void UpdateStopsForAllRoutes()
 {
     using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
     {
         var routes = from Route in db.Routes
                      select Route;
         foreach (var route in routes)
         {
             UpdateStopsForRoute(db, route.ID);
         }
     }
 }
コード例 #5
0
        public IHttpActionResult PostLocation(int id, LocationUpdate locationUpdate)
        {
            if (AppSettingsInterface.UseSyncromatics)
            {
                return(Ok());                                       // Disregard beacon if using Syncromatics
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                var trolley = (from Trolley t in db.Trolleys
                               where t.Number == id
                               select t).FirstOrDefault <Trolley>();
                if (trolley == null)
                {
                    return(NotFound());
                }

                if ((locationUpdate.Lat < -90.0) || (locationUpdate.Lat > 90))
                {
                    return(BadRequest("Invalid latitude"));
                }
                if ((locationUpdate.Lon < -180.0) || (locationUpdate.Lon > 180))
                {
                    return(BadRequest("Invalid longitude"));
                }

                trolley.CurrentLat     = locationUpdate.Lat;
                trolley.CurrentLon     = locationUpdate.Lon;
                trolley.LastBeaconTime = UTCToLocalTime.LocalTimeFromUTC(DateTime.UtcNow);
                if (lastTrolleyWriteTime.ContainsKey(trolley.Number))
                {
                    if ((DateTime.Now - lastTrolleyWriteTime[trolley.Number]).TotalSeconds > 30.0)
                    {
                        db.SaveChanges();
                        lastTrolleyWriteTime[trolley.Number] = DateTime.Now;
                    }
                }
                else
                {
                    lastTrolleyWriteTime.Add(trolley.Number, DateTime.Now);
                }
                TrolleyCache.UpdateTrolley(trolley);
                StopArrivalTime.UpdateTrolleyStopArrivalTime(trolley);

                return(Ok());
            }
        }
コード例 #6
0
 // GET: api/Routes
 public List <RouteSummary> GetRoutes()
 {
     using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
     {
         var routes        = db.Routes;
         var summaryRoutes = new List <RouteSummary>();
         foreach (var route in routes)
         {
             var summaryRoute = new RouteSummary(route);
             summaryRoutes.Add(summaryRoute);
         }
         return(summaryRoutes);
     }
 }
        public IHttpActionResult GetRouteSchedule(int id)
        {
            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                RouteSchedule routeSchedule = db.RouteSchedules.Find(id);
                if (routeSchedule == null)
                {
                    return(NotFound());
                }

                var routeScheduleSummary = new RouteScheduleSummary(routeSchedule);

                return(Ok(routeScheduleSummary));
            }
        }
コード例 #8
0
        // GET: api/Trolleys/5/Location
        public Trolley Get(int id)
        {
            if (!ModelState.IsValid)
            {
                return(null);
            }

            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                var trolley = (from Trolley t in db.Trolleys
                               where t.Number == id
                               select t).FirstOrDefault <Trolley>();

                return(trolley);
            }
        }
コード例 #9
0
        private Trolley GetTrolleyByNumber(int trolleyNumber)
        {
            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                Trolley trolley = (from Trolley t in db.Trolleys
                                   where t.Number == trolleyNumber
                                   select t).FirstOrDefault <Trolley>();

                if (trolley == null)
                {
                    SingleLog(SingleLogType.UnmatchedSyncromaticsVehicle, $"Unable to find Trolley {trolleyNumber}");
                }

                return(trolley);
            }
        }
コード例 #10
0
        private async Task SaveTrolleyToDB(Trolley trolley)
        {
            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                Trolley dbTrolley = (from Trolley t in db.Trolleys
                                     where t.ID == trolley.ID
                                     select t).FirstOrDefault <Trolley>();

                dbTrolley.CurrentLat     = trolley.CurrentLat;
                dbTrolley.CurrentLon     = trolley.CurrentLon;
                dbTrolley.LastBeaconTime = trolley.LastBeaconTime;
                dbTrolley.IconColorRGB   = trolley.IconColorRGB;
                dbTrolley.Capacity       = trolley.Capacity;
                dbTrolley.PassengerLoad  = trolley.PassengerLoad;
                await db.SaveChangesAsync(cancellationToken);
            }
        }
コード例 #11
0
        const double MinStopProximity = 20.0; // Meters

        #endregion Fields

        #region Methods

        /// <summary>
        /// Recalculate which routes the stops belong to, and the order.
        /// Call after any change to route or stops
        /// </summary>
        /// <param name="routeID">Route being recalculated</param>
        /// <param name="shapePoints"></param>
        /// <param name="stopPoints"></param>
        public void UpdateRouteStops(TrolleyTrackerContext db, int routeID, List<Coordinate> shapePoints, List<Stop> stops)
        {
            RemovePreviousRouteStops(db, routeID);

            var route = (from Route in db.Routes
                         where Route.ID == routeID
                         select Route).FirstOrDefault<Route>();

            // A stop is considered to belong to a route if it's within MinStopProximity meters of the route path
            var routeStopList = new List<Stop>();

            if (route.FlagStopsOnly)
            {
                // No stops to generate
                return;
            }

            for (int i=1; i< shapePoints.Count; i++)
            {
                for (int s=0; s< stops.Count; s++)
                {
                    var stop = stops[s];
                    var stopPosition = new Coordinate(0, stop.Lat, stop.Lon, null);
                    Coordinate closest = null;
                    var distance = FindDistanceToSegment(stopPosition, shapePoints[i], shapePoints[i - 1], out closest);
                    if (distance < MinStopProximity)
                    {
                        if (!routeStopList.Contains(stop))
                        {
                            routeStopList.Add(stop);
                        }
                        //break;   //  Bug? How to handle case of ordering multiple stops in a long straight segment
                    }
                }
            }

            for (int i=0; i < routeStopList.Count; i++)
            {
                var newRouteStop = db.RouteStops.Create();
                newRouteStop.RouteID = routeID;
                newRouteStop.StopID = routeStopList[i].ID;
                newRouteStop.StopSequence = i;
                db.RouteStops.Add(newRouteStop);
            }
            db.SaveChanges();
        }
コード例 #12
0
        public IHttpActionResult GetRoute(int id)
        {
            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                Route route = db.Routes.Find(id);
                if (route == null)
                {
                    return(NotFound());
                }

                // Assemble route + Stops + Shape
                var routeDetail = new RouteDetail(route);

                routeDetail.AddRouteDetail(db, route);

                return(Ok(routeDetail));
            }
        }
コード例 #13
0
        // GET: Stops/Regular
        // Mapped as - GET: api/v1/Stops/Regular
        public List <GeoJSONSummary> Get()
        {
            using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
            {
                var stops = (from stop in db.Stops
                             from routeSchedule in db.RouteSchedules
                             from routeStop in db.RouteStops
                             where (routeSchedule.Route.ID == routeStop.RouteID &&
                                    routeStop.StopID == stop.ID)
                             //select stop);
                             select stop).Select(stop => stop).ToList().Distinct(new StopComparer()).OrderBy(stop => stop.Name);

                var geoJSONStopsList = new List <GeoJSONSummary>();
                foreach (var stop in stops)
                {
                    geoJSONStopsList.Add(new GeoJSONSummary(stop));
                }

                return(geoJSONStopsList);
            }
        }
        public static RouteScheduleViewModel ConfigureScheduleView(TrolleyTrackerContext db, bool calculateEffectiveSchedule)
        {
            var vm = new RouteScheduleViewModel();
            var routeSchedules = from rs in db.RouteSchedules.Include(rs => rs.Route)
                                 orderby rs.DayOfWeek, rs.StartTime ascending
                                 select rs;
            vm.RouteSchedules = (System.Data.Entity.Infrastructure.DbQuery<RouteSchedule>)routeSchedules;

            if (calculateEffectiveSchedule)
            {
                var routeScheduleOverrideList = (from rso in db.RouteScheduleOverrides.Include(rso => rso.NewRoute)
                                                 orderby rso.OverrideDate, rso.StartTime, rso.NewRoute.ShortName
                                                 select rso).ToList<RouteScheduleOverride>();

                var routeScheduleList = routeSchedules.ToList<RouteSchedule>();
                vm.EffectiveRouteSchedules = BuildEffectiveRouteSchedule(routeScheduleList, routeScheduleOverrideList);
            }

            vm.Options = new MvcScheduleGeneralOptions
            {
                Layout = LayoutEnum.Horizontal,
                SeparateDateHeader = false,
                FullTimeScale = true,
                TimeScaleInterval = 60,
                StartOfTimeScale = new TimeSpan(6, 0, 0),
                EndOfTimeScale = new TimeSpan(23, 59, 59),
                IncludeEndValue = false,
                ShowValueMarks = true,
                ItemCss = "normal",
                AlternatingItemCss = "normal2",
                RangeHeaderCss = "heading",
                TitleCss = "heading",
                AutoSortTitles = false,
                BackgroundCss = "empty"
            };

            return vm;
        }
        private void RemovePreviousRouteStops(TrolleyTrackerContext db, int routeID)
        {
            var routeStops = from RouteStop rs in db.RouteStops
                              where rs.RouteID == routeID
                              select rs;

            foreach (var rs in routeStops)
            {
                db.RouteStops.Remove(rs);
            }
            db.SaveChanges();
        }
        public void UpdateStopsForRoute(TrolleyTrackerContext db, int routeID)
        {
            var shapes = (from Shape in db.Shapes
                         where Shape.RouteID == routeID
                         orderby Shape.Sequence
                              select Shape).ToList<Shape>();

            var shapePoints = new List<Coordinate>();
            foreach (var shape in shapes)
            {
                var coord = new Coordinate(shape.Lat, shape.Lon);
                shapePoints.Add(coord);
            }

            var stops = (from Stop s in db.Stops
                        select s).ToList<Stop>();

            UpdateRouteStops(db, routeID, shapePoints, stops);
        }
コード例 #17
0
        private void RemoveOldShape(int routeID, TrolleyTrackerContext db)
        {
            // Slow way
            //var oldShapes = from shape in db.Shapes
            //                where shape.RouteID == routeID
            //                select shape;
            //foreach(var shape in oldShapes)
            //{
            //    db.Shapes.Remove(shape);
            //}
            //db.SaveChanges();

            // delete existing records
            db.Database.ExecuteSqlCommand("DELETE FROM Shapes WHERE RouteID = " + routeID);
        }
コード例 #18
0
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Coordinate lastCoordinate = null;

                var strRouteID = collection.Get("RouteID");

                // Parse Geo-JSON formatted route coordinates
                var jsonShapes = collection.Get("JSONText");
                if (jsonShapes != null && strRouteID != null)
                {
                    int routeID = Convert.ToInt32(strRouteID);

                    using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
                    {
                        RemoveOldShape(routeID, db);

                        JavaScriptSerializer jss = new JavaScriptSerializer();
                        jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

                        dynamic shapeData = jss.Deserialize(jsonShapes, typeof(object)) as dynamic;

                        var features = shapeData.features;
                        var geometryBlock = features[0];
                        var geometry = geometryBlock["geometry"];
                        var geoJSONtype = geometry["type"];
                        var coordinates = geometry["coordinates"];

                        int segmentCount = coordinates.Count;
                        if (geoJSONtype == "LineString") segmentCount = 1;
                        int sequence = 0;
                        double totalDistance = 0.0;
                        for (int seg = 0; seg < segmentCount; seg++)
                        {
                            var coordArray = coordinates[seg];
                            if (geoJSONtype == "LineString") coordArray = coordinates;
                            int nodeCount = coordArray.Count;
                            for (int i = 0; i < nodeCount; i++)
                            {
                                var node = coordArray[i];
                                var strLon = node[0];
                                var strLat = node[1];
                                var lon = Convert.ToDouble(strLon);
                                var lat = Convert.ToDouble(strLat);

                                var thisCoordinate = new Coordinate(0, lat, lon, null);
                                double distance = 0.0;
                                if (lastCoordinate != null)
                                {
                                    distance = thisCoordinate.GreatCircleDistance(lastCoordinate);
                                }
                                lastCoordinate = thisCoordinate;
                                totalDistance += distance;

                                var dbShape = new TrolleyTracker.Models.Shape();
                                dbShape.Lat = lat;
                                dbShape.Lon = lon;
                                dbShape.RouteID = routeID;
                                dbShape.Sequence = sequence;
                                dbShape.DistanceTraveled = totalDistance;
                                sequence++;
                                db.Shapes.Add(dbShape);
                            }

                        }
                        db.SaveChanges();

                        var assignStops = new AssignStopsToRoutes();
                        assignStops.UpdateStopsForRoute(db, routeID);
                    }

                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                Coordinate lastCoordinate = null;

                var strRouteID = collection.Get("RouteID");


                // Parse Geo-JSON formatted route coordinates
                var jsonShapes = collection.Get("JSONText");
                if (jsonShapes != null && strRouteID != null)
                {
                    int routeID = Convert.ToInt32(strRouteID);

                    using (var db = new TrolleyTracker.Models.TrolleyTrackerContext())
                    {
                        RemoveOldShape(routeID, db);

                        JavaScriptSerializer jss = new JavaScriptSerializer();
                        jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });

                        dynamic shapeData = jss.Deserialize(jsonShapes, typeof(object)) as dynamic;

                        var features      = shapeData.features;
                        var geometryBlock = features[0];
                        var geometry      = geometryBlock["geometry"];
                        var geoJSONtype   = geometry["type"];
                        var coordinates   = geometry["coordinates"];

                        int segmentCount = coordinates.Count;
                        if (geoJSONtype == "LineString")
                        {
                            segmentCount = 1;
                        }
                        int    sequence      = 0;
                        double totalDistance = 0.0;
                        for (int seg = 0; seg < segmentCount; seg++)
                        {
                            var coordArray = coordinates[seg];
                            if (geoJSONtype == "LineString")
                            {
                                coordArray = coordinates;
                            }
                            int nodeCount = coordArray.Count;
                            for (int i = 0; i < nodeCount; i++)
                            {
                                var node   = coordArray[i];
                                var strLon = node[0];
                                var strLat = node[1];
                                var lon    = Convert.ToDouble(strLon);
                                var lat    = Convert.ToDouble(strLat);

                                var    thisCoordinate = new Coordinate(lat, lon);
                                double distance       = 0.0;
                                if (lastCoordinate != null)
                                {
                                    distance = thisCoordinate.GreatCircleDistance(lastCoordinate);
                                }
                                lastCoordinate = thisCoordinate;
                                totalDistance += distance;

                                var dbShape = new TrolleyTracker.Models.Shape();
                                dbShape.Lat              = lat;
                                dbShape.Lon              = lon;
                                dbShape.RouteID          = routeID;
                                dbShape.Sequence         = sequence;
                                dbShape.DistanceTraveled = totalDistance;
                                sequence++;
                                db.Shapes.Add(dbShape);
                            }
                        }
                        db.SaveChanges();

                        var assignStops = new AssignStopsToRoutes();
                        assignStops.UpdateStopsForRoute(db, routeID);

                        var route = db.Routes.Find(routeID);
                        logger.Info($"Modified route shape of '{route.Description}' - '{route.LongName}'");
                    }
                }

                return(RedirectToAction("Index"));
            }
            catch (Exception ex)
            {
                ViewBag.Message = "Shape save exception";

                logger.Error(ex, "Exception saving route shape");
                ViewBag.RouteID = new SelectList(db.Routes, "ID", "ShortName");
                return(View());
            }
        }