Introduction

Welcome back again to the series on “Conference Buddy” an app being written in Windows Phone 8 as well as Windows 8, in this blog post we will specifically target Windows Phone 8. Let’s take a look at what we have covered so far and what is coming up:

  • Speech Recognition – Is a powerful way for your end-users to navigate and interact with your app using their voice.
  • MultiResolutionImage –Makes it easy for Windows Phone 8 developers to support images in the various screen resolutions supported in Windows Phone 8.
  • DataForm (Part 1) – Was discussed earlier and this new component allows you to automatically generate the UI for your input forms, with support for validation and custom layouts.
  • DataForm (Part 2) – In this blog post, we will expand on what we learned earlier about the DataForm and show you how to persist data to isolated storage using our control with the very popular Json.net.

Initial Setup

I’m going to assume your development environment is setup and RadControls for Windows Phone 8 is installed. If you don’t have them yet then you can be downloaded from this link. This will also be a good time to go ahead and downloaded the completed source code for the part which can be found here.

Data Form Control in RadControls for Windows Phone 8.

Before we get started, let’s look at our prototype app design for the contact page in Figure 1 (click to enlarge it).

image

Figure 1: Contact Collect Detail Screen Design

Its UI was automatically generated using only a standard class and our DataForm. The contact details on the first page consist of: E-mail, First Name, Last Name, Title, Company and Phone Number and those are the fields that we will focus on for now.

First things First – About JSON

In order for our app to communicate with our backend server, the decision was made to use JSON to store the contact information. JSON stands for JavaScript Object Notation. It was chosen as it is an open standard designed for data interchange that is human-readable. It can represent object such as data structures and arrays that our backend will consume very easily.

Thankfully, since JSON has been around for so long, several open source projects support it in .NET (including Windows 8 and Windows Phone 8). So the rest of this article will describe how I used Json.net with our DataForm control to persist data to Isolated Storage. This will make sure our apps precious data is still protected in case our internet connection fails.

Let’s Get Started

The first thing that we are going to want to do is open our project and select “Manage NuGet Packages” as shown in Figure 2.

1

Now search for “json.net” and click “Install”. The newly added file can be seen under References in your project.

Taking a look at our MainPage.xaml

Our UI is simply going to contain the DataForm control and that is it, but we will need to wrap it in a ScrollViewer. Our users will be able to simply scroll down the page by doing this and able to access all data fields.

Let’s go ahead now and replace the existing Grid with the following code snippet.

   1: <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
   2: <ScrollViewer>
   3: <telerikInput:RadDataForm
   4: EditorCreationMode="CreateByDefault"
   5: DataFieldCreated="radDataForm_DataFieldCreated_1"
   6: x:Name="radDataForm"/>
   7: </ScrollViewer>
   8: </Grid>

We will also need to add an application bar that allows the user to Save the data or Delete the data.

  • If the user saves the data, then the contents in the fields will be written to isolated storage after they have been serialized.
  • If the user deletes the data, then the contents in the fields will become blank while the file living in isolated storage will be removed.

We can add an application bar very easily with the following code snippet:

   1: <phone:PhoneApplicationPage.ApplicationBar>
   2: <shell:ApplicationBar IsVisible="True">
   3: <shell:ApplicationBarIconButton IconUri="/Assets/AppBar/save.png" Click="Save_Click" Text="Save"/>
   4: <shell:ApplicationBarIconButton IconUri="/Assets/AppBar/delete.png" Click="Delete_Click" Text="Delete"/>
   5: </shell:ApplicationBar>
   6: </phone:PhoneApplicationPage.ApplicationBar>
Note: If you don’t have the images, then simply download my project or add them through Blend. 

Switching back to our MainPage.xaml.cs File.

The only changes that I’m going to make it here from the first part is adding in the click event handlers for the “Save” and “Delete” buttons.

   1: public void Save_Click(object sender, EventArgs e)
   2: {
   3: //Place holder to check if InputIsValid before calling Commit method().
   4: //if (radDataForm.IsInputValid == true)
   5: //{
   6: //Call Commit
   7:     radDataForm.Commit();
   8: //}
   9: //Setup Isolated Storage
  10:     IsolatedStorageFile myIsolatedStorage=IsolatedStorageFile.GetUserStoreForApplication();
  11:  
  12: //Create New File and we could append.
  13: using (StreamWriter writeFile=new StreamWriter(new IsolatedStorageFileStream("mycontacts.txt", FileMode.Create, FileAccess.Write, myIsolatedStorage)))
  14:     {
  15: string output=JsonConvert.SerializeObject(_contact);
  16:         writeFile.WriteLine(output);
  17:         writeFile.Close();
  18:         MessageBox.Show(output);
  19:     }
  20: }
  21:  
  22: public void Delete_Click(object sender, EventArgs e)
  23: {
  24: //Set our class to null 
  25:     Contact ct=new Contact();
  26:     radDataForm.Commit();  
  27:     radDataForm.CurrentItem=ct;
  28:  
  29: //Removes the file from Isolated Storage
  30:     IsolatedStorageFile storage=IsolatedStorageFile.GetUserStoreForApplication();
  31:     storage.DeleteFile("mycontacts.txt");
  32: }

Starting with the save button, we call the Commit method on our DataForm, then setup IsolatedStorage to save our file. The only thing to note here is that we are using Json.NET to serialize our contact class that we are using with our DataForm. Finally, I display a MessageBox where you can see the output.

Below is a sample of what this data may look like:

{"Email":"michael.crump@telerik.com","FirstName":"Michael","LastName":"Crump","Title":"Mr","Company":"Telerik","PhoneNumber":"111-111-1111"}

A quick note if you are using validation logic: It is good to check whether there are validation errors before calling the Commit method on RadDataForm. This can be accomplished by using the RadDataForm.IsInputValid property. This will ensure the data being saved is accurate and valid data. More information regarding this can be found here.

For the delete button, it is much easier – we instantiate a new class, commit it and then set it to our CurrentItem. Finally we remove the file in IsolatedStorage.

Now that that is complete, we can see our UI populated with data in Figure 3.

2

Figure 3: Contact Collector populated with data ready to serialize.

Go ahead and hit the save button and you will see every item serialized except the Title which is an Enum. The Json.NET documentation states that if you want to deserialize enumerations to their string representation is to tell the framework to apply its StringEnumConverter is to annotate the properties question like this example in our contact class:

   1: [JsonConverter(typeof(StringEnumConverter))]
   2: public UserTitle Title
   3: {
   4:     get
   5:     {
   6: return title;
   7:     }
   8:     set
   9:     {
  10:         title = value;
  11:     }
  12: }

Conclusion

In this article, we took a second look at DataForm and how a open-source project called Json.NET can be used with it. This really adds the icing to the cake as complicated data forms and serializing objects can be accomplished with just a few lines of code. You may go ahead and grab the source code to this project to take a look at it for yourself. If you have any questions, then just let me know in the comments below. Don’t forget you can download the source code here.

PS: The Nokia premium developer program allows you to get RadControls for Windows Phone for free and have a lot of resources to help you get started.

-Michael Crump (@mbcrump)

image


MichaelCrump
About the Author

Michael Crump

is a Microsoft MVP, Pluralsight and MSDN author as well as an international speaker. He works at Telerik with a focus on everything mobile.  You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

Related Posts

Comments