340 likes | 439 Views
Persisting data in isolated storage. Pongsakorn Poosankam. Microsoft Innovation Center Manager. Microsoft (Thailand) Limited. Topics. Windows Phone applications and isolated storage Using isolated storage to store files Storing name/value pairs
E N D
Persisting data in isolated storage Pongsakorn Poosankam Microsoft Innovation Center Manager Microsoft (Thailand) Limited
Topics • Windows Phone applications and isolated storage • Using isolated storage to store files • Storing name/value pairs • An introduction to the Dictionary collection class • Storing settings information in Isolated Storage
Isolated Storage • This storage is called isolated because each application on the phone has its own area • One application cannot access the storage of another • The data is stored in the mass storage of the phone • A program can store very large amounts of data in isolated storage
Jotpad program • This is the first version of the jotpad program • It displays a textbox for the user to enter text • It also has Load and Save buttons that can be used to load and save the jotted text to isolated storage
The Save button behaviour • When the user presses the Save button the event hander calls a method to save the text from the TextBox into a file • The saveText method is also given the name of the file to save the text in privatevoidsaveButton_Click(object sender, RoutedEventArgs e){saveText("jot.txt", jotTextBox.Text);}
The saveText method privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} • The method can be used to save data in a file in isolated storage
Using IsolatedStorage privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} • The method starts by getting a reference to the isolated storage for this application
Creating a file privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} • This reference is then used to create a stream connected to the newly created file
Writing to the file privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} • The method can now write data to the file and close it
The Load button behaviour privatevoidloadButton_Click(object sender, RoutedEventArgs e){string text;if ( loadText("jot.txt", out text ) ) {jotTextBox.Text = text; }else{jotTextBox.Text = "Type your jottings here...."; }} • The load behaviour is more complex because a the file might not be available • The load method displays a default message if loadText fails
Loading from Isolated storage try{using (IsolatedStorageFileStreamrawStream =isf.OpenFile(filename, System.IO.FileMode.Open)) {StreamReader reader = newStreamReader(rawStream); result = reader.ReadToEnd();reader.Close();}}catch {returnfalse;} • This code reads a file from isolated storage • It uses standard file input/output methods
The Isolated Storage File Store • Your applications can create many files in isolated storage • They can also build up a directory hierarchy within the storage • You can perform stream based input/output with files in the isolated storage
Demo Demo 1: Jotpad Demo
Using Settings Isolated storage • Creating files in isolated storage is useful, but often a program only wants to store name/value pairs • Examples of this: • Username • Home directory • Colour and display preferences • The Isolated storage in Windows Phone also provides setting storage
Settings and Dictionaries • The settings storage works like a Dictionary collection • A Dictionary holds a collection of a particular type which is indexed by key values of another type • Programs can look up items based on the value of the key
A Dictionary example classPerson{publicstring Name;publicstring Address;publicstring Phone;} • The Person class holds information about a given person in our system • The Person class could contain many more data properties than the ones above • We need to store and find Person items
A Dictionary example Dictionary<string, Person> Personnel = newDictionary<string, Person>(); • This creates a Dictionary called Personnel • This holds a collection of Person records that are indexed on a string • Generics are used to give the types of the index item and the data stored • We could use the name of the person as the index item
Storing in the Dictionary Person p1 = newPerson { Name = "Rob", Address = "His House", Phone = "1234" };Personnel.Add(p1.Name, p1); • This creates a Person value and adds it to the dictionary • The name value is used as the key • The dictionary will not allow duplicate keys
Reading from a Dictionary PersonfindPerson = Personnel["Rob"]; • We can use a string indexer to locate items in the dictionary • The Personnel dictionary will return Person values • If the item cannot be found this statement will throw an exception
Checking for Items if (Personnel.ContainsKey("Jim")){// If we get here the dictionary // contains Jim} • A Dictionary also provides a method that can be used to test for the existence of particular keys • Your code should do this rather than throw exceptions
Dictionaries in action • Dictionaries are very useful for storing collections that you want to index on a particular key value • The storing and searching is managed very efficiently • A system can contain multiple dictionaries to index on different key items • A program can also iterate through the dictionary contents
Dictionaries and Isolated Storage • The IsolatedStorageSettings class provides a Dictionary based model for storing and retrieving setting information • It stores any object indexed on a string key • This makes it very easy to store settings objects • Your application must call the “Save” method on the settings object to complete a save
Saving using settings privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} • This Save method stores a string of text with the supplied name
Getting the isolated store privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} • This statement gets a reference to the settings object
Removing an old version privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} • This removes an existing item with this name • Removing does not fail if the item is not there
Saving the data privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} • This adds the item and then saves the settings back to the isolated store
Saving items • You can save objects other than strings • Each object must have a unique name • Your program must call the Save method to persist the settings information when it has been added to the settings object
Reading from settings storage • Reading is the reverse of writing • Your program must provide the key of the item it wants to load • Note that the saved item will be returned in the form of an object reference which your program must cast to the required type • The settings storage does not provide a ContainsKey method
Loading from the setting storage privateboolloadText(string filename, outstring result) {IsolatedStorageSettingsisolatedStore = IsolatedStorageSettings.ApplicationSettings;result = "";try {result = (string)isolatedStore[filename];}catch {returnfalse;}returntrue;}
Managing the loading result = "";try {result = (string) isolatedStore[filename];}catch {returnfalse;} • Because it is not possible to check if a setting exists the load method must instead catch the exception that is thrown if a key is not found • The loatText method returns false to indicate that the load failed
Isolated Storage • A program can create and use as many files as the application requires • It is also possible to create folders within isolated storage so an application can organise data as required • The data will be persisted when the application is not running • If the application is removed from the phone all its isolated storage is deleted
Demo Demo 2: Settings Jotpad
Summary • Windows Phone provides “local” storage for applications • Data stored is local to an application and not shared with or visible to others • There is a local filesystem and a dictionary based setting store which can be used for name/value pairs