1 using Microsoft.Phone.Controls;
4 using System.Globalization;
6 using System.Windows.Controls;
7 using System.Windows.Navigation;
8 using WeatherInformation.Model;
9 using WeatherInformation.Model.Services;
10 using WeatherInformation.Resources;
11 using WeatherInformation.ViewModels;
12 using System.Threading.Tasks;
13 using WeatherInformation.Model.JsonDataParser;
14 using Microsoft.Phone.Shell;
16 namespace WeatherInformation
18 public partial class MainPage : PhoneApplicationPage
20 private MainViewModel _mainViewModel;
21 private bool _isNewPageInstance = false;
26 InitializeComponent();
28 _isNewPageInstance = true;
30 // Código de ejemplo para traducir ApplicationBar
31 //BuildLocalizedApplicationBar();
35 // Cargar datos para los elementos MainViewModel
36 protected override void OnNavigatedTo(NavigationEventArgs e)
38 base.OnNavigatedTo(e);
42 // If _isNewPageInstance is true, the page constuctor has been called, so
43 // state may need to be restored.
44 if (_isNewPageInstance)
46 if (_mainViewModel == null)
48 _mainViewModel = new MainViewModel(new SettingsViewModel());
51 DataContext = _mainViewModel;
53 // Set _isNewPageInstance to false. If the user navigates back to this page
54 // and it has remained in memory, this value will continue to be false.
55 _isNewPageInstance = false;
57 UpdateApplicationDataUI();
60 async private void UpdateApplicationDataUI()
62 Location locationItem = null;
63 using (var db = new LocationDataContext(LocationDataContext.DBConnectionString))
65 locationItem = db.Locations.Where(location => location.IsSelected).FirstOrDefault();
68 if (locationItem == null)
74 // If the application member variable is not empty,
75 // set the page's data object from the application member variable.
76 WeatherData weatherData = (Application.Current as WeatherInformation.App).ApplicationDataObject;
77 if (!IsDataFresh(locationItem.LastRemoteDataUpdate) || weatherData == null)
79 // Load remote data (aynchronous way by means of async/await)
81 // Gets the data from the web.
82 (Application.Current as WeatherInformation.App).ApplicationDataObject =
83 await GetRemoteDataAsync(locationItem);
85 using (var db = new LocationDataContext(LocationDataContext.DBConnectionString))
87 locationItem = db.Locations.Where(location => location.IsSelected).FirstOrDefault();
88 locationItem.LastRemoteDataUpdate = DateTime.UtcNow;
93 // Call UpdateUI on the UI thread.
94 // Without ConfigureAwait(false) await returns data on the calling thread. In this case the calling one
95 // is the UI thread. So, I can save the call to Dispatcher.BeginInvoke.
96 //Dispatcher.BeginInvoke(() => UpdateUI());
102 // Set the ApplicationData and ApplicationDataStatus members of the ViewModel
103 WeatherData weatherData = (Application.Current as WeatherInformation.App).ApplicationDataObject;
105 if (weatherData != null)
107 _mainViewModel.LoadData(weatherData);
111 private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
113 LongListSelector longListSelector = sender as LongListSelector;
115 // TODO: with LINQ :(
116 ItemViewModel element = longListSelector.SelectedItem as ItemViewModel;
117 int index = longListSelector.ItemsSource.IndexOf(element);
118 String uri = string.Format(CultureInfo.InvariantCulture, "/SelectedDatePage.xaml?parameter={0}", index);
119 NavigationService.Navigate(new Uri(uri, UriKind.Relative));
123 /// Retrieve remote weather data.
125 async public Task<WeatherData> GetRemoteDataAsync(Location locationItem)
127 double latitude = locationItem.Latitude;
128 double longitude = locationItem.Longitude;
129 int resultsNumber = Convert.ToInt32(AppResources.APIOpenWeatherMapResultsNumber);
131 CustomHTTPClient httpClient = new CustomHTTPClient();
133 string formattedForecastURL = String.Format(
134 CultureInfo.InvariantCulture, AppResources.URIAPIOpenWeatherMapForecast,
135 AppResources.APIVersionOpenWeatherMap, latitude, longitude, resultsNumber);
136 string jsonForecast = await httpClient.GetWeatherDataAsync(formattedForecastURL).ConfigureAwait(false);
138 string formattedCurrentURL = String.Format(
139 CultureInfo.InvariantCulture, AppResources.URIAPIOpenWeatherMapCurrent,
140 AppResources.APIVersionOpenWeatherMap, latitude, longitude, resultsNumber);
141 string jsonCurrent = await httpClient.GetWeatherDataAsync(formattedCurrentURL).ConfigureAwait(false);
143 var parser = new ServiceParser(new JsonParser());
144 var weatherData = parser.WeatherDataParser(jsonForecast, jsonCurrent, locationItem.City, locationItem.Country);
149 private bool IsDataFresh(DateTime? lastUpdate)
151 if (lastUpdate == null)
156 // Check the time elapsed since data was last saved to isolated storage.
157 TimeSpan TimeSinceLastSave = DateTime.UtcNow - lastUpdate.Value;
159 if (TimeSinceLastSave.TotalSeconds < 30)
167 private void Location_Click(object sender, EventArgs e)
169 NavigationService.Navigate(new Uri("/MapPage.xaml", UriKind.Relative));
172 private void Settings_Click(object sender, EventArgs e)
174 NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
177 private void CreateFlipTile()
179 ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(
180 x => x.NavigationUri.ToString().Contains("flip"));
181 tile = ShellTile.ActiveTiles.First();
182 var activeTiles = ShellTile.ActiveTiles;
184 var tileData = new FlipTileData();
185 tileData.Title = "GUSTAVO RULES";
186 tileData.BackTitle = "Gustavo Rules Back";
187 tileData.BackContent = "Gustavo Back Content";
188 tileData.WideBackContent = "Gustavo Wid Back Content";
189 tile.Update(tileData);
193 // Código de ejemplo para compilar una ApplicationBar traducida
194 //private void BuildLocalizedApplicationBar()
196 // // Establecer ApplicationBar de la página en una nueva instancia de ApplicationBar.
197 // ApplicationBar = new ApplicationBar();
199 // // Crear un nuevo botón y establecer el valor de texto en la cadena traducida de AppResources.
200 // ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
201 // appBarButton.Text = AppResources.AppBarButtonText;
202 // ApplicationBar.Buttons.Add(appBarButton);
204 // // Crear un nuevo elemento de menú con la cadena traducida de AppResources.
205 // ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
206 // ApplicationBar.MenuItems.Add(appBarMenuItem);