Ejemplo n.º 1
0
        public static void MyClassInitialize(TestContext testContext)
        {
            var currentState = new CurrentState();
            currentState.InitialiseRoutes(getRoutes());

            routeService = new RouteService(currentState);
        }
        public RequestDelivery(ClientController clientCon, ClientState clientState)
        {
            InitializeComponent();
            var state = new CurrentState();
            var routeService = new RouteService(state);
            _pathFinder = new PathFinder(routeService);
            _clientState = clientState;
            _pathfindService = new DeliveryService(state, _pathFinder);
            _clientController = clientCon;

            foreach (var routeNode in clientState.GetAllRouteNodes())
            {
                ComboBoxItem cbi = new ComboBoxItem();
                if (routeNode is DistributionCentre)
                    cbi.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort)
                    cbi.Content = routeNode.Country.Name;
                cbi.Tag = routeNode.ID;
                this.origin.Items.Add(cbi);

                ComboBoxItem cbi2 = new ComboBoxItem();
                if (routeNode is DistributionCentre)
                    cbi2.Content = ((DistributionCentre)routeNode).Name;
                else if (routeNode is InternationalPort)
                    cbi2.Content = routeNode.Country.Name;
                cbi2.Tag = routeNode.ID;
                this.destination.Items.Add(cbi2);
            }

            _clientController.OptionsReceived += new ClientController.DeliveryOptionsDelegate(DeliveryOptions_Returned);
            _clientController.DeliveryOK+= new ClientController.DeliveryConfirmedDelegate(DeliveryConfirmed);
        }
Ejemplo n.º 3
0
 public PathFinder(RouteService routeService)
 {
     this.routeService = routeService;
     time = new TimeEvaluator(this);
     cost = new CostEvaluator(this);
     airOnly = new AirOnlyExcluder(this);
     allRoutes = new NullExcluder(this);
 }
Ejemplo n.º 4
0
        public Controller(CountryService countryService, CompanyService companyService, DeliveryService deliveryService, PriceService priceService, RouteService routeService, LocationService locationService, StatisticsService statisticsService, EventService eventService)
        {
            this.countryService = countryService;
            this.companyService = companyService;
            this.deliveryService = deliveryService;
            this.priceService = priceService;
            this.routeService = routeService;
            this.locationService = locationService;
            this.statisticsService = statisticsService;
            this.eventService = eventService;

            Network.Instance.MessageReceived += new Network.MessageReceivedDelegate(OnReceived);
        }
Ejemplo n.º 5
0
        public static void MyClassInitialize(TestContext testContext)
        {
            // initialise state
            CurrentState state = new CurrentState();
            routeNodes = new List<RouteNode>();
            routeNodes.Add(new DistributionCentre("Christchurch"));
            routeNodes.Add(new DistributionCentre("Wellington"));
            routeNodes.Add(new DistributionCentre("Auckland"));

            routes = getRoutes(routeNodes);

            state.InitialiseRoutes(getRoutes(routeNodes));

            // initialise routeService
            var routeService = new RouteService(state);

            // initialise pathfinder
            pathFinder = new PathFinder(routeService);
        }
        public void Setup()
        {
            _routeCreator = MockRepository.GenerateStub<IRouteCreator>();
            _heightMapImageBuilder = MockRepository.GenerateStub<IHeightMapImageBuilder>();
            _heightMapImageCache = MockRepository.GenerateStub<IHeightMapImageCache>();
            _geographicRouteLocator = MockRepository.GenerateStub<IGeographicRouteLocator>();
            _routeToRouteResultMapper = MockRepository.GenerateStub<IRouteToRouteResultMapper>();
            _unitOfWork = MockRepository.GenerateStub<IUnitOfWork>();
            _sortSecurity = MockRepository.GenerateStub<ISortSecurity>();
            _routeFileCreator = MockRepository.GenerateStub<IRouteFileCreator>();
            _routeRepository = MockRepository.GenerateStub<IRepository<Route>>();
            _unitOfWork.Stub(s => s.GetRepository<Route>()).Return(_routeRepository);

            _routeService = new RouteService(_routeCreator,
                                                         _heightMapImageBuilder,
                                                         _heightMapImageCache,
                                                         _geographicRouteLocator,
                                                         _routeToRouteResultMapper,
                                                         _unitOfWork,
                                                         _sortSecurity,
                                                         _routeFileCreator);
        }
        public void When_HasInvalidDestinationAirport_ReturnsError()
        {
            // Arrange
            Mock <IRouteRepository> routeRepository = new Mock <IRouteRepository>();

            routeRepository.Setup(a => a.GetAll()).Returns(MockRouteData());
            RouteService routeService = new RouteService(routeRepository.Object);

            Mock <IAirportRepository> airportRepository = new Mock <IAirportRepository>();

            airportRepository.Setup(a => a.GetAll()).Returns(MockAirportData());
            AirportService airportService = new AirportService(airportRepository.Object);

            RouteController controller = new RouteController(routeService, airportService);
            string          origin     = "ORD";
            string          destin     = "XXX";

            // Act
            string result = controller.Get(origin, destin);

            // Assert
            Assert.AreEqual("Invalid Destination", result);
        }
Ejemplo n.º 8
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RouteService x_rService = new RouteService();
            var          list       = x_rService.Get(a => a.IsValid == 1);

            cb_routelist.ItemsSource       = list;
            cb_routelist.DisplayMemberPath = "Routecode";

            var info = x_rkService.GetById(rackId);

            if (info != null)
            {
                tb_code.Text = info.Rackcode;
                tb_name.Text = info.Rackname;
                foreach (ComboBoxItem item in cb_routelist.Items)
                {
                    if (item.Content.ToString() == info.RouteCode)
                    {
                        item.IsSelected = true;
                        break;
                    }
                }
                foreach (ComboBoxItem itemm in cb_layercount.Items)
                {
                    if (itemm.Content.ToString() == info.RacklayerCount.ToString())
                    {
                        itemm.IsSelected = true;
                        break;
                    }
                }
            }
            else
            {
                cb_routelist.SelectedIndex = 0;
                cb_routelist.SelectedIndex = 2;
            }
        }
Ejemplo n.º 9
0
        public void process_invalid_route()
        {
            var route1 = new Route("GRU");
            var route2 = new Route("BRC");

            route1.ConnectTo(route2, 10);

            var route3 = new Route("SCL");
            var route4 = new Route("ORL");

            route3.ConnectTo(route4, 20);

            var routes = new List <Route>();

            routes.Add(route1);
            routes.Add(route2);
            routes.Add(route3);
            routes.Add(route4);

            var result = RouteService.BestRouteProcess(route1, route4);

            Assert.True(result.RoutePathDescription.Equals("no route available"));
            Assert.True(result.Routes == null);
        }
Ejemplo n.º 10
0
        public IHttpActionResult GetRouteTotalValue(string jsonAddresses, int routeTypes)
        {
            try
            {
                if (String.IsNullOrEmpty(jsonAddresses))
                {
                    throw new Exception("O parâmetro jsonAddresses não pode ser null ou vazio!");
                }

                IList <Address> addresses = JsonConvert.DeserializeObject <List <Address> >(jsonAddresses);

                IRouteService                 routeService                 = new RouteService();
                IAddressFinderService         addressFinderService         = new AddressFinderService();
                ICalculateTotalOfRouteService calculateTotalOfRouteService = new CalculateTotalOfRouteService(routeService, addressFinderService);

                return(Ok(calculateTotalOfRouteService.GetTotalValuesOfRoute(addresses, routeTypes)));
            }
            catch (Exception ex)
            {
                //Passando apenas a mensagem de erro e removendo o stacktrace
                var exception = new Exception(ex.Message);
                return(InternalServerError(exception));
            }
        }
        public async Task <ActionResult> MovedStopPopup(int routePlanId, int modifiedType)
        {
            //call service layer to get collection of stops with the route plan ID
            var matchingStopCollection = new List <Stop>(await RouteService.GetStopsByRoutePlanIdAsync(routePlanId));

            //stop collection should only ever have 2 entries
            if (matchingStopCollection.Count != 2)
            {
                throw new UnexpectedStopException("An unexpected number of Stops was encountered");
            }
            //decide which stop is destination based on direction you are coming from
            int desiredRouteId = matchingStopCollection.First(s => s.RoutePlanModificationTypeId != modifiedType).RouteId;

            //get route info from routeID
            var model = new MovedStopPopupRouteStopViewModel(await RouteService.GetByRouteIdAsync(desiredRouteId))
            {
                //need both route and stop column options
                StopColumnOption  = new ColumnOptionViewModel(await LookUpService.GetColumnOptionsForUserAndPage(UserName, "ROUTETRACKERSTOPS"), ColumnTypes.Stop),
                RouteColumnOption = new ColumnOptionViewModel(await LookUpService.GetColumnOptionsForUserAndPage(UserName, "ROUTETRACKERROUTES"), ColumnTypes.Route)
            };

            //send model of route info to popup
            return(PartialView("_movedStopPopup", model));
        }
Ejemplo n.º 12
0
        public void GetRoutesFromFile_ShouldReturn_CorrectParsedDictionary()
        {
            var fileMock = new List <string>
            {
                "GRU,BRC,10",
                "BRC,SCL,5 ",
                "GRU,CDG,75",
                "GRU,SCL,20",
                "GRU,ORL,56",
                "ORL,CDG,5 ",
                "SCL,ORL,20",
            };

            var fileRepositoryMock = new Mock <IFileRepository>();

            fileRepositoryMock.Setup(m => m.ReadCsv()).Returns(fileMock);

            var routeService = new RouteService(fileRepositoryMock.Object);

            var routesDic = routeService.GetRoutesFromFile();

            Assert.Equal(4, routesDic["GRU"].Count);
            Assert.Contains(routesDic["GRU"].First().ToString(), fileMock);
        }
Ejemplo n.º 13
0
        public async Task <Order> CreateOrder(BookingAM booking)
        {
            using (var transaction = await TransactionService.BeginTransaction())
            {
                try
                {
                    var domainCustomer = await CustomerService.GetDomainCustomer(booking.Customer);

                    var domainCargo = await CargoService.CreateDomainCargo(booking.Cargo);

                    var domainBill = await BillService.CreateDomainBill(booking.BillInfo, booking.Basket);

                    var route = await RouteService.GetRoute(booking.RootAddress, booking.Waypoints);

                    var domainRoute = await RouteService.CreateDomainRoute(route);

                    var result = await DomainOrderService.Create(
                        booking.OrderTime,
                        domainCustomer.Id,
                        domainCargo.Id,
                        domainRoute.Id,
                        domainBill.Id);

                    await OrderStateService.New(result.Id);

                    transaction.Commit();

                    return(result);
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
Ejemplo n.º 14
0
 // GET: api/Messages
 public IHttpActionResult Get()
 {
     try
     {
         var messages = RouteService.GetMessagesMobile(GetDeviceId(Request));
         if (messages == null)
         {
             return(Unauthorized());
         }
         if (messages.Count < 1)
         {
             return(Ok(new MessageList()));
         }
         var listMessage       = new MessageList();
         var customMessageList = new List <CustomMessage>();
         foreach (var logMensaje in messages)
         {
             var message = new CustomMessage
             {
                 Id          = logMensaje.Id,
                 Description = logMensaje.Texto.Split(':')[1].Trim(),
                 DateTime    = logMensaje.Fecha,
                 Latitude    = logMensaje.Latitud,
                 Longitude   = logMensaje.Longitud
             };
             customMessageList.Add(message);
         }
         listMessage.MessageItems = customMessageList.ToArray();
         return(Ok(listMessage));
     }
     catch (Exception error)
     {
         LogicTracker.App.Web.Api.Providers.LogWritter.writeLog(error);
         return(BadRequest());
     }
 }
Ejemplo n.º 15
0
 public RoutesController(RouteService routeService)
 {
     _routeService = routeService;
 }
Ejemplo n.º 16
0
        private void BenDBTests(CountryService countryService, RouteService routeService)
        {
            try
            {

                CountryDataHelper cdh = new CountryDataHelper();

                // create country if doesn't exist
                Country country = new Country { ID = 1, Name = "Wellington", Code = "WLG" };
                if (!countryService.Exists(country))
                {
                    country = countryService.Create("Wellington", "WLG");
                }

                country = countryService.Update(country.ID, "WLN");
                country = countryService.Update(country.ID, "BEN");

                // get latest version
                Country loadedCountry = countryService.Get(country.ID);

                cdh.LoadAll(DateTime.Now);

                // create new zealand
                country = new Country { Name = "New Zealand", Code = "NZ" };
                if (!countryService.Exists(country))
                {
                    country = countryService.Create(country.Name, country.Code);
                }

                // create australia
                country = new Country { Name = "Australia", Code = "AUS" };
                if (!countryService.Exists(country))
                {
                    country = countryService.Create(country.Name, country.Code);
                }

                // load all countries
                var allCountries = countryService.GetAll();

                // create christchurch depot
                RouteNode routeNode = new DistributionCentre("Christchurch");
                if (!locationService.Exists(routeNode))
                {
                    routeNode = locationService.CreateDistributionCentre("Christchurch");
                }

                // wellington depot
                routeNode = new DistributionCentre("Wellington");
                if (!locationService.Exists(routeNode))
                {
                    routeNode = locationService.CreateDistributionCentre("Wellington");
                }

                // australia port
                country = countryService.GetAll().AsQueryable().First(t => t.Name == "Australia");
                var destination = new InternationalPort(country);
                if (!locationService.Exists(destination))
                {
                    destination = locationService.CreateInternationalPort(country.ID);
                }

                // get a company
                var company = new Company() { Name = "NZ Post" };
                if (!companyService.Exists(company))
                {
                    company = companyService.Create(company.Name);
                }

                // create a new route
                Route route = new Route()
                    {
                        Origin = routeNode,
                        Destination = destination,
                        Company = company,
                        Duration = 300,
                        MaxVolume = 5000,
                        MaxWeight = 5000,
                        CostPerCm3 = 3,
                        CostPerGram = 5,
                        TransportType = TransportType.Air,
                        DepartureTimes = new List<WeeklyTime> { new WeeklyTime(DayOfWeek.Monday, 5, 30) }
                    };

                var routeDataHelper = new RouteDataHelper();

                int id = routeDataHelper.GetId(route);
                Logger.WriteLine("Route id is: " + id);
                if (id == 0)
                {
                    routeDataHelper.Create(route);
                }

                //route = routeDataHelper.Load(1);

                // edit departure times
                route.DepartureTimes.Add(new WeeklyTime(DayOfWeek.Wednesday, 14, 35));

                // update
                //routeDataHelper.Update(route);

                // delete
                routeDataHelper.Delete(route.ID);

                var routes = routeDataHelper.LoadAll();

                var delivery = new Delivery { Origin = routeNode, Destination = destination, Priority = Priority.Air, WeightInGrams = 200, VolumeInCm3 = 2000, TotalPrice = 2500, TotalCost = 1000, TimeOfRequest = DateTime.UtcNow, TimeOfDelivery = DateTime.UtcNow.AddHours(5.5), Routes = new List<RouteInstance> { new RouteInstance(route, DateTime.UtcNow)} };

                var deliveryDataHelper = new DeliveryDataHelper();

                deliveryDataHelper.Create(delivery);

                deliveryDataHelper.Load(delivery.ID);

                deliveryDataHelper.LoadAll();

                var price = new Price { Origin = routeNode, Destination = destination, Priority = Priority.Air, PricePerCm3 = 3, PricePerGram = 5 };
                var priceDataHelper = new PriceDataHelper();
                //priceDataHelper.Create(price);

                price.PricePerGram = 10;
                price.ID = 1;

                Logger.WriteLine(price.ToString());

            }
            catch (Exception e)
            {
                Logger.WriteLine(e.Message);
                Logger.Write(e.StackTrace);
            }
        }
        public async void Should_Set_Coordinates_For_A_Known_Address()
        {


            var routeService = new RouteService(new MapLinkCoordinateFinder(new MapLinkToken()), new MapLinkRouteCalculator(new MapLinkToken()));

            var address1 = new AddressSearch("Avenida Paulista", 1000, "São Paulo", "SP");
            var address2 = new AddressSearch("Avenida Paulista", 2000, "São Paulo", "SP");

            var list = new List<AddressSearch>() { address1, address2 };

            await routeService.CalculateRouteAsync(list, RouteType.DefaultRouteFaster);

            Assert.IsTrue(address1.Latitude != 0 && address1.Longitude != 0);
        }
        public void GenerateRoute()
        {
            RouteService service = new RouteService();

            Route = service.GenerateNewRoute(Procescell);
        }
        public async void Should_Calculate_The_Route_For_A_Known_Address()
        {


            var routeService = new RouteService(new MapLinkCoordinateFinder(new MapLinkToken()), new MapLinkRouteCalculator(new MapLinkToken()));

            var address1 = new AddressSearch("Avenida Paulista", 1000, "São Paulo", "SP");
            var address2 = new AddressSearch("Avenida Paulista", 2000, "São Paulo", "SP");

            var list = new List<AddressSearch>() { address1, address2 };

            var route = await routeService.CalculateRouteAsync(list, RouteType.DefaultRouteFaster);

            Assert.IsTrue(route.TotalCost > 0);
            Assert.IsTrue(route.TotalDistance > 0);
            Assert.IsTrue(route.TotalFuelCost > 0);
            Assert.IsTrue(route.TotalTime != string.Empty);
        }
        public async Task <IActionResult> GetPdfExampleCables()
        {
            var listElementosCables = new ResponseElementoCables();
            ///var controller = "";
            var prefix   = "";
            var URL_BASE = "";

            ///controller = "odata/datatakedev/";
            prefix = string.Format("{0}", "odata/datatakedev/Viewfromcablesms?$top=500&$skip=20000&$count=true");
            var route = RouteService.GetInstance();

            URL_BASE = route.RouteBaseAddress;

            var response = await ApiService.GetList <ResponseElementoCables>(URL_BASE, prefix);

            if (!response.IsSuccess)
            {
                return(Ok(response));
            }

            var cables         = (ResponseElementoCables)response.Result;
            var globalSettings = new GlobalSettings
            {
                ColorMode   = ColorMode.Color,
                Orientation = Orientation.Portrait,
                PaperSize   = PaperKind.A4,
                Margins     = new MarginSettings {
                    Top = 6
                },
                DocumentTitle = "Formato General Inventario"
            };


            var templatePdfGeneral = new TemplatePdfGeneral();
            //var template= await templatePdfAutorizacion.GetHTMLString(requestPma,_hostingEnvironment.WebRootPath);

            var objectSettings = new ObjectSettings
            {
                PagesCount = true,
                // Page= "http://interedes.co/",
                HtmlContent = await templatePdfGeneral.GetHTMLString(cables, _hostingEnvironment.WebRootPath),
                WebSettings =
                {
                    DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "style_inventario.css")
                },
                HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = false, Spacing = 1 },
                //FooterSettings = { FontName = "Arial", FontSize = 9, Line = false, HtmUrl =Path.Combine(Directory.GetCurrentDirectory(), "assets", "footer/footer.html"), Left = ""  }
                FooterSettings = { FontName = "Arial", FontSize = 9, Line = false, Center = "" }
            };

            var pdf = new HtmlToPdfDocument()
            {
                GlobalSettings = globalSettings,
                Objects        = { objectSettings }
            };

            var file = _converter.Convert(pdf);

            return(File(file, "application/pdf", "Formato_Inventario_General.pdf"));
            ///return Ok(response);
        }
Ejemplo n.º 21
0
        public void GetRouteCost(string route, int expected)
        {
            var service = new RouteService(TestData.Edges);

            Assert.AreEqual(expected, service.GetDistance(route));
        }
        public async Task <ActionResult> ChangeStopTime(UpdateRouteWithStopsViewModel route)
        {
            var updatedRouteStopList = new List <atm.services.models.UpdateStop>();
            var stops = route.Stops;

            //Get the current version of the route from the API
            var existingRoute = await RouteService.GetByRouteIdAsync(route.RouteId);

            var existingRouteStops = existingRoute.RouteStops;

            for (int x = 0; x < stops.Count(); x++)
            {
                var existingStop = existingRouteStops.Single(s => s.RoutePlanId == stops[x].RoutePlanId);
                var updatedStop  = new UpdateStop()
                {
                    RoutePlanId = stops[x].RoutePlanId,
                    RouteId     = stops[x].RouteId,
                    BillTo      = stops[x].BillTo,
                    ShipTo      = stops[x].ShipTo,
                    AdjustedDeliveryDateTime  = stops[x].AdjustedDeliveryDateTime,
                    ScheduledDeliveryDateTime = stops[x].ScheduledDeliveryDateTime,
                    Comment   = stops[x].LastCustomerCommunicationComment,
                    EarlyLate = stops[x].EarlyLate,
                    RoutePlanModificationTypeId = stops[x].RoutePlanModificationTypeId,
                    RouteNumber         = stops[x].RouteNumber,
                    AdjustedRouteNumber = stops[x].AdjustedRouteNumber,
                    StopNumber          = stops[x].AdjustedStopNumber,
                    AdjustedStopNumber  = stops[x].AdjustedStopNumber,
                };
                //Set the comment to empty string if value is null otherwise leave it alone
                existingStop.Comment = existingStop.Comment ?? "";
                updatedStop.Comment  = updatedStop.Comment ?? "";

                //if User has updated the Comment and/or ScheduledDeliveryDateTime
                if (!System.DateTime.Equals(updatedStop.AdjustedDeliveryDateTime, existingStop.AdjustedDeliveryDateTime) || !System.DateTime.Equals(updatedStop.ScheduledDeliveryDateTime, existingStop.ScheduledDeliveryDateTime) || updatedStop.Comment != existingStop.LastCustomerCommunicationComment)
                {
                    //If stop currently has RoutePlanModificationTypeId of NONE or stop was added and time modified.
                    if (updatedStop.RoutePlanModificationTypeId == 0 || updatedStop.RoutePlanModificationTypeId == 2)
                    {
                        //Set status to Time Changed.  If the original modification type was a 2, the API will reset it back to 2.
                        updatedStop.RoutePlanModificationTypeId = 3;
                    }

                    if (updatedStop.StopNumber != existingStop.StopNumber)
                    {
                        updatedStop.IncludesStopChanges = true;
                    }
                    if (!System.DateTime.Equals(updatedStop.ScheduledDeliveryDateTime, existingStop.ScheduledDeliveryDateTime))
                    {
                        updatedStop.IncludesStopScheduledDateTimeChanges = true;
                        if (!System.DateTime.Equals(updatedStop.AdjustedDeliveryDateTime, updatedStop.ScheduledDeliveryDateTime))
                        {
                            updatedStop.IncludesStopAdjustedDateTimeChanges = true;
                        }
                    }
                    else
                    {
                        if (!System.DateTime.Equals(updatedStop.AdjustedDeliveryDateTime, existingStop.AdjustedDeliveryDateTime))
                        {
                            updatedStop.IncludesStopAdjustedDateTimeChanges = true;
                        }
                    }


                    //Save the stop
                    updatedRouteStopList.Add(updatedStop);
                }
            }

            var updateRouteWithStops = new UpdateRouteWithStops()
            {
                SygmaCenterNo = route.SygmaCenterNo,
                RouteNumber   = route.RouteNumber,
                RouteId       = route.RouteId,
                RouteName     = route.RouteName,
                RouteStops    = updatedRouteStopList
            };

            await RouteService.UpdateRouteAsync(route.RouteNumber, route.SygmaCenterNo, updateRouteWithStops);

            foreach (var stop in updateRouteWithStops.RouteStops)
            {
                if (!string.IsNullOrEmpty(stop.Comment.Trim()))
                {
                    var existingStop = existingRouteStops.Single(s => s.RoutePlanId == stop.RoutePlanId);
                    if (existingStop.LastCustomerCommunicationComment != stop.Comment)
                    {
                        await CommentService.AddCommentAsync(new services.models.AddComment
                        {
                            CenterNumber      = updateRouteWithStops.SygmaCenterNo,
                            CreatedBy         = LastFirstName.ToUpperInvariant(),
                            Status            = 3, // non-internal
                            PrimaryRecordId   = $"{((int)stop.BillTo).ToString()}-{((int)stop.ShipTo).ToString()}",
                            SecondaryRecordId = stop.RoutePlanId.ToString(),
                            Screen            = "RT",
                            ShortComment      = "Customer Communication",
                            LongComment       = stop.Comment
                        });
                    }
                }

                if (stop.IncludesStopChanges)
                {
                    var existingStop = existingRouteStops.Single(s => s.RoutePlanId == stop.RoutePlanId);
                    await CommentService.AddCommentAsync(new services.models.AddComment
                    {
                        CenterNumber      = updateRouteWithStops.SygmaCenterNo,
                        CreatedBy         = LastFirstName.ToUpperInvariant(),
                        Status            = 2, // internal
                        PrimaryRecordId   = $"{((int)stop.BillTo).ToString()}-{((int)stop.ShipTo).ToString()}",
                        SecondaryRecordId = stop.RoutePlanId.ToString(),
                        Screen            = "RT",
                        ShortComment      = "Stop Adjustment",
                        LongComment       = $"Stop moved from Stop: {stop.StopNumber} at {existingStop.AdjustedDeliveryDateTime} to Stop: {stop.AdjustedStopNumber} at {stop.AdjustedDeliveryDateTime}"
                    });
                }

                if (stop.IncludesStopAdjustedDateTimeChanges)
                {
                    var existingStop = existingRouteStops.Single(s => s.RoutePlanId == stop.RoutePlanId);
                    await CommentService.AddCommentAsync(new services.models.AddComment
                    {
                        CenterNumber      = updateRouteWithStops.SygmaCenterNo,
                        CreatedBy         = LastFirstName.ToUpperInvariant(),
                        Status            = 2, // internal
                        PrimaryRecordId   = $"{((int)stop.BillTo).ToString()}-{((int)stop.ShipTo).ToString()}",
                        SecondaryRecordId = stop.RoutePlanId.ToString(),
                        Screen            = "RT",
                        ShortComment      = "Time Adjustment",
                        LongComment       = $"Stop {stop.StopNumber} adjusted delivery was changed from {existingStop.AdjustedDeliveryDateTime} to {stop.AdjustedDeliveryDateTime}"
                    });
                }
                if (stop.IncludesStopScheduledDateTimeChanges)
                {
                    var existingStop = existingRouteStops.Single(s => s.RoutePlanId == stop.RoutePlanId);
                    await CommentService.AddCommentAsync(new services.models.AddComment
                    {
                        CenterNumber      = updateRouteWithStops.SygmaCenterNo,
                        CreatedBy         = LastFirstName.ToUpperInvariant(),
                        Status            = 2, // internal
                        PrimaryRecordId   = $"{((int)stop.BillTo).ToString()}-{((int)stop.ShipTo).ToString()}",
                        SecondaryRecordId = stop.RoutePlanId.ToString(),
                        Screen            = "RT",
                        ShortComment      = "Time Adjustment",
                        LongComment       = $"Stop {stop.StopNumber} scheduled delivery was changed from {existingStop.ScheduledDeliveryDateTime} to {stop.ScheduledDeliveryDateTime}"
                    });
                }
            }

            return(new HttpStatusCodeResult(System.Net.HttpStatusCode.Created));
        }
 public RoutesController(RouteService routeService, IMapper mapper)
 {
     _routeService = routeService;
     _mapper       = mapper;
 }
Ejemplo n.º 24
0
 public RouteController(RouteService RouteService, SchoolService SchoolService)
 {
     _RouteService  = RouteService;
     _SchoolService = SchoolService;
 }
Ejemplo n.º 25
0
        public async void CreatePost_RouteCreateViewModelIsValid_SectionAddedAndRedirectsToListAction()
        {
            // Arrange

            #region User Setup
            var userId1  = "0f8fad5b-d9cb-469f-a165-70867728950e";
            var userId2  = "ffffad5b-d9cb-469f-a165-70867728950e";
            var appUser1 = new ApplicationUser {
                DisplayName = "User1"
            };
            var appUser2 = new ApplicationUser {
                DisplayName = "User2"
            };
            UserService.Setup(service => service.FindByIdAsync(It.Is <string>(id => id.Equals(userId1))))
            .Returns(Task.FromResult(appUser1));
            UserService.Setup(service => service.FindByIdAsync(It.Is <string>(id => id.Equals(userId2))))
            .Returns(Task.FromResult(appUser2));
            #endregion

            #region File Setup
            string fakeWebRootPath = "fake/fakepath/veryfakepath/";
            HostingEnvironment.Setup(envi => envi.WebRootPath).Returns(fakeWebRootPath);

            string[] relativePaths =
            {
                "uploads/awidjqo.jpg"
            };

            IFormFileCollection formFileCollection = new FormFileCollection
            {
                new FormFile(Stream.Null, 0, 200, "Images/imageToDelete1", "imageToDelete1.jpg"),
                new FormFile(Stream.Null, 0, 200, "Images/imageToDelete2", "imageToDelete2.jpg"),
                new FormFile(Stream.Null, 0, 200, "Images/imageToUpload", "imageToUpload.jpg")
            };

            AttachmentHandler.Setup(
                handler => handler.SaveImagesOnServer(
                    It.Is <IList <IFormFile> >(
                        files => files.Intersect(formFileCollection).Count() == files.Count),
                    It.Is <string>(path => path.Equals(fakeWebRootPath)),
                    It.Is <string>(uploadPath => uploadPath.Equals("uploads"))))
            .Returns(Task.FromResult(relativePaths));

            var request = new Mock <HttpRequest>();
            request.SetupGet(x => x.Form["jfiler-items-exclude-Images-0"]).Returns("[\"imageToDelete1.jpg\",\"imageToDelete2.jpg\"]");
            request.SetupGet(x => x.Form.Files).Returns(formFileCollection);

            var context = new Mock <HttpContext>();
            context.SetupGet(x => x.Request).Returns(request.Object);
            RouteController.ControllerContext =
                new ControllerContext(new ActionContext(context.Object, new RouteData(), new ControllerActionDescriptor()));
            #endregion

            #region Route & ViewModel
            var viewModel = new RouteCreateViewModel
            {
                Note      = "This is a test note.",
                RouteID   = 1,
                GripColor = "000000",
                Type      = RouteType.Boulder,
                Builders  = new List <string>
                {
                    userId1,
                    userId2
                },
                Date = "14-12-2016",
                RouteDifficultyID = 1,
                RouteSectionID    = new List <int>
                {
                    1,
                    2
                },
                VideoUrl = "https://www.youtube.com/watch?v=bEYSyfEL8nY"
            };

            Route routeToCreate = new Route
            {
                Note       = viewModel.Note,
                RouteID    = viewModel.RouteID,
                GripColour = viewModel.GripColor,
                Type       = viewModel.Type
            };
            #endregion

            // Act
            IActionResult result = await RouteController.Create(viewModel);

            // Assert
            #region Assertions
            RouteService.Verify(service => service.AddRoute(It.Is <Route>(route => RouteEquals(route, routeToCreate)),
                                                            It.Is <string>(date => date.SequenceEqual(viewModel.Date)),
                                                            It.Is <int>(diff => diff == viewModel.RouteDifficultyID)),
                                Times.Once);

            RouteService.Verify(service => service.AddRouteToSections(It.Is <Route>(route => RouteEquals(route, routeToCreate)),
                                                                      It.Is <List <int> >(idList => idList.SequenceEqual(viewModel.RouteSectionID.ToList()))
                                                                      ),
                                Times.Once);

            RouteService.Verify(
                service => service.AddBuildersToRoute(It.Is <Route>(route => RouteEquals(route, routeToCreate)),
                                                      It.Is <ApplicationUser[]>(users => users.SequenceEqual(new[]
            {
                appUser1,
                appUser2
            })
                                                                                )),
                Times.Once);

            RouteService.Verify(service => service.AddAttachment(It.Is <Route>(route => RouteEquals(route, routeToCreate)),
                                                                 It.Is <string>(url => url.Equals(viewModel.VideoUrl)),
                                                                 It.Is <string[]>(paths => paths.SequenceEqual(relativePaths))
                                                                 ), Times.Once);

            var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result);
            Assert.Equal("Route", redirectToActionResult.ControllerName);
            Assert.Equal("List", redirectToActionResult.ActionName);
            #endregion
        }
Ejemplo n.º 26
0
        // POST: api/Messages
        public IHttpActionResult Post([FromBody] List <CustomMessage> messages)
        {
            try
            {
                var deviceId = GetDeviceId(Request);
                if (deviceId == null)
                {
                    return(Unauthorized());
                }

                if (messages == null)
                {
                    return(BadRequest());
                }

                var mensajes = new List <LogMensaje>();
                foreach (var message in messages)
                {
                    var logMensaje = new LogMensaje
                    {
                        Fecha    = message.DateTime,
                        Texto    = message.Description,
                        Latitud  = message.Latitude,
                        Longitud = message.Longitude
                    };
                    bool esMensajeOculto = false;
                    if (!String.IsNullOrEmpty(message.codigomensaje) &&
                        message.codigomensaje.StartsWith("R"))
                    {
                        message.codigomensaje = message.codigomensaje.Substring(1, message.codigomensaje.Length - 1);
                        TicketRechazo.MotivoRechazo rechazoEnum = (TicketRechazo.MotivoRechazo) int.Parse(message.codigomensaje.ToString());
                        switch (rechazoEnum)
                        {
                        case TicketRechazo.MotivoRechazo.MalFacturado:
                        case TicketRechazo.MotivoRechazo.MalPedido:
                        case TicketRechazo.MotivoRechazo.NoEncontroDomicilio:
                        case TicketRechazo.MotivoRechazo.NoPedido:
                        case TicketRechazo.MotivoRechazo.Cerrado:
                        case TicketRechazo.MotivoRechazo.CaminoIntransitable:
                        case TicketRechazo.MotivoRechazo.FaltaSinCargo:
                        case TicketRechazo.MotivoRechazo.FueraDeHorario:
                        case TicketRechazo.MotivoRechazo.FueraDeZona:
                        case TicketRechazo.MotivoRechazo.ProductoNoApto:
                        case TicketRechazo.MotivoRechazo.SinDinero:
                        {
                            esMensajeOculto = true;
                            var messageLog = DaoFactory.LogMensajeDAO.FindById(message.Id);

                            Dispositivo device = DaoFactory.DispositivoDAO.FindByImei(deviceId);
                            if (device == null)
                            {
                                continue;
                            }

                            var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device);
                            if (employee == null)
                            {
                                continue;
                            }

                            var idRechazo = Convert.ToInt32(messageLog.Texto.Split(':')[0].Split(' ').Last());
                            var rechazo   = DaoFactory.TicketRechazoDAO.FindById(idRechazo);

                            if (rechazo != null)
                            {
                                try
                                {
                                    if (rechazo.UltimoEstado == TicketRechazo.Estado.Notificado1 ||
                                        rechazo.UltimoEstado == TicketRechazo.Estado.Notificado2 ||
                                        rechazo.UltimoEstado == TicketRechazo.Estado.Notificado3)
                                    {
                                        IMessageSaver saver       = new MessageSaver(DaoFactory);
                                        var           messagetEXT = MessageSender.CreateSubmitTextMessage(device, saver);
                                        string        usuario     = "";
                                        try
                                        {
                                            rechazo.ChangeEstado(Logictracker.Types.BusinessObjects.Rechazos.TicketRechazo.Estado.Alertado, "Confirma atención", employee);
                                            DaoFactory.TicketRechazoDAO.SaveOrUpdate(rechazo);

                                            //El usuario tomo existosamente el rechazo
                                            foreach (var item in rechazo.Detalle)
                                            {
                                                if (item.Estado == TicketRechazo.Estado.Alertado)
                                                {
                                                    usuario = item.Empleado.Entidad.Descripcion;
                                                    break;
                                                }
                                            }
                                            messagetEXT.AddMessageText("INFORME DE RECHAZO NRO " + idRechazo + " SE CONFIRMA LA ASISTENCIA PARA: " + usuario);
                                            messagetEXT.Send();
                                        }
                                        catch (Exception ex)
                                        {
                                            messagetEXT.AddMessageText("INFORME DE RECHAZO NRO " + idRechazo + " HA OCURRIDO UN ERROR, POR FAVOR INTENTE NUEVAMENTE ASISTIR EL RECHAZO");
                                            messagetEXT.Send();
                                            throw ex;
                                        }
                                    }
                                    else
                                    {
                                        //El usuario ya fue alertado
                                        IMessageSaver saver       = new MessageSaver(DaoFactory);
                                        var           messagetEXT = MessageSender.CreateSubmitTextMessage(device, saver);
                                        string        usuario     = "";
                                        foreach (var item in rechazo.Detalle)
                                        {
                                            if (item.Estado == TicketRechazo.Estado.Alertado)
                                            {
                                                usuario = item.Empleado.Entidad.Descripcion;
                                                break;
                                            }
                                        }
                                        messagetEXT.AddMessageText("INFORME DE RECHAZO NRO " + idRechazo + " EL RECHAZO YA FUE TOMADO POR: " + usuario);
                                        messagetEXT.Send();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (!ex.Message.ToString().Contains("Cambio de estado invalido"))
                                    {
                                        throw ex;
                                    }
                                }
                            }
                            break;
                        }

                        default:
                        {
                            TicketRechazo.Estado rechazoEstadoEnum = (TicketRechazo.Estado) int.Parse(message.codigomensaje.ToString());
                            switch (rechazoEstadoEnum)
                            {
                            case TicketRechazo.Estado.RespuestaExitosa:
                            {
                                esMensajeOculto = true;
                                var device = DaoFactory.DispositivoDAO.FindByImei(deviceId);
                                if (device == null)
                                {
                                    continue;
                                }
                                var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device);
                                if (employee == null)
                                {
                                    continue;
                                }
                                var rechazo = DaoFactory.TicketRechazoDAO.FindById(message.Id);

                                if (rechazo != null &&
                                    message.Id > 0)
                                {
                                    try
                                    {
                                        if (rechazo.UltimoEstado != TicketRechazo.Estado.RespuestaExitosa)
                                        {
                                            rechazo.ChangeEstado(Logictracker.Types.BusinessObjects.Rechazos.TicketRechazo.Estado.RespuestaExitosa, message.Description, employee);
                                            DaoFactory.TicketRechazoDAO.SaveOrUpdate(rechazo);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        if (!ex.Message.ToString().Contains("Cambio de estado invalido"))
                                        {
                                            throw ex;
                                        }
                                    }
                                }
                                break;
                            }

                            case TicketRechazo.Estado.RespuestaConRechazo:
                            {
                                esMensajeOculto = true;

                                var device = DaoFactory.DispositivoDAO.FindByImei(deviceId);
                                if (device == null)
                                {
                                    continue;
                                }
                                var employee = DaoFactory.EmpleadoDAO.FindEmpleadoByDevice(device);
                                if (employee == null)
                                {
                                    continue;
                                }
                                var rechazo = DaoFactory.TicketRechazoDAO.FindById(message.Id);
                                if (rechazo != null &&
                                    rechazo.Id != 0)
                                {
                                    try
                                    {
                                        if (rechazo.UltimoEstado != TicketRechazo.Estado.RespuestaConRechazo)
                                        {
                                            rechazo.ChangeEstado(Logictracker.Types.BusinessObjects.Rechazos.TicketRechazo.Estado.RespuestaConRechazo, message.Description, employee);
                                            DaoFactory.TicketRechazoDAO.SaveOrUpdate(rechazo);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        if (!ex.Message.ToString().Contains("Cambio de estado invalido"))
                                        {
                                            throw ex;
                                        }
                                    }
                                }
                                break;
                            }

                            default:
                                break;
                            }
                            break;
                        }
                        }
                    }
                    if (!esMensajeOculto)
                    {
                        mensajes.Add(logMensaje);
                    }
                }


                var value = RouteService.SendMessagesMobile(deviceId, mensajes);

                return(CreatedAtRoute("DefaultApi", null, value));
            }
            catch (Exception error)
            {
                LogicTracker.App.Web.Api.Providers.LogWritter.writeLog(error);
                return(BadRequest());
            }
        }
Ejemplo n.º 27
0
        static void Main(string[] args)
        {
            RouteService service = new RouteService();

            service.RunAsync().GetAwaiter().GetResult();
        }
Ejemplo n.º 28
0
 public RouteController(RouteService routeService, AirportService airportService)
 {
     _routeService   = routeService;
     _airportService = airportService;
 }
Ejemplo n.º 29
0
 public ApiController(DocumentModel model, RouteService router)
 {
     _model  = model;
     _router = router;
 }
Ejemplo n.º 30
0
 public AdminRideController(RideService rideService, TrainService trainService, RouteService routeService,
                            StopToRouteService stopToRouteService)
 {
     _rideService        = rideService;
     _trainService       = trainService;
     _routeService       = routeService;
     _stopToRouteService = stopToRouteService;
 }
Ejemplo n.º 31
0
        public async Task <JsonResult> StopsData(int id, int centerNumber)
        {
            var model = await RouteService.GetByRouteIdAndCenterNumberAndRouteNumberAsync(id, centerNumber);

            return(Json(JsonConvert.SerializeObject(model), JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            var serviceProvider   = ServicesRegistry
                                    .Register(serviceCollection)
                                    .BuildServiceProvider();

            var distances = new List <string>()
            {
                { "A-B-C" },
                { "A-D" },
                { "A-D-C" },
                { "A-E-B-C-D" },
                { "A-E-D" }
            };

            Console.WriteLine("Enter the list of routes eg.(AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7):");
            string            readLine   = Console.ReadLine();
            var               routeCodes = readLine.Split(",");
            List <RouteModel> routes     = new List <RouteModel>();

            routeCodes.ToList().ForEach(x => {
                var result = RouteModelBuilder.Get()
                             .WithChainOfProperties(x)
                             .Build();

                if (result.IsSuccess)
                {
                    routes.Add(result.Value);
                }
            });

            var service = new RouteService(routes);

            List <Result <int> > outputs = new List <Result <int> >();

            for (int i = 0; i < distances.Count; i++)
            {
                var result = service.EvaluateDistance(distances[i]);

                if (result.IsSuccess)
                {
                    Console.WriteLine($"Output #{ i + 1}: { result.Value }");
                }
                else
                {
                    Console.WriteLine($"Output #{ i + 1}: { result.Message }");
                }
            }
            var C_C = service.NumberOfTrips('C', 'C').Where(x => x.NumberOfStops == 2 || x.NumberOfStops == 3).Count();
            var A_C = service.NumberOfTrips('A', 'C').Where(x => x.NumberOfStops == 4).Count();

            Console.WriteLine($"Output #6: { C_C }");
            Console.WriteLine($"Output #7: { A_C }");

            Console.WriteLine($"Output #8: { service.ShortestDistance('A', 'C') }");
            Console.WriteLine($"Output #9: { service.ShortestDistance('B', 'B') }");


            var n = service.NumberOfTrips('C', 'C');
        }
Ejemplo n.º 33
0
        // This is the callback method for the CalculateRoute request.
        private void routeService_CalculateRouteCompleted(object sender, RouteService.CalculateRouteCompletedEventArgs e)
        {

            RouteResponse routeResponse = e.Result;

            // If the route calculate was a success and contains a route, then draw the route on the map.
            if (routeResponse.ResponseSummary.StatusCode != RouteService.ResponseStatusCode.Success)
            {
                //outString = "error routing ... status <" + e.Result.ResponseSummary.StatusCode.ToString() + ">";
            }
            else if (0 == e.Result.Result.Legs.Count)
            {
                //outString = "Cannot find route";
            }
            else
            {

                Color routeColor = Colors.Blue;
                SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
                //outString = "Found route ... coloring route";
                //ToOutput.Foreground = routeBrush;
                MapPolyline routeLine = new MapPolyline();
                routeLine.Locations = new LocationCollection();
                routeLine.Stroke = routeBrush;
                routeLine.Opacity = 0.65;
                routeLine.StrokeThickness = 5.0;
                foreach (RouteService.Location p in routeResponse.Result.RoutePath.Points)
                {
                    routeLine.Locations.Add(new MapControl.Location(p.Latitude, p.Longitude));
                }
                RouteLayer.Children.Add(routeLine);
                LocationRect rect = new LocationRect(routeLine.Locations[0], routeLine.Locations[routeLine.Locations.Count - 1]);

                foreach (RouteService.ItineraryItem itineraryItem in e.Result.Result.Legs[0].Itinerary)
                {
                    Ellipse point = new Ellipse();
                    point.Width = 10;
                    point.Height = 10;
                    point.Fill = new SolidColorBrush(Colors.Red);
                    point.Opacity = 0.65;
                    Microsoft.Maps.MapControl.Location location = new Microsoft.Maps.MapControl.Location(itineraryItem.Location.Latitude, itineraryItem.Location.Longitude);
                    MapLayer.SetPosition(point, location);
                    MapLayer.SetPositionOrigin(point, PositionOrigin.Center);
                    point.Tag = itineraryItem;
                    point.MouseEnter += MyMap_MouseEnter;
                    point.MouseLeave += MyMap_MouseLeave;

                    RouteLayer.Children.Add(point);
                }

                MyMap.SetView(rect);
            }
        }
Ejemplo n.º 34
0
 public HomeController()
 {
     repository   = new EFUnitOfWork();
     routeService = new RouteService(repository);
 }
Ejemplo n.º 35
0
 public RouteController(RouteService service)
 {
     _routeService = service;
 }
Ejemplo n.º 36
0
 public VehiclesController(VehicleRepository repository, RouteService routeService)
 {
     _routeService = routeService;
     _repository   = repository;
 }
Ejemplo n.º 37
0
        void Main()
        {
            var service = new RouteService();

            service.Create(new Route)
        }
Ejemplo n.º 38
0
 public NextToArriveViewModel(string urlBase)
 {
     RouteService = new RouteService(urlBase);
     StopService  = new StopService(urlBase);
 }
Ejemplo n.º 39
0
        public RouteServiceTestSuite()
        {
            RouteRepositoryMock = new Mock <IRouteRepository>();

            RouteService = new RouteService(RouteRepositoryMock.Object);
        }
Ejemplo n.º 40
0
 void Main()
 {
     var service = new RouteService();
     service.Create(new Route)
 }
        private void CalculateRouteCompleted(object sender, RouteService.CalculateRouteCompletedEventArgs e)
        {
            try
            {
                if ((e.Result.ResponseSummary.StatusCode == RouteService.ResponseStatusCode.Success) & (e.Result.Result.Legs.Count != 0))
                {
                    var markers = new List<GeoCoordinate>();
                    Microsoft.Phone.Controls.Maps.MapPolyline routeLine = SetRouteProperties();
                    int i = 1;
                    foreach (Microsoft.Phone.Controls.Maps.Platform.Location p in e.Result.Result.RoutePath.Points)
                    {
                        GeoCoordinate gc = new GeoCoordinate(p.Latitude, p.Longitude);
                        routeLine.Locations.Add(gc); //pin location is the same as start and end points
                        if ((e.Result.Result.RoutePath.Points.Count == i) || (1 == i))
                        {
                            Microsoft.Phone.Controls.Maps.Pushpin pin = new Microsoft.Phone.Controls.Maps.Pushpin();
                            pin.Location = gc;
                            if (1 == i)
                            {
                                pin.Background = new SolidColorBrush(Colors.Red);
                                pin.Content = "You are here";
                            }
                            else
                            {
                                pin.Background = new SolidColorBrush(Colors.Purple);
                                pin.Content = "MOBICA";
                            }

                            routedMap.Children.Add(pin);
                        }
                        markers.Add(gc);
                        i++;
                    }

                    if (null != routedMap)
                    {
                        routedMap.Children.Add(routeLine);
                    }

                    routedMap.ZoomLevel = 19;

                    routedMap.SetView(Microsoft.Phone.Controls.Maps.LocationRect.CreateLocationRect(markers));
                    markers.Clear();
                    MapResponseSendHere(routedMap);
                }
            }
            catch (Exception ex)
            {
                if ("No route was found for the waypoints provided." == ex.Message)
                    MessageBox.Show("You are too far away from your destination, please find another Mobica office.");
                else
                    MessageBox.Show("An exception occured: " + ex.Message);

                MapResponseSendHere(null);
            }
        }
Ejemplo n.º 42
0
        public MainViewModel(VehicleService vs, VehicleListener vl, MapViewModel mp, TelemetryListener tl, CommandService cs, MissionService ms, RouteService rs, VehicleCommand vc)
        {
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap <ServiceTelemetryDTO, ClientTelemetry>();
            });

            logger.LogInfoMessage("Main window initialized");
            MapViewModel    = mp;
            _vehicleService = vs;
            _commandService = cs;
            _missionService = ms;
            _routeService   = rs;
            _vehicleCommand = vc;
            try
            {
                ClientVehicle                   = new ClientVehicle();
                ClientVehicle.Vehicle           = vs.GetVehicleByName(Settings.Default.UgcsDroneProfileName);
                ClientVehicle.Telemetry.Vehicle = ClientVehicle.Vehicle;
                var subscription = new ObjectModificationSubscription();
                subscription.ObjectId   = ClientVehicle.Vehicle.Id;
                subscription.ObjectType = "Vehicle";
                _commandService.TryAcquireLock(ClientVehicle.Vehicle.Id);
                tl.AddVehicleIdTolistener(ClientVehicle.Vehicle.Id, TelemetryCallBack);
                vl.SubscribeVehicle(subscription, (e) =>
                {
                    //Subscribe vehicle changes
                });
                MapViewModel.Init(ClientVehicle);
                NotifyOfPropertyChange(() => MissionName);
                NotifyOfPropertyChange(() => RouteName);
                NotifyOfPropertyChange(() => VehicleName);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                Application.Current.Shutdown();
            }
        }
Ejemplo n.º 43
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            // initialise logger
            Logger.Instance.SetOutput(logBox);
            Logger.WriteLine("Server starting..");

            // initialise database
            Database.Instance.Connect();

            // initialise the state object
            currentState = new CurrentState();

            // initialise all the services (they set up the state themselves) and pathfinder
            countryService = new CountryService(currentState);
            companyService = new CompanyService(currentState);
            routeService = new RouteService(currentState);
            var pathFinder = new PathFinder(routeService); // pathfinder needs the RouteService and state
            deliveryService = new DeliveryService(currentState, pathFinder); // DeliveryService needs the PathFinder
            priceService = new PriceService(currentState);
            locationService = new LocationService(currentState);
            eventService = new EventService(currentState);
            statisticsService = new StatisticsService();

            // initialise network
            Network.Network network = Network.Network.Instance;
            network.Start();
            network.Open();

            // create controller
            var controller = new Controller(countryService, companyService, deliveryService, priceService, routeService,
                                            locationService, statisticsService, eventService);

            //BenDBTests(countryService, routeService);
            //SetUpDatabaseWithData();

            /*try
            {
                var priceDH = new PriceDataHelper();

                var standardPrice = new DomesticPrice(Priority.Standard) { PricePerGram = 3, PricePerCm3 = 5 };
                //standardPrice = priceService.CreateDomesticPrice(standardPrice.Priority, standardPrice.PricePerGram, standardPrice.PricePerCm3);

                standardPrice.PricePerCm3 = 8;
                //standardPrice = priceService.UpdateDomesticPrice(standardPrice.ID, standardPrice.Priority, standardPrice.PricePerGram, standardPrice.PricePerCm3);

                var loadedPrice = priceService.GetDomesticPrice(1);
                var prices = priceService.GetAllDomesticPrices();

                var normalPrices = priceService.GetAll();
            }
            catch (DatabaseException er) {
                Logger.WriteLine(er.Message);
                Logger.Write(er.StackTrace);
            }*/
        }
        private void routeService_CalculateRouteCompleted(object sender, RouteService.CalculateRouteCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                // If the route calculate was a success and contains a route, then draw the route on the map.
                if ((e.Result.ResponseSummary.StatusCode == RouteService.ResponseStatusCode.Success) & (e.Result.Result.Legs.Count != 0))
                {
                    // Set properties of the route line you want to draw.
                    Color routeColor = Colors.Blue;
                    SolidColorBrush routeBrush = new SolidColorBrush(routeColor);
                    MapPolyline routeLine = new MapPolyline();
                    routeLine.Locations = new LocationCollection();
                    routeLine.Stroke = routeBrush;
                    routeLine.Opacity = 0.65;
                    routeLine.StrokeThickness = 5.0;

                    // Retrieve the route points that define the shape of the route.
                    foreach (Location p in e.Result.Result.RoutePath.Points)
                    {
                        Location location = new Location();
                        location.Latitude = p.Latitude;
                        location.Longitude = p.Longitude;
                        routeLine.Locations.Add(location);
                    }

                    // Add a map layer in which to draw the route.
                    MapLayer myRouteLayer = new MapLayer();
                    map1.Children.Add(myRouteLayer);

                    // Add the route line to the new layer.
                    myRouteLayer.Children.Add(routeLine);

                }
            }
        }
 public TripReceivedEventArgs(List<Trip> trips, RouteService.RouteResult routeResult)
 {
     Trips = trips;
     Error = false;
     RouteResult = routeResult;
 }