So far I’ve really enjoyed developing applications for Windows 8. I still can’t claim to be particularly good at XAML design work yet, but I’m getting the hang of Windows Store Apps in C# using Windows RT. That said, there are have been a number of times when I’ve been lost and had to hit MSDN and search engines in order to figure things out. What makes this particularly challenging is that much of the information you’ll find is old and not appropriate for Windows 8 RTM. Consequently, I thought I’d share with you at least one thing I learned today.

Today I wanted to do two things.

  1. Get an ID specific to the application.
  2. Get an ID specific to the device/hardware (also called App Specific Hardware ID or ASHWID).

There are a lot of different reasons for wanting this information. For me, I’m storing this information in a Windows Azure table along with a Windows Notification Service (WNS) Channel URI so that I can choose the right application and device to send notifications.

While trying to figure out how to get the Application ID wasn’t particularly difficult – that is, if you find the RTM documentation – I did struggle to figure out how to get the device/hardware ID. Finally, I found an answer on Stack Overflow that helped.

Here’s how to get the application ID with C#:

string appId = CurrentApp.AppId.ToString();

Note that during development the GUID comes back as “00000000-0000-0000-0000-000000000000″. Once released through the Windows Store you will get a specific value.

Getting the ASHWID is a bit more difficult. Prior to the RTM release a lot of folks created their own GUID and stored it in the Windows.Storage.ApplicationData.Current.LocalSettings. This is a reasonable hack but of course the user can delete local storage and then your application would change the value – not good if you’re depending on something unique.

Fortunately the RTM release includes the GetPackageSpecificToken class that can return the ASHWID. Of course, I looked at some guidance and MSDN method documentation on getting the ASHWID and never found a good sample on how to get the ASHWID and store it as a string. Consequently, I hope this short snippet – again, found on Stack Overflow, helps:

private string GetHardwareId()
{
    var token = HardwareIdentification.GetPackageSpecificToken(null);
    var hardwareId = token.Id;
    var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(hardwareId);

    byte[] bytes = new byte[hardwareId.Length];
    dataReader.ReadBytes(bytes);

    return BitConverter.ToString(bytes);
}  

From here you can just load it into a string and do whatever you desire.

string deviceId = GetHardwareId(); 

Now you’ll get a value that’s something like 03-00-F0-7E-03-00-76-F3-05-00-5C-54-05-00-8A-DE-06-00-01-00-04-00-54-49-04-00-C2-4A-04-00-DE-4D-01-00-A4-52-02-00-2E-B2-09-00-42-88 that you can store for future use.

Nothing groundbreaking here but hopefully this saves you a few minutes.

I’ve long advocated using JSON when building mobile and cloud applications. If nothing else, the payload size makes it extremely efficient when transferred over the wire – take a look at the size of the same information formatted as OData, REST-XML, and lastly JSON:

JSON versus OData versus REST-XML

Pretty compelling.

Despite the use of JSON – and great frameworks like JSON.NET and SimpleJson – I always struggled with creating my C# classes when working with an existing web service that returned JSON. It can take a long time to create these C# classes correctly, and often time I’d take a lazy approach and either use the JObject or an IDictionary such that I didn’t have to have a C# class – something like:

var json = (IDictionary<string, object>)SimpleJson.DeserializeObject(data);

Yesterday I stumbled upon a tool that makes this SO amazingly easy. In many ways I’m bothered by the fact that it’s taken me so long to find it – has this been one of the best kept secrets on the Internet or did I just miss it?

http://json2csharp.com/

This website is as simple as it is powerful. Simply paste your JSON into the textbox, click Generate, and voilà you have C# objects!

Take a look. Here’s some JSON returned back from the Untappd API:

{
  "meta": {
    "code": 200,
    "response_time": {
      "time": 0.109,
      "measure": "seconds"
    }
  },
  "notifications": [],
  "response": {
    "pagination": {
      "next_url": "http://api.untappd.com/v4/thepub?max_id=11697698",
      "max_id": 11697698,
      "since_url": "http://api.untappd.com/v4/thepub?min_id=11697724"
    },
    "checkins": {
      "count": 2,
      "items": [
        {
          "checkin_id": 11697724,
          "created_at": "Wed, 22 Aug 2012 12:56:41 +0000",
          "checkin_comment": "",
          "user": {
            "uid": 205218,
            "user_name": "asiahobo",
            "first_name": "Bum",
            "last_name": "",
            "location": "",
            "url": "0",
            "relationship": null,
            "bio": "0",
            "user_avatar": "https://untappd.s3.amazonaws.com/profile/7d21ba831edb33341b98f86e09795ed7_thumb.jpg",
            "contact": {
              "twitter": "asiahobo",
              "foursquare": 31652652
            }
          },
          "beer": {
            "bid": 9652,
            "beer_name": "Maredsous 8° Brune",
            "beer_label": "https://untappd.s3.amazonaws.com/site/beer_logos/beer-maredsous.jpg",
            "beer_style": "Belgian Dubbel",
            "auth_rating": 0,
            "wish_list": false
          },
          "brewery": {
            "brewery_id": 6,
            "brewery_name": "Abbaye de Maredsous (Duvel Moortgat)",
            "brewery_label": "https://untappd.s3.amazonaws.com/site/brewery_logos/brewery-AbbayedeMaredsousDuvelMoortgat_6.jpeg",
            "country_name": "Belgium",
            "contact": {
              "twitter": "",
              "facebook": "www.facebook.com/pages/Abbaye-De-Maredsous/208016262548587fine",
              "url": "www.maredsous.be/"
            },
            "location": {
              "brewery_city": "",
              "brewery_state": "Denée",
              "lat": 50.3044,
              "lng": 4.77149
            }
          },
          "venue": [],
          "comments": {
            "count": 0,
            "items": []
          },
          "toasts": {
            "count": 0,
            "auth_toast": null,
            "items": []
          },
          "media": {
            "count": 0,
            "items": []
          }
        },
        {
          "checkin_id": 11697723,
          "created_at": "Wed, 22 Aug 2012 12:56:35 +0000",
          "checkin_comment": "",
          "user": {
            "uid": 137722,
            "user_name": "Mjoepp",
            "first_name": "Christoffer",
            "last_name": "",
            "location": "Linköping",
            "url": "",
            "relationship": null,
            "bio": "",
            "user_avatar": "http://gravatar.com/avatar/f1672535a7caa3bd686267257d33c588?size=100&d=https%3A%2F%2Funtappd.s3.amazonaws.com%2Fsite%2Fassets%2Fimages%2Fdefault_avatar.jpg",
            "contact": {
              "foursquare": 25958771
            }
          },
          "beer": {
            "bid": 12145,
            "beer_name": "Chocolate",
            "beer_label": "https://untappd.s3.amazonaws.com/site/beer_logos/beer-ChocolatePorter_12145.jpeg",
            "beer_style": "English Porter",
            "auth_rating": 0,
            "wish_list": false
          },
          "brewery": {
            "brewery_id": 844,
            "brewery_name": "Meantime Brewing Company",
            "brewery_label": "https://untappd.s3.amazonaws.com/site/brewery_logos/brewery-MeantimeBrewingCompanyLimited_844.jpeg",
            "country_name": "England",
            "contact": {
              "twitter": "MeantimeBrewing",
              "facebook": "http://www.facebook.com/meantimebrewing",
              "url": "http://www.meantimebrewing.com"
            },
            "location": {
              "brewery_city": "London",
              "brewery_state": "",
              "lat": 51.5081,
              "lng": -0.128005
            }
          },
          "venue": [],
          "comments": {
            "count": 0,
            "items": []
          },
          "toasts": {
            "count": 0,
            "auth_toast": null,
            "items": []
          },
          "media": {
            "count": 0,
            "items": []
          }
        }
      ]
    }
  }
}

I’m sad to admit that, in the past, I’d like create my C# objects by hand and then either conform to the JSON or map between the two. It requires a TON of time and is extremely error prone. With http://json2csharp.com/ all I do is paste this into the textbox and click Generate. I’ll get the following output:

public class ResponseTime
{
    public double time { get; set; }
    public string measure { get; set; }
}

public class Meta
{
    public int code { get; set; }
    public ResponseTime response_time { get; set; }
}

public class Pagination
{
    public string next_url { get; set; }
    public int max_id { get; set; }
    public string since_url { get; set; }
}

public class Contact
{
    public string twitter { get; set; }
    public int foursquare { get; set; }
}

public class User
{
    public int uid { get; set; }
    public string user_name { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string location { get; set; }
    public string url { get; set; }
    public object relationship { get; set; }
    public string bio { get; set; }
    public string user_avatar { get; set; }
    public Contact contact { get; set; }
}

public class Beer
{
    public int bid { get; set; }
    public string beer_name { get; set; }
    public string beer_label { get; set; }
    public string beer_style { get; set; }
    public int auth_rating { get; set; }
    public bool wish_list { get; set; }
}

public class Contact2
{
    public string twitter { get; set; }
    public string facebook { get; set; }
    public string url { get; set; }
}

public class Location
{
    public string brewery_city { get; set; }
    public string brewery_state { get; set; }
    public double lat { get; set; }
    public double lng { get; set; }
}

public class Brewery
{
    public int brewery_id { get; set; }
    public string brewery_name { get; set; }
    public string brewery_label { get; set; }
    public string country_name { get; set; }
    public Contact2 contact { get; set; }
    public Location location { get; set; }
}

public class Comments
{
    public int count { get; set; }
    public List<object> items { get; set; }
}

public class Toasts
{
    public int count { get; set; }
    public object auth_toast { get; set; }
    public List<object> items { get; set; }
}

public class Media
{
    public int count { get; set; }
    public List<object> items { get; set; }
}

public class Item
{
    public int checkin_id { get; set; }
    public string created_at { get; set; }
    public string checkin_comment { get; set; }
    public User user { get; set; }
    public Beer beer { get; set; }
    public Brewery brewery { get; set; }
    public List<object> venue { get; set; }
    public Comments comments { get; set; }
    public Toasts toasts { get; set; }
    public Media media { get; set; }
}

public class Checkins
{
    public int count { get; set; }
    public List<Item> items { get; set; }
}

public class Response
{
    public Pagination pagination { get; set; }
    public Checkins checkins { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public List<object> notifications { get; set; }
    public Response response { get; set; }
}

Pretty amazing! Now, note that it’s not perfect – there’s both a Contact and Contact2 class, but that’s easy to fix by merging the two and updating references. I’ll gladly perform this little bit of cleanup given the hours this tool just saved me.

Now that I have these classes, it’s really easy to use JSON.NET to load them with data.

RootObject publicFeed = new RootObject();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    data = reader.ReadToEnd();

    publicFeed = JsonConvert.DeserializeObject<RootObject>(data);
}

Now it’s a simple matter of using my RootObject within my applications.

I feel like I may be the last person to have heard of this tool, in which case I’m both embarrassed and bitter – couldn’t you all have told me about this years ago? Smile

I hope this helps!

Excellent keynote today by Scott Guthrie and the Windows Azure team! I don’t know if it’s because I’m seeing it on the other side for the first time or if it’s due to the amazing new capabilities introduced into Windows Azure, but I loved every second of it! Within a few minutes Scott had jumped into a demo and it was nonstop thereafter!

I’ve been waiting for almost a year to write this blog post.

Keynote with Scott Guthrie

WP_000321

In order to get this post out quickly I decided to share my rough notes from the keynote. Over the coming days and weeks I will certainly expand this with more information.

Scott Guthrie:

  • Today’s release “elevates Windows Azure to a new level”
  • Capabilities like Windows Azure Web Sites and open source libraries open the platform to many more developers
  • Three pillars of Windows Azure:
    • Flexible
    • Open
    • Solid
  • Windows Azure has pioneered Platform-as-a-Service
  • Today we’re enabling Infrastructure-as-a-Service (IaaS)
  • Support of Linux is how we’re embracing openness in a new way
  • Supporting more languages, protocols, and SDKs
  • Open-source libraries and SDKs on Github under the Apache 2.0 license

Demo: New Windows Azure website

  • There’s a new Linux and Mac installer for Node.js
  • Spent time optimizing the portal to work across platforms
  • Full monitoring and statistics through the portal
  • Everything done through the portal is communicating to APIs thereby allowing you to do everything through the command line
  • IaaS
    • Create a new virtual machine
    • Anything installed on the machine will persist; full durable VM
    • Image gallery
      • Linux distribution built into the portal
    • We have a number of SDKs to download, including Mac
      • installs an Azure utility and wires up a BASH shell
      • including ASCII art
      • SSH’d into Ubuntu machine
  • Virtual Networks
    • Not just upload VMs into the cloud
    • Integrate into your existing networks and VMs you already have
    • Shipping virtual private networking
    • A wizard to create an address space and subnet; we’ll virtualize these addresses
    • You can provide DNS servers in the cloud or on-premises

Scott Guthrie on VMs:

  • Virtual machine portability
    • Between the cloud and different environments
    • All VMs are running a VHD format which is an open spec
    • Because it’s the same file format you can take a VM and move to Windows Azure or even move it back; you don’t have to export or convert the VHDs
    • This allows you to run in your data center, other service providers, or within Windows Azure: flexibility, portability, and no lock-in
  • VM persistent drive
    • Mount durable drives to the virtual machines
    • Reliable and consistent
    • When you mount a drive the disk is backed with the Windows Azure storage system
      • Triple replicate the content; no interruption of service if there’s a failure
      • Continuous storage and geo-replication

Partner: RightScale

  • Michael Crandell, CEO
  • Mission: to build a broad cloud management platform
  • Web-based environment that allows companies to manage everything from development to delivery of applications running on cloud infrastructures
  • Think of us as a bridge between the apps and the infrastructures you want to run on (public, private, or hybrid)
  • Partner: worked with the Windows Azure team to interact with the new IaaS APIs
  • Brought to Windows Azure the full set of RightScale capabilities
  • When run by RightScale the solution includes auto scale
  • Why Windows Azure?
    • Microsoft knows how to run global cloud infrastructure with a high degree of operational excellence
    • IaaS + PaaS is an industry first – provides an entire environment for the development and deployment of apps that are compelling, from simple to complex
    • Openness – a clear commitment of openness at multiple levels

Scott Guthrie on Web sites:

  • Benefits
    • Build with ASP.NET, Node.js, or PHP
    • Deploy in seconds with FTP, Git, or TFS
    • Start for free, scale up as your traffic grows
  • Bill Staples demo
  • Opposite end of the cloud spectrum
    • don’t want to focus on the platform; don’t want to install the frameworks
  • Visual Studio & .NET
    • Quickly created a website
    • Downloaded a publishing profile that includes all the connection information
    • Opens up Visual Studio and ASP.NET MVC 4
    • Import the profile and publish
    • Support in both VS 20120 and VS 2012
    • Built and published into the cloud in just a few seconds
    • Updated a string and republished
      • Preview shows the deltas between local and cloud
      • Just push the change
  • Mac with Node.js
    • Instead of the portal use the commandline
    • Use the azure command
    • Uses git to deploy
    • One update connects to Mongo running in a Linux VM
  • Sometimes it’s nice to build an application without writing code
    • Best of Windows Azure and the power of open source
    • MySQL: worked with ClearDB to provide MySQL as a service
  • Scale
    • Scale out
      • By default, website is running as a Shared Website
      • You can increase instance count
    • Scale up
      • Move from Shared to Reserved
      • Only my websites are routed
  • 10 free shared websites

Scott Guthrie on Cloud Services:

  • Another model for building infinitely scalable applications and services
  • The traditional PaaS offering that Windows Azure has had since release
  • Creates a multi-tier applications using the website Bill created and adding a worker role
  • Process
    • Upload a service package (which is essentially a zip file) into the cloud
    • Fabric controller provisions the machines and deploys my bits and brings it into rotation through load balancer

Scott Guthrie on Building Blocks:

  • Overall message is to enable developers to focus on applications and less about infrastructure
  • Application building blocks
    • big data
    • database
    • storage
    • traffic
    • caching
    • messaging
    • identity
    • media
    • CDN
    • networking
  • Delivered by MSFT and partners
  • Language support for: .NET, Node.JS, Java, PHP, Python
    • Libraries you can consume natively
    • Libraries on Github under Apache2
  • SQL Database
    • Relational SQL database
    • Clustered for high availability
    • Fully managed service
    • SQL Reporting support
  • Blob storage
    • Features
      • Highly available, scalable and secure file system
      • Blobs can be exposed publically over http
      • Continuous geo-replication across datacenters
    • Real-time data showed in portal
    • SQLs surfaced in the portal
  • Cache
    • implementing Memcached protocol support
    • Use the distributed service or run it in your own instances
  • Identity
    • Integrate with enterprise identity
    • Enable single sign-on within your apps
    • Enterprise Graph REST API
    • 93% of Fortune 1000 use Active Directory
  • Service Bus
    • Secure messaging and relay capabilities
    • Easily build hybrid apps
    • Enable loosely coupled solutions
    • Cross platform SDKs
  • Media Service
    • Create, manage, and distribute content
    • Target any device or media format
    • Ingest, Encode, Protect, Stream
  • Marketplace integration
  • Azure in 89 countries and territories

Today’s release marks a significant milestone for Windows Azure. To date, Windows Azure has been a platform that allows developers to build and run applications across Microsoft’s global datacenters – the key emphasis has been on “applications”. Windows Azure has not been a platform for providing the underlying infrastructure for running your own virtual machine – this has been a key pain point for many customers looking to move to the cloud that Microsoft has heard loud and clear. Today’s announcement makes it clear that Windows Azure is more than just a Platform-as-a-Service provider.

In my opinion, there are three significant components of today’s announcements worth delving into deeper:

  • New Infrastructure-as-a-Service (IaaS) capabilities.
  • Free (or low-cost) hosting with Windows Azure Websites.
  • Enhanced cloud networking capabilities that support VPN connections between an on-premises corporate network and Windows Azure.

Until now, Microsoft has never competed directly with Amazon EC2 with respects to IaaS nor with cloud platforms like Heroku. The new IaaS and Websites capabilities, combined with the ability to extend on-premises networks to the cloud, provides a number of ways that Windows Azure can now distinguish itself from other platforms and—in my opinion—will drive many new enterprises and a large number of developers to adopt Windows Azure.

Infrastructure-as-a-Service

Windows Azure has long had the concept of a “Virtual Machine role” but the fundamental problem has been the inability to persist changes made to the virtual machine image provided by the customer (i.e. the guest VM) during reboots or recycling. Supporting VM persistence in Windows Azure means that the guest VM will not lose these updates. This unlocks many workloads that previously did not work in Windows Azure – certainly products like SharePoint and SQL Server but also custom line-of business applications that previously were difficult to move to Windows Azure.

In addition to VM persistence, Windows Azure will also give customers the ability to run Linux VMs. There’s been a lot of interest and speculation regarding Microsoft’s strategy moving forward with Linux and open source. I think Microsoft recognizes that their customers run more than just Windows in their enterprise, and this is an opportunity for Windows Azure to run as many workloads as possible. We’ve seen this shift in Microsoft in a number of different ways – support for Node.js and Java in Windows and Windows Azure, the creation of a new interoperability subsidiary, and many more. The cloud provides a way to make it easier to connect all of these different platforms and technologies, and my take is that Microsoft is trying to make Windows Azure the best and simplest place to run your applications regardless of the platform or technology.

Windows Azure Websites

It’s exciting to see Microsoft continue to evolve its strategy with Windows Azure to make it increasingly accessible to the breadth of developers out there.
Windows Azure Websites is a hosting platform for web applications. It provides a number of different deployment and runtime options beyond the existing Web Role, including:

  • Target both Microsoft and non-Microsoft technologies already running in the environment, including SQL Azure, MySQL, PHP, Node.js, and (of course) .NET.
  • Deploy via Git, Web Deploy, FTP, or TFS.
  • Run in a high-density / multitenant VM for little-to-no cost or choose a dedicated deployment path.

In addition to providing simpler and more consistent ways to deploy applications across different hosting platforms (e.g. Windows Azure, Windows Server, and hosting providers), Windows Azure Websites provides a way for Microsoft to bring thousands—perhaps even hundreds of thousands—of new developers to the platform with the offer of little-to-no cost hosting.

Cloud Networking

Windows Azure Virtual Networks allows a company to connect their cloud applications and solutions to their local network. This occurs at the networking layer through standard VPN devices. Coupled with IaaS support, this provides a ton of flexibility with respects to the kinds of workloads a customer moves to Windows Azure. Don’t want to move your sensitive SQL Server database? You don’t need to. Setup a VPN to your applications in Windows Azure and let them communicate directly back to your applications that live on-premises.

There’s certainly a lot more to talk about – new services, portal, SDK, tools, and so much more! These thoughts are pretty early—in fact, I write this before today’s MEET Windows Azure event—and there’s so much more to talk about!

Recently Steve Marx and I spent a few hours working on a best practices document for Windows Azure. As expected, this was a fun and educational experience – plenty of goofing around, but also some really good discussion on things to think about when building applications for Windows Azure. One of the items we discussed is a better approach for sleeping inside the Worker Role when pulling from queues. Rather than defaulting to a retry every 10 seconds we decided that the best approach is to exponentially back-off on your queue reads while capping it with an upper bound.

The primary value of this is to decrease the number of storage transactions when reading from your queue, and therefore reduce both bandwidth and transaction costs.

There are plenty of other good posts on this topic that provide a lot more detailed justification and rationale for this approach:

The logic and approach is deceptively simple and I thought I’d share a really simple, yet effective, example. (Incidentally, credit goes to Steve for very quickly putting together the basis of this really simple example.)

Here’s the code:

   string queueName = "queuetest";

   int minInterval = 1;
   int interval = minInterval;

   int exponent = 2;
   int maxInterval = 60;

   CloudStorageAccount account = CloudStorageAccount.DevelopmentStorageAccount;
   CloudQueueClient queueClient = account.CreateCloudQueueClient();
   CloudQueue queue = queueClient.GetQueueReference(queueName);
   queue.CreateIfNotExist();

   while (true)
   {
      var msg = queue.GetMessage();
      if (msg != null)
      {
         // do something
         queue.DeleteMessage(msg);
         interval = minInterval;

         Trace.WriteLine(string.Format("Interval reset to {0} seconds", interval));
      }
      else
      {
         Trace.WriteLine(string.Format("Sleep for {0} seconds", interval));
         Thread.Sleep(TimeSpan.FromSeconds(interval));
         interval = Math.Min(maxInterval, interval * exponent);
      }
   }

As I said, really simple. The magic is in the last line where we check to see which is smaller – the maximum interval or the product of the interval and the exponent. At some point the product of the interval and exponent grows larger than the maximum interval, and consequently the interval value is set to the maximum interval.

Here’s the output in the Windows Azure Compute Emulator:

   Sleep for 1 seconds 
   Sleep for 2 seconds 
   Sleep for 4 seconds 
   Sleep for 8 seconds 
   Sleep for 16 seconds 
   Sleep for 32 seconds 
   Sleep for 60 seconds 
   Sleep for 60 seconds 
   ...

Now, the application will continue to sleep until it finds a message in the queue, at which point the interval is reset back to one. To test this I used the Azure Storage Explorer and created a new queue message.

AzureStorageExplorerQueue

Once the message is created the output is as follows:

   Interval reset to 1 seconds 
   Sleep for 1 seconds
   Sleep for 2 seconds
   Sleep for 4 seconds
   Sleep for 8 seconds
   ...

And so forth.

You can find all the source code for this sample in my CappedExponentialBackOff repository on GitHub.

Pretty simple but quite useful. I hope this helps!