TimeSinceLastSave = DateTime.Now - dataLastSaveTime;
}
- // Check to see if data exists in isolated storage and see if the data is fresh.
- // This example uses 30 seconds as the valid time window to make it easy to test.
- // Real apps will use a larger window.
- using(IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
+ if (!IsNewLocation)
{
- if (isoStore.FileExists("JSONDataFile.txt") && TimeSinceLastSave.TotalSeconds < 30)
+ // Check to see if data exists in isolated storage and see if the data is fresh.
+ // This example uses 30 seconds as the valid time window to make it easy to test.
+ // Real apps will use a larger window.
+ using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
- using (StreamReader sr = new StreamReader(isoStore.OpenFile("JSONDataFile.txt", FileMode.Open)))
- {
- // This method loads the data from isolated storage, if it is available.
- string JSONRemoteForecastWeatherData = sr.ReadLine();
- // string remoteCurrentWeatherData = sr.ReadLine();
- var weatherData = WeatherParser(JSONRemoteForecastWeatherData, null);
- weatherData.JSONRemoteForecastWeatherData = JSONRemoteForecastWeatherData;
- weatherData.JSONRemoteCurrentWeatherData = null;
- weatherData.WasThereRemoteError = false;
- ApplicationDataObject = weatherData;
- }
- }
- else
- {
- // Otherwise, it gets the data from the web.
- var task = LoadDataAsync();
- try
- {
- // TODO: I guess, I may do this because this code is running in a new thread :/ Better alternative just using async? WIP :(
- task.Wait();
- }
- catch (AggregateException ae)
+ if (isoStore.FileExists("JSONDataFile.txt") && TimeSinceLastSave.TotalSeconds < 30)
{
- ae.Handle(e =>
+ using (StreamReader sr = new StreamReader(isoStore.OpenFile("JSONDataFile.txt", FileMode.Open)))
{
- // If the data request fails, alert the user.
- ApplicationDataObject = new WeatherData
- {
- RemoteForecastWeatherData = null,
- RemoteCurrentWeatherData = null,
- JSONRemoteForecastWeatherData = null,
- JSONRemoteCurrentWeatherData = null,
- WasThereRemoteError = true
- };
-
- return true;
- });
+ // This method loads the data from isolated storage, if it is available.
+ string JSONRemoteForecastWeatherData = sr.ReadLine();
+ // string remoteCurrentWeatherData = sr.ReadLine();
+ var weatherData = WeatherParser(JSONRemoteForecastWeatherData, null);
+ weatherData.JSONRemoteForecastWeatherData = JSONRemoteForecastWeatherData;
+ weatherData.JSONRemoteCurrentWeatherData = null;
+ weatherData.WasThereRemoteError = false;
+ ApplicationDataObject = weatherData;
+ }
+
+ // TODO: write more methods or something else to avoid nested returns like this... no time right now... :(
+ return;
}
}
}
+
+ // Otherwise, it gets the data from the web.
+ var task = LoadDataAsync();
+ try
+ {
+ // TODO: I guess, I may do this because this code is running in a new thread :/ Better alternative just using async? WIP :(
+ // Using Task.WhenAll to avoid deadlock :)
+ Task.WhenAll(task);
+ }
+ catch (Exception ex)
+ {
+ // If the data request fails, alert the user.
+ ApplicationDataObject = new WeatherData
+ {
+ RemoteForecastWeatherData = null,
+ RemoteCurrentWeatherData = null,
+ JSONRemoteForecastWeatherData = null,
+ JSONRemoteCurrentWeatherData = null,
+ WasThereRemoteError = true
+ };
+ }
}
/// <summary>
- /// Crear y agregar unos pocos objetos ItemViewModel a la colección Items.
+ /// Retrieve remote weather data.
/// </summary>
async public Task LoadDataAsync()
{
sw.Write(value.JSONRemoteForecastWeatherData);
fileStream.Flush(true);
}
-
- IsolatedStorageSettings.ApplicationSettings["DataLastSaveTime"] = DateTime.Now;
+
+ IsolatedStorageSettings.ApplicationSettings["DataLastSavedTime"] = DateTime.Now;
}
weatherData.WasThereRemoteError = false;
ApplicationDataObject = weatherData;
}
+ if (PhoneApplicationService.Current.State.ContainsKey("IsNewLocation"))
+ {
+ IsNewLocation = (bool)IsolatedStorageSettings.ApplicationSettings["IsNewLocation"];
+ }
}
// Código para ejecutar cuando la aplicación se desactiva (se envía a segundo plano)
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
// If there is data in the application member variable...
- if (ApplicationDataObject != null)
+ var weatherData = ApplicationDataObject;
+ if (weatherData != null)
{
- var weatherData = ApplicationDataObject;
if (!string.IsNullOrEmpty(weatherData.JSONRemoteForecastWeatherData))
{
// Store it in the State dictionary.
PhoneApplicationService.Current.State["JSONRemoteForecastWeatherData"] = weatherData.JSONRemoteForecastWeatherData;
}
+ PhoneApplicationService.Current.State["IsNewLocation"] = IsNewLocation;
// Also store it in isolated storage, in case the application is never reactivated.
SaveDataToIsolatedStorage("JSONDataFile.txt", weatherData);
{
// Asegurarse de que el estado de la aplicación requerida persiste aquí.
// The application will not be tombstoned, so save only to isolated storage.
- if (ApplicationDataObject != null)
+ var weatherData = ApplicationDataObject;
+ if (weatherData != null)
{
- SaveDataToIsolatedStorage("JSONDataFile.txt", ApplicationDataObject);
+ SaveDataToIsolatedStorage("JSONDataFile.txt", weatherData);
}
}
-->
<!--Control Pivot-->
- <phone:Pivot Title="City, country">
+ <phone:Pivot x:Name="TitleTextCityCountry" Title="{Binding LocalizedResources.MainPageTitle, Mode=OneWay, Source={StaticResource LocalizedStrings}}">
<!--Elemento Pivot uno-->
<phone:PivotItem Header="{Binding LocalizedResources.MainPageForecastHeader, Mode=OneWay, Source={StaticResource LocalizedStrings}}">
<phone:LongListSelector x:Name="ForecastItems" Margin="0,0,-12,0" ItemsSource="{Binding ForecastItems}" SelectionChanged="LongListSelector_SelectionChanged">
<!--Elemento Pivot dos-->
<phone:PivotItem Header="{Binding LocalizedResources.MainPageCurrentHeader, Mode=OneWay, Source={StaticResource LocalizedStrings}}">
- <phone:LongListSelector Margin="0,0,-12,0" ItemsSource="{Binding ForecastItems}">
- <phone:LongListSelector.ItemTemplate>
- <DataTemplate>
- </DataTemplate>
- </phone:LongListSelector.ItemTemplate>
- </phone:LongListSelector>
+ <ScrollViewer HorizontalScrollBarVisibility="Auto">
+ </ScrollViewer>
</phone:PivotItem>
</phone:Pivot>
using Microsoft.Phone.Controls;
using System;
+using System.Globalization;
+using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
MessageBoxButton.OK);
return;
}
+
+ App.MainViewModel.LoadData(weatherData);
(Application.Current as WeatherInformation.App).IsNewLocation = false;
- App.MainViewModel.LoadData(weatherData);
+
+ // TODO: Should I try to move this code to MainViewModel. It seems so but how?
+ string country = (string)IsolatedStorageSettings.ApplicationSettings["Country"];
+ string city = (string)IsolatedStorageSettings.ApplicationSettings["City"];
+ string cityCountry = String.Format(CultureInfo.InvariantCulture, "{0}, {1}", city, country);
+ this.TitleTextCityCountry.Title = cityCountry;
}
private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
+using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
{
async public Task<string> GetWeatherDataAsync(string url)
{
+
using (HttpClient client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
{
- return await client.GetStringAsync(url);
+ // TODO: I wish my string to be converted to UTF-8. WTH is doing HttpClient? Dunno :(
+ // How do I control the encoding used by HttpClient?
+
+ // Disable WindowsPhone cache
+ HttpRequestHeaders headers = client.DefaultRequestHeaders;
+ headers.IfModifiedSince = DateTime.UtcNow;
+
+ string jsonData = await client.GetStringAsync(url);
+
+ return jsonData;
}
}
}
}
/// <summary>
+ /// Busca una cadena traducida similar a City, country.
+ /// </summary>
+ public static string MainPageTitle {
+ get {
+ return ResourceManager.GetString("MainPageTitle", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Busca una cadena traducida similar a Location autodetection seems to be disabled in your phone.
/// </summary>
public static string NoticeErrorLocationAutodetection {
-<data name="ApplicationTitle" xml:space="preserve"><value>MI APLICACIÓN</value></data><data name="AppBarButtonText" xml:space="preserve"><value>agregar</value></data><data name="AppBarMenuItemText" xml:space="preserve"><value>Elemento de menú</value></data><data name="SettingsLanguageHeader" xml:space="preserve"><value>Idioma</value><comment>Text in settings page as header</comment></data><data name="SettingsTemperatureUnitsHeader" xml:space="preserve"><value>Unidades de temperatura</value><comment>Text in settings page</comment></data><data name="SettingsLanguageSelectionEnglish" xml:space="preserve"><value>inglés</value><comment>Settings page, select English language</comment></data><data name="SettingsLanguageSelectionSpanish" xml:space="preserve"><value>español</value><comment>Settings page, select Spanish language</comment></data><data name="SettingsTemperatureUnitsSelectionCentigrade" xml:space="preserve"><value>celsius</value><comment>Settings page, select tempereature units centigrade</comment></data><data name="SettingsTemperatureUnitsSelectionFahrenheit" xml:space="preserve"><value>fahrenheit</value><comment>Settings page, select temperature units fahrenheit</comment></data><data name="AskForLocationConsentMessageBoxCaption" xml:space="preserve"><value>Localización</value><comment>Ask for location consent in map window</comment></data><data name="NoticeThereIsNotCurrentLocation" xml:space="preserve"><value>No hay localizaciones almacenadas.</value><comment>Main window, notice message, no available locations</comment></data><data name="NoticeErrorLocationAutodetection" xml:space="preserve"><value>Detección automática de la ubicación parece ser desactivado en el teléfono</value><comment>Map window, notice message, error while location autodetection</comment></data><data name="SettingsForecastDayNumbersHeader" xml:space="preserve"><value>Prevision, numero días</value><comment>Text in settings page as header</comment></data><data name="SettingsForecastDayNumbersSelectionTen" xml:space="preserve"><value>Previsión 10 días</value><comment>Settings page, select forecast day numbers</comment></data><data name="SettingsForecastDayNumbersSelectionFourteen" xml:space="preserve"><value>Previsión 14 días</value><comment>Settings page, select forecast day numbers</comment></data><data name="SettingsForecastDayNumbersSelectionFive" xml:space="preserve"><value>Previsión 5 días</value><comment>Settings page, select forecast day numbers</comment></data><data name="TemperatureUnitsFahrenheitSymbol" xml:space="preserve"><value>º F</value></data><data name="LocationPageSubTitle" xml:space="preserve"><value>Ciudad, país</value><comment>Subtitle in location page</comment></data><data name="LocationPageTitle" xml:space="preserve"><value>Selecciona tu localización</value><comment>Title in location page</comment></data><data name="MainPageForecastHeader" xml:space="preserve"><value>previsión</value><comment>Forecast header in main page</comment></data><data name="SettingsPageHeaderSettings" xml:space="preserve"><value>configuración de</value><comment>Header settings in settings page</comment></data><data name="MainPageCurrentHeader" xml:space="preserve"><value>actual</value><comment>Current header in main page</comment></data><data name="TemperatureUnitsCentigradeSymbol" xml:space="preserve"><value>º C</value></data><data name="AskForLocationConsentMessageBox" xml:space="preserve"><value>Esta aplicación accede a los datos de tu localización. ¿Estás de acuerdo?</value><comment>Ask for location consent in map window</comment></data></root>
\ No newline at end of file
+<data name="ApplicationTitle" xml:space="preserve"><value>MI APLICACIÓN</value></data><data name="AppBarButtonText" xml:space="preserve"><value>agregar</value></data><data name="AppBarMenuItemText" xml:space="preserve"><value>Elemento de menú</value></data><data name="SettingsLanguageHeader" xml:space="preserve"><value>Idioma</value><comment>Text in settings page as header</comment></data><data name="SettingsTemperatureUnitsHeader" xml:space="preserve"><value>Unidades de temperatura</value><comment>Text in settings page</comment></data><data name="SettingsLanguageSelectionEnglish" xml:space="preserve"><value>inglés</value><comment>Settings page, select English language</comment></data><data name="SettingsLanguageSelectionSpanish" xml:space="preserve"><value>español</value><comment>Settings page, select Spanish language</comment></data><data name="SettingsTemperatureUnitsSelectionCentigrade" xml:space="preserve"><value>celsius</value><comment>Settings page, select tempereature units centigrade</comment></data><data name="SettingsTemperatureUnitsSelectionFahrenheit" xml:space="preserve"><value>fahrenheit</value><comment>Settings page, select temperature units fahrenheit</comment></data><data name="AskForLocationConsentMessageBoxCaption" xml:space="preserve"><value>Localización</value><comment>Ask for location consent in map window</comment></data><data name="NoticeThereIsNotCurrentLocation" xml:space="preserve"><value>No hay localizaciones almacenadas.</value><comment>Main window, notice message, no available locations</comment></data><data name="NoticeErrorLocationAutodetection" xml:space="preserve"><value>Detección automática de la ubicación parece ser desactivado en el teléfono</value><comment>Map window, notice message, error while location autodetection</comment></data><data name="SettingsForecastDayNumbersHeader" xml:space="preserve"><value>Prevision, numero días</value><comment>Text in settings page as header</comment></data><data name="SettingsForecastDayNumbersSelectionTen" xml:space="preserve"><value>Previsión 10 días</value><comment>Settings page, select forecast day numbers</comment></data><data name="SettingsForecastDayNumbersSelectionFourteen" xml:space="preserve"><value>Previsión 14 días</value><comment>Settings page, select forecast day numbers</comment></data><data name="SettingsForecastDayNumbersSelectionFive" xml:space="preserve"><value>Previsión 5 días</value><comment>Settings page, select forecast day numbers</comment></data><data name="TemperatureUnitsFahrenheitSymbol" xml:space="preserve"><value>º F</value></data><data name="LocationPageSubTitle" xml:space="preserve"><value>Ciudad, país</value><comment>Subtitle in location page</comment></data><data name="LocationPageTitle" xml:space="preserve"><value>Selecciona tu localización</value><comment>Title in location page</comment></data><data name="MainPageForecastHeader" xml:space="preserve"><value>previsión</value><comment>Forecast header in main page</comment></data><data name="SettingsPageHeaderSettings" xml:space="preserve"><value>configuración de</value><comment>Header settings in settings page</comment></data><data name="MainPageCurrentHeader" xml:space="preserve"><value>actual</value><comment>Current header in main page</comment></data><data name="TemperatureUnitsCentigradeSymbol" xml:space="preserve"><value>º C</value></data><data name="AskForLocationConsentMessageBox" xml:space="preserve"><value>Esta aplicación accede a los datos de tu localización. ¿Estás de acuerdo?</value><comment>Ask for location consent in map window</comment></data><data name="MainPageTitle" xml:space="preserve"><value>Ciudad, país</value><comment>Title in main page</comment></data></root>
\ No newline at end of file
</trans-unit>
<trans-unit id="Resx/ApplicationTitle" translate="yes" xml:space="preserve">
<source>MY APPLICATION</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">MI APLICACIÓN</target>
+ <target state="translated" state-qualifier="mt-suggestion">MI APLICACIÓN</target>
</trans-unit>
<trans-unit id="Resx/AppBarButtonText" translate="yes" xml:space="preserve">
<source>add</source>
</trans-unit>
<trans-unit id="Resx/AppBarMenuItemText" translate="yes" xml:space="preserve">
<source>Menu item</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Elemento de menú</target>
+ <target state="translated" state-qualifier="mt-suggestion">Elemento de menú</target>
</trans-unit>
<trans-unit id="Resx/SettingsLanguageHeader" translate="yes" xml:space="preserve">
<source>Language</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Idioma</target>
+ <target state="translated" state-qualifier="mt-suggestion">Idioma</target>
<note from="MultilingualBuild" annotates="source" priority="2">Text in settings page as header</note>
</trans-unit>
<trans-unit id="Resx/SettingsTemperatureUnitsHeader" translate="yes" xml:space="preserve">
<source>Temperature units</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Unidades de temperatura</target>
+ <target state="translated" state-qualifier="mt-suggestion">Unidades de temperatura</target>
<note from="MultilingualBuild" annotates="source" priority="2">Text in settings page</note>
</trans-unit>
<trans-unit id="Resx/SettingsLanguageSelectionEnglish" translate="yes" xml:space="preserve">
<source>english</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">inglés</target>
+ <target state="translated" state-qualifier="mt-suggestion">inglés</target>
<note from="MultilingualBuild" annotates="source" priority="2">Settings page, select English language</note>
</trans-unit>
<trans-unit id="Resx/SettingsLanguageSelectionSpanish" translate="yes" xml:space="preserve">
</trans-unit>
<trans-unit id="Resx/TemperatureUnitsFahrenheitSymbol" translate="yes" xml:space="preserve">
<source>ºF</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">º F</target>
+ <target state="translated" state-qualifier="mt-suggestion">º F</target>
</trans-unit>
<trans-unit id="Resx/LocationPageSubTitle" translate="yes" xml:space="preserve">
<source>City, country</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">Ciudad, país</target>
+ <target state="translated" state-qualifier="mt-suggestion">Ciudad, país</target>
<note from="MultilingualBuild" annotates="source" priority="2">Subtitle in location page</note>
</trans-unit>
<trans-unit id="Resx/LocationPageTitle" translate="yes" xml:space="preserve">
</trans-unit>
<trans-unit id="Resx/MainPageForecastHeader" translate="yes" xml:space="preserve">
<source>forecast</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">previsión</target>
+ <target state="translated" state-qualifier="mt-suggestion">previsión</target>
<note from="MultilingualBuild" annotates="source" priority="2">Forecast header in main page</note>
</trans-unit>
<trans-unit id="Resx/SettingsPageHeaderSettings" translate="yes" xml:space="preserve">
<target state="needs-review-translation" state-qualifier="mt-suggestion">configuración de</target>
<note from="MultilingualBuild" annotates="source" priority="2">Header settings in settings page</note>
</trans-unit>
+ <trans-unit id="Resx/MainPageTitle" translate="yes" xml:space="preserve">
+ <source>City, country</source>
+ <target state="translated">Ciudad, país</target>
+ <note from="MultilingualBuild" annotates="source" priority="2">Title in main page</note>
+ </trans-unit>
<trans-unit id="Resx/MainPageCurrentHeader" translate="yes" xml:space="preserve">
<source>current</source>
- <target state="needs-review-translation" state-qualifier="mt-suggestion">actual</target>
+ <target state="translated" state-qualifier="mt-suggestion">actual</target>
<note from="MultilingualBuild" annotates="source" priority="2">Current header in main page</note>
</trans-unit>
<trans-unit id="Resx/TemperatureUnitsCentigradeSymbol" translate="yes" xml:space="preserve">
<target state="new">settings</target>
<note from="MultilingualBuild" annotates="source" priority="2">Header settings in settings page</note>
</trans-unit>
+ <trans-unit id="Resx/MainPageTitle" translate="yes" xml:space="preserve">
+ <source>City, country</source>
+ <target state="new">City, country</target>
+ <note from="MultilingualBuild" annotates="source" priority="2">Title in main page</note>
+ </trans-unit>
<trans-unit id="Resx/MainPageCurrentHeader" translate="yes" xml:space="preserve">
<source>current</source>
<target state="new">current</target>
<value>settings</value>
<comment>Header settings in settings page</comment>
</data>
+ <data name="MainPageTitle" xml:space="preserve">
+ <value>City, country</value>
+ <comment>Title in main page</comment>
+ </data>
</root>
\ No newline at end of file
namespace WeatherInformation.ViewModels
{
- public class MainViewModel : INotifyPropertyChanged
+ public class MainViewModel
{
// The key names of _settings
// TODO: reuse settings object instead of using the same code here again...
string symbol = isFahrenheit ? AppResources.TemperatureUnitsFahrenheitSymbol : AppResources.TemperatureUnitsCentigradeSymbol;
var remoteForecastWeatherData = weatherData.RemoteForecastWeatherData;
+ this.ForecastItems.Clear();
foreach (WeatherInformation.Model.ForecastWeatherParser.List item in remoteForecastWeatherData.list)
{
DateTime unixTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
return value;
}
-
- public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChanged(String propertyName)
- {
- PropertyChangedEventHandler handler = PropertyChanged;
- if (null != handler)
- {
- handler(this, new PropertyChangedEventArgs(propertyName));
- }
- }
}
}
\ No newline at end of file