(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

WP7 Stock Quote Demo Part 5: Push Phone side

(0 votes)
John McFetridge
>
John McFetridge
Joined Feb 12, 2010
Articles:   5
Comments:   0
More Articles
4 comments   /   posted on Sep 28, 2010
Tags:   windows-phone-7 , push-notifications , john-mcfetridge
Categories:   Windows Phone

This article is compatible with the latest version of Silverlight for Windows Phone 7.

This article is Part 5 of the series WP7 Stock Quote Demo.

Part 5 is a continuation of the adding a Push mode to our Stock Quote application as we now look at the Phone side.We setup the notifications by calling DoConnect in a class called SetupPush that was mostly lifted out of  the WP7 Labs example.

As shown above DoConnect will first check if there is already a channel open for our channel name that we call StockAlertChannel by calling HttpNotificationChannel.Find. If there is not then we will create a new channel using HttpNotificationChannel.Open :

 private void DoConnect()
         {
             try
             {
                 //First, try to pick up existing channel
                httpChannel = HttpNotificationChannel.Find(channelName);
 
                 if (null != httpChannel)
                 {
                     SubscribeToChannelEvents();
                     SubscribeToService();
                     SubscribeToNotifications();
                 }
                 else
                 {
                     //Create the channel
                     httpChannel = new HttpNotificationChannel(channelName, "StockAlerts");
                     SubscribeToChannelEvents();
                     httpChannel.Open();
                 }
  
             }
             catch (Exception ex)
             {
                 Trace("Channel error: " + ex.Message);
             }
         }

The paths are different for a new and existing channel, if its new we subscribe to events for the newly created channel:

        ChannelUriUpdated is fired when the channel successfully opens.

        ErrorOccurred is fired if an exception is fired.

Then assuming Push services opens the  channel opens successfully our ChannelUriUpdated handler fires:

Now we are able to use the channel to subscribe to our Quote service and tell it what type of notifications our phone wants to receive which in this case we limit to Tile.

 void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
         {
             Trace("Subscribing to channel events");
             SubscribeToService();
             SubscribeToNotifications();
            Trace("Channel created successfully");
         }
  

The call to SubscribeToservice is where we call the Register method on our service and the code looks like:

 private void SubscribeToService()
        {
  
             string baseUri = "http://localhost:8000/QuotePushService/Register?uri={0}";
             string theUri = String.Format(baseUri, httpChannel.ChannelUri.ToString());
             //save the uri that will be received by the server's register method
             IsolatedStorageSettings.ApplicationSettings["DeviceId"] = httpChannel.ChannelUri.ToString();
             WebClient client = new WebClient();
             client.DownloadStringCompleted += (s, e) =>
             {
                 if (null == e.Error)
                     Trace("Registration succeeded");
                 else
                     Trace("Registration failed: " + e.Error.Message);
                
             };
             client.DownloadStringAsync(new Uri(theUri));
         }

So we have reached this point in the process where we register the Uri the Push service will use to send notifications to our phone .These uris typically look like:

http://localhost:8000/QuotePushService/Register?uri=http://sn1.notify.live.net/throttledthirdparty/01.00/AAGchF8jvnHuQJynP2QlGt0kAgAAAAADAQAAAAQUZm52OjIzOEQ2NDJ

As a result the Register method is called on our service and our phone is now a subscriber to Push notifications. the input Uri will be used in the Http Post that our Quote service uses to communicate to our phone.

Of course there is nothing to push as we have not set any alerts and we really do not want to Push any alerts till the Phone app is closed down as we are using Tile Notifications. When the user touches the Back button to close the Quote app the Application_Closing event is fired and we add code here that will pass the alert info to our service.

 private void Application_Closing(object sender, ClosingEventArgs e)
        {
            if (viewModel.alerts.Count() > 0)
            {
                viewModel.quoteSuppier.t.Dispose();
                XElement quote = new XElement("Quotes",
                     from q in viewModel.alerts
                     select new XElement("Quote",
                         new XElement("Symbol", q.Symbol),
                         new XElement("GTorLT", q.Comparer),
                         new XElement("Guid", IsolatedStorageSettings.ApplicationSettings["DeviceId"]),
                         new XElement("Alert", q.Threshold)));
  
                viewModel.quoteSuppier.SetServerInfo(quote.ToString());
            }
        }

Now Tile Notifications will be received by the phone as the code in our service deems necessary. We have now offloaded the I/O intensive operations to our service and the Phone becomes just a message receiver.

In many case this is the preferred architecture as we the phone user only wants to be notified when a desired change has occured. It is a waste of resources to perform these tasks on the phone and in addition this architecture helps provide the illusion that there is multitasking occuring. Remember on the phone 3rd party applications cannot multitask.

Thus ends my series on WP7 development and I hope I helped show what a powerful development platform Microsoft is providing. I hope you enjoyed some of these and only time will tell if WP7 is successful as the competition is very good too.

John McFetridge

jmcfet@bellsouth.net

Architect, Developer and Trainer for Sandkey Software which specializes in Silverlight and WP7 development. more articles and videos by the author


Subscribe

Comments

  • -_-

    RE: WP7 Stock Quote Demo Part 5: Push Phone side


    posted by CArlos on Dec 23, 2010 11:22
    Is the Solution available?
  • -_-

    RE: WP7 Stock Quote Demo Part 5: Push Phone side


    posted by John McFetridge on Dec 23, 2010 15:14
    I am going to make it available and 5 videos in the New Year
  • -_-

    RE: WP7 Stock Quote Demo Part 5: Push Phone side


    posted by Carlos on Dec 24, 2010 09:21

    Excelent work, really good stuff.

    Thanks

  • -_-

    RE: WP7 Stock Quote Demo Part 5: Push Phone side


    posted by mike on Mar 30, 2011 17:44

    Good stuff.

     

    Where to find source code?

Add Comment

Login to comment:
  *      *       

From this series