WinRT app guide: Step 16: Sharing content by contract in 4 easy steps
To read the other steps in the step by step guide for creating a Metro/ WinRT application go here
Recap
We are building a small application where a user can register study activities and update their progression and see some graphs based on that data. Last time we implemented a function that allows the user to write the activities to a text file, and this time we will allow the user to share the activities with another app that allows html content- for example an email client. We will be using the share contract for this.
Two new new concepts introduced
Sharing is caring
People today love to share information, as a matter of fact- we expect to be able to share content. (Read more about the expectations and guidelines here) So I would say it is almost mandatory that an app with information content allows the user to do so. And if not mandatory, well- it sure would be appreciated by the user. Besides the user experience, it is also a great way for you to promote your application, the content, or just extending the usage of the application.
The share charm can be found on the right side of the screen when swiping in, or taking to mouse to the upper or lower right corner
Sharing by using a contract
A new concept introduced in Windows 8 are contracts and extensions, these are a kind of common platform on which windows store apps can interact with each other. As you know windows store apps are heavily sandboxed, but to provide the user with the possibility to share content, the need for some apps to interact, and also for practical reasons- there are ways for the applications to interact in a secure way on this common platform.
Contracts are app to app interaction, and extensions are app to windows interaction. Sharing content is done by contract, and an app can be a share target, share source, or both. Our app will be a share source, so we will be able to share content from our app with apps that are share targets. The apps sharing don’t need to know of each other, which is pretty cool, as long as they accept the type of content we provide. We will provide text content, but more types can be shared if you wanted to, and you could extend this to include special types as well. The core of the share operations is something called DataPackage, and supported types (out of the box) are plain text, URIs, HTML, formatted text, bitmaps, files and then there is also developer defined data.
Implementing share contract
1. Add the namespace
(code snippets from msdn)
using Windows.ApplicationModel.DataTransfer;
2. Set up the datatransfer manager
Create the instance:
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
The DataTransferManager initiates the the exchange of content with other apps. The class consists of only two methods and two events, one of these events is the DataRequested event.
3. Listen for the event
dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, DataRequestedEventArgs>(this.ShareTextHandler);
The DataRequested event occurs when a share operation starts. The TypedEventHandler is a strongly typed eventhandler that allows us greater control.
4. Set up the handler where the fun happens
Set up the handler:
private void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs e) { DataRequest request = e.Request; request.Data.Properties.Title = “Study activities”; request.Data.Properties.Description = “User study activities”; request.Data.SetText(“text to share”); }
That easy? Yes it is! But, we do have a smaller problem, we want to format the text so it’s not just one big chunk of text and Data.SetText will do that. While there is the RTF format, my email client does not support that and therefore we will format the text to html instead so we can spicy up the formatting and display the text in a nicer way. But feel free to play around with the different types, and you can of course set up sharing that supports several types.
This is the code me need to add in the codebehind to share code.
[sourcecode language=“csharp”]
public MainPage()
{
this.InitializeComponent();
\_studyActivityRepository = new StudyActivityRepository();
SetUpAsShareSource();
}
private void SetUpAsShareSource()
{
DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
dataTransferManager.DataRequested += new TypedEventHandler(this.ShareTextHandler);
}
private void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs e)
{
DataRequest request = e.Request;
string dataPackageText = GetHtmlFormattedText(\_allEntries);
if (!String.IsNullOrEmpty(dataPackageText))
{
request.Data.Properties.Title = "Study activities";
request.Data.Properties.Description = "User study activities";
request.Data.SetHtmlFormat(dataPackageText);
}
else
{
request.FailWithDisplayText("No activities available to share");
}
}
static internal string GetHtmlFormattedText(IEnumerable userActivities)
{
if (userActivities == null)
return "";
var emailText = userActivities.Aggregate("", (current, activity) => current + string.Format(
"</pre>
" +
"
Time est. : {3}" +
" Time spent: {4}
" +
"
Worth: {5}" +
" Importance: {6}" +
" Urgency: {7}
“,
activity.Title,
activity.CategoryName,
activity.Comment,
activity.TimeEstimate,
activity.TimeSpent,
activity.WorthScore,
activity.ImportanceScore,
activity.UrgencyScore));
return HtmlFormatHelper.CreateHtmlFormat(emailText);
}
[/sourcecode]
After clicking share you can see which apps are share targets, for example an email client
Previewing before sending
This is how easy it is to let an app share content!
We have now everything we need, and next time we will clean up the UI and prepare the application for publication!
Comments
Last modified on 2012-12-04