Getting Deep into .net

April 21, 2012

Windows Phone Tasks in Caliburn Micro Way

Filed under: Caliburn Micro,How To,Windows Phone 7 — goldytech @ 2:54 pm
Tags: ,

I had blogged earlier about my windows phone 7 app ,Bollywood ringtones which is now reaching almost 10k downloads. In that post I promised my readers to share my technical findings for my this pet project. I am man of my commitment and here I am to present my first knowledge share to the community. This post shows you how you can use the Caliburn Micro Framework for handling the Windows Phone Tasks. I specifically talk about SaveRingtoneTask but the same funda can be applied to most of the tasks (Launchers and Choosers) like EmailComposeTask,PhoneNumberChooserTask etc.

This blog post assumes that you are already aware of MVVM pattern and has some basic knowledge of Caliburn Micro Framework as this topic deals with some advanced concepts of this framework. I strongly recommend to read the documentation.

Caliburn Micro has much neater way of handling the launchers and choosers in MVVM pattern. The entire heavy lifting is done by IEventAggregator interface which is injected in the constructor of the ViewModel. Let us see the code to make things more clear.

Setting up windows Phone Ringtone in Caliburn Micro
  1. using Caliburn.Micro;
  2. using Microsoft.Phone.Tasks;
  3. using System.Windows;
  4. namespace RingtoneSample {
  5.     public class MainPageViewModel : Screen, IHandle<TaskCompleted<TaskEventArgs>>
  6.     {
  7.         readonly IEventAggregator _eventAggregator;
  8.  
  9.         public MainPageViewModel(IEventAggregator eventAggregator)
  10.         {
  11.             _eventAggregator = eventAggregator;
  12.         }
  13.  
  14.  
  15.        
  16.  
  17.         /// <summary>
  18.         /// The Button Handler
  19.         /// </summary>
  20.         public void SetRingtone()
  21.         {
  22.             _eventAggregator.RequestTask<SaveRingtoneTask>(r=>{
  23.                 r.DisplayName="My Ringtone";
  24.                 r.IsShareable = true;
  25.                 r.Source = new System.Uri(@"appdata:/MyRingtone.wma", System.UriKind.RelativeOrAbsolute);
  26.              });
  27.         }
  28.  
  29.         /// <summary>
  30.         /// IHandle Interface Implementation
  31.         /// </summary>
  32.         /// <param name="message"></param>
  33.         public void Handle(TaskCompleted<TaskEventArgs> message)
  34.         {
  35.             switch (message.Result.TaskResult)
  36.             {
  37.                 case TaskResult.OK:
  38.                     MessageBox.Show("Ringtone is set");
  39.                     break;
  40.                 case TaskResult.Cancel:
  41.                     MessageBox.Show("Save was cancelled");
  42.                     break;
  43.                 case TaskResult.None:
  44.                     MessageBox.Show("No information");
  45.                     break;
  46.             }
  47.         }
  48.  
  49.         protected override void OnActivate()
  50.         {
  51.             _eventAggregator.Subscribe(this); //Register for event
  52.             base.OnActivate();
  53.         }
  54.  
  55.         protected override void OnDeactivate(bool close)
  56.         {
  57.             _eventAggregator.Unsubscribe(this); //Unregister
  58.             base.OnDeactivate(close);
  59.         }
  60.     }
  61. }

I would like to bring few things to your mind here from the above code. These are bare minimum piece of code that you must write to make this work.

  • Your ViewModel class must implement  IHandle interface of Caliburn Micro Framework. If the windows phone task class have the TaskCompleted Event then this interface should be something like, IHandle<TaskCompleted<EventCompletedEventArgs>>. The TaskCompleted belongs to Caliburn Micro whereas the EventCompletedEventArgs should be replaced by the appropriate task completed EventArgs .So in my code for the SaveRingtoneTask has the completed event attached to it my IHandle interface is of the TaskEventArgs. This interface has the Handle method which is synonymous to the EventHandler. You can use this method as your callback method once the event is triggered and it is completed.
  • The Viewmodel class constructor should be injected with IEventAggregator.
  • I am using IEventAggregator RequestTask<SaveRingtoneTask> method and passing all the properties of the SaveRingtoneTask class via lambda expressions. The RequestTask method is similar to the Show method of the task ,if you take the classical approach of handling the Tasks.
  • You need to call the subscribe method when your viewmodel loads as my viewmodel is also inheriting from the Screen class I am using the OnActivate override method to do this job. This is very important step otherwise you may not get the callback event handler.
  • And finally you need to unregister so that the memory clean up happens. The good thing over here is that IEventAggregator creates a WeakReference of the events hence there are no chance of memory leaks. But it is always good practice to unregister all the hook events. I am performing this task by overriding the OnDeactivate method.

 

So you have seen that using ViewModel first approach how innovatively we handled the launchers and choosers in windows phone 7 , keeping the essence of MVVM pattern. You can download the sample code for this post from here.

Cheers and keep rocking.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Rubric Theme Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: