Exemple #1
0
        public SettingsPage()
        {
            InitializeComponent();

            BindingContext = new SettingsPageViewModel();

            languagePicker.Items.Add("English");

            foreach (var file in PlatformDependentSettings.GetLocalizations().Select(x => new FileInfo(x)))
            {
                if (file.Extension == ".xml")
                {
                    languagePicker.Items.Add(file.Name.Split('.')[0]);
                }
            }

            languagePicker.SelectedItem = (from object item in languagePicker.Items where item.ToString() == Settings.Localization.ToString() select item).First();

            languagePicker.SelectedIndexChanged += LanguagePicker_SelectedIndexChanged;

            speedSlider.Value = Settings.WalkingSpeedCoefficient * 100;

            subwaySwitch.IsToggled   = Settings.AllowSubway;
            tramSwitch.IsToggled     = Settings.AllowTram;
            busSwitch.IsToggled      = Settings.AllowBus;
            trainSwitch.IsToggled    = Settings.AllowTrain;
            cablecarSwitch.IsToggled = Settings.AllowCablecar;
            shipSwitch.IsToggled     = Settings.AllowShip;
            wifiSwitch.IsToggled     = Settings.UseCellularsToUpdateCache;
        }
Exemple #2
0
        private void FindClosestStation(object sender, EventArgs e)
        {
            try
            {
                Utilities.Position pos = new Position();

                try
                {
                    pos = AsyncHelpers.RunSync <Position>(DataFeedClient.GeoWatcher.GetCurrentPosition);
                }
                catch
                {
                    PlatformDependentSettings.ShowMessage(Settings.Localization.PositioningNeeded);
                }

                var station = DataFeedClient.Basic.Stations.FindClosestStation(pos);
                if (station != null)
                {
                    sourceStopEntry.Text = station.Name;
                }
            }
            catch
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Request.CheckBasicDataValidity();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
        private bool useStopNotStation;                                              // False if open from journey/departure window.
        private void SetMapScope(IEnumerable <StopsBasic.StopBasic> stops, bool zoomAtCurrentLoc = true, bool adaptiveZoom = false)
        {
            double lat, lon, distance;

            var loc = new Utilities.Position(double.NaN, double.NaN);

            try
            {
                loc = AsyncHelpers.RunSync(DataFeedClient.GeoWatcher.GetCurrentPosition);
            }
            catch
            {
                zoomAtCurrentLoc = false;
                PlatformDependentSettings.ShowMessage(Settings.Localization.PositioningNeeded);
            }

            if (!zoomAtCurrentLoc || double.IsNaN(loc.Latitude) || double.IsNaN(loc.Longitude))
            {
                lat      = stops.GetAverageLatitude();
                lon      = stops.GetAverageLongitude();
                distance = adaptiveZoom ? 10000 : 1000;
            }
            else
            {
                lat      = loc.Latitude;
                lon      = loc.Longitude;
                distance = 350;
            }

            map.MoveToRegion(MapSpan.FromCenterAndRadius(new Xamarin.Forms.GoogleMaps.Position(lat, lon), new Distance(distance)), false);
        }
Exemple #4
0
        private void FavoritesButtonClicked(object sender, EventArgs e)
        {
            try
            {
                Structures.Basic.RoutesInfoBasic.RouteInfoBasic route = Request.GetRouteInfoFromLabel(lineEntry.Text);

                if (route == null)
                {
                    PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindRouteInfo + ": " + lineEntry.Text);
                    return;
                }

                if (LineInfoCached.Select(route.ID) != null)
                {
                    return;
                }

                var fav = new LineInfoCached(route.ID);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Request.CacheDepartureBoardAsync(fav.ConstructNewRequest());
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                favoritesStackLayout.Children.Add(new FavoriteItemContentView(favoritesStackLayout, scrollView, fav, lineEntry));
            }
            catch
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Request.CheckBasicDataValidity();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
Exemple #5
0
        private void LanguagePicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            var name = (sender as Picker).SelectedItem.ToString();

            Settings.Localization = name == "English" ?
                                    Timetables.Client.Localization.GetTranslation("English") :
                                    Timetables.Client.Localization.GetTranslation(new Tuple <Stream, string>(
                                                                                      PlatformDependentSettings.GetStream(new FileInfo($"loc/{ name }.xml")), name));
            PlatformDependentSettings.ShowMessage(Settings.Localization.RestartToApplyChanges);
        }
Exemple #6
0
        public App()
        {
            bool firstCall = false;             // ConnectivityTypeChanged event is broken, it's called twice everytime the type is changed.

            Plugin.Connectivity.CrossConnectivity.Current.ConnectivityTypeChanged += async(s, e) =>
            {
                firstCall = !firstCall;

                if (!firstCall)
                {
                    return;
                }

                bool isWifi = false;

                foreach (var connectionType in e.ConnectionTypes)
                {
                    if (connectionType == Plugin.Connectivity.Abstractions.ConnectionType.WiFi)
                    {
                        isWifi = true;
                    }
                }

                if (isWifi)
                {
                    try
                    {
                        await Request.UpdateCachedResultsAsync(true);
                    }
                    catch { }
                }
            };

            InitializeComponent();

            Settings.Load();

            try
            {
                Settings.LoadDataFeedAsync();
            }
            catch (WebException)
            {
                PlatformDependentSettings.ShowMessage(Settings.Localization.UnreachableHost);
            }

            if (Settings.UseCellularsToUpdateCache)
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            {
                Request.UpdateCachedResultsAsync();
            }
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            MainPage = new MainPage();
        }
Exemple #7
0
        /// <summary>
        /// Returns station object with given name. If not found, returns error message.
        /// </summary>
        /// <param name="name">Name of the station.</param>
        /// <returns>Station object.</returns>
        public static Structures.Basic.StationsBasic.StationBasic GetStationFromString(string name)
        {
            Structures.Basic.StationsBasic.StationBasic source = DataFeedClient.Basic.Stations.FindByName(name);

            if (source == null)
            {
                PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindStation + ": " + name);
            }

            return(source);
        }
Exemple #8
0
 /// <summary>
 /// Returns true if everything is OK.
 /// </summary>
 public static async Task <bool> CheckBasicDataValidity()
 {
     try
     {
         await DataFeedClient.DownloadAsync(true);                 // Checks basic data validity.
     }
     catch (System.Net.WebException)
     {
         PlatformDependentSettings.ShowMessage(Settings.Localization.UnreachableHost);
         return(false);
     }
     return(true);
 }
Exemple #9
0
        public static async Task <RouterResponse> SendRouterRequestAsync(RouterRequest routerRequest, bool forceCache = false)
        {
            RouterResponse routerResponse = null;

            using (var routerProcessing = new RouterProcessing())
            {
                var cached = JourneyCached.Select(routerRequest.SourceStationID, routerRequest.TargetStationID);

                if (cached == null || (cached.ShouldBeUpdated || forceCache))
                {
                    try
                    {
                        if (!await CheckBasicDataValidity())
                        {
                            var results = cached?.FindResultsSatisfyingRequest(routerRequest);
                            return(results?.Journeys.Count == 0 ? null : results);
                        }

                        // Process the request immediately so the user does not have to wait until the caching is completed.

                        routerResponse = await routerProcessing.ProcessAsync(routerRequest, routerRequest.Count == -1?int.MaxValue : Settings.TimeoutDuration);

                        // Then update the cache.

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                        if (cached != null && cached.ShouldBeUpdated && routerRequest.Count != -1 && CanBeCached)
                        {
                            Task.Run(async() => cached.UpdateCache(await routerProcessing.ProcessAsync(cached.ConstructNewRequest(), int.MaxValue)));
                        }
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                    }
                    catch (System.Net.WebException)
                    {
                        PlatformDependentSettings.ShowMessage(Settings.Localization.UnreachableHost);
                    }
                }

                else
                {
                    routerResponse = cached?.FindResultsSatisfyingRequest(routerRequest);
                    if (routerResponse?.Journeys.Count == 0)
                    {
                        routerResponse = await routerProcessing.ProcessAsync(routerRequest, Settings.TimeoutDuration);
                    }
                }
            }

            return(routerResponse);
        }
Exemple #10
0
        /// <summary>
        /// Returns route info object with given name. If not found, returns error message.
        /// </summary>
        /// <param name="label">Route label.</param>
        /// <returns>Route info object.</returns>
        public static Structures.Basic.RoutesInfoBasic.RouteInfoBasic GetRouteInfoFromLabel(string label)
        {
            if (string.IsNullOrEmpty(label))
            {
                return(null);
            }

            Structures.Basic.RoutesInfoBasic.RouteInfoBasic route = DataFeedClient.Basic.RoutesInfo.FindByLabel(label);

            if (route == null)
            {
                PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindRouteInfo + ": " + label);
            }

            return(route);
        }
Exemple #11
0
        public DepartureBoardResultsPage(DepartureBoardResponse res, bool stationInfo, string name)
        {
            InitializeComponent();

            Title = (stationInfo ? Settings.Localization.Station : Settings.Localization.Line) + " " + name;

            Response = res;

            resultsWebView.Scripting = new DepartureBoardScripting(resultsWebView, this);

            resultsWebView.Source = new HtmlWebViewSource
            {
                Html = Response.TransformToHtml(
                    PlatformDependentSettings.GetStream(Settings.DepartureBoardSimpleXslt),
                    PlatformDependentSettings.GetStream(Settings.DepartureBoardSimpleCss),
                    PlatformDependentSettings.GetStream(Settings.OnLoadActionsJavaScript)
                    )
            };
        }
Exemple #12
0
        protected async void LoadContent(Uri uri, System.IO.FileInfo xslt, System.IO.FileInfo css)
        {
            try
            {
                if (uri == null)
                {
                    throw new ArgumentException();
                }

                using (var wc = new WebClient())
                {
                    wc.Encoding = Encoding.UTF8;

                    var downloading = wc.DownloadStringTaskAsync(uri);

                    if (await Task.WhenAny(downloading, Task.Delay(Settings.TimeoutDuration)) == downloading && downloading.Status == TaskStatus.RanToCompletion)
                    {
                        resultsWebView.Source = new HtmlWebViewSource
                        {
                            Html = (await downloading).TransformToHtml(
                                PlatformDependentSettings.GetStream(xslt), PlatformDependentSettings.GetStream(css))
                        }
                    }
                    ;
                    else
                    {
                        throw new WebException();
                    }
                }
            }

            catch (ArgumentException)
            {
                resultsWebView.Source = new HtmlWebViewSource {
                    Html = "Invalid Uri address."
                };
            }

            catch (WebException)
            {
                PlatformDependentSettings.ShowMessage(Settings.Localization.UnreachableHost);
            }
        }
        public FindJourneyResultsPage(RouterResponse res, string source, string target)
        {
            InitializeComponent();

            Title = Settings.Localization.Journey + " " + source + " - " + target;

            Response = res;

            resultsWebView.Scripting = new JourneyScripting(resultsWebView, this);

            resultsWebView.Source = new HtmlWebViewSource
            {
                Html = Response.TransformToHtml(
                    PlatformDependentSettings.GetStream(Settings.JourneySimpleXslt),
                    PlatformDependentSettings.GetStream(Settings.JourneySimpleCss),
                    PlatformDependentSettings.GetStream(Settings.OnLoadActionsJavaScript)
                    )
            };
        }
Exemple #14
0
        /// <summary>
        /// Loads data feed.
        /// </summary>
        public static async void LoadDataFeedAsync()
        {
            try
            {
                DataFeedClient.Load();                 // Load some data first if exists, then try to update them.
            }
            catch
            {
            }

            try
            {
                await DataFeedClient.DownloadAsync(false, TimeoutDuration);
            }
            catch
            {
                PlatformDependentSettings.ShowMessage(Settings.Localization.UnreachableHost);
            }
        }
Exemple #15
0
        public DepartureBoardResultsPage(Departure dep)
        {
            InitializeComponent();

            Title = Settings.Localization.Departure + " " + dep.Headsign;

            Response = new DepartureBoardResponse(new List <Departure> {
                dep
            });

            resultsWebView.Scripting = new DepartureBoardScripting(resultsWebView, this);

            resultsWebView.Source = new HtmlWebViewSource
            {
                Html = Response.Departures[0].TransformToHtml(
                    PlatformDependentSettings.GetStream(Settings.DepartureBoardDetailXslt),
                    PlatformDependentSettings.GetStream(Settings.DepartureBoardDetailCss),
                    PlatformDependentSettings.GetStream(Settings.OnLoadActionsJavaScript)
                    )
            };
        }
Exemple #16
0
        private void FavoritesButtonClicked(object sender, EventArgs e)
        {
            try
            {
                Structures.Basic.StationsBasic.StationBasic source = Request.GetStationFromString(sourceStopEntry.Text);
                Structures.Basic.StationsBasic.StationBasic target = Request.GetStationFromString(targetStopEntry.Text);

                if (source == null)
                {
                    PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindStation + ": " + sourceStopEntry.Text);
                    return;
                }

                if (target == null)
                {
                    PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindStation + ": " + targetStopEntry.Text);
                    return;
                }

                if (JourneyCached.Select(source.ID, target.ID) != null)
                {
                    return;
                }

                var fav = new JourneyCached(source.ID, target.ID);

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Request.CacheJourneyAsync(fav.ConstructNewRequest());
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

                favoritesStackLayout.Children.Add(new FavoriteItemContentView(favoritesStackLayout, scrollView, fav, sourceStopEntry, targetStopEntry));
            }
            catch
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Request.CheckBasicDataValidity();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
Exemple #17
0
        private async void FindButtonClicked(object sender, EventArgs e)
        {
            try
            {
                Structures.Basic.StationsBasic.StationBasic source = Request.GetStationFromString(sourceStopEntry.Text);
                Structures.Basic.StationsBasic.StationBasic target = Request.GetStationFromString(targetStopEntry.Text);

                if (source == null)
                {
                    PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindStation + ": " + sourceStopEntry.Text);
                    return;
                }
                if (target == null)
                {
                    PlatformDependentSettings.ShowMessage(Settings.Localization.UnableToFindStation + ": " + targetStopEntry.Text);
                    return;
                }

                var routerRequest = new RouterRequest(source.ID, target.ID, leavingTimeDatePicker.Date.Add(leavingTimeTimePicker.Time),
                                                      (int)transfersSlider.Value, (int)countSlider.Value, Settings.WalkingSpeedCoefficient, Settings.GetMoT());

                findButton.IsEnabled = false;
                var routerResponse = await Request.SendRouterRequestAsync(routerRequest);

                findButton.IsEnabled = true;

                if (routerResponse != null)
                {
                    await Navigation.PushAsync(new FindJourneyResultsPage(routerResponse, source.Name, target.Name), true);
                }
            }
            catch
            {
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
                Request.CheckBasicDataValidity();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            }
        }
        public FindJourneyResultsPage(Journey journey)
        {
            InitializeComponent();

            Title = Settings.Localization.Journey + " " +
                    DataFeedClient.Basic.Stops.FindByIndex(journey.JourneySegments.First().SourceStopID).ParentStation.Name + " - " +
                    DataFeedClient.Basic.Stops.FindByIndex(journey.JourneySegments.Last().TargetStopID).ParentStation.Name;

            Response = new RouterResponse(new List <Journey> {
                journey
            });

            resultsWebView.Scripting = new JourneyScripting(resultsWebView, this);

            resultsWebView.Source = new HtmlWebViewSource
            {
                Html = Response.Journeys[0].TransformToHtml(
                    PlatformDependentSettings.GetStream(Settings.JourneyDetailXslt),
                    PlatformDependentSettings.GetStream(Settings.JourneyDetailCss),
                    PlatformDependentSettings.GetStream(Settings.OnLoadActionsJavaScript)
                    )
            };
        }
Exemple #19
0
 /// <summary>
 /// Copies the settings file from assets to local directory.
 /// </summary>
 private static void CopyFromAssets()
 {
     using (var sw = new StreamWriter(DataFeedClient.BasePath + SettingsFile, false))
         using (var sr = new StreamReader(PlatformDependentSettings.GetStream(SettingsFile)))
             sw.Write(sr.ReadToEnd());
 }
Exemple #20
0
        /// <summary>
        /// Loads the settings.
        /// </summary>
        public static void Load()
        {
            // First launch = copy settings from assets to temporary path.
            if (!File.Exists(DataFeedClient.BasePath + SettingsFile))
            {
                CopyFromAssets();
            }

            XmlDocument settings = new XmlDocument();

            try
            {
                settings.Load(DataFeedClient.BasePath + SettingsFile);
            }
            catch
            {
                CopyFromAssets();
                settings.Load(DataFeedClient.BasePath + SettingsFile);
            }

            try
            {
                var locName = settings.GetElementsByTagName("Language")?[0].InnerText;
                Localization = locName == "English" ?
                               Localization.GetTranslation("English") :
                               Localization.GetTranslation(new Tuple <Stream, string>(
                                                               PlatformDependentSettings.GetStream(new FileInfo("loc/" + locName + ".xml")),
                                                               locName));
            }
            catch
            {
                Localization = new Localization();
            }

            void SetIpAddress()
            {
                PlatformDependentSettings.ShowDialog("Enter server IP address.", ip => {
                    try {
                        Client.DataFeedClient.ServerIpAddress = IPAddress.Parse(ip);
                        Save();
                        LoadDataFeedAsync();
                    } catch { SetIpAddress(); }
                });
            }

            try
            {
                Client.DataFeedClient.ServerIpAddress = settings.GetElementsByTagName("ServerIp")[0].InnerText == string.Empty ? null : IPAddress.Parse(settings.GetElementsByTagName("ServerIp")[0].InnerText);
            }
            catch
            {
                SetIpAddress();
            }

            Client.DataFeedClient.RouterPortNumber = settings.GetElementsByTagName("RouterPort")[0].InnerText == string.Empty ? default(int) : int.Parse(settings.GetElementsByTagName("RouterPort")[0].InnerText);

            Client.DataFeedClient.DepartureBoardPortNumber = settings.GetElementsByTagName("DepartureBoardPort")[0].InnerText == string.Empty ? default(int) : int.Parse(settings.GetElementsByTagName("DepartureBoardPort")[0].InnerText);

            Client.DataFeedClient.BasicDataPortNumber = settings.GetElementsByTagName("BasicDataPort")[0].InnerText == string.Empty ? default(int) : int.Parse(settings.GetElementsByTagName("BasicDataPort")[0].InnerText);

            Lockouts = string.IsNullOrEmpty(settings.GetElementsByTagName("LockoutsUri")[0].InnerText) ? null : new Uri(settings.GetElementsByTagName("LockoutsUri")[0].InnerText);

            ExtraordinaryEvents = string.IsNullOrEmpty(settings.GetElementsByTagName("LockoutsUri")[0].InnerText) ? null : new Uri(settings.GetElementsByTagName("ExtraEventsUri")[0].InnerText);

            try
            {
                AllowSubway = bool.Parse(settings.GetElementsByTagName("AllowSubway")[0].InnerText);

                AllowTram = bool.Parse(settings.GetElementsByTagName("AllowTram")[0].InnerText);

                AllowCablecar = bool.Parse(settings.GetElementsByTagName("AllowCablecar")[0].InnerText);

                AllowBus = bool.Parse(settings.GetElementsByTagName("AllowBus")[0].InnerText);

                AllowTrain = bool.Parse(settings.GetElementsByTagName("AllowTrain")[0].InnerText);

                AllowShip = bool.Parse(settings.GetElementsByTagName("AllowShip")[0].InnerText);

                WalkingSpeedCoefficient = double.Parse(settings.GetElementsByTagName("WalkingSpeedCoefficient")[0].InnerText);

                UseCellularsToUpdateCache = bool.Parse(settings.GetElementsByTagName("UseCellularsToUpdateCache")[0].InnerText);
            }
            catch
            {
                AllowSubway = true; AllowTram = true; AllowCablecar = true; AllowBus = true; AllowTrain = true; AllowShip = true;

                WalkingSpeedCoefficient = 1.0;

                UseCellularsToUpdateCache = false;
            }

#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed

            DataFeedClient.GeoWatcher = new CPGeolocator(() =>
            {
                var position = AsyncHelpers.RunSync(CrossGeolocator.Current.GetLastKnownLocationAsync);

                return(new Position(position.Latitude, position.Longitude));
            });
        }