JSON Deserialization Made Simple With System.Web.Helpers and List<dynamic>

February 3 2011

Been playing with WebMatrix and have come across some crazy and beautiful code that I really liked in the FourSquare helper on CodePlex. Check this method out, which returns a graph of friends from the fourquare api

/// Returns a list of friends
    /// </summary>
    /// <param name="accessToken">The access token of the authenticating user.</param>
    /// <param name="userId">The Id of the person for whom to pull a friend graph. if not specified, the authenticating user's list of friends will be returned.</param>
    public static IList<dynamic> GetFriends(string accessToken, int userId = 0) {
        var url = "https://api.foursquare.com/v2/users/{0}/friends?oauth_token={1}";

        var client = new WebClient();
        var jsonResult = client.DownloadString(string.Format(url, userId == 0 ? "self" : userId.ToString(), accessToken));
        var result = Json.Decode(jsonResult);
        return new List<dynamic>(result.response.friends.items);

Notice how tight this code is. And note the crazy dynamic typing that C#4 provides in combination with the Json.Decode method. If you are wondering where that JSON.Decode method came from, it is from System.Web.Helpers -- you can use this dll anywhere, doesn't have to be with WebMatrix or Razor. Here's a link to the docs on System.Web.Helpers.Json: http://msdn.microsoft.com/en-us/library/system.web.helpers.json(VS.99).aspx 

 Serialization and JSON have long been painful in .NET because of .NET's strong typing.  This got better with the C# dynamic keyword (see this post and this post) but nothing is as elegant as the code above.

Check this example out, which returns a user's FourSquare badges:

/// <summary>
    /// Returns badges for a given user.
    /// </summary>
    /// <param name="accessToken">The access token of the authenticating user</param>
    /// <param name="userId">The Id of the user</param>
    public static IList<dynamic> GetBadges(string accessToken, int userId = 0) {
        var url = "https://api.foursquare.com/v2/users/{0}/badges?oauth_token={1}";
        var client = new WebClient();
        var jsonResult = client.DownloadString(string.Format(url, userId == 0 ? "self" : userId.ToString(), accessToken));
        var result = Json.Decode(jsonResult);
        var badges = new List<dynamic>();
var groups = new List<dynamic>(result.response.sets.groups); var allBadgesGroup = groups.FirstOrDefault(g => g.type == "all"); if (allBadgesGroup != null) { foreach(var badgeId in allBadgesGroup.items) { badges.Add(result.response.badges[badgeId]); } } return badges; }

Notice how the two dynamic lists get created which are then manipulated with a LINQ lambda query.  Nice! Having dealt so often with either manually mapping JSON to CLR objects and/or dealing with arrays nested in arrays nested in arrays, I'm absolutely loving this.


YouTube Flips Switch On IFrame as Default Embed Code

February 2 2011
Interesting to see that YouTube has made their embed code default to an iFrame instead of using an <object> tag to insert a Flash player. This capability was introduced this summer, but it was more experimental then and only became the default experience last week.
The main motivation for the switch?  So that if you are on an HTML5 browser, you won't be sent Flash, but rather your browser will use the <video> tag and serve up either WebM or H.264.  Read more here.
What's interesting is that HTML5 on YouTube's site was an experiment, but with making their embed code an IFrame by default, it means HTML5 video becomes much more prevalent.The average Joe user who wants to embed a video on his blog will now be serving up HTML5 whether he realizes it or not.

BinPress Programming Contest: $40,000 in prizes

January 25 2011

I have the honor of being a judge in the recently announced BinPress Contest. As they say on their site:

Have you been developing custom solutions for the web? pick your best feature, module or UI component that can be packaged and re-used and publish it on Binpress. Binpress is a marketplace for source-code, where developers can sell and buy source code from each other.

If you've been writing reusable components or libraries, consider submitting. What have you got to lose?

Mobile Breathalyzer - Another Free Windows Phone App

January 19 2011

Got another (free) Windows Phone App in the marketplace:

 The Mobile Breathalyzer

Using revolutionary technology in Windows Phone 7, the Mobile Breathalyzer allows you to determine your blood alcohol content using your phone. Um, yeah, right. Download this joke app and then have your drunk friends try it. Watch them blow into the phone, expecting a result. Good times!

Give it a try! Thanks to @systim for doing the design. Good old designer/developer workflow on this one -- Blend/VS did the trick.


Using The Nonlinear Navigation Service To Solve Back Button Problems With Window Phone 7 Apps

January 10 2011

Started using the NonlinearNavigationService to solve some issues in my app where the back button threw my app into a loop and the user could never back out of the app to close it. Which made the app fail certification incidentally. (Because you manually can't prune the navigation history, this is really the best workaround to avoid this type of loop.) This service works great -- just add the dll and you are good to go -- except it doesn't work with the Page Transition Service from the Silverlight Toolkit.  That's too bad, but hopefully someone out there will address that! If anyone does, let me know...

Music Buzz - A Free Windows Phone 7 Application For Discovering Music and News About Your Favorite Bands

January 7 2011

I've taken Buzz off the Marketplace and replaced it with Music Buzz, which is the same thing, but free!  The ecomonics of the app store are worth noting: Buzz, priced at 99 cents, received 5 downloads in two months. Music Buzz has already been downloaded 1000 times in the last two weeks! 

Here's a description of the app:

Find music, news and more about the bands you love. You'll be amazed at the latest buzz and music (remixes, bootlegs and more) that the Music Buzz application will discover.  Please give it a try!

Here's a screenshot:



Eschewing NavigationService Model in favor of RootVisual Model

January 7 2011

When developing Windows Phone 7 apps, one is inclined toward the navigation model for moving between pages.  But it is worth calling out that there is a different way to proceed, which is to simply load your new page in the root visual, as follows:

App.Current.RootVisual = new Screen4();

This has the advantage and disadvantage of entirely bypassing the navigation framework, which means that the back button always exits your app. I say this is an advantage because for certain applications, that's the very behavior you seek, and you can find yourself getting into a lot of trouble with the navigtation history problems, which can cause your app to end up in a loop and not be able to be exited (since there is no App.Exit() method for Windows Phone 7 - see this blog post for the reasoning).  I say disadvantage because you lose the ability to do navigation transitions, as explained in this post.

Nonetheless, it is worth considering up front when you start an application as to whether you should use the NavigationService model or the RootVisual model.

IRhetoric Ported to BlogEngine 2.0

January 6 2011

Hat's off to the BlogEngine.NET folks on their 2.0 release.  A great release it is!  I've ported this blog to the 2.0 release. Everything went pretty smooth. The only issue I had was that I had to rem out the following line in web.config:

<!--<add name="ScriptModule"type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>-->


I suspect because my provider includes that already in their web.config, which gets inherited by my web.config.

I LOVE the new admin interface in BlogEngine.NET 2.0. Fantastic work.  Check out the video here to see it in action.  The comment moderation and capabilities are super strong. And I like how they baked in code formatting using the defacto standard of http://alexgorbatchev.com/ Syntax Highlighter.

Lastly, I'm really impressed with how they integrated the HTML5 audio/video tags with a super smooth fallback to Flash/Silverlight. You can see that in action below:

WebException on an HTC Windows Phone 7

December 9 2010

So, had this issue where HTTPWebRequest was throwing a WebException on a production HTC HD7 device – the error was "The remote server returned an error: NotFound."  However, the browser itself worked fine. What was really weird was that these same HTTPWebRequest calls work fine in the emulator and Samsung devices. I was totally flummoxed.

Turns out that there were a few misleading things to solve this bug.

First, was that all Web Request errors are mapped to a 404. So the real error could be (and was) different. In fact, the error from the server was a 500. The reason? The call to the server was the start of an OAuth handshake which involved sending a timestamp. Apparently, HTC phones with no SIM card don’t set the date or time correctly, and thus the DateTime.UtcNow was returning something totally bogus, and the server was rejecting the call.

The fix was to add a dialog to the app in the event that the time hasn’t been properly set.

One suggestion for debugging these types of HTTP failures is by setting the WiFi proxy on the phone to your machine’s IP, then using Fiddler2, and enabling the “Remote connections” option under Fiddler’s options.

SFMusicTech Notes

December 9 2010

I attended SFMusicTech, a conference in San Francisco that “brings together visionaries in the music/technology space, along with the best and brightest developers, entrepreneurs, investors, service providers, journalists, musicians and organizations who work with them at the convergence of culture and commerce. We meet to discuss the evolving music/business/technology ecosystem in a proactive, conducive to dealmaking environment.”

It’s a great conference to stay on top of what’s happening and see the trends in Silicon Valley through the lens of music.

Here’s a braindump of my notes:

Panel: Cutting Edge Legal Issues in Digital Music

· Apple’s clout: just recently forced music companies to support 90 second preview instead of 30 second. Don’t underestimate Apple’s power

· Pandora special cased from legal perspective

· Commerce a huge play for Facebook

· Terms of Service of a website can trump copyright law, other legal matters; beware of TOS!

· How would you change copyright law if you could wave magic wand? Make it 7 years instead of 75.

· Forgiveness model: but use up front with assumption that you are solid

· YouTube getting sued right now

· Look at Grokster as case where forgiveness model would never work

· TorrentFinder DNS shut down by immigration dept since server abroad

· COICA – law to allow feds to kill DNS inside states, probably won’t hit senate this year, maybe next year

Panel: Connected Devices

· Dropbox: great service

· Digital Fingerprinting: will be used to grab metadata while watching a movie or listening to a song

· Is it “one device to rule them all” or multiple devices?

· Android on the TV: Google TV

· Are we back to Mac vs. PC when looking at iOS vs. Android?

· Bluetooth: great example of even when there’s a standard, implementation can take years to sort out

· Finding apps is still an issue (GetJar, AppBrain: alternate stores for Android)

· Content: middle dropping out – its either Universal or indies, but the middle folks getting squeezed

New Product And Technology Demos

· Vocooo – karoke for mp3, very slick iOS implementation

· WinAmp for Android – equivalent to iTunes to iOS, allows management of library from pc to device, plus shoutcast integration

· AudioGalaxy – Redone, uses local exe to sync files, playlists. Works on Mac now

· Ex.fm – Chrome plugin, plus website integration with v2

· StageIt – webcam conferences, can tip musician, people making money with this doing shows

· RJDJ – Augmented sound, Bruce Sterling cred, Did app with Christopher Nolan and Hans Zimmer

· BeatLab – Like a poor man’s sequencer on the web, used audio manipulation in Flash 10

· Musixmatch – Lyrics API

Panel: Developer Platforms

· Twillio – great example of app gallery

· Imeem died, dev moved to Soundcloud

· Still can make huge money on Facebook platform: look at Phrases – 58 million users

· Don’t use APIs that are core to product; only ancillary features and functions

· Shout out to Gowalla as better than Fourquare in terms of aesthetics of API