Windows 8 Persisting Conference Buddy JSON To A File

In my most recent posting on Conference Buddy, I showed how to store the data we’ll be accumulating in JSON format.  Today, I’ll show how to write that JSON data to a file for local storage. 

Let’s return to the application; if you need a starting point you can download the source here. CapabilitiesTab

Windows Store applications cannot just access any file anywhere on the local machine.  They must access files only in certain known locations.  You set access permission using the capabilities tab of the appx manifest; in this case checking the Documents Library to allow writing to the Documents folder. 

When you set this, however, you’ll discover that you need to provide additional file-association settings.  Even applications that have access to the Documents Library must specify the supported extensions in advance. This is done through the Declarations tab.

First, in the Available Declarations drop down, select File Type Associations and click Add.  Under Properties select a Display name and a Name and check Open is Safe.  In the Supported Files Type section add a content type (text/plain) and a File type (.json).  Feel free to make up your own extension, as I have done here. 

Save the AppxManifest file.Declarations

Creating the View Model

We will need a ViewModel to act as the DataContext for our View.  Create a new file named MainViewModel and have it implement INotifyPropertyChanged (you’ll need to add a using statement for System.ComponentModel). 

 

public class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged( string p )
{
if ( PropertyChanged != null )
PropertyChanged( this, new PropertyChangedEventArgs( p ) );
}

 

Add a property for the current folder, which will be of type StorageFolder.  Storage folders are used to manipulate both folders and their contents.  You can read more about StorageFolders here.

private StorageFolder _currentFolder;
public StorageFolder CurrentFolder
{
get { return _currentFolder; }
set
{
_currentFolder = value;
NotifyPropertyChanged( "CurrentFolder" );
}
}

We can now add a method to set the CurrentFolder to the DocumentsLibrary using the KnownFolders object. The KnownFolders static class provides access to common locations that contain user content, such as in libraries HomeGroup, etc.  You can learn more about the KnownFolder class here.

public void LoadDocumentsLibrary()
{
CurrentFolder = KnownFolders.DocumentsLibrary;
}

We are now ready to create the key method in our ViewModel: CreateFile.  This method will take a sub-folder name and a file name and will create or open each in turn, returning a StorageFile.  Because the method to create the folder is Asynchronous (as is the method to open a file) we’ll use the await keyword, and thus will mark this method with the async keyword and will return a Task<StorageFile>,

public async Task<StorageFile> CreateFile( string subFolderName, string fileName )
{
if ( CurrentFolder != null )
{
var folder = await CurrentFolder.CreateFolderAsync(
subFolderName, CreationCollisionOption.OpenIfExists );


return await folder.CreateFileAsync(
fileName, CreationCollisionOption.OpenIfExists ).AsTask();
}
else
return null;
}
Notice the CreationCollisionOption.  This is an enumerated constant as shown in the figure.CreationCollision  We’ve chosen OpenIfExists so that we will append to the file as we add new JSON data.
 
This method, CreateFile, is called, indirectly, from the event handler for the Save button in the AppBar.  WE’ll add one line to the event handler, which will in turn call a helper method to write the data,
 
private void Save_Click( object sender, RoutedEventArgs e )
{
Customer cust = new Customer();
cust.Company = Company.Text;
cust.Email = Email.Text;
cust.FirstName = FirstName.Text;
cust.LastName = LastName.Text;
cust.PhoneNumber = PhoneNumber.Text;
cust.Title = Title.Text;

string JSON = JsonConvert.SerializeObject( cust );
Message.Text = JSON;
WriteToFile( JSON );

ClearFields();
}

Notice the new call to WriteToFile, passing in the JSON string.  The Helper method WriteToFile starts by obtaining the names of the subdirectory and the file we’ll be writing to.  These could well be in the application’s settings; for now we’ll just hardwire them,

private async void WriteToFile(string json)
{
string folderName = "ConferenceBuddy";
string fileName = "ConferenceBuddy.json";

Next, we’ll set the local variable contents to the json string that was passed in, and we’ll se the current directory to the Documents directory,

string contents = json;

_vm.LoadDocumentsLibrary();

We are ready to write the file, which we do by calling CreateFile on the VM,

var file = await _vm.CreateFile( folderName, fileName );

We get back an object of type Windows.Storage.StorageFile which we can check to ensure is not null and if not, we can use to write the contents to the file,

if ( file != null )
{
await FileIO.AppendTextAsync( file, contents );
}

If it is null, we’ll display a modal message dialog indicating that we were unable to create the file,

else
{
var dlg = new MessageDialog( "Unable to create file" );
await dlg.ShowAsync();
}

The file will be opened, appended to and closed.  Here is the JSON that’s written to the file:

{“Email”:“Jesse.Liberty@Telerik.com”,“FirstName”:“Jesse”,“LastName”:“Liberty”,“Title”:“XAML Evangelist”,“Company”:“Telerik”,“PhoneNumber”:“617-848-9684”}
{“Email”:“Michael.Crump@Telerik.com”,“FirstName”:“Michael”,“LastName”:“Crump”,“Title”:“XAML Evangelist”,“Company”:“Telerik”,“PhoneNumber”:“Unknown”}
{“Email”:“StaceyLiberty@foo.com”,“FirstName”:“Stacey”,“LastName”:“Liberty”,“Title”:“QA Specialist”,“Company”:“Liberty Associates, Inc.”,“PhoneNumber”:“617-848-9684”}

Download the Source Code Here.

In this blog post we saw how to add the data to a file. In a future post we’ll look at how we might store this data to the cloud.

Download the code

Win8_Download (2)

About the author

Jesse Liberty

Jesse Liberty

Jesse Liberty is a Technical Evangelist for Telerik and has three decades of experience writing and delivering software projects. He is the author of 2 dozen books and has been a Distinguished Software Engineer for AT&T and a VP for Information Services for Citibank and a Software Architect for PBS. You can read more on his personal blog and his Telerik blog or follow him on twitter

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Essentials. Bookmark the permalink.

3 Responses to Windows 8 Persisting Conference Buddy JSON To A File

Comments are closed.