public void Should_Return_All_Routes()
 {
     using (var repos = new RouteRepository(DataFilePath)) {
         var result = repos.GetAllRoutes();
         Assert.That(result.Count(t => t != null), Is.EqualTo(DataFileRowCountMinusHeader));
     }
 }
예제 #2
0
        public void GetRoutes()
        {
            RouteRepository routeRepository = new RouteRepository();

            Route[] routes = routeRepository.GetAllRoutes();
            Assert.IsTrue(routes != null);
        }
예제 #3
0
        public static string PrepareSearchResponse(string searchRequest)
        {
            string[] searchParams  = searchRequest.Split('?');
            string   departureDate = searchParams[(int)SearchParam.DepartureDate];
            string   fromStation   = searchParams[(int)SearchParam.FromStation];
            string   toStation     = searchParams[(int)SearchParam.ToStation];

            Console.WriteLine($" Search input: \n" +
                              $"departureDate: {departureDate}\n" +
                              $"fromStation: {fromStation}\n" +
                              $"toStation: {toStation}\n");

            RouteRepository        routeRepository = new RouteRepository();
            List <TrainConnection> result          = routeRepository.SearchForTrainConnection(Convert.ToDateTime(departureDate), fromStation, toStation);

            result.Sort(new TrainConnectionComparator());

            string resultString = "";

            foreach (TrainConnection r in result)
            {
                SearchResponse searchResponse
                    = new SearchResponse(
                          r.travel_id,
                          r.train_name,
                          r.departure_date.ToString(),
                          r.departure_hour.ToString(),
                          r.total_price.ToString(),
                          r.total_duration.ToString());
                resultString += searchResponse.ToString() + ';';
            }
            resultString = resultString.Remove(resultString.Length - 1, 1);
            return(resultString);
        }
예제 #4
0
        public void new_route_must_be_persisted_in_file()
        {
            var newFile = "../../../stdin/new- route.csv";

            try
            {
                File.Create(newFile).Close();
                var inputRep = new RouteRepository(newFile);
                var newRoute = inputRep.Save(new infra.dto.RouteData("GIG", "LAG", 150));

                Assert.True(newRoute.OriginAirport.Equals("GIG"));
                Assert.True(newRoute.DestinationAirport.Equals("LAG"));
                Assert.True(newRoute.FlightPrice.Equals(150));

                var result = inputRep.Get();
                Assert.True(result.Count == 2);
                Assert.True(result.Exists(x => x.AirportName.Equals("GIG")));
                Assert.True(result.Exists(x => x.AirportName.Equals("LAG")));
                Assert.True(result.Find(x => x.AirportName.Equals("GIG")).Connections.Exists(x => x.Airport.AirportName.Equals("LAG")));
                Assert.True(result.Find(x => x.AirportName.Equals("GIG")).Connections.Find(x => x.Airport.AirportName.Equals("LAG")).Price == 150);
            }
            finally { if (File.Exists(newFile))
                      {
                          File.Delete(newFile);
                      }
            }
        }
예제 #5
0
        /// <summary>
        ///     Copy Constructor
        /// </summary>
        /// <param name="routeCopy"></param>
        public Route(Route routeCopy)
        {
            var rr = new RouteRepository();

            Name        = "Copy of " + routeCopy.Name;
            Description = routeCopy.Description;
            //routesTA.Insert(this.Name, this.Description, out tempID);

            var route = new Models.Inrix.Route();

            route.Route_Name        = Name;
            route.Route_Description = Description;

            rr.Add(route);


            var copiedRoute = rr.GetRouteByName(name);

            ID = Convert.ToInt32(copiedRoute.Route_ID);


            foreach (var segment in routeCopy.Items)
            {
                Items.Add(segment);
            }

            SaveMembers();
        }
예제 #6
0
        //
        // GET: /Route/

        public ActionResult ShowAllRoutes()
        {
            IRouteRepository routeRepository = new RouteRepository();
            var aggregatedRoutes             = routeRepository.GetAggregatedRoutes(50 * 1000); // w metrach
            var routes = routeRepository.getAllRoutes();
            List <POIModelExtended> RoutesList = new List <POIModelExtended>();
            POIModelExtended        routeToAdd;
            string place;

            //foreach(var route in routes)
            //{
            //    routeToAdd = new POIModel("", route.StartPoint, route.StartLat.GetValueOrDefault(), route.StartLong.GetValueOrDefault());
            //    RoutesList.Add(routeToAdd);
            //    routeToAdd = new POIModel("", route.EndPoint, route.EndLat.GetValueOrDefault(), route.EndLong.GetValueOrDefault());
            //    RoutesList.Add(routeToAdd);
            //}

            foreach (var route in aggregatedRoutes)
            {
                routeToAdd = new POIModelExtended("", route.StartName, route.StartLat, route.StartLong, route.Rate);
                RoutesList.Add(routeToAdd);
                routeToAdd = new POIModelExtended("", route.EndName, route.EndLat, route.EndLong, route.Rate);
                RoutesList.Add(routeToAdd);
            }

            return(View(RoutesList));
        }
예제 #7
0
        public DataAccessService()
        {
            DataContext context = new DataContext();

            CityRepository  = new CityRepository(context);
            RouteRepository = new RouteRepository(context);
        }
예제 #8
0
        public async Task ShouldCreateEntry()
        {
            var route = new Route(_mapPoint1Id, _mapPoint2Id, 10, 10);

            using (var context = _contextFactory.CreateDbContext())
            {
                var routeRepository = new RouteRepository(context);

                await routeRepository.AddAsync(route);

                await routeRepository.SaveChangesAsync();

                Assert.NotEqual(Guid.Empty, route.Id);
            }

            using (var context = _contextFactory.CreateDbContext())
            {
                var routeRepository = new RouteRepository(context);

                var fetchedRoute = await routeRepository.GetByIdAsync(route.Id);

                Assert.Equal(route.FromId, fetchedRoute.FromId);
                Assert.Equal(route.ToId, fetchedRoute.ToId);

                _routeId = fetchedRoute.Id;
            }
        }
예제 #9
0
 public UnitOfWork(bool test = false)
 {
     if (!test && !Test)
     {
         AccountTypes   = new AccountTypeRepository(new AccountTypeOracleContext());
         Employees      = new EmployeeRepository(new EmployeeOracleContext());
         AttachedTracks = new AttachedTrackRepository(new AttachedTrackOracleContext());
         Routes         = new RouteRepository(new RouteOracleContext());
         Sectors        = new SectorRepository(new SectorOracleContext());
         Statuses       = new StatusRepository(new StatusOracleContext());
         Tracks         = new TrackRepository(new TrackOracleContext());
         //TrackRoutes = new TrackRouteRepository(new TrackRouteOracleContext());
         Trams      = new TramRepository(new TramOracleContext());
         TramRoutes = new TramRouteRepository(new TramRouteOracleContext());
         Tasks      = new TaskRepository(new TaskOracleContext());
     }
     else
     {
         AccountTypes   = new AccountTypeRepository(new AccountTypeTestContext());
         Employees      = new EmployeeRepository(new EmployeeTestContext());
         Tracks         = new TrackRepository(new TrackTestContext());
         Sectors        = new SectorRepository(new SectorTestContext());
         Trams          = new TramRepository(new TramTestContext());
         Routes         = new RouteRepository(new RouteTestContext());
         AttachedTracks = new AttachedTrackRepository(new AttachedTrackTestContext());
         TramRoutes     = new TramRouteRepository(new TramRouteTestContext());
         TrackRoutes    = new TrackRouteRepository(new TrackRouteTestContext());
         TramStatuses   = new TramStatusRepository(new TramStatusTestContext());
     }
 }
예제 #10
0
        public static void Init()
        {
            if (Inited == false)
            {
                Inited = true;
                IRouteRepository             _IRouteRepository             = new RouteRepository();
                IRouteService                _IRouteService                = new RouteService(_IRouteRepository);
                IConnectionRepository        _IConnectionRepository        = new ConnectionRepository();
                IConnectionService           _IConnectionService           = new ConnectionService(_IConnectionRepository);
                IStationRepository           _IStationRepository           = new StationRepository();
                IStationService              _IStationService              = new StationService(_IStationRepository, _IConnectionRepository);
                IWalkingConnectionRepository _IWalkingConnectionRepository = new WalkingConnectionRepository();
                IWalkingConnectionService    _IWalkingConnectionService    = new WalkingConnectionService(_IWalkingConnectionRepository);

                oldStationList           = _IStationService.GetAllStation();
                oldConnectionList        = _IConnectionService.GetAllConnection();
                oldWalkingConnectionList = _IWalkingConnectionService.GetAllWalkingConnection();
                oldRouteList             = _IRouteService.GetRoute();
                newConnectionList        = new List <ViewModelNewConnection>();
                newStationList           = new List <ViewModelNewStation>();
                fanOut = new Dictionary <int, List <Vertex> >();
                //Graph.CreateNewGraph();
                Graph.CreateNewWalkingGraph();
                InitCompleted = true;
                _IRouteRepository.Dispose();
                _IConnectionRepository.Dispose();
                _IStationRepository.Dispose();
            }
        }
예제 #11
0
        protected override void Seed(TransportSchedule.Schedule.Repo.Context context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            DataRepository <Route>   routes   = new RouteRepository();
            DataRepository <Station> stations = new StationRepository();
            List <User> users = WorkinhWithUserMethods.GetUsers();

            foreach (var item in stations.Items)
            {
                context.Stations.AddOrUpdate(c => c.Id, item);
            }
            foreach (var item in routes.Items)
            {
                foreach (var station in item.Stations)
                {
                    station.Station = context.Stations.SingleOrDefault(x => x.Id == station.StationID);
                }
                context.Routes.AddOrUpdate(c => c.Name, item);
            }
            foreach (var item in users)
            {
                foreach (var station in item.FavouriteStations)
                {
                    station.Station = context.Stations.SingleOrDefault(x =>
                                                                       x.Id == station.StationID);
                    station.User = item;
                }
                context.Users.AddOrUpdate(c => c.UserId, item);
            }
            context.SaveChanges();
        }
예제 #12
0
        public void invalid_source_must_throw_exception()
        {
            var inputRep             = new RouteRepository("invalid-source");
            FileNotFoundException ex = Assert.Throws <FileNotFoundException>(() => inputRep.Get());

            Assert.Equal("stdin-not-found", ex.Message);
        }
예제 #13
0
        public void empty_file_must_return_empty_list()
        {
            var inputRep = new RouteRepository("../../../stdin/no-content.csv");
            var result   = inputRep.Get();

            Assert.True(result.Count == 0);
        }
예제 #14
0
        public static string PrepareTicketResponse(string ticketRequest)
        {
            string userId = ticketRequest;

            Console.WriteLine($" Ticket input: \n" +
                              $"userId: {userId}\n");

            SaleRepository saleRepository = new SaleRepository();
            List <Sale>    saleResults    = saleRepository.GetUserSales(Convert.ToInt32(userId));

            RouteRepository routeRepository = new RouteRepository();

            string resultString = "";

            foreach (Sale sale in saleResults)
            {
                Route route = routeRepository.Get(sale.route_id);
                List <TrainConnection> result = routeRepository.SearchForTrainConnection(route.departure_date, sale.from_station, sale.to_station);
                decimal  price = 0;
                TimeSpan time  = new TimeSpan();
                TimeSpan hour  = new TimeSpan();

                foreach (TrainConnection r in result)
                {
                    if (r.travel_id == route.id)
                    {
                        price = r.total_price;
                        time  = r.total_duration;
                        hour  = r.departure_hour;
                    }
                }

                string   saleTicketNameAmountPercentage     = saleRepository.GetSaleTicketNameAmountPercentage(sale.id);
                string[] saleTicketNameAmountPercentagArray = saleTicketNameAmountPercentage.Split(',');
                var      ticketName       = saleTicketNameAmountPercentagArray[0];
                var      ticketsAmount    = saleTicketNameAmountPercentagArray[1];
                var      ticketPercentage = saleTicketNameAmountPercentagArray[2];

                var totalPrice = price * (Convert.ToInt32(ticketsAmount)) * (Convert.ToDecimal(ticketPercentage) / 100);
                //(Convert.ToInt32(ticketPercentage) / 100.0) *
                TicketResponse ticketResponse
                    = new TicketResponse(
                          route.train_name.ToString(),
                          sale.from_station,
                          sale.to_station,
                          sale.sale_date.ToString(),
                          route.departure_date.ToString(),
                          hour.ToString(),
                          totalPrice.ToString(),
                          time.ToString(),
                          sale.payment_status.ToString(),
                          ticketName,
                          ticketsAmount);
                resultString += ticketResponse.ToString() + ';';
            }

            resultString = resultString.Remove(resultString.Length - 1, 1);
            return(resultString);
        }
예제 #15
0
 public IEnumerable <Route> GetAllRoutes()
 {
     using (var context = new ConfigurationToolContext())
     {
         var repository = new RouteRepository(context);
         return(repository.GetAll());
     }
 }
예제 #16
0
 public UnitOfWork(McDbContext context)
 {
     _context = context;
     Adresses = new AdresseRepository(_context);
     Events   = new EventRepository(_context);
     Routes   = new RouteRepository(_context);
     Users    = new UserRepository(_context);
 }
예제 #17
0
        public DatabaseRoutesFixture()
        {
            Route4MeDbManager.DatabaseProvider = DatabaseProviders.InMemory;

            GetDbContext(DatabaseProviders.InMemory);

            _routeRepository = new RouteRepository(_route4meDbContext);
        }
예제 #18
0
        public AdminController(IConfiguration Configuration)
        {
            VehiclesRepo     = new VehiclesRepository();
            MetroStationRepo = new MetroStationRepository();
            RouteRepo        = new RouteRepository();
            ValidationRepo   = new ValidationHistoryRepository();

            _config = Configuration;
        }
예제 #19
0
 public UnitOfWork()
 {
     Items     = new ItemRepository();
     Merchants = new MerchantRepository();
     Monsters  = new MonsterRepository();
     Routes    = new RouteRepository();
     Towns     = new TownRepository();
     Elements  = new ElementRepository();
 }
예제 #20
0
        public void Save()
        {
            var file    = Path.GetFileNameWithoutExtension(dbFilePath);
            var newPath = dbFilePath.Replace(file, $"{file}-{DateTime.Now:yyyyMMddhhmmss}");

            File.Move(dbFilePath, newPath);

            RouteRepository.SaveRoute(dbFilePath, Route);
        }
예제 #21
0
 public void DeleteRoute(Route route)
 {
     using (ConfigurationToolContext context = new ConfigurationToolContext())
     {
         var repository = new RouteRepository(context);
         repository.Delete(route);
         context.SaveChanges();
     }
 }
예제 #22
0
        public async Task <RouteListTransactionResponse> Handle(RouteListTransactionRequest request, CancellationToken cancellationToken)
        {
            var Routes = await RouteRepository.GetAll(cancellationToken);

            RouteListTransactionResponse response = new RouteListTransactionResponse();

            response.RouteList =
                Routes.Select(x => Conversions.FromDTOToModel(x)).ToList();
            return(response);
        }
예제 #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UnitOfWork"/> class.
 /// </summary>
 /// <param name="context">The context<see cref="ApplicationContext"/>.</param>
 public UnitOfWork(ApplicationContext context)
 {
     _context  = context;
     Buses     = new BusRepository(_context);
     Stops     = new StopRepository(_context);
     Routes    = new RouteRepository(_context);
     BusRoutes = new BusRouteRepository(_context);
     Bookings  = new BookingRepository(_context);
     Users     = new UserRepository(_context);
 }
예제 #24
0
        public async Task <RouteUpdateTransactionResponse> Handle(RouteCreateTransactionRequest request, CancellationToken cancellationToken)
        {
            var Route = await RouteRepository.Add(
                Conversions.FromModelToDTO(request.Route), cancellationToken);

            RouteUpdateTransactionResponse response = new RouteUpdateTransactionResponse();

            response.Route = Conversions.FromDTOToModel(Route);
            return(response);
        }
예제 #25
0
        public void input_sample_route_must_have_connections()
        {
            var inputRep = new RouteRepository("../../../stdin/input-routes_sample.csv");
            var result   = inputRep.Get();

            Assert.True(result.Count == 2);
            Assert.True(result.Exists(x => x.AirportName.Equals("GRU")));
            Assert.True(result.Exists(x => x.AirportName.Equals("BRC")));
            Assert.True(result.Find(x => x.AirportName.Equals("GRU")).Connections.Exists(x => x.Airport.AirportName.Equals("BRC")));
            Assert.True(result.Find(x => x.AirportName.Equals("GRU")).Connections.Find(x => x.Airport.AirportName.Equals("BRC")).Price.Equals(10));
        }
예제 #26
0
        public void SetUp()
        {
            var repository      = new RouteRepository(Context);
            var repositoryEmpty = new RouteRepository(ContextEmpty);

            var service      = new RouteService(repository, Mapper);
            var serviceEmpty = new RouteService(repositoryEmpty, Mapper);

            _routesController      = new RoutesController(service, Mapper);
            _routesControllerEmpty = new RoutesController(serviceEmpty, Mapper);
        }
예제 #27
0
        public UnitOfWork(ApplicationDbContext context)
        {
            _context = context;

            Countries        = new Repository <Country>(context);
            Locations        = new Repository <Location>(context);
            RailwayPlatforms = new Repository <RailwayPlatform>(context);
            RailwayStations  = new RailwayStationRepository(context);
            Routes           = new RouteRepository(context);
            Users            = new Repository <User>(context);
        }
예제 #28
0
 public RouteService(
     OrderRepository order,
     VehicleRepository vehicle,
     RouteRepository route,
     VehicleService vehicleService
     )
 {
     _order          = order;
     _vehicle        = vehicle;
     _route          = route;
     _vehicleService = vehicleService;
 }
예제 #29
0
        public void input_route_must_remove_escaped_rows()
        {
            var inputRep = new RouteRepository("../../../stdin/escape-rows.csv");
            var result   = inputRep.Get();

            Assert.True(result.Count == 5);
            Assert.True(result.Exists(x => x.AirportName.Contains("GRU")));
            Assert.True(result.Exists(x => x.AirportName.Contains("BRC")));
            Assert.True(result.Exists(x => x.AirportName.Contains("SCL")));
            Assert.True(result.Exists(x => x.AirportName.Contains("ORL")));
            Assert.True(result.Exists(x => x.AirportName.Contains("CDG")));
        }
		public void WhenGetsANonOkResponseShouldThrowsAnException()
		{
			_responseHandler.AddResponse(FIND_ROUTES_URL, new HttpResponseMessage(HttpStatusCode.BadRequest));
			_responseHandler.AddResponse(FIND_STOPS_URL, new HttpResponseMessage(HttpStatusCode.BadRequest));
			_responseHandler.AddResponse(FIND_DEPARTURES_URL, new HttpResponseMessage(HttpStatusCode.BadRequest));
			var client = new HttpClient (_responseHandler);

			var repository = new RouteRepository (client);

			Assert.Throws<Exception> (async () => await repository.FindRoutesByStopNameAsync (string.Empty));
			Assert.Throws<Exception> (async () => await repository.FindStopsByRouteIdAsync (0));
			Assert.Throws<Exception> (async () => await repository.FindDeparturesByRouteIdAsync (0));
		}
예제 #31
0
        private async void showRoutes(int?RouteID)
        {
            progRing.IsActive   = true;
            progRing.Visibility = Visibility.Visible;

            RouteRepository r = new RouteRepository();

            try
            {
                List <Route> routes;
                if (RouteID.GetValueOrDefault() > 0)
                {
                    routes = await r.GetRoutesByRegion(RouteID.GetValueOrDefault());
                }
                else
                {
                    routes = await r.GetRoutes();
                }
                routeList.ItemsSource = routes.OrderBy(e => e.ID);
            }
            catch (ApiException apiEx)
            {
                var sbuilder = new StringBuilder();
                sbuilder.AppendLine("Errors:");
                foreach (var error in apiEx.Errors)
                {
                    sbuilder.AppendLine("-" + error);
                }
                ProfessorOak.ShowMessage("Could not complete operation:", sbuilder.ToString());
                progRing.IsActive   = false;
                progRing.Visibility = Visibility.Collapsed;
            }
            catch (Exception ex)
            {
                if (ex.InnerException.Message.Contains("server"))
                {
                    ProfessorOak.ShowMessage("Error", "No connection with the server.");
                }
                else
                {
                    ProfessorOak.ShowMessage("Error", "Could not complete operation.");
                }
            }
            finally
            {
                progRing.IsActive   = false;
                progRing.Visibility = Visibility.Collapsed;
            }
        }
 public TransferRequestByDateBLL()
 {
     RouteRepository            = new RouteRepository();
     BusTypeRepository          = new BusTypeRepository();
     AgencyRepository           = new AgencyRepository();
     RoleRepository             = new RoleRepository();
     BookingRepository          = new BookingRepository();
     BusByDateRepository        = new BusByDateRepository();
     BookingBusByDateRepository = new BookingBusByDateRepository();
     LockingTransferRepository  = new LockingTransferRepository();
     ExpenseRepository          = new ExpenseRepository();
     ExpenseServiceRepository   = new ExpenseServiceRepository();
     CostTypeRepository         = new CostTypeRepository();
     GuideRepository            = new GuideRepository();
 }
		public async void GivenOneRouteFromServiceThenReturnsThisRouteWithItsData()
		{
			var responseContent = "{ \"rows\": [ { \"id\": 32, \"shortName\": \"133\", \"longName\": \"AGRONÔMICA VIA MAURO RAMOS\", \"lastModifiedDate\": \"2012-07-23T03:00:00+0000\", \"agencyId\": 9 } ], \"rowsAffected\": 0 }";
			var response = new HttpResponseMessage(HttpStatusCode.OK);
			response.Content = new StringContent (responseContent);
			_responseHandler.AddResponse(FIND_ROUTES_URL, response);
			var client = new HttpClient (_responseHandler);

			var repository = new RouteRepository (client);
			var routes = await repository.FindRoutesByStopNameAsync (string.Empty);

			Assert.AreEqual (1, routes.Count);
			Assert.AreEqual (32, routes [0].Id);
			Assert.AreEqual ("133", routes [0].ShortName);
			Assert.AreEqual ("AGRONÔMICA VIA MAURO RAMOS", routes [0].LongName);
		}
        public void Add_Route()
        {
            string routeName = "Test Route to Add";

            // Add to database
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                RouteRepository routeRepository = new RouteRepository(ctx);
                routeRepository.Add(new Route { Name = routeName, TimeTable = new TimeTable { Name = "TimeTable to add" } });
                routeRepository.SaveChanges();
            }

            // Check that it is there
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                List<Route> routes = ctx.Routes.Where(route => route.Name == routeName).ToList();
                Assert.AreEqual(1, routes.Count());
            }
        }
        public void Delete_Route_By_Route()
        {
            string routeName = "Test Route to Delete";

            // Add to database
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                RouteRepository routeRepository = new RouteRepository(ctx);
                Route route = new Route { 
                    Name = routeName, 
                    TimeTable = new TimeTable { Name = "TimeTable" }
                };

                route.Schedules = new List<Schedule>() { new Schedule { 
                    Route = route, 
                    Pier = new Pier { Name = "Pier" },
                    Time = new TimeSpan(1, 0, 0)
                    }
                };

                routeRepository.Add(route);
                routeRepository.SaveChanges();
            }

            // Find and delete it
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                List<Route> routes = ctx.Routes.Where(route => route.Name == routeName).ToList();
                Assert.AreEqual(1, routes.Count());

                RouteRepository routeRepository = new RouteRepository(ctx);
                routeRepository.Delete(routes[0]);
                routeRepository.SaveChanges();
            }

            // Check that nothing is there
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                List<Route> routes = ctx.Routes.Where(route => route.Name == routeName).ToList();
                Assert.AreEqual(0, routes.Count());
            }
        }
		public async void GivenTwoStopFromServiceThenReturnsTheseStopsWithTheirData()
		{
			var responseContent = new StringBuilder ()
				.Append ("{ \"rows\": [")
				.Append ("{ \"id\": 1, \"name\": \"TICEN\", \"sequence\": 1, \"route_id\": 35 },")
				.Append ("{ \"id\": 2, \"name\": \"RUA ANTÔNIO PEREIRA OLIVEIRA NETO\", \"sequence\": 2, \"route_id\": 35 }")
				.Append ("], \"rowsAffected\": 0 }")
				.ToString ();
					
			var response = new HttpResponseMessage(HttpStatusCode.OK);
			response.Content = new StringContent (responseContent);
			_responseHandler.AddResponse(FIND_STOPS_URL, response);
			var client = new HttpClient (_responseHandler);

			var repository = new RouteRepository (client);
			var stops = await repository.FindStopsByRouteIdAsync (0);

			Assert.AreEqual (2, stops.Count);
			Assert.AreEqual ("TICEN", stops [0].Name);
			Assert.AreEqual (1, stops [0].Sequence);
			Assert.AreEqual ("RUA ANTÔNIO PEREIRA OLIVEIRA NETO", stops [1].Name);
			Assert.AreEqual (2, stops [1].Sequence);
		}
예제 #37
0
        /// <summary>
        /// When implemented in a derived class, executes the scheduled job asynchronously. Implementations that want to know whether
        ///             the scheduled job is being cancelled can get a <see cref="P:Microsoft.WindowsAzure.Mobile.Service.ScheduledJob.CancellationToken"/> from the <see cref="M:CancellationToken"/> property.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Threading.Tasks.Task"/> representing the asynchronous operation.
        /// </returns>
        public override async Task ExecuteAsync()
        {
            // Load Feed Message
            var dbConnStr = ConfigurationManager.ConnectionStrings["MTA_DB"].ConnectionString;

            var service = new StaticFileService(new StaticFileDownloader());


            StringBuilder sb = new StringBuilder();

            List<string> tableNames = new List<string>()
            {
                "agency",
                "calendar",
                "calendar_dates",
                "shapes",
                "stop_times",
                "transfers",
                "trips",
                "routes",
                "stops",
            };

            tableNames.ForEach(s => sb.AppendFormat("TRUNCATE TABLE {0};", s));

            using (var conn = new SqlConnection(dbConnStr))
            {
                using (var cmd = new SqlCommand(sb.ToString(), conn))
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }


                //Agency
                using (var repository = new AgencyRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetAgencies());
                }

//            using (var repository = new CalendarDateRepository(dbConnStr))
//            {
//                // Load Tables
//                repository.AddRange(service.GetCalendarDates());
//            }

                //Calendars
                using (var repository = new CalendarRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetCalendars());
                }
                //Route
                using (var repository = new RouteRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetRoutes());
                }
                //Shape
                using (var repository = new ShapeRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetShapes());
                }
                //Stop
                using (var repository = new StopRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetStops());
                }
                //Stop Time
                using (var repository = new StopTimeRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetStopTimes());
                }
                //Transfer
                using (var repository = new TransferRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetTransfers());
                }
                //Trip
                using (var repository = new TripRepository() {Connection = conn})
                {
                    // Load Tables
                    repository.AddRange(await service.GetTrips());
                }

                // Build Stations
                using (var cmd = new SqlCommand("sp_BuildStations", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
//                    conn.Open();
                    cmd.ExecuteNonQuery();
                }

                using (var cmd = new SqlCommand("sp_CreateStaticSchedule", conn))
                {
                    cmd.CommandTimeout = 120;
                    cmd.CommandType = CommandType.StoredProcedure;
                    //                    conn.Open();

                    TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
                    DateTime easternTimeNow = TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc,
                                                                    easternZone);
                    cmd.Parameters.AddWithValue("@today", easternTimeNow);

                    cmd.ExecuteNonQuery();
                }
            }
        }
		public async void GivenThreeDeparturesThenReturnsTheseDeparturesWithTheirData()
		{
			var responseContent = new StringBuilder ()
				.Append ("{ \"rows\": [")
				.Append ("{ \"id\": 76, \"calendar\": \"WEEKDAY\", \"time\": \"00:07\" },")
				.Append ("{ \"id\": 114, \"calendar\": \"SATURDAY\", \"time\": \"23:35\" },")
				.Append ("{ \"id\": 133, \"calendar\": \"SUNDAY\", \"time\": \"23:29\" }")
				.Append ("], \"rowsAffected\": 0 }")
				.ToString ();

			var response = new HttpResponseMessage(HttpStatusCode.OK);
			response.Content = new StringContent (responseContent);
			_responseHandler.AddResponse(FIND_DEPARTURES_URL, response);
			var client = new HttpClient (_responseHandler);

			var repository = new RouteRepository (client);
			var departures = await repository.FindDeparturesByRouteIdAsync (0);

			Assert.AreEqual (3, departures.Count);
			Assert.AreEqual ("WEEKDAY", departures [0].Calendar);
			Assert.AreEqual ("00:07", departures [0].Time);
			Assert.AreEqual ("SATURDAY", departures [1].Calendar);
			Assert.AreEqual ("23:35", departures [1].Time);
			Assert.AreEqual ("SUNDAY", departures [2].Calendar);
			Assert.AreEqual ("23:29", departures [2].Time);
		}
        public void Update_Route()
        {
            string routeName = "Test Route to Update";
            string routeNameUpdated = "Test Route Updated";

            // Add to database
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                RouteRepository routeRepository = new RouteRepository(ctx);
                routeRepository.Add(new Route { Name = routeName, TimeTable = new TimeTable { Name = "TimeTable" } });
                routeRepository.SaveChanges();
            }

            // Find and update it
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                List<Route> routes = ctx.Routes.Where(route => route.Name == routeName).ToList();
                Assert.AreEqual(1, routes.Count());

                RouteRepository routeRepository = new RouteRepository(ctx);
                routes[0].Name = routeNameUpdated;
                routeRepository.Update(routes[0]);
                routeRepository.SaveChanges();
            }

            // Check that the new name is there
            using (ThamesClipperContext ctx = new ThamesClipperContext())
            {
                List<Route> routes = ctx.Routes.Where(route => route.Name == routeNameUpdated).ToList();
                Assert.AreEqual(1, routes.Count());
            }
        }