public void ResolveVehicleLocationProviderType_Cabs_Passes() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { Step stepEntity = new Step(); stepEntity.StepNumber = 1; stepEntity.StartDate = DateTime.Parse("1/1/2014 10:02"); stepEntity.EndDate = DateTime.Parse("1/1/2014 10:40"); stepEntity.FromName = "Quartz Street"; stepEntity.FromProviderId = (int)Providers.CABS; stepEntity.FromStopCode = "1001"; stepEntity.ModeId = (int)Modes.Bus; stepEntity.RouteNumber = "039"; stepEntity.Distance = (decimal)12.2; stepEntity.ToName = "Slate Run Road"; stepEntity.ToProviderId = (int)Providers.CABS; stepEntity.ToStopCode = "2002"; unitOfWork.Repository <Step>().Insert(stepEntity); unitOfWork.Save(); TConnect tconn = new TConnect(); tconn.InboundStepId = stepEntity.Id; unitOfWork.Repository <TConnect>().Insert(tconn); unitOfWork.Save(); IVehicleLocation iv = VehicleLocationMonitorWorker.ResolveVehicleLocationProviderType(tconn, unitOfWork, scheduleFakes); Assert.AreEqual(iv.ProviderName, Providers.CABS); } }
public void SetupNewTConnects_Passes() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { Traveler traveler = new Traveler(); traveler.Id = 1; traveler.LastName = "MDT2"; Trip trip = new Trip(); trip.Id = 1; trip.TripStartDate = DateTime.Parse("1/1/2014 10:40"); trip.TravelerId = traveler.Id; trip.Traveler = traveler;//must set object for navigation property or lazy loading wont work for mock. Step stepEntity = new Step(); stepEntity.Id = 1; stepEntity.StepNumber = 1; stepEntity.TripId = trip.Id; stepEntity.StartDate = DateTime.Parse("1/1/2014 10:02"); stepEntity.EndDate = DateTime.Parse("1/1/2014 10:40"); stepEntity.FromName = "Quartz Street"; stepEntity.FromProviderId = (int)Providers.CapTrans; stepEntity.FromStopCode = "1001"; stepEntity.ModeId = (int)Modes.Bus; stepEntity.RouteNumber = "039"; stepEntity.Distance = (decimal)12.2; stepEntity.ToName = "Slate Run Road"; stepEntity.ToProviderId = (int)Providers.CapTrans; stepEntity.ToStopCode = "2002"; stepEntity.Trip = trip;//must set object for navigation property or lazy loading wont work for mock. TConnect tconn = new TConnect(); tconn.Id = 1; tconn.TConnectStatusId = (int)TConnectStatuses.New; tconn.InboundStepId = stepEntity.Id; tconn.InboundStep = stepEntity;//must set object for navigation property or lazy loading wont work for mock. unitOfWork.Repository <Traveler>().Insert(traveler); unitOfWork.Repository <Trip>().Insert(trip); unitOfWork.Repository <Step>().Insert(stepEntity); unitOfWork.Repository <TConnect>().Insert(tconn); unitOfWork.Save(); List <TConnect> newTconnects = unitOfWork.Repository <TConnect>().Query().Include(i => i.InboundStep.Trip.Traveler).Get() .Where(s => s.TConnectStatusId == (int)TConnectStatuses.New).ToList(); TConnectMonitorWorker worker = new TConnectMonitorWorker(null); worker.SetupNewTConnects(unitOfWork); List <TConnect> monitoredTConnects = unitOfWork.Repository <TConnect>().Query().Get() .Where(s => s.TConnectStatusId == (int)TConnectStatuses.Monitored).ToList(); Assert.AreEqual(1, monitoredTConnects.Count); } }
/// <summary> /// Based on the TConnect's Inbound Step Provider, determine if the appropriate /// type of vehicle location provider to use /// Uses TOprovider /// </summary> /// <param name="mt"></param> /// <returns></returns> public static IVehicleLocation ResolveVehicleLocationProviderType(TConnect mt, IUnitOfWork Uow, List <IBusSchedule> busScheduleAPIs) { IVehicleLocation vehLoc = null; Step inboundStep = Uow.Repository <Step>().Query().Get() .Where(s => s.Id.Equals(mt.InboundStepId)).First(); if (inboundStep.ToProviderId == (int)Providers.CapTrans) { vehLoc = new CapTransVehicleLocation(); } else { foreach (IBusSchedule busSchedule in busScheduleAPIs) { if (inboundStep.ToProviderId == (int)busSchedule.GetProviderId()) { vehLoc = new CabsVehicleLocation(busSchedule); } } } if (vehLoc == null) { throw new NotImplementedException("Tconnects only handled from CapTrans and CABS currently. "); } return(vehLoc); }
/// <summary> /// A TConnectRequest had previously been created for this TConnect. Update it /// with new ETA information if the inbound vehicle is falling further behind schedule. /// The update will revert the TConnectRequest to status New, unless another TConnectRequest already /// has been accepted with a longer time. /// </summary> /// <param name="Uow"></param> /// <param name="newEta"></param> /// <param name="tr"></param> /// <param name="outboundStep"></param> async private static void UpdateExistingTConnectRequest(IUnitOfWork Uow, TConnect tConnect, DateTime newEta, TConnectRequest tr) { string msg = "Still monitoring TConnect. Eta=" + newEta.ToShortTimeString() + " : "; msg += "T-Connect Window [" + ((DateTime)tConnect.StartWindow).ToShortTimeString() + "-"; msg += ((DateTime)tConnect.EndWindow).ToShortTimeString() + "]"; LogTripEventIfDifferentFromLast(Uow, tConnect.InboundStep.TripId, msg); //We've already created a tConnect for this item, lets update it to see //if it has gotten even later. int newHoldMinutes = (int)Math.Ceiling((newEta - (DateTime)tConnect.StartWindow).TotalMinutes); if (newHoldMinutes > tr.RequestedHoldMinutes)//inbound getting even later. { tr.EstimatedTimeArrival = newEta; tr.RequestedHoldMinutes = newHoldMinutes; //By default, this updated time will be placed as "new" since we don't know if //this alteration is acceptable. //tr.TConnectStatusId = (int)TConnectStatuses.New; //However, If the ETA is beyond the EndWindow, then we know the bus will not //wait this long , and it must be automatically rejected. if (newEta > tConnect.EndWindow) { tr.TConnectStatusId = (int)TConnectStatuses.Rejected; //End monitoring --- Update status to done. tConnect.TConnectStatusId = (int)TConnectStatuses.Done; Uow.Repository <TConnect>().Update(tConnect); Uow.Repository <TripEvent>().Insert(new TripEvent(tConnect.InboundStep.TripId, "ETA of " + newEta.ToShortTimeString() + " is outside the T-Connect End Window")); } //Last, see if anyone else has requested a wait this long and had it accepted. //If so, we know this is accepted too. var l = Uow.Repository <TConnectedVehicle>().Query().Get().Where(s => s.Id.Equals(tr.TConnectedVehicleId)); if (l.Any()) { int acceptedWaitTime = l.First().CurrentAcceptedHoldMinutes; if (acceptedWaitTime >= newHoldMinutes && tr.TConnectStatusId != (int)TConnectStatuses.Accepted) { //A longer time has been accepted, so we can accept this too. tr.TConnectStatusId = (int)TConnectStatuses.Accepted; Uow.Repository <TripEvent>().Insert(new TripEvent(tConnect.InboundStep.TripId, "T-Connect Request set to Accepted due to previous accepted request")); Uow.Repository <TConnectRequest>().Update(tr); } } } else { //update arrival time, even though it is running earlier //and not at risk for missing connection tr.EstimatedTimeArrival = newEta; tr.RequestedHoldMinutes = newHoldMinutes; Uow.Repository <TConnectRequest>().Update(tr); } Uow.Save(); }
/// <summary> /// Calculates eta for the inbound vehicle involved in this TConnect /// </summary> /// <param name="Uow"></param> /// <param name="mt"></param> /// <returns></returns> private static async Task <DateTime> GetEtaForTConnectAsync(IUnitOfWork Uow, TConnect mt, List <IBusSchedule> busSchedulerAPIs) { IVehicleLocation vehLoc; vehLoc = VehicleLocationMonitorWorker.ResolveVehicleLocationProviderType(mt, Uow, busSchedulerAPIs); DateTime newEta = await vehLoc.CalculateEstimatedTimeOfArrivalAsync(mt, Uow); return(newEta); }
/// <summary> /// Cap Trans Inbound Vehicle's name will be the name of the traveler, which in turn /// is the name of the MDT (MDT1, MDT2, etc) /// </summary> /// <param name="tConnect"></param> /// <param name="Uow"></param> /// <returns></returns> public string GetInboundVehicleName(TConnect tConnect, IUnitOfWork Uow) { string vehicleName = ""; var t = Uow.Repository <TConnect>().Query().Include(i => i.InboundStep.Trip.Traveler).Get() .Where(code => code.Id.Equals(tConnect.Id)).First(); vehicleName = t.InboundStep.Trip.Traveler.LastName; return(vehicleName); }
public void GetCoordForOutboundStep_Passes() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { Step inbound = new Step(); inbound.Id = inbound.StepNumber = 1; inbound.StartDate = DateTime.Parse("1/1/2014 10:02"); inbound.EndDate = DateTime.Parse("1/1/2014 10:40"); inbound.FromName = "Quartz Street"; inbound.FromProviderId = (int)Providers.CapTrans; inbound.FromStopCode = "1001"; inbound.ModeId = (int)Modes.Bus; inbound.RouteNumber = "039"; inbound.Distance = (decimal)12.2; inbound.ToName = "Broad St Gate"; inbound.ToProviderId = (int)Providers.CapTrans; inbound.ToStopCode = "DCSCBRD1"; Step outbound = new Step(); outbound.Id = outbound.StepNumber = 2; outbound.StartDate = DateTime.Parse("1/1/2014 10:02"); outbound.EndDate = DateTime.Parse("1/1/2014 10:40"); outbound.FromName = "Broad St Gate"; outbound.FromProviderId = (int)Providers.CapTrans; outbound.FromStopCode = "DCSCBRD1"; outbound.ModeId = (int)Modes.Bus; outbound.RouteNumber = "039"; outbound.Distance = (decimal)12.2; outbound.ToName = "Slate Run Road"; outbound.ToProviderId = (int)Providers.CapTrans; outbound.ToStopCode = "DCSCBRD1"; unitOfWork.Repository <Step>().Insert(inbound); unitOfWork.Save(); TConnect tconn = new TConnect(); tconn.InboundStepId = inbound.Id; tconn.OutboundStepId = outbound.Id; tconn.InboundStep = inbound; tconn.OutboundStep = outbound; unitOfWork.Repository <TConnect>().Insert(tconn); unitOfWork.Save(); GeoCoordinate mainGate = new GeoCoordinate { Latitude = 39.975148, Longitude = -82.894379 }; GeoCoordinate coord = GetCoordForInboundStep(tconn, unitOfWork); Assert.AreEqual(coord, mainGate); } }
public void ListVehicles_Passes() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { //Setup TConnectedVehicle vehicleEnt1 = new TConnectedVehicle(); vehicleEnt1.Id = 1; TConnect tc = new TConnect { Id = 1, TConnectStatusId = (int)TConnectStatuses.Monitored }; unitOfWork.Repository <TConnect>().Insert(tc); TConnectRequest reqEnt1 = new TConnectRequest(); reqEnt1.TConnectedVehicleId = vehicleEnt1.Id; reqEnt1.TConnectId = tc.Id; reqEnt1.TConnectStatusId = (int)TConnectStatuses.New; unitOfWork.Repository <TConnectedVehicle>().Insert(vehicleEnt1); unitOfWork.Repository <TConnectRequest>().Insert(reqEnt1); unitOfWork.Save(); TConnectedVehicle vehicleEnt2 = new TConnectedVehicle(); vehicleEnt2.Id = 2; TConnect tc2 = new TConnect { Id = 2, TConnectStatusId = (int)TConnectStatuses.Monitored }; unitOfWork.Repository <TConnect>().Insert(tc2); TConnectRequest reqEnt2 = new TConnectRequest(); reqEnt2.TConnectedVehicleId = vehicleEnt2.Id; reqEnt2.TConnectId = tc2.Id; reqEnt2.TConnectStatusId = (int)TConnectStatuses.New; unitOfWork.Repository <TConnectedVehicle>().Insert(vehicleEnt2); unitOfWork.Repository <TConnectRequest>().Insert(reqEnt2); unitOfWork.Save(); var bc = unitOfWork.Repository <TConnect>().Query().Get() .Where(r => r.TConnectStatusId.Equals((int)TConnectStatuses.Monitored)).ToList(); var vehicleidsWithNew = unitOfWork.Repository <TConnectRequest>().Query().Get().Include(r => r.TConnect) .Where(r => r.TConnectStatusId.Equals((int)TConnectStatuses.New) // && r.TConnect.TConnectStatusId.Equals((int)TConnectStatuses.Monitored) ) .Select(r => r.TConnectedVehicleId).Distinct(); int a = vehicleidsWithNew.Count(); //.Include does not work on Fake Repository! TConnectedVehicleController tvCont = new TConnectedVehicleController(unitOfWork); List <TConnVehicleViewModel> vehicles = tvCont.GetVehiclesWithPendingRequests(); Assert.AreEqual(2, vehicles.Count()); } }
public void SetupNewTConnects_NoAction() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { Traveler traveler = new Traveler(); traveler.Id = 1; traveler.LastName = "MDT2"; Trip trip = new Trip(); trip.Id = 1; trip.TripStartDate = DateTime.UtcNow.AddMinutes(20); //make in future trip.TravelerId = traveler.Id; trip.Traveler = traveler; //must set object for navigation property or lazy loading wont work for mock. Step stepEntity = new Step(); stepEntity.Id = 1; stepEntity.StepNumber = 1; stepEntity.TripId = trip.Id; stepEntity.Trip = trip;//must set object for navigation property or lazy loading wont work for mock. TConnect tconn = new TConnect(); tconn.Id = 1; tconn.TConnectStatusId = (int)TConnectStatuses.New; tconn.InboundStepId = stepEntity.Id; tconn.InboundStep = stepEntity;//must set object for navigation property or lazy loading wont work for mock. unitOfWork.Repository <Traveler>().Insert(traveler); unitOfWork.Repository <Trip>().Insert(trip); unitOfWork.Repository <Step>().Insert(stepEntity); unitOfWork.Repository <TConnect>().Insert(tconn); unitOfWork.Save(); List <TConnect> newTconnects = unitOfWork.Repository <TConnect>().Query().Include(i => i.InboundStep.Trip.Traveler).Get() .Where(s => s.TConnectStatusId == (int)TConnectStatuses.New).ToList(); TConnectMonitorWorker worker = new TConnectMonitorWorker(new List <BusScheduleInterface.IBusSchedule>(new StubIBusSchedule[] { new StubIBusSchedule() })); worker.SetupNewTConnects(unitOfWork); List <TConnect> monitoredTConnects = unitOfWork.Repository <TConnect>().Query().Get() .Where(s => s.TConnectStatusId == (int)TConnectStatuses.New).ToList(); Assert.AreEqual(1, monitoredTConnects.Count); } }
/// <summary> /// Calculates the distance from the Cap Trans stop destination (one of two possible) to the current /// location (from the azure table) and then estimates an arrival time. /// </summary> /// <param name="tConnect"></param> /// <param name="Uow"></param> /// <returns></returns> public async Task <DateTime> CalculateEstimatedTimeOfArrivalAsync(TConnect tConnect, IUnitOfWork Uow) { return(await Task.Factory.StartNew(() => { GeoCoordinate busStopLoc = GetCoordForInboundStep(tConnect, Uow); LastVehiclePosition lvp = Uow.Repository <LastVehiclePosition>().Query().Get().First(v => v.VehicleName == tConnect.InboundVehicle); DateTime currentLocTime = lvp.PositionTimestamp; GeoCoordinate currentLoc = new GeoCoordinate(lvp.Latitude, lvp.Longitude); DateTime eta = CalcPointBEtaFromPointA(busStopLoc, currentLocTime, currentLoc); return eta; })); }
/// <summary> /// The MDT wants to see status of request. /// </summary> /// <param name="tc"></param> /// <returns></returns> public TConnectStatusModel.Status DeduceExternalStatusForTConnect(TConnect tc) { TConnectStatusModel.Status externalStatus = TConnectStatusModel.Status.Monitored; var trlist = Uow.Repository <TConnectRequest>().Query().Get() .Where(t => t.TConnectId.Equals(tc.Id)).ToList(); if (trlist.Count > 0)//Has a Request { var tr = trlist.First(); if (tc.TConnectStatusId == (int)TConnectStatuses.Done && tr.TConnectStatusId == (int)TConnectStatuses.New) { //This request expired with no response, same as rejected. externalStatus = TConnectStatusModel.Status.AutoRejected; } else { if (tr.TConnectStatusId == (int)TConnectStatuses.Accepted) { externalStatus = TConnectStatusModel.Status.Accepted; } else if (tr.TConnectStatusId == (int)TConnectStatuses.Rejected) { externalStatus = TConnectStatusModel.Status.Rejected; } else//New { externalStatus = TConnectStatusModel.Status.Requested; } } } //else //TConnect has no requests //{ // if (tc.TConnectStatusId == (int)TConnectStatuses.New // || tc.TConnectStatusId == (int)TConnectStatuses.Monitored) // { // //'New' for a tconnect is a very tiny window before the monitor picks it // //up, it is essentially the same as Monitored. // externalStatus = (int)TConnectStatuses.Monitored; // } // else //Done // { // externalStatus = (int)TConnectStatuses.Done; // } //} return(externalStatus); }
public string GetInboundVehicleName(TConnect tConnect, IUnitOfWork Uow) { var getIdTask = Task.Factory.StartNew(async() => { if (string.IsNullOrEmpty(tConnect.InboundStep.FromStopCode) || string.IsNullOrEmpty(tConnect.InboundStep.RouteNumber)) { return(string.Empty); } else { return(await this.busTimeApi.GetNextVehicleIDAsync(tConnect.InboundStep));//tConnect.InboundStep.FromStopCode, tConnect.InboundStep.RouteNumber); } }).Unwrap(); return(getIdTask.Result); }
public void TConnect_NoRequest_Passes() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { TConnect tc = new TConnect { Id = 1, TConnectStatusId = (int)TConnectStatuses.New }; unitOfWork.Repository <TConnect>().Insert(tc); unitOfWork.Save(); var controller = new TConnectController(idtoFakeContext); int status = (int)controller.DeduceExternalStatusForTConnect(tc); Assert.AreEqual((int)TConnectStatusModel.Status.Monitored, status); } }
public override DataTable UpdateGrid() { DataTable tclientes = new DataTable(); try { TConnect conn = new TConnect(); conn.Sql = "select codigo,nome,cpf,dtcadastro as cadastro from cliente"; tclientes = conn.selecionar(); } catch (Exception e) { MessageBox.Show("Erro ao acessar Banco de dados: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(tclientes); }
/// <summary> /// Finds the Inbound Step involved in this tconnect, and returns the lat/long location of it. /// Matches Inbound step to a known list of stops for Cap Trans. /// </summary> /// <param name="tConnect">tconnect that has the outbound step to resolve to GeoCoordinate.</param> /// <param name="Uow"></param> /// <returns></returns> protected GeoCoordinate GetCoordForInboundStep(TConnect tConnect, IUnitOfWork Uow) { //Tconnect InboundStepId ToStopCode should match to _stops list. Get correct stop lat long. var t = Uow.Repository <TConnect>().Query().Include(i => i.InboundStep).Get() .Where(code => code.Id.Equals(tConnect.Id)).First(); string busStop = t.InboundStep.ToStopCode; if (!_stops.ContainsKey(busStop)) { throw new NotImplementedException("CapTrans bus stop not found: " + busStop); } GeoCoordinate busStopLoc; _stops.TryGetValue(busStop, out busStopLoc); return(busStopLoc); }
public void GetCoordForOutboundStep_ThrowsEx() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { Step inbound = new Step(); inbound.Id = inbound.StepNumber = 1; inbound.StartDate = DateTime.Parse("1/1/2014 10:02"); inbound.EndDate = DateTime.Parse("1/1/2014 10:40"); inbound.FromName = "Quartz Street"; inbound.FromProviderId = (int)Providers.CapTrans; inbound.FromStopCode = "1001"; inbound.ModeId = (int)Modes.Bus; inbound.RouteNumber = "039"; inbound.Distance = (decimal)12.2; inbound.ToName = "Slate Run Road"; inbound.ToProviderId = (int)Providers.CapTrans; inbound.ToStopCode = "2002"; Step outbound = new Step(); outbound.Id = outbound.StepNumber = 2; outbound.StartDate = DateTime.Parse("1/1/2014 10:02"); outbound.EndDate = DateTime.Parse("1/1/2014 10:40"); outbound.FromName = "NotMain Gate";//change gate FromName so that it does not match the list. outbound.FromProviderId = (int)Providers.CapTrans; outbound.FromStopCode = "1001"; outbound.ModeId = (int)Modes.Bus; outbound.RouteNumber = "039"; outbound.Distance = (decimal)12.2; outbound.ToName = "Slate Run Road"; outbound.ToProviderId = (int)Providers.CapTrans; outbound.ToStopCode = "2002"; unitOfWork.Repository <Step>().Insert(inbound); unitOfWork.Save(); TConnect tconn = new TConnect(); tconn.InboundStepId = inbound.Id; tconn.OutboundStepId = outbound.Id; tconn.InboundStep = inbound; tconn.OutboundStep = outbound; unitOfWork.Repository <TConnect>().Insert(tconn); unitOfWork.Save(); Assert.Throws <NotImplementedException>(delegate { GetCoordForInboundStep(tconn, unitOfWork); }); } }
public override long Cadastrar() { long id = new long(); try { TConnect c = new TConnect(); c.Sql = "insert into cliente(nome,cpf,dtcadastro)values('" + this.Nome + "','" + this.Cpf + "','" + this.dtCadastro + "')"; id = c.Inserir(); MessageBox.Show("Cliente cadastrado com sucesso!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception e) { MessageBox.Show("Erro ao acessar Banco de dados: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(id); }
public override long Editar() { long id = new long(); try { TConnect c = new TConnect(); c.Sql = "update cliente set nome ='" + this.Nome + "',cpf = '" + this.Cpf + "',dtcadastro ='" + this.dtCadastro + "' where codigo = '" + this.Codigo + "'"; id = c.UpdateSql(); MessageBox.Show("Cliente atualizado com sucesso!", "Sucesso", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception e) { MessageBox.Show("Erro ao acessar Banco de dados: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(id); }
public void DoneTConnect_AcceptedRequest_Passes() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { TConnect tc = new TConnect { Id = 1, TConnectStatusId = (int)TConnectStatuses.Done }; unitOfWork.Repository <TConnect>().Insert(tc); TConnectRequest tr = new TConnectRequest { TConnectId = tc.Id, TConnectStatusId = (int)TConnectStatuses.Accepted }; unitOfWork.Repository <TConnectRequest>().Insert(tr); unitOfWork.Save(); var controller = new TConnectController(idtoFakeContext); int status = (int)controller.DeduceExternalStatusForTConnect(tc); Assert.AreEqual((int)TConnectStatusModel.Status.Accepted, status); } }
/// <summary> /// Checks TConnect to see if TConnectRequest already exists for this TConnect. /// Updates TConnectRequest (if already exists) or creates a new one if needed. /// </summary> /// <param name="Uow"></param> /// <param name="mt"></param> /// <param name="newEta">Expected arrival of the inbound vehicle for the tConnect</param> protected void MonitorTConnect(IUnitOfWork Uow, TConnect mt, DateTime newEta) { //First determine if we are updating an item that already has an active TRequest, or if //this is a general Monitored vehicle that has not yet generated a TConnectRequest. //Check TConnectRequest table for a matching row for this tconnect var tr = Uow.Repository <TConnectRequest>().Query().Get().Where(s => s.TConnectId.Equals(mt.Id)); //Will need outbound departure time and stopcode Step outboundStep = Uow.Repository <Step>().Query().Include(s => s.Block).Get().First(s => s.Id.Equals(mt.OutboundStepId)); if (tr.Any()) { TConnectRequest treq = tr.First(); UpdateExistingTConnectRequest(Uow, mt, newEta, treq); } else { CreateNewTConnectRequestIfNeeded(Uow, mt, newEta, outboundStep); } }
public async Task <DateTime> CalculateEstimatedTimeOfArrivalAsync(TConnect tConnect, IUnitOfWork Uow) { string DATE_FORMAT = "MM/dd/yyyy h:mm:ss"; DateTime dtParsed = DateTime.MinValue; try { var predictions = await busTimeApi.GetPredictionsAsync(tConnect.InboundStep.ToStopCode, tConnect.InboundStep.RouteNumber); var prediction = predictions.Find(p => tConnect.InboundVehicle.Equals(p.VehicleID.ToString(), StringComparison.CurrentCultureIgnoreCase)); bool wasParsed = DateTime.TryParseExact(prediction.PredictedTimeOfArrivalOrDeparture, DATE_FORMAT, System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dtParsed); if (!wasParsed) { DATE_FORMAT = "M/d/yyyy h:m:s tt"; wasParsed = DateTime.TryParseExact(prediction.PredictedTimeOfArrivalOrDeparture, DATE_FORMAT, System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dtParsed); if (!wasParsed) { DATE_FORMAT = "MM/dd/yyyy hh:mm:ss tt"; wasParsed = DateTime.TryParseExact(prediction.PredictedTimeOfArrivalOrDeparture, DATE_FORMAT, System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.None, out dtParsed); } } DateTime dtUTC = TimeZoneInfo.ConvertTime(dtParsed, TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time"), TimeZoneInfo.Utc); return(dtUTC); } catch (Exception ex) { return(DateTime.MinValue); // Eat this. Logging would be cool though. } }
public void ResolveVehicleLocationProviderType_Other_Fails() { using (IDbContext idtoFakeContext = new IDTOFakeContext()) using (IUnitOfWork unitOfWork = new UnitOfWork(idtoFakeContext)) { Step stepEntity = new Step(); stepEntity.StepNumber = 1; stepEntity.StartDate = DateTime.Parse("1/1/2014 10:02"); stepEntity.EndDate = DateTime.Parse("1/1/2014 10:40"); stepEntity.FromName = "Quartz Street"; stepEntity.FromProviderId = (int)Providers.COTA; stepEntity.FromStopCode = "1001"; stepEntity.ModeId = (int)Modes.Bus; stepEntity.RouteNumber = "039"; stepEntity.Distance = (decimal)12.2; stepEntity.ToName = "Slate Run Road"; stepEntity.ToProviderId = (int)Providers.COTA; stepEntity.ToStopCode = "2002"; unitOfWork.Repository <Step>().Insert(stepEntity); unitOfWork.Save(); TConnect tconn = new TConnect(); tconn.InboundStepId = stepEntity.Id; unitOfWork.Repository <TConnect>().Insert(tconn); unitOfWork.Save(); try { IVehicleLocation iv = VehicleLocationMonitorWorker.ResolveVehicleLocationProviderType(tconn, unitOfWork, scheduleFakes); Assert.AreEqual(true, false, "Test should have thrown an exception and not executed this line."); } catch (Exception ex) { //unhandled type } } }
/// <summary> /// Note, this setup is a bit 'integration test-y' because I call SaveTrip to load up all the stuff and the Tconnect. /// </summary> /// <param name="unitOfWork"></param> /// <param name="tripEntity"></param> /// <param name="steps"></param> /// <param name="mt"></param> private void SetupUowWithTripAndTConnect(IUnitOfWork unitOfWork, out Trip tripEntity, out List <Step> steps, out TConnect mt) { Diagnostics = new IdtoDiagnostics(); //to avoid null ref exc. set up base diagnostics. tripEntity = TestData.GetTrip(); steps = TestData.GetSteps(); //trips and steps get added in savetrip service call TConnectOpportunity TConnOpp = TestData.GetTConnectOpportunity(); unitOfWork.Repository <TConnectOpportunity>().Insert(TConnOpp); unitOfWork.Save(); ITripService tripService = new TripService(5); int id = tripService.SaveTrip(tripEntity, steps, unitOfWork); //Get the TConnect just created by the SaveTrip function mt = unitOfWork.Repository <TConnect>().Query().Get().First(); Assert.AreEqual(1, unitOfWork.Repository <TConnect>().Query().Get().Count(), "TConnect that should have been created by SaveTrip did not get created."); }
/// <summary> /// Adds a trip and its steps to the database. Also determines /// if the trip contains steps that match special criteria for a TConnect. /// </summary> /// <param name="trip"></param> /// <param name="steps"></param> /// <param name="Uow"></param> /// <returns></returns> public int SaveTrip(Trip trip, List <Step> steps, IUnitOfWork Uow) { //Save trip and steps to database Uow.Repository <Trip>().Insert(trip); Uow.Repository <TripEvent>().Insert(new TripEvent(trip.Id, "Trip Created")); Uow.Save(); foreach (Step s in steps) { s.TripId = trip.Id;//assign the step to the trip Uow.Repository <Step>().Insert(s); Uow.Save(); } //Use TConnectOpportunity table as the list of "special" connections. //Compare endpoints in table to endpoints between steps in trip. //Remove walking steps, because those are not relevant to this determination. //If given: //Step A : StartA StopA //Step B : StartB StopB //If TConnectOpportunity CheckPointStopCode == StopA and TConnectStopCode == StartB //then a TConnect should be created Step[] busSteps = steps.Where(t => t.ModeId != (int)Modes.Walk).ToArray(); bool notTheEnd = true; var e = busSteps.GetEnumerator(); /* * var tostopcodesArray = busSteps.Select(k => k.ToStopCode).ToList(); * var tOppCheckpointsAsArray = Uow.Repository<TConnectOpportunity>().Query().Get().Select(asdf => asdf.CheckpointStopCode).ToList(); * var allTOpps = Uow.Repository<TConnectOpportunity>().Query().Get().AsEnumerable().ToList(); * var thecodethatmatched = tostopcodesArray.Where(code => Uow.Repository<TConnectOpportunity>().Query().Get().Any(tconn => tconn.CheckpointStopCode.Equals(code))).ToList(); * var stepsInTOppTable = busSteps.Where(code => Uow.Repository<TConnectOpportunity>().Query().Get().Any(tconn => tconn.CheckpointStopCode.Equals(code.ToStopCode))).ToList(); * * var tOppInStep = Uow.Repository<TConnectOpportunity>().Query().Get().Where(code => busSteps.Any(tconn => tconn.ToStopCode.Equals(code.CheckpointStopCode))).ToList(); * * foreach (TConnectOpportunity topp in tOppInStep) * { * var enumerable = busSteps.Select(k => k.ToStopCode.Equals(topp.CheckpointStopCode)).GetEnumerator();//get the tOpp that matched * var current = enumerable.Current; * enumerable.MoveNext(); * var next = enumerable.Current; * * } * * * e.MoveNext();//move to first spot. * while (notTheEnd) * { * Step theStep = (Step)e.Current; * var tOppMatchingStep = Uow.Repository<TConnectOpportunity>().Query().Get().Where(code => code.CheckpointStopCode.Equals(theStep.ToStopCode)).ToList(); * if (tOppMatchingStep.Count > 1) * { * //TODO * throw new Exception("we could have one checkpoint that has multiple different tconnects, yes???"); * } * else if (tOppMatchingStep.Count == 1) * { * notTheEnd = e.MoveNext();//see if the from code for the next step matches the tconnect for the match. * if (notTheEnd) * { * theStep = (Step)e.Current; * if (tOppMatchingStep[0].TConnectStopCode == theStep.FromStopCode) * { * //Add TConnect * var tconnect = "add new"; * } * } * } * else * { * notTheEnd = e.MoveNext();//no matches, go onto next step to check it too * * } * } * * * e.Reset(); */ e.MoveNext();//move to first step. while (notTheEnd) { Step theStep = (Step)e.Current; notTheEnd = e.MoveNext();//see if the from code for the next step matches the tconnect for the pair. if (notTheEnd) { Step theNextStep = (Step)e.Current; var tOppMatchingStep = Uow.Repository <TConnectOpportunity>().Query().Get() .Where(code => code.CheckpointStopCode.Equals(theStep.ToStopCode) && code.TConnectStopCode.Equals(theNextStep.FromStopCode) && code.TConnectRoute.Equals(theNextStep.RouteNumber)).ToList(); if (tOppMatchingStep.Count > 1) { //To Stop Code and from stop code pairings in TConnectOpportunity should be unique. throw new Exception("TripService: TConnectOpportunity should not have duplicate rows."); } else if (tOppMatchingStep.Count == 1) { //Add TConnect //Tconnect created with Status New. //InboundVehicle,TConnectRequestID will all be //filled in later by the Monitor TConnect newTConnect = new TConnect(); newTConnect.CreatedDate = DateTime.UtcNow; newTConnect.ModifiedDate = DateTime.UtcNow; newTConnect.ModifiedBy = "WebAPI"; //newTConnect.TConnectStatusId = Uow.Repository<TConnectStatus>().Query().Filter(s => s.Name.Equals("New")).Get().Select(s => s.Id).First(); newTConnect.TConnectStatusId = (int)TConnectStatuses.New; newTConnect.InboundStepId = theStep.Id; newTConnect.OutboundStepId = theNextStep.Id; TimeSpan walkDuration = CalculateWalkDuration(theStep, theNextStep, steps); //Start time of the departing step minus walk time would be the earliest time a TConnect would be issued. //If bus left at 2:00, and walking takes 5 minutes, the arriving bus would have to arrive by 1:55 to make it. newTConnect.StartWindow = theNextStep.StartDate - walkDuration; //For now, we assume the bus will never wait more than 8 minutes. However, //I think this may be provider and even stop-dependent. Bus routes that have busses that //leave every 10 minutes would probably not wait more than 2 minutes, but routes that are //only hourly or daily may be willing to wait longer. Perhaps the max wait time should go //into the tconnectopportunity table per route. newTConnect.EndWindow = theNextStep.StartDate.AddMinutes(_tConnectWindowInMinutes) - walkDuration; Uow.Repository <TConnect>().Insert(newTConnect); Uow.Repository <TripEvent>().Insert(new TripEvent(trip.Id, "T-Connect Created")); Uow.Save(); } } } return(trip.Id); }
private void MonitorTravelerLocation(TConnect mt) { try { if (DateTime.UtcNow >= mt.InboundStep.StartDate && DateTime.Now <= mt.InboundStep.StartDate.AddMinutes(1)) { //get traveler location int travelerId = mt.InboundStep.Trip.TravelerId; var travelerLocations = Uow.Repository <TravelerLocation>().Query() .Get().Where(s => s.TravelerId == travelerId).OrderByDescending(s => s.PositionTimestamp); var lastTravelerLocation = travelerLocations.FirstOrDefault <TravelerLocation>(); if (lastTravelerLocation != null) { //get vehicle location nearest to the traveler location time LastVehiclePosition lvp = Uow.Repository <LastVehiclePosition>().Query().Get().First(v => v.VehicleName == mt.InboundVehicle); //get distance between them double dist_m = Conversions.distanceMeters(lastTravelerLocation.Latitude, lastTravelerLocation.Longitude, lvp.Latitude, lvp.Longitude); //get time between the vehilcle location and the traveler location TimeSpan tsDiff = lastTravelerLocation.PositionTimestamp - lvp.PositionTimestamp; //do a fuzzy match, like distance within 100 meters if (Math.Abs(tsDiff.TotalSeconds) < 30) { if (dist_m > 100) { //We are there. Time to stop monitoring. mt.TConnectStatusId = (int)TConnectStatuses.Done; Uow.Repository <TConnect>().Update(mt); Uow.Repository <TripEvent>().Insert(new TripEvent(mt.InboundStep.TripId, "Done monitoring T-Connect." + " Traveler never arrived and is " + dist_m.ToString() + " meters away." + " Traveler loc (" + lastTravelerLocation.Latitude.ToString() + "," + lastTravelerLocation.Longitude.ToString() + ") @ " + lastTravelerLocation.PositionTimestamp.ToString("hh:mm:ss") + " Vehicle loc (" + lvp.Latitude.ToString() + "," + lvp.Longitude.ToString() + ") @ " + lvp.PositionTimestamp.ToString("hh:mm:ss") )); Uow.Save(); } } } } }catch (Exception ex) { String innerExString = ""; String stackTraceString = ""; if (ex.InnerException != null) { innerExString = ex.InnerException.Message; if (ex.InnerException.StackTrace != null) { stackTraceString = ex.InnerException.StackTrace.ToString(); } } Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Error, TraceEventId.TraceGeneral, " Error in MonitorTravelerLocation for TConnect: " + mt.Id + ". " + ex.Message + " InnerEx: " + innerExString + " StackTrace: " + stackTraceString); } }
private async Task MonitorLocationTimes(TConnect mt) { TimeSpan ts = TimeSpan.FromSeconds(120); LocationMonitoringNotificationSwitchboard switchboard = new LocationMonitoringNotificationSwitchboard(); if (locationNotificationTrackingDictionary.ContainsKey(mt.InboundStep.TripId)) { switchboard = locationNotificationTrackingDictionary[mt.InboundStep.TripId]; } Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "MonitorLocationTimes tConnect.Id=" + mt.Id + "InboundStartDate=" + mt.InboundStep.StartDate.ToLongTimeString() + "NowUtc=" + DateTime.UtcNow.ToLongTimeString() + "sent=" + switchboard.SentStartInboundStep.ToString()); if (DateTime.UtcNow >= mt.InboundStep.StartDate.AddMinutes(-1) && switchboard.SentStartInboundStep == false) { Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "MonitorLocationTimes Sending Start Monitoring Locationat Start of Inbound Step for tConnect.Id=" + mt.Id); //send notification to track location bool result = await notificationManager.SendIOSSilentNotificationAsync( mt.InboundStep.Trip.TravelerId.ToString(), (int)ts.TotalSeconds); result = await notificationManager.SendGcmSilentNotificationAsync( mt.InboundStep.Trip.TravelerId.ToString(), (int)ts.TotalSeconds); Uow.Repository <TripEvent>().Insert(new TripEvent(mt.InboundStep.TripId, "Send notification to start monitoring start of inbound step location for " + ts.TotalSeconds.ToString() + " seconds")); Uow.Save(); switchboard.SentStartInboundStep = true; } Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "MonitorLocationTimes tConnect.Id=" + mt.Id + "InboundEndDate=" + mt.InboundStep.EndDate.ToLongTimeString() + "NowUtc=" + DateTime.UtcNow.ToLongTimeString() + "sent=" + switchboard.SentEndInboundStep.ToString()); if (DateTime.UtcNow >= mt.InboundStep.EndDate.AddMinutes(-1) && switchboard.SentEndInboundStep == false) { Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "MonitorLocationTimes Sending Start Monitoring Locationat End of Inbound Step for tConnect.Id=" + mt.Id); //send notification to track location bool result = await notificationManager.SendIOSSilentNotificationAsync( mt.InboundStep.Trip.TravelerId.ToString(), (int)ts.TotalSeconds); result = await notificationManager.SendGcmSilentNotificationAsync( mt.InboundStep.Trip.TravelerId.ToString(), (int)ts.TotalSeconds); Uow.Repository <TripEvent>().Insert(new TripEvent(mt.InboundStep.TripId, "Send notification to start monitoring end of inbound step location for " + ts.TotalSeconds.ToString() + " seconds")); Uow.Save(); switchboard.SentEndInboundStep = true; } Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "MonitorLocationTimes tConnect.Id=" + mt.Id + "OutboundStartDate=" + mt.OutboundStep.StartDate.ToLongTimeString() + "NowUtc=" + DateTime.UtcNow.ToLongTimeString() + "sent=" + switchboard.SentStartOutboundStep.ToString()); if (DateTime.UtcNow >= mt.OutboundStep.StartDate.AddMinutes(-1) && switchboard.SentStartOutboundStep == false) { Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "MonitorLocationTimes Sending Start Monitoring Locationat Start of Outbound Step for tConnect.Id=" + mt.Id); //send notification to track location bool result = await notificationManager.SendIOSSilentNotificationAsync( mt.InboundStep.Trip.TravelerId.ToString(), (int)ts.TotalSeconds); result = await notificationManager.SendGcmSilentNotificationAsync( mt.InboundStep.Trip.TravelerId.ToString(), (int)ts.TotalSeconds); Uow.Repository <TripEvent>().Insert(new TripEvent(mt.InboundStep.TripId, "Send notification to start monitoring start of outbound step location for " + ts.TotalSeconds.ToString() + " seconds")); Uow.Save(); switchboard.SentStartOutboundStep = true; } if (locationNotificationTrackingDictionary.ContainsKey(mt.InboundStep.TripId)) { locationNotificationTrackingDictionary[mt.InboundStep.TripId] = switchboard; } else { locationNotificationTrackingDictionary.Add(mt.InboundStep.TripId, switchboard); } }
/// <summary> /// Checks the Eta for the inbound vehicle to the departure window that would warrant /// a TConnectRequest. Creates a TConnectRequest if possible. /// </summary> /// <param name="Uow"></param> /// <param name="tConnect"></param> /// <param name="newEta"></param> /// <param name="outboundStep"></param> async protected void CreateNewTConnectRequestIfNeeded(IUnitOfWork Uow, TConnect tConnect, DateTime newEta, Step outboundStep) { if (newEta > tConnect.StartWindow && newEta <= tConnect.EndWindow) { //We want to issue a TConnect Request. Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "Requesting TConnect. newEta=" + newEta.ToShortTimeString() + " endwindow=" + tConnect.EndWindow.ToString() + " tConnect.Id=" + tConnect.Id); TConnectRequest newRequest = new TConnectRequest(); //Need a TConnectedVehicle for this new request. int acceptedWaitTime = 0; newRequest.TConnectedVehicleId = GetOrCreateTConnectedVehicleKey(Uow, outboundStep, out acceptedWaitTime); //set ref to vehicle newRequest.TConnectId = tConnect.Id; //set ref to owning tConnect. newRequest.EstimatedTimeArrival = newEta; //Calculate how late we'll be newRequest.RequestedHoldMinutes = (int)System.Math.Ceiling((newEta - (DateTime)tConnect.StartWindow).TotalMinutes); newRequest.ModifiedBy = ModifiedBy; newRequest.ModifiedDate = DateTime.UtcNow; if (newRequest.RequestedHoldMinutes <= acceptedWaitTime) { //This request is asking for a wait less than the amount the bus already agreed to, so this //is automatically accepted. newRequest.TConnectStatusId = (int)TConnectStatuses.Accepted; Uow.Repository <TripEvent>().Insert(new TripEvent(outboundStep.TripId, "T-Connect Request created and auto accapted")); } else { newRequest.TConnectStatusId = (int)TConnectStatuses.New;//new request Uow.Repository <TripEvent>().Insert(new TripEvent(outboundStep.TripId, "T-Connect Request created.")); } Uow.Repository <TConnectRequest>().Insert(newRequest); Uow.Save(); } else if (newEta > tConnect.EndWindow) { //Will be Too late to issue a TConnect, bus wont wait this long. Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Information, TraceEventId.TraceGeneral, "Bus Missed before there was a chance to issue a request. newEta=" + newEta.ToShortTimeString() + " endwindow=" + tConnect.EndWindow.ToString() + " tConnect.Id=" + tConnect.Id); //Update status to done. tConnect.TConnectStatusId = (int)TConnectStatuses.Done; Uow.Repository <TConnect>().Update(tConnect); Uow.Repository <TripEvent>().Insert(new TripEvent(outboundStep.TripId, "T-Connect Request not created, Inbound bus will be too late.")); Uow.Save(); //Notify Traveler of TConnect creation //TODO need to find traveller device type (Android, IOS, etc) for now defaulting to Android //find traveler email and send push update Traveler t = Uow.Repository <Traveler>().Query().Get().Where(s => s.Id == tConnect.InboundStep.Trip.TravelerId).First(); if (t != null && t.Email != null) { bool result = await notificationManager.SendRejectNotificationsAsync(t.Email); } } else { string msg = "No need to issue a request yet. Eta=" + newEta.ToShortTimeString() + " : "; msg += "T-Connect Window [" + ((DateTime)tConnect.StartWindow).ToShortTimeString() + "-"; msg += ((DateTime)tConnect.EndWindow).ToShortTimeString() + "]"; LogTripEventIfDifferentFromLast(Uow, outboundStep.TripId, msg); //really verbose message Diagnostics.WriteMainDiagnosticInfo(TraceEventType.Verbose, TraceEventId.TraceGeneral, "No need to issue a request yet. newEta=" + newEta.ToShortTimeString() + " endwindow=" + tConnect.EndWindow.ToString() + " tConnect.Id=" + tConnect.Id); } }