This is a continuous example from Part I tutorials. If you want to skip Part 1, you could download the project here. And if you want source code and code snippet for the whole project, you could download it here.
– How to pass data between pages – isolated storage
– How to use CameraTask in your application
In Part 2, I will introduce two things: Isolated storage and Camera Task.
Before started, I want to introduce why. If you want to pass data from one page to the other, you have to store data somewhere since its stateless between pages. And you could use Isolated Storage. What’s Isolated Storage? Very simple. It is just storage inside your phone but “Isolated” to only your phone. If you lost your phone, you lost data inside your isolated storage in your phone.
1.You could open app.xaml and add in the following code. App.xaml is a file running before running Mainpage.xaml.
[cc lang=’c’]
//IsolatedStroage Manager
public static class IsolatedStorageCacheManager
{
//Store information into file
public static void Store(string filename, T obj)
{
//create filestream for writing into Isolated Stroage
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = appStore.OpenFile(filename, FileMode.Create))
{
//Use DataContractSerializer to serialize data and write to the filestream
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(fileStream, obj);
}
}
//Method for retriving object from file in Isolated Stroage
public static T Retrieve(string filename)
{
T obj = default(T);
IsolatedStorageFile appStore = IsolatedStorageFile.GetUserStoreForApplication();
//Open file if filename exists in Isolated Stroage
if (appStore.FileExists(filename))
{
using (IsolatedStorageFileStream fileStream = appStore.OpenFile(filename, FileMode.Open))
{
//Use Serializer to read filestream and retrieve object
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
obj = (T)serializer.ReadObject(fileStream);
}
}
return obj;
}
}
[/cc]
2. Methods in App.xaml could be used directly by other file in the project. You could just type “App.” to access all the method inside. We need to serialize data object into a file format that could be stored. There are mainly two ways to do that. Firstly, you could use Build-in DataContractSerialize. It will serialize object based on [DataContract] and [DataMember] these two attributes. The second method is using Linq to XML API from System.XML.Linq namespace.
High level speaking. This IsolatedStroageCacheManager has two methods. One is to store your object into file on Isolated storage. And the other method is to retrieve object from file in Isolated Stroage, with a particular filename you used to save the object.
3. We need to add a reference into the project. Right click on References folder in your project file explorer. Choose System.Xml.Serialization.
4. Add another namespaces in App.xaml to resolve.
[cc lang=’c’]
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization;
[/cc]
5. Add we come back to Mainpage.xaml to implement the following functionality: we will click save button and save whatever customer ordered into isolated storage and retrieve it out from next page (OrderConfirm.xaml).
6. Add this button in MainPage.xaml:
[cc lang=’c’]
[/cc]
7. Go to MainPage.xaml.cs and add SaveBtn_Click this method:
[cc lang=’c’]
private void SaveBtn_Click(object sender, RoutedEventArgs e)
{
//Save data into order.xml in Isolatedstroage
App.IsolatedStorageCacheManager>.Store(“order.xml”, orderlist);
//Navigate to next page
NavigationService.Navigate(new Uri(“/OrderConfirm.xaml”, UriKind.Relative));
}
[/cc]
8. Click on Project file explorer and add a new Phone page called OrderConfirm.xaml. Plug in the following code: (Replace the default Content Panel)
[cc lang=’c’]
[/cc]
9. In OrderConfirm.xaml.cs, put in the following code as a private variable which will load the order list. We will bind this list to the view as well.
[cc lang=’c’]
private ObservableCollection OrderConfirmList;
[/cc]
10. Add the following code in the in OrderConfirm.xaml.cs:
[cc lang=’c’]
//Retrieve order user places from IsolatedStroage
OrderConfirmList = App.IsolatedStorageCacheManager>.Retrieve(“order.xml”);
//DataBind OrderList to OrderItems
OrderList.DataContext = new OrderViewModel(OrderConfirmList);
[/cc]
11. We need to change OrderViewModel.cs as well. Open the file and put in a new method inside:
[cc lang=’c’]
public ObservableCollection OrderItems { get; private set; }
//Initiate OrderItems to the final order user has chosen
public OrderViewModel(ObservableCollection FinalOrder)
{
OrderItems = FinalOrder;
}
[/cc]
12. we need to change OrderModel as well:
[cc lang=’c’]
[DataContract]public class OrderModel
{
[DataMember]public String name { get; set; }
[DataMember]public int quantity { get; set; }
public OrderModel(String name, int quantity)
{
this.name = name;
this.quantity = quantity;
}
}
[/cc]
Here, we let DataContractSerialize understand OrderModel this object is the [DataContract] and name and quantity are [DataMember].
13. From Step 7, what we did is to save object into a file named “order.xml” into isolated storage and in Step 10, we retrieved the object from Isolated storage with “order.xml”. OrderList.DataContext is another way of binding from cs file instead of Xaml file. And what it did is the same, to initialize an instance in OrderViewModel as OrderModel and bind it to XAML file in front.
14. It may be a bit confusing from the previous steps. What I suggest is to put several breakpoints and run the application in debug mode, you will get the flow very easily.
15. Now compile the file and you will see once you click on Save button, your order showed on the confirmation page.
16. Now we will start the second task: utilizing cameratask method in the SDK, take a photo and save it into BitmapImage.
17. Double click on Take a photo button in OrderConfirm.xaml, it will lead you to OrderConfirm.xaml.cs and plug in the following code:
[cc lang=’c’]
// The Completed event handler. In this example, a new BitmapImage is created and
// the source is set to the result stream from the CameraCaptureTask
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
image1.Source = bmp;
}
}
private void PhotoBtn_Click(object sender, RoutedEventArgs e)
{
try
{
cameraCaptureTask.Show();
}
catch (System.InvalidOperationException ex)
{
// Catch the exception, but no handling is necessary.
}
}
[/cc]
18. Replace your OrderConfirm constructor with the code below:
[cc lang=’c’]
CameraCaptureTask cameraCaptureTask;
public OrderConfirm()
{
InitializeComponent();
//Retrieve order user places from IsolatedStroage
OrderConfirmList = App.IsolatedStorageCacheManager>.Retrieve(“order.xml”);
//DataBind OrderList to OrderItems
OrderList.DataContext = new OrderViewModel(OrderConfirmList);
// Initialize the CameraCaptureTask and assign the Completed handler in the page constructor.
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler
(cameraCaptureTask_Completed);
}
[/cc]
19. Add the following namespace:
[cc lang=’c’]
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
[/cc]
20. Let me explain the follow. Firstly, you need to initialize a cameraCaptureTask instance in the constructor when this page loaded. And hook up this task with an event handler. In this event handler (cameraCaptureTask_Completed), we save the image taken into a BitmapImage. There is no further action for this BitmapImage in this sample. But you could consider to save image somewhere or upload image to external source.
21. There are many choosers and launchers Microsoft offers in Phone SDK. They are very useful for mobile development, which make phone developers life much easier.