Friday, November 28, 2014

Data storage options in windows phone 8.1


Where can I store my app data in windows phone 8.1?

  1. Local storage(folders and settings): save your data here which is local to your app(** no data limits)
  2. Roaming Storage (folder and settings): if your want to save some data which you want to access across devices in which your app is installed , then your should be saving your data in Roaming storage (** have a data limit of 100kb).
  3. Temp Storage(folder ): if your have any data that needs to be saved for  only limited amount of time  and does not really affect the app if lost then save your data in temp folder
  4. PasswordVault: if you want to same some user credentials data securely then you will save  then in the PasswordVault(** this data roams across devices).

  How do I save and retrieve values from  local settings ?

   Below is the code snippet on to how  you save a load  from local settings 

//Get the LocalSettings object 
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;          
 //Check if the key already exists 
 if (localSettings.Values.ContainsKey("MySetting"))
 {
    //overwrite the value if you need to 
 }
else
 {
    localSettings.Values["MySetting"] = "Green Theme";
 }
 //Read the value ** will return null objet if there is no key as "MySetting"
Object value = localSettings.Values["MySetting"];
//Delete the "MySetting" entry if exists 
localSettings.Values.Remove("MySetting");           

How do I save and retrieve values from local folders?

few point worth  remembering
  • you can access your files through uri's (ms-appdata:///local/,ms-appdata:///roaming/,ms-appdata:///temp/)
  • you can also access the files though the api(Windows.Storage.ApplicationData.Current.LocalFolder,RoamingFolder,TempFolder).
  • you can write and read from  a file either by using FileIO or by using the streams
Below Code Snippet  to  write data to a file  and read data from a file with FileIO
     public async void writeTextToLocalStorageFile(string filename, string text)
        {
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            /* you can get access to the file as shown below as well
               Uri  theFileUri = new Uri(string.Format("ms-appdata:///local/{0}",filename));
               StorageFile fileToWrite = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(theFileUri);
               await FileIO.WriteTextAsync(fileToWrite, text);
             * */
       
            //Or you can get access to the file directly 
            //you use the CreationCollisionOption to suit your needs 
            
            StorageFile file = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
            await FileIO.WriteTextAsync(file, text);
        }
  public  async Task readTextFromLocalStorage(string filename)
        {
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
             /* you can get access to the file as shown below as well
               Uri  theFileUri = new Uri(string.Format("ms-appdata:///local/{0}",filename));
               var folder = Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(theFileUri);
             */
            StorageFile file = await localFolder.GetFileAsync(filename);
            string result = await FileIO.ReadTextAsync(file);
            return result;
        }

Working with Roaming Settings and Roaming Folders?

The concept of reading  and writing to the  roaming settings and folders is exactly same as that of  local settings and folders .
But there is two important points that you need to remember while you are working with roaming settings .
  1. Both your apps needs to have same name (say if are developing a app for big windows and windows phone  then both these app needs to have the same name).
  2. You need to make the package store association for both your windows phone and big windows app , its very simple to do it all you need to do is right click on the project (windows and windows phone store) navigate to the stores context menu option and then click on Associate app with store  menu
** if your apps don't satisfy above two conditions then your roaming data does not work.

How to save Objects to File and read them back ?

In the nutshell we can save the public properties and fields of objects into a file in json/xml format through  serialization , and we can  load the json back as objects  in the memory  through deserialization . 
   public class Employee 
    {
        public string Name { get; set; }

        public string Designation { get; set; }

        public int ID { get; set; }
    }

    public class Employees 
    {

        public List employeeList = new List();


        public Employees()
        {
            employeeList.Add(new Employee() { Name = "testname1", ID = 1, Designation = "testDesignation1" });
            employeeList.Add(new Employee() { Name = "testname2", ID = 2, Designation = "testDesignation2" });
            employeeList.Add(new Employee() { Name = "testname3", ID = 3, Designation = "testDesignation3" });
            employeeList.Add(new Employee() { Name = "testname4", ID = 4, Designation = "testDesignation4" });
        }
    }

 // Code to Serialize to json 
       public async void writeEmployeesJsonToLocalStorage(string filename)
        {

            Employees empCollection = new Employees();
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
          
            StorageFile file = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);


            using (Stream stream = await file.OpenStreamForWriteAsync())
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Employees));

                jsonSerializer.WriteObject(stream, empCollection);
            } ;

        }

// Code to deSerialize from json
 public async void ReadEmployeesJsonFromLocalStorage(string filename)
        {

            Employees empCollection;
            var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

            StorageFile file = await localFolder.GetFileAsync(filename);



            using (Stream stream = await file.OpenStreamForReadAsync())
            {
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Employees));

                empCollection = jsonSerializer.ReadObject(stream) as Employees;
            };

        }

Working with credential locker

CredentialLocker lets to you save secure data like username and password on the device and also lets these data roam across device .

Below is the  code .snippet to save a retrieve  the data from the password vault.

 // Store credentials in the CredentialLocker
 private void SaveMyCred(string userName, string password) 
  {
   PasswordVault myVault = new PasswordVault();
   PasswordCredential userCred = new PasswordCredential("MyResource", userName, password);
   myVault.Add(userCred);
   }

  private void GetCred() 
   {
      PasswordVault myVault = new PasswordVault();
      List allCred;
      PasswordCredential myCred;
      try
       {
         allCred = myVault.FindAllByResource("MyResource") as List;
          myCred =allCred.FirstOrDefault();
        }
      catch (Exception)
        {
          // Handle any exception
        }

   }

Assess user data

you can get access to photos in the Picture library (camera roll ,saved pictures),Music library and video library . 
** first thing you need to make sure when working with these folders is that you have to check the capabilities  in the app manifest file .

Below is the code to get access to Know Folders
           //Gives access to PicturesLibrary
           var picturesFolders =  Windows.Storage.KnownFolders.PicturesLibrary;
           //Gives access to VideosLibrary
           var videoFolders = Windows.Storage.KnownFolders.VideosLibrary;
           //Gives access to MusicLibrary
           var musicFolders = Windows.Storage.KnownFolders.MusicLibrary;

Once you get access to these folders, you can

  • Create your own  Sub folders 
  • Loop though all the sub folders and access the files 
  • get meta data of the folders and files 
  • read and write files with FileIO and stream 
** in the capabilities if you have checked Removable storage then the files in  PicturesLibrary,VideosLibrary and MusicLibrary of the SD Card is also  accessible with the same above API's


Working with SD Card .

you can write to read data from SD card .

** as usual don't forget to check the Removable storage capability in app manifest 

same apis will work if  you want to access the picture library , music library and video library  from SD Card as discussed in the previous section .

if you want to access  files in other folders then you do associate the file type that you need to access.

How to i do the fie association ?

In the Package.appxmanifest file got the Declaration and Select the File Type Associations as shown below .




















Once the file type associations are done you can access the files of that type from the app

Below is the sample code snippets lets your access a text file in the sd card
** TO DO

0 comments:

Post a Comment