Contracts
Imagine you are constructing a feed reader application that aggregates data from multiple sources and provides a snappy user interface for browsing top stories and drilling into the details. You want to make it easy for that user to print articles, email them to friends, or even post the links to Twitter, Facebook, or perhaps another social networking site that hasn’t been launched yet. What do you do?
In Windows 8 Metro, you simply invoke a Share contract. You start by informing the platform that you are interested in allowing your users to share content:
_dataTransferManager = DataTransferManager.GetForCurrentView(); _dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs> (_dataTransferManager_DataRequested);
That’s all there is to make sharing available to users. Now, from anywhere within your application, they can either slide their thumb in from the right side of the display or hold their mouse pointer over the right edge of the application, and a “Charm Bar” will appear. This bar provides several options including the ability to share content. If the user taps the icon, the system will provide a list of applications that can receive shared content. When the user selects the target application, you simply pass along the details, like this:
args.Request.Data.Properties.Title = "C#er : IMage"; args.Request.Data.Properties.Description = "A Windows 8 blog."; args.Request.Data.SetUri(new Uri("http://csharperimage.jeremylikness.com/"));
You didn’t have to learn how to log in to Twitter to post a tweet or read RFC 821 to understand the Simple Mail Transfer Protocol (SMTP) in order to fire off an email. This simple contract allows you to post data to any application willing to receive it. That means as the user installs more applications, your application will also evolve because it is able to interact with these new applications. Sharing can be extended to bitmap images and HTML code, and other contracts exist such as enabling your application to receive search requests.
To register as a target, you simply add a template for receiving the data and update the manifest to indicate the types of data your application can receive. A share request that targets your application will raise an event that you can respond to by collecting the data and handling it however it makes sense. This feature known as “Contracts” that are accessible through “Charms” is what provides the “connected and alive” aspect of the Metro experience.