Windows 8 Demo Code

4/30/2012 8:24:14 AM

Code for my Windows 8 demos is now available for download.  You can get the files here.  Enjoy.

Tags:

Windows 8

Windows Phone to Windows 8 Online Sessions

4/24/2012 9:23:12 AM

Online Workshops

Option One
Date May 16th, 2012

clip_image001

Option Two
Date May 18th, 2012

clip_image001[1]

FREE Events
Capacity is limited,
so arrive on time.
Events run from
8:30am to 12:30pm CST

Updated on 5/3/2012 with new registration links!!!

Windows 8 with Metro-style applications offers one of the biggest opportunities for developers in a very long time. As a Windows Phone developer, you are uniquely positioned to be able to get in on the ground floor of this exciting new platform.

Microsoft has already provided some great resources that you may want to look to learn how you can move your Windows Phone applications to the Windows 8 platform:

Migrating WP7 to Window 8

Metro UX style, design and principles

Creating your first Metro app with C#/XAML

Samples and SDK

Because of your interest in Windows Phone 7 you are also asked to please join us for a special, invitation-only Windows 8 event created specifically for Windows Phone developers – Windows Phone to Windows 8 Workshop. Because of your interest in Windows Phone 7, and your past attendance at a Windows Phone Boot Camp, Microsoft would like to extend to you a unique opportunity to get ready for Windows 8.

These FREE half-day workshops will provide you an overview getting from Windows Phone to Windows 8. Leveraging your XAML and .NET skills, these workshops will introduce the fundamentals of developing Windows 8 Metro-style applications, tips for migrating your Windows Phone applications, and guidance on Metro UX. Technical experts will be on hand to address your questions, discuss your existing Windows Phone applications, and help get you started on developing your applications on Windows 8 and getting them into the Windows Store.

To participate in a workshop, all you need to do is pick one of the two dates and attend the online seminar. Each workshop is the same, so you only need to attend one workshop. Each meeting has limited online capacity, so join on time.

Tags:

Windows 8 | Windows Phone | Headlines

Heads Up: Working with JSON on Windows 8

4/16/2012 10:42:13 AM

Just a quick heads up for working with JSON on Windows 8.

If you have worked with JSON on Windows Phone 7, you are most likely very familiar with the DataContractJsonSerializer class.  When working with JSON, using DataContractJsonSerializer is the most common approach I see.  The approach typically looks something like this.

First, you define a class that will contain the parsed JSON data.  You mark with class up with [DataContract] and [DataMember] attributes.  If I was getting data from Twitter, it might look something like this:

[DataContract]
public class Tweet
{
     [DataMember("text")]
     public string Text {get;set)
 
     [DataMember("profile_image_url")]
     public string ImageUrl{get;set)
 
     [DataMember("from_user_name")]
     public string Poster{get;set)
}

While straightforward, it is a bit cumbersome.  You have to create class.  You then may want to map the property names from Twitter to different property names in your .NET class.  It gets even more complicated if the JSON has properties that contain other JSON objects.  Now you have to create additional classes to parse those results.

Once you have your classes created, you would then parse the JSON as shown:

var jsonSerializer = new DataContractJsonSerializer(typeof(Tweet));
var results = jsonSerialzer.ReadObject(someStream) as Tweet;

The above is closer to pseudo code than real code, but the one thing to point out is that the ReadObject method requires an input stream that provides the JSON.  If you are working with a string of JSON, you have to put it into a MemoryStream and then parse it.  The extra step can be annoying.

JSON in Windows 8 – A Simpler Approach

In Windows 8, we have the JsonObject class that makes life simpler when working with JSON.  The JsonObject has existed in “regular” Silverlight for sometime, but never made an appearance on Windows Phone. It has undergone some changes on Windows 8, giving us some new methods to work with. For quick and dirty JSON processing, the JsonObject works pretty well.  If you have more complex needs, you may want to checkout the JSON.Net library.

With the JsonObject, we can parse are JSON like this:

var json = JsonObject.Parse(jsonString);

Things don’t get much easier than that.  I can access properties on the parsed results with just as easily:

var prop = json.GetNamedString(“someProperty”);

There are other methods like GetNamedBoolean, GetNamedObject, and GetNamedArray.  Let’s take a look at GetNamedArray, in particular, since I think it will be used frequently.

If you take a look at this Twitter search, you will see that the actual results of the search are contained in an array of JSON objects called “results”.  This is a pretty common occurrence in the world of JSON. 

Handling it with JsonObject is pretty straightforward once you get the hang of it.  If I wanted to databind the results of that search to a list of tweet results, I could do something like this:

var results = json.GetNamedArray("results");
 
var tweets = from r in results
                      select new { text = r.GetObject().GetNamedString("text"),
                                           image = r.GetObject().GetNamedString("profile_image_url"),
                                           poster = r.GetObject().GetNamedString("from_user_name") };

The “tricky” part is that the values stored in a call to GetNamedArray are not JSON objects, even though we know the results property contains JSON objects.  The returned array is actually a list of JsonValue’s because it is possible that we are dealing with an array of strings, for example.  As a result, when iterating through the results, we need to make a call to GetObject on each item in the list. 

Obviously, not a lot of error checking going on, but it does a fine job illustrating the core concepts.  If you are interested in how this would be used in an application, here is an example method that calls the Twitter search reference above:

private async void SomeMethod()
{
    var http = new HttpClient();
    http.MaxResponseContentBufferSize = Int32.MaxValue;
    var response = await http.GetStringAsync("");
   
    var json = JsonObject.Parse(response);
    var results = json.GetNamedArray("results");
    var tweets = from r in results 
                          select new { 
                                    text = r.GetObject().GetNamedString("text"),
                                    image = r.GetObject().GetNamedString("profile_image_url"),
                                    poster = r.GetObject().GetNamedString("from_user_name") };
}

Tags:

Windows 8

Consuming HTTP Streams in Windows 8 with C#/XAML

4/12/2012 12:58:42 PM

Let’s say you play a multiplayer game online that provides updates via a Twitter stream.  Let’s say it’s a game like QONQR.  Now, you may be a little bit addicted to playing that game.  I’m not saying I know anyone that is, but if someone was, they may want to consume that Twitter stream and do some fun things with the information.  You could mess around with some kind of traditional polling client, but Twitter has a Streaming API available, so why not use that?  Of course, if you were going to write some cool new app to leverage that data, you would certainly test it out on Windows 8, right?

Conceptually, the idea seems pretty straightforward.  I want to consume the Http Stream on a continuous basis, and update my application as new tweets are received.  A couple things complicate this idea.  First, we usually deal with Http requests in a connect-request-receive-disconnect approach.  Get in, get out.  So how do we keep a connection open to the server that we can read from continually?  Second, in Windows 8, all of the network operations are asynchronous, so how do we get the updates from the async operation back to the UI?

First, we will create class to handler the streaming.  In trail blazing fashion, I will name this class HttpStreaming.  Because of problem #2, I know that any work that is done by the HttpStreaming class will most likely need to be marshaled back on the UI thread.  In my simple app, all I want to do is read in Tweets and add them into a GridView control.  My class starts of looking like this:

public class HttpStreaming
{
        CoreDispatcher _dispatcher;
 
        public HttpStreaming(CoreDispatcher dispatcher)
        {
            _dispatcher = dispatcher;
        }
}

The HttpStreaming class asks for the Dispatcher associated with the application’s UI thread.  We’ll see how to that shortly.

Now, it is time for the meat of the problem.  Accessing and processing the Http stream.  The basic operation looks like this:

public void Start(Action<JsonObject> action)
{
    try {
        var webRequest = (HttpWebRequest) WebRequest.Create("https://stream.twitter.com/1/
                                                              statuses/filter.json?follow=255956231");
        webRequest.Credentials = new NetworkCredential("user","password");
 
        webRequest.BeginGetResponse((callback) => {
        try {
            Encoding encode = Encoding.GetEncoding("utf-8");
            var request = callback.AsyncState as HttpWebRequest;
            var response = request.EndGetResponse(callback) as HttpWebResponse;
 
            while (true)
            {
                try
                {
                    var responseStream = new StreamReader(response.GetResponseStream(), encode);
                    var json = responseStream.ReadLine();
                    var data = JsonObject.Parse(json);
                    if (action != null && data != null)
                    {
                        _dispatcher.InvokeAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                        (s, e) =>
                        {                     
                            action(data);
                        },
                        this,
                        null);
                    }
 
                }
                catch (IOException ex) { }
                catch (OutOfMemoryException ex) { }
            }
        }
        catch (WebException ex) {}
        catch (IOException ex) {}
        catch (OutOfMemoryException ex) {}
        catch (Exception ex) {}
        },webRequest);
    }
    catch (WebException ex) {}
}

There is a lot going on here, so let’s break it down because it is really not that complicated.  First, the Start method accepts an Action that expects to get a JsonObject passed to it.  This makes sense since the Twitter stream will be feeding us Json representations of the tweets.

Next, we set up the HttpWebRequest.  Twitter requires authentication to access the stream, so you can omit this if yours does not.  We start the async request by calling BeginGetResponse. The callback lamda expression does all of the processing.  The heart is the continual while loop.  The only time we break out of the loop is if there is an Exception

The loop does continually reads from the Http Stream, and if there is a json object, it uses the dispatcher to call the Action.  I’ll leave it up to you on how to handle the various exceptions.

In the the code-behind of my application’s page I put this code:

HttpStreaming httpStream;
ObservableCollection<string> tweetList = new ObservableCollection<string>();
public BlankPage()
{
    this.InitializeComponent();
    tweetView.ItemsSource = tweetList;
}
 
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    httpStream =  new HttpStreaming(this.Dispatcher);
 
    httpStream.Start((json) => {
                var tweetText = json.GetNamedString("text");
                tweetList.Add(tweetText);
    });
}

When the page is navigated to, it sets up the HttpStreaming object with the Dispatcher and then connects to the stream. You could set this up differently to suit the needs of your application.  In my demo app, I have created an ObservableCollection that will hold the tweets that I want updated on my page.  The Action assigned to the Start method simply takes the returned json object, pulls the text value, and inserts the text string into the ObservableCollection.

All in all, it is pretty straightforward stuff, but not intuitively obvious.  At least it wasn’t for me. You may find it useful in this world of web connected software.  Now, let’s see if I can figure it out in javascript.  Stay tuned…

Note:  Special thanks to Shannon Whitley that got me pointed in the right direction when I first thought about this problem with his helpful blog post - Open Source .NET (C#) Twitter Streaming API Client

Tags:

Windows 8

Powered by BlogEngine.NET 1.6.0.0
Theme by Mads Kristensen

About the author

Jeff Brand Jeff Brand

This is the personal web site of Jeff Brand, self-proclaimed .NET Sex Symbol and All-Around Good guy. Content from my presentations, blog, and links to other useful .NET information can all be found here.

E-mail me Send mail


Calendar

<<  June 2013  >>
MoTuWeThFrSaSu
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar

My Twitter Updates

XBOX
Live

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2013

Sign in