How to retain data even after app is closed in windows phone? - windows-phone-7

In my app i'm having two variables, which i want to retain even after my application is closed.
Which would be the right way to accompolish it?

You can store the values in an IsolatedStorage. There is a very nice article on MSDN regarding the persistance of information on Windows Phone. You can read it here http://msdn.microsoft.com/en-us/library/gg680266(v=pandp.11).aspx
The example shown by Microsoft looks something like this:
private const string CAR_PHOTO_FILE_NAME = "CarPhoto.jpg";
private const string CAR_KEY = "FuelTracker.Car";
private static readonly IsolatedStorageSettings appSettings =
IsolatedStorageSettings.ApplicationSettings;
public static void SaveCar(Action errorCallback)
{
try
{
appSettings[CAR_KEY] = Car;
appSettings.Save();
DeleteTempCarPhoto();
SaveCarPhoto(CAR_PHOTO_FILE_NAME, Car.Picture, errorCallback);
NotifyCarUpdated();
}
catch (IsolatedStorageException)
{
errorCallback();
}
}
The process of reading the information is very much the same. Go through the article and adopt it for your own needs.

There are a number of different storages available on Windows Phone 7.x as well as Windows Phone 8
If these two values of yours are settings, you want to preserve, I recommend you to use the IsolatedStorageSettings. This is a simple key / value store to save and load variables after restart your app. See the the following sample of MSDN (How to create settings)
See a list of other API's and samples on when and how to use it here (Data for Windows Phone on MSDN)

Related

How to persist Serilog.Sinks.Xamarin logs

Sinks.Xamarin on a xamarin forms app, so far it works great, but I'm looking forward to persist the logs so I can send them to the server later.
this are the solutions I have found so far
1) sqlite
Serilog.Sinks.SQLite only write once in db in Xamarin Form(Android)
2)Json file
Serilog.Extensions.Logging.File
so far I like more the second option but that nuget is for asp.net mvc, is there any option for xamarin forms that persist the log in a file?
This looks like a case of data persistence.
Data can be persisted using Application.Current.Properties.
The Properties dictionary uses a string key and stores an object value.
For instance, you could put the following line in OnDisappearing() in your cs.
Application.Current.Properties ["store"] = someClass.ID;
In the OnStart() or OnResume() methods:
if (Application.Current.Properties.ContainsKey("id"))
{
var id = Application.Current.Properties ["id"] as int;
// do something with id
}
Here's some more helpful documentation of this.

Shared Preferences in Xamarin.forms

I have tried to save login value as true if user has logged in once by using
Application.Current.Properties["isLoggedIn"] = "true";
but its not working. If i remove my app from background it again shows the login page but if user is logged in it should show the next page.
When using 'Application Properties Dictionary' you have to keep in mind few things:
According to the official documentation: 'The Properties dictionary is saved to the device automatically'. However, if you want to ensure persistence you have to explicitly call SavePropertiesAsync().
The Properties dictionary can only serialize primitive types for storage. Attempting to store other types such as List can fail silently.
Read the official documentation carefully and pay attention to details. Here is a code example:
private async Task SaveApplicationProperty<T>(string key, T value)
{
Xamarin.Forms.Application.Current.Properties[key] = value;
await Xamarin.Forms.Application.Current.SavePropertiesAsync();
}
private T LoadApplicationProperty<T>(string key)
{
return (T) Xamarin.Forms.Application.Current.Properties[key];
}
// To save your property
await SaveApplicationProperty("isLoggedIn", true);
// To load your property
bool isLoggedIn = LoadApplicationProperty<bool>("isLoggedIn");
Base on your needs you may consider Local Database or Settings Plugin instead. However for saving just a few primitive values Application Properties approach should be good enough.
Xamarin Forms now includes Xamarin Forms Essentials and contains the Preferences component that you need. Check out the official website and try it.
https://learn.microsoft.com/en-us/xamarin/essentials/preferences?tabs=ios
This is an example of how to manage preferences with Essentials.
To save a value for a given key in preferences:
Preferences.Set("my_key", "my_value");
To retrieve a value from preferences or a default if not set:
var myValue = Preferences.Get("my_key", "default_value");
To remove the key from preferences:
Preferences.Remove("my_key");
To remove all preferences:
Preferences.Clear();
Supported Data Types:
bool
double
int
float
long
string
DateTime
First we set the key and value using below code
Xamarin.Essentials.Preferences.Set("UserId", content.userId);
We can get the above value in any page of project using below code
Xamarin.Essentials.Preferences.Get("UserId", "");

How to obtain the country code in a windows phone7 application?

My app use phone number as user ID, It will be good to detect the home PLMN of the SIM card and convert it to the country code(like +1, +33, etc.), then you don't have input the digits.
I guess it could be done with RIL in windows mobile, but in a windows phone 7 it seems there is no such kind of APIs.
Another choice is to get the CultureInfo, but some times the CultureInfo may not match with the SIM you are using, for example you take your phone abroad, usually you keep the phone region settings as your home land but you may use a local SIM card.
There does not appear to be any API action that allows you to look at the specific cultures embedded into a SIM for WP7. However, if you the general culture option is still appropriate you could do something like this:
string countryCode = CultureInfo.CurrentCulture.Name;
try {
RegionInfo reg = new RegionInfo(countryCode);
string name = reg.Name;
string displayname = reg.DisplayName;
string ISORegion = reg.TwoLetterISORegionName;
string currency = reg.CurrencySymbol;
string eng = reg.EnglishName;
string native = reg.NativeName;
}
catch (ArgumentException argEx) {
// The country code was not valid
}
If your application needs to be based on the current location please consider using the GPS task. Details for getting GPS data can be reviewed here.
Also converting the GPS data to a specifc country can be completed by geocode reversing as shown here.

how to save and load a object in a windows phone 7 app?

is it possible in a WP7 app to save some objects which i create and then load it when the app is started again?
You'll want to look to store persistent items into IsolatedStorage. You can see an overview and an example of how to use IsolatedStorage here. There are also a range of examples on this site, showing how to save different types of objects.
Here's an example storing a string, but you should be able to store any type of object this way.
Add IsolatedStorage to your references:
using System.IO.IsolatedStorage;
In your class:
private string myString;
In the Loaded event for your page:
try
{
myString = (string)IsolatedStorageSettings.ApplicationSettings["myString"];
}
catch
{
IsolatedStorageSettings.ApplicationSettings.Add("myString", "this value is a string");
}
and later, when you want to save:
IsolatedStorageSettings.ApplicationSettings["myString"] = myString;
try after
the example code above to add this.
IsolatedStorageSettings.ApplicationSettings.save

how to manage the data in an xml file in wp7?

I have written a simple wp7 application. i am using wcf service to interact with the database. Now i want to store a part of user's info in the mobile also. this info needs to be accessible across the wp7 app.
I found multiple ways to do this like : isolated storage, resource files or static data in the app.xaml
Which one would be more suitable? as i may wish to edit the data in future...i may not opt for packaged files as they are read-only. also do not wish to lose data by storing in isolated storage.
Please suggest the most suitable option for me
Thanks in advance
Bindu
It sounds like you want to store downloaded data between uses of the app. In this case Isolated Storage is probably your best bet. It will remain in the phone's non-volatile memory and you will not lose it.
Details here
Resource files and static data in the app.xaml won't work for you since you want to be able to change these items at a later date since these will be read only.
I don't know what you are referring to when you say "lose data" by storing in IsolatedStorage. This is your best bet and is actually really easy to do. Here is an example of saving a simple boolean:
private void SaveSettings()
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
settings["VibrationOn"] = VibrationOn;
}
Then to load it later:
private void LoadSettings()
{
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
bool vo;
if (settings.TryGetValue<bool>("VibrationOn", out vo))
VibrationOn = vo;
else
VibrationOn = true;
}
You would call your LoadSettings() method in the Application_Launching and Application_Activated events and then your SaveSettings() in the Application_Deactivated and Application_Closing events within your App.xaml.cs.
You can also serialize objects or write whole files.

Resources