Tutorial about developing android flashlight / torchlight application. Very simple application with minimal design and implementation.
Programming
A reduction in DevOps tickets not only drives IT efficiency, but also creates a cultural shift where teams look forward to rapidly achieving accomplishments. Business stakeholders operate in an agile environment where no change request is too small, and rapidly testing business ideas is the new normal.
Today, the Windows and Windows Server teams announced that Windows 8 and Windows Server 2012 have been released to manufacturing. in keeping with our goal of delivering great tools on the same cadence as our platforms, I’m thrilled to announce that we have completed final builds of Visual Studio 2012 and .NET 4.5.
This has been an exciting road for all of us involved in these projects, and we’re glad to be able to deliver these to our customers.
For MSDN Subscribers, the bits will be available for download on August 15th. Visual Studio Professional, Premium, Test Professional, and Ultimate with MSDN Subscribers can also sign up for a free, one year developer account for Windows Store today, with Windows Phone developer accounts coming soon.
We’re also planning an exciting launch event on September 12th, so mark your calendars, and visit http://visualstudiolaunch.com for more details.
Thank you to all of you that have taken the time to try the Visual Studio 2012 Developer Preview, Beta, and Release Candidate releases. your feedback has been very helpful.
See C++/CX part 0 of [N]: an Introduction for an introduction to this series.
The hat (^) is one of the most prominent features of C++/CX–it’s hard not to notice it when one first sees C++/CX code. so, what exactly is a ^ type? a hat type is a smart pointer type that (1) automatically manages the lifetime of a Windows Runtime object and (2) provides automatic type conversion capabilities to simplify use of Windows Runtime objects.
We’ll start off by discussing how Windows Runtime objects are used via WRL, then explain how the C++/CX hat works to make things simpler. For demonstration purposes, we’ll use the following modified version of the Number class that we introduced in part 1:
public interface struct IGetValue { int GetValue() = 0; }; public interface struct ISetValue { void SetValue(int value) = 0; }; public ref class Number sealed : public IGetValue, ISetValue { public: Number() : _value(0) { } virtual int GetValue() { return _value; } virtual void SetValue(int value) { _value = value; } private: int _value; };
In this modified Number implementation, we define a pair of interfaces, IGetValue and ISetValue, that declare the two member functions of Number; Number then implements these two interfaces. Otherwise, things should look pretty familiar.
Note that Number actually implements three Windows Runtime interfaces: in addition to IGetValue and ISetValue, the compiler still generates the __INumberPublicNonVirtuals interface, which Number implements. Because all of the members of Number are declared by explicitly implemented interfaces (IGetValue and ISetValue), the compiler-generated __INumberPublicNonVirtuals does not declare any members. this interface is still required, though, as it is the default interface for the Number type. Every runtime type must have one default interface, and the default interface should almost always be unique to the class. We’ll see why the default interface is important a bit later.
Lifetime Management
Windows Runtime reference types use reference counting for object lifetime management. All Windows Runtime interfaces (including all three of the interfaces implemented by Number) derive directly from the IInspectable interface, which itself derives from the COM IUnknown interface. IUnknown declares three member functions that are used to control the lifetime of an object and to allow type conversion.
The MSDN article “Rules for Managing Reference Counts” has a thorough overview of how IUnknown lifetime management works. the principles are quite straightforward, though: whenever you create a new reference to an object, you must call IUnknown::AddRef to increment its reference count; whenever you “destroy” a reference to an object, you must call IUnknown::Release to decrement the reference count. the reference count is initialized to zero, and after a series of calls to AddRef and Release, when the reference count reaches zero again, the object destroys itself.
Of course, when programming in C++, we should rarely–practically never–call AddRef and Release directly. Instead, we should prefer wherever possible to use a smart pointer that automatically makes these calls when they are required. Use of a smart pointer helps to ensure that objects are neither leaked due to a missed Release nor prematurely destroyed due to a premature Release or failure to AddRef.
ATL includes CComPtr and a family of related smart pointers that have long been used in COM programming for automatically managing the reference counting of objects that implement IUnknown. WRL includes ComPtr, which is an improved and modernized CComPtr (an example improvement: ComPtr does not overload the unary & like CComPtr does).
For those who have not done much COM programming and are unfamiliar with ComPtrs: if you’ve used shared_ptr (included as part of C++11, C++ TR1, and Boost), ComPtr has effectively the same behavior with respect to lifetime management. the mechanism is different (ComPtr makes use of the internal reference counting provided by IUnknown, while shared_ptr supports arbitrary types and must thus use an external reference count), but the lifetime management behavior is the same.
The C++/CX hat has exactly the same lifetime management semantics as a ComPtr. when a T^ is copied, AddRef is called to increment the reference count, and when a T^ goes out of scope or is reassigned, Release is called to decrement the reference count. We can consider a simple example to demonstrate the reference counting behavior:
{ T^ t0 = ref new A(); T^ t1 = ref new B(); t0 = t1; t0 = nullptr; }
First, we create an A object and give ownership of it to t0. the reference count of this A object is 1 because there is one T^ that has a reference to it. We then create a B object and give ownership of it to t1. the reference count of this B object is also 1.
The end result of t0 = t1 is that both t0 and t1 point to the same object. this must be done in three steps. First, t1->AddRef() is called to increment the reference count of the B object, because t1 is gaining ownership of the object. second, t0->Release() is called to release t0′s ownership of the A object. this causes the reference count of the A object to drop to zero and the A object destroys itself. this causes the reference count of the B object to increase to 2. third and finally, t1 is set to point to the B object.
We then assign t0 = nullptr. this “resets” t0 to be null, which causes it to release its ownership of the B object. this calls t0->Release(), causing the reference count of the B object to decrease to 1.
Finally, execution will reach the closing brace of the block: }. At this point, all of the local variables are destroyed, in reverse order. First, t1 is destroyed (the smart pointer, not the object pointed to). this calls t1->Release(), causing the reference count of the B object to drop to zero, so the B object destroys itself. t0 is then destroyed, which is a no-op because it is null.
If lifetime management was our only concern, there wouldn’t really be a need for the ^ at all: ComPtr<T> is sufficient to manage object lifetime.
Type Conversion
In C++, some type conversions involving class types are implicit; others may be performed using a cast or a series of casts. For example, if Number and the interfaces it implements were ordinary C++ types and not Windows Runtime types, conversion from Number* to IGetValue* would be implicit, and we could convert from IGetValue* to Number* using a static_cast or a dynamic_cast.
These conversions do not work with Windows Runtime reference types because the implementation of a reference type is opaque and the layout of a reference type in memory is left unspecified. a reference type implemented in C# may be laid out in memory differently from an equivalent reference type implemented in C++. Thus, we cannot rely on C++ language specific features like implicit derived-to-base conversions and casts when working directly with Windows Runtime types.
To perform these conversions, we must instead use the third member function of the IUnknown interface: IUnknown::QueryInterface. this member function can be considered as a language-neutral dynamic_cast: it attempts to perform a conversion to the specified interface and returns whether the conversion succeeded. Because each runtime type implements the IUnknown interface and provides its own definition for QueryInterface, it can do whatever is required to get the correct interface pointer in the language and framework with which it is implemented.
Using an object via WRL
Let’s take a look at how we’d use our Number class via WRL. this example accepts an instance of Number and calls SetValue to set the value and GetValue to get the value back. (Error checking has been omitted for brevity.)
void F(ComPtr<__INumberPublicNonVirtuals> const& numberIf) { // Get a pointer to the object’s ISetValue interface and set the value: ComPtr<ISetValue> setValueIf; numberIf.As(&setValueIf); setValueIf->SetValue(42); // Get a pointer to the object’s IGetValue interface and get the value: ComPtr<IGetValue> getValueIf; numberIf.As(&getValueIf); int value = 0; getValueIf->GetValue(&value); }
The As member function template of the WRL ComPtr simply encapsulates a call to IUnknown::QueryInterface in a way that helps to prevent common programming errors. We use this first to get the ISetValue interface pointer to call SetValue then again to get the IGetValue interface pointer to call GetValue.
This would be a lot simpler if we obtained a Number* and called SetValue and GetValue via that pointer. unfortunately, we can’t do that: recall that the implementation of a reference type is opaque and that we only ever interact with an object via a pointer to one of the interfaces that it implements. this means that we can never have a Number*; there is really no such thing. rather, we can only refer to a Number object via an IGetValue*, an ISetValue*, or an __INumberPublicNonVirtuals*.
This is an awful lot of code just to call two member functions and this example demonstrates one of the key hurdles that we have to overcome to make it easier to use Windows Runtime types. unlike COM, Windows Runtime does not allow an interface to derive from another Windows Runtime interface; all interfaces must derive directly from IInspectable. each interface is independent, and we can only interact with an object via interfaces, so if we are using a type that implements multiple interfaces (which many types do), we are stuck having to write a lot of rather verbose type conversion code so that we can obtain the correct interface pointer to make each function call.
Using an object via C++/CX
One of the key advantages of C++/CX is that the compiler knows which types are Windows Runtime types. it has access to the Windows Metadata (WinMD) file that defines each interface and runtime type, so–among other things–it knows the set of interfaces that each runtime type implements. For instance, the compiler knows that the Number type implements the ISetValue and IGetValue interfaces, because the metadata specifies that it does. the compiler is able to use this type information to automatically generate type conversion code.
Consider the following C++/CX example, which is equivalent to the WRL example that we presented:
void F(Number^ number) { ISetValue^ setValueIf = number; setValueIf->SetValue(42); IGetValue^ getValueIf = number; int value = getValueIf->GetValue(); }
Because the compiler knows that the Number type implements the ISetValue and IGetValue interfaces, it allows implicit conversion from Number^ to ISetValue^ and IGetValue^. this implicit conversion causes the compiler to generate a call to IUnknown::QueryInterface to get the right interface pointer. aside from the cleaner syntax, there’s really no magic here: the compiler is just generating the type conversion code that we otherwise would have to write ourselves.
dynamic_cast also works much as we’d expect: we can, for example, amend this example to obtain the IGetValue^ from the ISetValue^:
void F(Number^ number) { ISetValue^ setValueIf = number; setValueIf->SetValue(42); IGetValue^ getValueIf = dynamic_cast<IGetValue^>(setValueIf); int value = getValueIf->GetValue(); }
This example has the same behavior as the first example, we just take different steps to get that same behavior. dynamic_cast can return nullptr if the cast fails (though we know that it will succeed in this specific case). C++/CX also provides safe_cast, which throws a Platform::InvalidCastException exception if the cast fails.
When we discussed the WRL example above, we noted that there’s no such thing as a Number*: we only ever work with interface pointers. this begs the question: what is a Number^? At runtime, a Number^ is a __INumberPublicNonVirtuals^. a hat that refers to a runtime type (and not an interface) actually holds a pointer to the default interface of that runtime type.
At compile-time, though, the compiler treats Number^ as if it refers to the whole Number object. the compiler aggregates all of the members of all of the interfaces implemented by Number and allows all of those members to be called directly via a Number^. We can use a Number^ as if it were an IGetValue^ or an ISetValue^ and the compiler will inject the required calls to QueryInterface to perform the conversions required to make the function call.
Therefore, we can shorten our C++/CX program further:
void F(Number^ number) { number->SetValue(42); int value = number->GetValue(); }
This code does exactly the same thing as our first C++/CX example and as our WRL example. There’s still no magic: the compiler is simply generating all of the boilerplate to perform the type conversion required to make each function call.
You may have noticed that this example is much shorter and less verbose than the WRL example that we started with.
All of the boilerplate is gone and we’re left with code that–aside from the ^ and ref that tell the compiler we are dealing with Windows Runtime types–looks exactly like similar C++ code that interacts with ordinary C++ types. this is the point, though: ideally our code that uses Windows Runtime types should be as similar as possible to code that uses C++ types.
Final Notes
Both ComPtr<T> and T^ are “no-overhead” smart pointers: the size of each is the same as the size of an ordinary pointer, and operations using them do not do any unnecessary work. If you need to interoperate between code that uses C++/CX and code that uses WRL, you can simply use reinterpret_cast to convert a T^ to a T*:
ABI::ISetValue* setValuePtr = reinterpret_cast(setValueIf);
(The ABI level definitions of types are defined in namespaces under the ABI namespace so that they do not conflict with the “high-level” definitions of the types used by C++/CX, which are defined under the global namespace.)
In addition to its type conversion capabilities, the hat provides other benefits that could not otherwise be accomplished via use of an ordinary smart pointer like ComPtr. one of the most important of these benefits is that the hat can be used uniformly, everywhere. a member function that takes an interface pointer as an argument is declared as taking a raw pointer (this is part of the Windows Runtime ABI, which is designed to be simple and language-neutral, and thus knows nothing of what a C++ smart pointer is). so, while one can use ComPtr most places, raw pointers still need to be used at the ABI boundary, and there is room for subtle (and not-so-subtle) programming errors.
With C++/CX, the compiler already transforms member function signatures to translate between exceptions and HRESULTs and the compiler is also able to inject conversions from T^ to T* where required, substantially reducing the opportunity for programming errors.
In previous posts, I’ve alluded to one of our key focus areas for Visual Studio 2012 being the theme of connected devices and continuous services. This includes creating a top-notch set of tools in Visual Studio 2012 to both design and build amazing Windows apps and the services that back them.
With Windows 8 and Visual Studio 2012 released, I’ve decided to explore and document the end-to-end development of a basic Windows Store app that uses services on the backend. for this task I’ve chosen to use Visual Studio Express 2012 for Windows 8.
My primary goal here is to highlight just how straightforward it is now to build a modern, connected experience. for the sake of simplicity and minimizing the coding involved, I’ll build a simple RSS reader: “News by Soma.” In this two-part blog post, I’ll document the experience of building this app. Hopefully my notes are detailed enough that you can follow along and build (and then expand upon) your own version of this app, as well.
Getting Started
Since my goal here is to showcase the full end-to-end experience, I’m starting from a Windows 8 system without Visual Studio installed. I download the Visual Studio Express 2012 for Windows 8 installer, click through the setup wizard, and begin the installation:
Within a few minutes, I have my development environment up and running:
From File | new Project, I create a new Windows Store “Grid App (XAML)” using C#:
The Grid App template maps nicely to the scenario I have in mind, that of being able to have multiple RSS feeds (the “groups”), each of which contains multiple posts (the “items” in each group). the template provides all of the infrastructure necessary to build such an app very quickly. After the project is created, I press F5 to see my (not yet modified) app in action:
With the basic structure in place, I can now begin customizing it for my specific needs.
Configuring Basic App Properties
I of course want my app to look nice, so I spend a little time in Visual Studio customizing its properties via the Package.appxmanifest file. Opening this file presents a detailed editor in Visual Studio:
Here I configure both my app’s tile (for the Windows Start page) and splash screen (displayed when the app starts) the way I want them. This involves creating several images, which I do by starting with a picture of myself, and creating various cuts of it in Paint to fit the sizes specified in the configuration editor (e.g. 150×150 for the Logo, 310×150 for the Wide Logo, etc.):
This results in a nice tile experience when the app is pinned to my Start screen, whether using the Small tile:
or the Wide tile:
My app also now has a nice splash screen experience:
Getting Data
The Grid App template gets all of its data from a SampleDataSource type (in the file DataModelSampleDataSource.cs) that exposes an AllGroups property which returns an ObservableCollection<SampleDataGroup>. This enables the UI to data bind to a collection of groups, each represented by the generic data model type SampleDataGroup. SampleDataGroup in turn contains a collection of SampleDataItem instances.
In my app, SampleDataGroup maps to RSS feeds, and SampleDataItem maps to the entries in a feed. Rather than replace SampleDataGroup and SampleDataItem with my own custom data types, for the sake of simplicity I simply repurpose them. the template includes on these types enough relevant properties so I don’t actually need to modify them at all; rather, I just need to modify SampleDataSource to populate and return instances of these with the right data.
There’s a fair amount of code in the SampleDataSource type included with the template, much of which is about populating the “lorem ipsum” nonsensical text items shown in the previous screenshots. I delete all of that, and replace the AllGroups property with a simple static declaration (fixing up all of the references in the process):
public static readonly ObservableCollection<SampleDataGroup> AllGroups =
new ObservableCollection<SampleDataGroup>();
My UI can continue binding to AllGroups, which is initially empty. as new groups (RSS feeds) are added to AllGroups, the UI will be notified automatically of the addition and will update itself accordingly. Therefore, I need to expose a method to add groups:
public static async Task<bool> AddGroupForFeedAsync(string feedUrl)
{
if (SampleDataSource.GetGroup(feedUrl) != null) return false;
var feed = await new SyndicationClient().RetrieveFeedAsync(new Uri(feedUrl));
var feedGroup = new SampleDataGroup(
uniqueId: feedUrl,
title: feed.Title != null ? feed.Title.Text : null,
subtitle: feed.Subtitle != null ? feed.Subtitle.Text : null,
imagePath: feed.ImageUri != null ? feed.ImageUri.ToString() : null,
description: null);
foreach (var i in feed.Items)
{
string imagePath = GetImageFromPostContents(i);
if (imagePath != null && feedGroup.Image == null)
feedGroup.SetImage(imagePath);
feedGroup.Items.Add(new SampleDataItem(
uniqueId: i.Id, title: i.Title.Text, subtitle: null, imagePath: imagePath,
description: null, content: i.Summary.Text, @group: feedGroup));
}
AllGroups.Add(feedGroup);
return true;
}
Using the SyndicationClient class from Windows Runtime (WinRT), and the new async/await keywords in C#, I asynchronously download the feed at the requested URL. I then create a SampleDataGroup to represent the feed, populating it with information about the feed from the SyndicationFeed I was handed. And then for each item in the syndication feed, I map its properties into a new SampleDataItem. These items are all added to the group, and then the group is added to the AllGroups collection. with that, I’m almost done teaching the app how to get all of the data it needs.
The one remaining piece of code here has to do with images. the UI knows how to bind to SampleDataGroup and SampleDataItem, including showing an image for every group and item. Typically, RSS feed items aren’t associated with an image, but I want something appropriate and interesting to show up in the UI for each feed item whenever possible. as such, I have one more function that parses the RSS item looking for PNG and JPG images, returning the first one with a fully-qualified path it finds:
private static string GetImageFromPostContents(SyndicationItem item)
{
return Regex.Matches(item.Summary.Text,
“href\s*=\s*(?:”(?<1>[^"]*)”|(?<1>\S+))”,
RegexOptions.None)
.Cast<Match>()
.Where(m =>
{
Uri url;
if (Uri.TryCreate(m.Groups[1].value, UriKind.Absolute, out url))
{
string ext = Path.GetExtension(url.AbsolutePath).ToLower();
if (ext == “.png” || ext == “.jpg”) return true;
}
return false;
})
.Select(m => m.Groups[1].Value)
.FirstOrDefault();
}
Finally, before I can really run the app, I need one more change: to modify the GroupedItemsPage.LoadState method (in the file GroupedItemsPage.xaml.cs) to use this new SampleDataSource.AddGroupForFeedAsync method. I replace the LoadState from the template with one line to hook up AllGroups to the UI, and add a few additional lines to initially populate the UI with a few blogs:
protected override async void LoadState(
object navigationParameter, Dictionary<string, object> pageState)
{
this.DefaultViewModel["Groups"] = SampleDataSource.AllGroups;
// temporary hardcoded feeds
await SampleDataSource.AddGroupForFeedAsync(“http://blogs.msdn.com/b/somasegar/rss.aspx”);
await SampleDataSource.AddGroupForFeedAsync(“http://blogs.msdn.com/b/jasonz/rss.aspx”);
await SampleDataSource.AddGroupForFeedAsync(“http://blogs.msdn.com/b/visualstudio/rss.aspx”);
}
And that’s it. I’m now able to F5 again to see RSS data populated into my app:
Main grouped-items page:
Group page (when I click on a group header on the main page):
Item page (when I click on an item on the main or group pages):
One thing to note here is that I haven’t modified the default template for the item page yet, and it uses a RichTextBlock to display the post’s contents. as a result, the HTML from the RSS item is displayed as the HTML source rather than as rendered content.
To make this a bit nicer, I can update the template to render the HTML. the ItemDetailPage.xaml displays the SampleDataItem using a FlipView control, with a DataTemplate that uses a UserControl for the template item. I replace the contents of that UserControl (which in the original code contains the RichTextBlock-related controls) with the following XAML that uses a WebView control:
<UserControl Loaded=”StartLayoutUpdates” Unloaded=”StopLayoutUpdates”>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=”Auto”/>
<RowDefinition Height=”*”/>
</Grid.RowDefinitions>
<TextBlock Margin=”10,10,10,10″ Text=”{Binding Title}”
Style=”{StaticResource SubheaderTextStyle}”
IsHitTestVisible=”false” Grid.Row=”0″ />
<WebView local:WebViewExtension.HtmlSource=”{Binding Content}” Grid.Row=”1″/>
</Grid>
</UserControl>
The WebView control itself doesn’t have a property that allows me to bind the WebView directly to the HTML string contentI already have, but I found code from Tim Heuer for an HtmlSource extension property that uses WebView’s NavigateToString method to achieve the same thing. And with that addition to my project, I now see the feed item rendered nicely in the app:
User Interaction
In the previous section on getting Data, I simply hardcoded which feeds I wanted the app to display. However, I want to allow the user to enter such their own choices of feeds manually, so I’ll augment the template UI slightly to enable this user interaction.
One of the common design elements of a Windows Store app is an “app bar.” I’ll use an AppBar control to allow the user to enter a URL into a TextBox and click an Add button to get the feed included in the app. I drag an AppBar control from the Visual Studio Toolbox onto the designer for my GroupedItemsPage.xaml file:
I then move the resulting XAML into a Page.BottomAppBar element so that the app bar shows up at the bottom of my app:
<Page.BottomAppBar>
<AppBar>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Orientation=”Horizontal”/>
<StackPanel Grid.Column=”1″ HorizontalAlignment=”Right” Orientation=”Horizontal”/>
</Grid>
</AppBar>
</Page.BottomAppBar>
And I add three controls to the left-aligned StackPanel:
<TextBox x:Name=”txtUrl” VerticalAlignment=”Center” />
<Button x:Name=”btnAddFeed” Style=”{StaticResource AddAppBarButtonStyle}” Click=”btnAddFeed_Click” />
<ProgressRing x:Name=”prAddFeed” IsActive=”false”
Foreground=”{StaticResource ApplicationForegroundThemeBrush} “/>
(Note that AddAppBarButtonStyle, along with ~140 other styles for AppBar buttons, is defined in the StandardStyles.xaml file included in the Grid App template, but it’s commented out by default. I just uncomment it so that I can use it here.)
To complete the experience, I need to implement the btnAddFeed_Click method (in the GroupedItemsPage.xaml.cs file), wiring it up to the SampleDataSource.AddGroupForFeedAsync method I previously wrote (and, of course, removing the three lines I previously hardcoded in LoadState):
async void btnAddFeed_Click(object sender, RoutedEventArgs e)
{
await AddFeedAsync(txtUrl.Text);
}
async Task AddFeedAsync(string feed)
{
txtUrl.IsEnabled = false;
btnAddFeed.IsEnabled = false;
prAddFeed.IsActive = true;
try
{
await SampleDataSource.AddGroupForFeedAsync(feed);
}
catch (Exception exc)
{
var dlg = new MessageDialog(exc.Message).ShowAsync();
}
finally
{
txtUrl.Text = string.empty;
txtUrl.IsEnabled = true;
btnAddFeed.IsEnabled = true;
prAddFeed.IsActive = false;
}
}
With that in place, when a user brings up the app bar, types in a URL, and clicks the Add button, the feed will be added, and for the duration of the add operation, the app will display the progress ring and prevent the user from adding additional feeds.
Enabling Live Tiles
Windows 8 provides multiple mechanisms for creating live tiles on the Start screen. for the purposes of my app, I want to update my live tile to list the current feeds in the app.
To do this, in GroupedItemPage.xaml.cs I create a function to generate the template XML expected by the TileUpdateManager, and I use a TileUpdater to push the visuals to the tile:
private void UpdateTile()
{
var groups = SampleDataSource.AllGroups.ToList();
var xml = new XmlDocument();
xml.LoadXml(
string.Format(
@”<?xml version=”"1.0″” encoding=”"utf-8″” ?>
<tile>
<visual branding=”"none”">
<binding template=”"TileWideText01″”>
<text id=”"1″”>News by Soma</text>
<text id=”"2″”>{0}</text>
<text id=”"3″”>{1}</text>
<text id=”"4″”>{2}</text>
</binding>
<binding template=”"TileSquarePeekImageAndText01″”>
<image id=”"1″” src=”"ms-appx:///Assets/Logo.png”" alt=”"alt text”"/>
<text id=”"1″”>News by Soma</text>
<text id=”"2″”>{0}</text>
<text id=”"3″”>{1}</text>
<text id=”"4″”>{2}</text>
</binding>
</visual>
</tile>”,
groups.Count > 0 ? groups[0].Title : “”,
groups.Count > 1 ? groups[1].Title : “”,
groups.Count > 2 ? groups[2].Title : “”));
TileUpdateManager.CreateTileUpdaterForApplication().Update(new TileNotification(xml));
}
(For your own apps, the “App tiles and badges” Windows SDK Sample includes some helpful code for working with tiles.)
Then I modify GroupedItemsPage.LoadState to call this UpdateTile method after successfully adding a feed:
if (await SampleDataSource.AddGroupForFeedAsync(feed))
{
UpdateTile();
}
Now, after starting my app and adding my blog feed and Jason Zander’s blog feed, I can see this information available on my tile:
Enabling Search
Having integrated with live tiles, the next feature I want to integrate is Search. Windows 8 provides the Search charm that enables users to search relevant apps from anywhere in the system.
To start this, I right-click on my project in Visual Studio and select Add | new Item…, picking “Search Contract” as the item to be added:
This does a few things:
- It updates my package manifest to declare Search:

- It adds a new SearchResultsPage.xaml to my project.
- It augments my App.xaml.cs with the necessary OnSearchActivated method override to correctly connect a Search request from the system with my new SearchResultsPage.xaml.
The added SearchResultsPage.xaml (and associated SearchResultsPage.xaml.cs) already contains most of the UI and logic necessary to make this scenario work. so as with the other templates we’ve seen Visual Studio create, I just need to plug in the logic specific to my application and its data.
The SearchResultsPage.xaml.cs file includes a simple view model type called Filter. This type is used by the template to represent a group of search results, such that a user can see and select from multiple categories of results to quickly narrow down their choices. to simplify coding a bit, I first modify this Filter to make it Filter<T> and add a Results property to it… that way, I can perform one search and populate all of the filters, such that as the user chooses different filter categories in the UI, I don’t have to keep re-searching:
private sealed class Filter<T> : News_by_Soma.Common.BindableBase
{
…
private List<T> _results;
public Filter(string name, IEnumerable<T> results, bool active = false)
{
…
this.Results = results.ToList();
}
public int Count { get { return _results.Count; } }
public List<T> Results
{
get { return _results; }
set { if (this.SetProperty(ref _results, value)) this.OnPropertyChanged(“Description”); }
}
…
}
In the page’s LoadState override, I replace the hardcoded search results filter group that was provided in the template:
var filterList = new List<Filter>();
filterList.Add(new Filter(“All”, 0, true));
with code to actually do the search across each RSS feed, creating a filter for each feed, and then creating an “All” filter with aggregation of all of the results:
var filterList = new List<Filter<SampleDataItem>>(
from feed in SampleDataSource.AllGroups
select new Filter<SampleDataItem>(feed.Title,
feed.Items.Where(item => (item.Title != null && item.Title.Contains(queryText)) ||
(item.Content != null && item.Content.Contains(queryText))),
false));
filterList.Insert(0,
new Filter<SampleDataItem>(“All”, filterList.SelectMany(f => f.Results), true));
Next, in the Filter_SelectionChanged, I store the results into the DefaultViewModel:
this.DefaultViewModel["Results"] = selectedFilter.Results;
I then add an ItemClick event handler to the resultsListView control from the template. This navigates to the selected item when the user clicks on it:
private void resultsListView_ItemClick(object sender, ItemClickEventArgs e)
{
var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
this.Frame.Navigate(typeof(ItemDetailPage), itemId);
}
Finally, the SearchResultsPage.xaml page contains two lines of XAML that should be deleted. the Grid App template already includes the application name in the App.xaml file, so we don’t need to also configure that here:
<!– TODO: Update the following string to be the name of your app –>
<x:String x:Key=”AppName”>App Name</x:String>
With that, search is functioning in my application:
As it stands, this will only search the feeds that have been loaded into the app when the app’s main page loads. that works great if the search is performed while the app is running. if, however, the app isn’t running, its main page won’t have executed, and groups won’t have populated. if I were to persist feed information, then if the app hadn’t been running when the search request arrived, I could update the search logic to first load the feeds that had been persisted.
What’s Next?
In this first of two posts, I’ve explored getting up and running with Visual Studio Express 2012 for Windows 8, and using it to build a basic app that integrates with live tiles and search. In my next post, I’ll focus on extending this application via multiple backend services. Stay tuned…
As far back as 2005, cross-site scripting (XSS) was recognized as the most commonly reported type of software vulnerability. a more recent study by Veracode using data from the Web Hacking Incident Database shows that XSS is the most prevalent vulnerability in Web applications and the second most likely to be leveraged in real-world attacks.

Chart courtesy of Veracode; used by permission
Data from the Microsoft Security Response Center (MSRC) demonstrates the growth in reported XSS vulnerabilities:

Growth in reported XSS vulnerabilities 2004 – 2012 (first half)
The chart above illustrates how we are seeing XSS actually start to crowd out other types of reported vulnerabilities percentage-wise, year-over-year.
To help protect users, Internet Explorer pioneered the implementation of multiple overlapping mitigations targeting XSS, including httpOnly cookies, security=restricted IFRAMES, toStaticHTML(), and the IE XSS Filter. IE10 introduces support for the new HTML5 standard IFRAME Sandbox, which allows developers of Web applications to more tightly control the behavior of embedded content. We’re intent on continuing these investments, as real-world data continues to show an uptick in the relative quantity of XSS vulnerabilities in the wild.
To review the impact of the IE XSS Filter, we’ve done a deep analysis of all vulnerabilities reported to MSRC in the first half of 2012. This analysis has shown that currently the IE XSS Filter applies for 37% of all legitimate vulnerabilities that are reported to the MSRC. (For some perspective, another highly reported vulnerability class is memory safety, accounting for 24% of vulnerabilities within the same data set.)
The IE XSS Filter is just one example of how our browser’s threat-mitigation strategy doesn’t stop with memory safety mitigations like ASLR and DEP/NX. As more customers and businesses leverage Web technologies, mitigating XSS and other Web application vulnerabilities has become increasingly important. We are happy to see the impact mitigations have made against the threat of XSS, and are looking to continuously innovate in this space going forward.
—David Ross, Principal Security Software Engineer, Microsoft Security Response Center
Internet Explorer 9 introduced support for CSS 2D Transforms. Internet Explorer 10 Developer Preview added support for CSS 3D Transforms and CSS Animations. By tapping the power of your GPU and running asynchronously from regular JavaScript, these IE10 features provide a more performant and flexible alternative to traditional script-based animations for Web content.
In previous blog posts, we covered CSS 3D Transforms as well as CSS Animations and Transitions. In this post, we introduce a more “unconventional” use case for these technologies by describing the concept of “full-page animations” that can be used during the navigation process to add fluidity and continuity to browsing. Our target is to achieve a seamless browsing experience in which content smoothly appears into view when the user visits a page and transitions away when he clicks on a link or performs a relevant action.
These effects can be accomplished by transforming the HTML <body> element using CSS Animations. However, this use case presents some considerations that we felt were worthy of discussion, such as the effect of layout and sizing on transforming <body>, as well as how to appropriately time page navigations so that they mesh properly with our animations.
The code samples in this post use unprefixed CSS markup as supported by IE10 Release Preview; other browsers may require vendor prefixes for the CSS Animations and CSS Transforms properties used.
Transforming a Page’s Entire Content
CSS Transforms are defined on the stylistic properties of an HTML DOM Element. For example, the markup for rotating an element 45 degrees along its Z axis would look like this:
transform: rotateZ(45deg);
Attaching a transform to the <body> element of your HTML document works exactly the same way. so performing in order to declaratively add the same effect to your document’s <body> you could do something like this:
transform: rotateZ(45deg);
Let’s look at a before-and-after shot of a page when applying a transform to the body element:

Applying a rotateZ(45deg) transform to the body element of a document.
For three dimensional transformations, the CSS Transforms specification defines the perspective property that can be specified on the parent of the element that we transforming. when transforming the <body> element of your content, it has to be applied to the <html> element that resides above it in the DOM hierarchy. doing so is straightforward:
perspective: 500px;
Combining this with a rotateY(45deg) transform on the <body> element yields the following result:

Applying a rotate(45deg) transform to <body> with perspective: 500px set on <html>.
We can manipulate the transform-origin property on the body element for interesting results. Let’s look at a couple of examples:
transform-origin: 50% 100%;
transform: rotateX(45deg);
The above markup sets a rotation along X for the body element while shifting the origin of rotations to the bottom of the element using transform-origin. Effectively this rotates the document’s contents “into” the screen like this:

We can also manipulate the perspective-origin property on the root element of our document to achieve an off-axis projection effect. Changing the style for <html> to:
perspective: 500px;
perspective-origin: 90% 50%;
Our page now looks like this:

By using CSS Transforms, we can easily manipulate the visual appearance of the entirety of our page’s content. since the usual layout and sizing rules still apply, some transforms on the body element (particularly ones that use percentage values or rely on the transform-origin property) can result in different visual effects depending on the content of our page. Recall our previous rotateX(45deg) example with transform-origin set to 50% 100%.
Below you can see the results before and after the transform is applied.

Notice how the content does not actually pivot on the bottom of the window but rather at some point outside of the viewport. this is expected behavior for CSS Transforms: the <body> is laid out normally, then it is rotated along its bottom edge that is somewhere off screen. you will also notice that the actual foot print of the content has expanded (take a look at the scroll bars in the “after” picture) in order to accommodate the transformed content (the fact that we are using perspective projection makes this effect even more pronounced).
So how do we deal with arbitrarily sized content when applying transforms to our body element? Custom tailoring all content in order to ensure that the size of the body does not expand more than a certain amount may be unrealistic. instead, we can use a simple HTML/CSS pattern that allows us to fix the size of the body element to that of the browser window and append content inside a wrapper <div>. The following markup achieves just that:
position: absolute;
The illustration below shows what happens when a page is scrolled vertically and we apply a rotateY(45deg) transform to the <body> element of our document directly (left) and using the wrapper pattern (right):

The direct application of the transform results in a skewed visual result due to the off-axis projection (since we are no longer looking at the “center” of the body element). Using the wrapper pattern ensures that the <html> element’s perspective-origin property (50% 50% by default) will always be correctly centered with relation to the <body> element, giving us a pleasant visual effect.
By utilizing the above pattern and setting up CSS Transforms with percentage values whenever possible, we can affect our <body> element in consistent ways, regardless of the size of its contents.
From Transforms to Animations
Having sorted out the intricacies of applying CSS Transforms to the <body> element, CSS Animations are the next step. By following the principles described above, we can create animations that bring our Web content into view (or remove it from view) in interesting ways.
Consider this basic @keyframes rule:
@keyframes rotateInLeft {
transform-origin: 0% 0%;
transform: rotateY(180deg);
transform-origin: 0% 0%;
transform: rotateY(0deg);
When applied to an element, this animation will cause it to rotate on its left side. When applied to a <body> element that uses our wrapper pattern the visual result is more interesting. the document will actually rotate from outside of the visible area of the browser window and into full view:

Similarly, we can compose animations that fluidly remove our Web content from view. For example, if we wanted our page to disappear into the distance while rotating, we could use something like this:
@keyframes whirlOut {
transform: scale(0) rotateZ(1260deg);
With the visual result being:

Since we can use the full power of CSS Animations to affect the entirety of our Web content, we have a lot of flexibility in terms of generating these page effects (and we are certainly not limited to just using CSS Transforms). But once we have composed the effects that we want to apply to our content, how do we cause them to trigger during the page navigation process?
Attaching Animations to <body>
Our goal is to use trigger animations at strategic times during the browser experience in order to give the appearance of content transitioning into view when a page loads and out of view when the user clicks on a link.
The first intuitive place to add an animation to the body element would be the onload JavaScript event. as it turns out however, adding an animation when onload fires is actually too late. this event actually triggers when the entirety of the content in our page has finished loading (including any images or other bandwidth-intensive resources). Attaching an animation to onload on a bandwidth-intensive page would result in our content displaying “normally,” followed by the animation triggering and re-bringing the content into view. Not exactly the effect that we were aiming for.
Alternatively, we could utilize the DOMContentLoaded event that triggers when the browser has finished parsing the DOM structure of our content (but potentially before resources have finished loading). the IE Test Drive DOMContentLoaded demo illustrates the difference between these two events. However, in cases of complex Web content, a modern browser may choose to perform “progressive” rendering, displaying the page before the entirety of the DOM tree has been loaded. In these situations, the visual result would be similar to the onload scenario.
The optimal place to set up an animation that transitions our page content in view is inline at the top of the <body> element. this ensures that the animation will commence right as the content is being rendered (and that the starting position of the content will be that of the from keyframe of our selected animation). a pleasant side effect of this approach is that the animation may actually mask any progressive rendering, re-layout or resource loading that can occur with complex content.
Setting up the animations that transition our content out of view is also interesting. One could assume that we could attach an onclick handler to all elements of interest in our content (for instance all <a> tags) and just set the relevant animation properties (animation-name, animation-duration, etc.) in the callback function. However, if we do not actually delay the navigation from happening, we will not see our expected fluid transition.
This is a good opportunity to utilize the animation events described in the CSS Animations specification. In particular, we can use the animationend event to detect when the animation has completed and then trigger a navigation (by setting window.location.href, for instance). thus our onclick will trigger the “remove-from-view” animation and register a handler for animationend on <body> that will ensure that the navigation event occurs.
Live Demo Available
We’ve created a demonstration and tutorial on bringing pages alive with CSS Transforms & Animations that provide depth and examples beyond what we’ve been able to show here. the tutorial itself utilizes full page animations during page navigation that work in Internet Explorer 10 on Windows 8 as well as recent versions of Chrome and Firefox..
To simply enjoy the page-to-page animations, step through the pages of the tutorial using the “Continue to …” links in the lower right corner of each page.
At the end of the tutorial we provide some additional guidance and sample code on how to incorporate these animations with your own Web content.
Conclusion
CSS Transforms and CSS Animations are two powerful feature-sets that enable richer and more immersive Web experiences. this blog post outlined the considerations of using CSS Transforms and CSS Animations to bring the entirety of your Web content to life. With a small amount of effort you can create Web pages (even static ones) that provide a fluid and almost app-like navigation experience.
—Charilaos “Harris” Papadopoulos, Program Manager Intern, Internet Explorer Graphics
Hi, I’m Andy Rich, a tester on the C++ frontend compiler and one of the primary testers of the C++/CX language extensions. if you’re like me, making use of a technology without understanding how it works can be confusing and frustrating. This blog post will help explain how XAML and C++ work together in the build system to make a Windows Store application that still respects the C++ language build model and syntax. (Note: this blog post is targeted towards Windows Store app developers.)
The Build Process
From a user-facing standpoint, Pages and other custom controls are really a trio of user-editable files. For example, the definition of the class MainPage is comprised of three files: MainPage.xaml, MainPage.xaml.h, and MainPage.xaml.cpp. both mainpage.xaml and mainpage.xaml.h contribute to the actual definition of the MainPage class, while MainPage.xaml.cpp provides the method implementations for those methods defined in MainPage.xaml.h. however, how this actually works in practice is far more complex.
This drawing is very complex, so please bear with me while I break it down into its constituent pieces.
Every box in the diagram represents a file. the light-blue files on the left side of the diagram are the files which the user edits. these are the only files that typically show up in the Solution Explorer. I’ll speak specifically about MainPage.xaml and its associated files, but this same process occurs for all xaml/h/cpp trios in the project.
The first step in the build is XAML compilation, which will actually occur in several steps. First, the user-edited MainPage.xaml file is processed to generate MainPage.g.h. This file is special in that it is processed at design-time (that is, you do not need to invoke a build in order to have this file be updated). the reason for this is that edits you make to MainPage.xaml can change the contents of the MainPage class, and you want those changes to be reflected in your Intellisense without requiring a rebuild. Except for this step, all of the other steps only occur when a user invokes a Build.
Partial Classes
You may note that the build process introduces a problem: the class MainPage actually has two definitions, one that comes from MainPage.g.h:
partial ref class MainPage : public ::Windows::UI::Xaml::Controls::Page,
public ::Windows::UI::Xaml::Markup::IComponentConnector
{
public:
void InitializeComponent();
virtual void Connect(int connectionId, ::Platform::Object^ target);
private:
bool _contentLoaded;
};
And one that comes from MainPage.xaml.h:
public ref class MainPage sealed
{
public:
MainPage();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
};
This issue is reconciled via a new language extension: Partial Classes.
The compiler parsing of partial classes is actually fairly straightforward. First, all partial definitions for a class must be within one translation unit. Second, all class definitions must be marked with the keyword partial except for the very last definition (sometimes referred to as the ‘final’ definition). during parsing, the partial definitions are deferred by the compiler until the final definition is seen, at which point all of the partial definitions (along with the final definition) are combined together and parsed as one definition. This feature is what enables both the XAML-compiler-generated file MainPage.g.h and the user-editable file MainPage.xaml.h to contribute to the definition of the MainPage class.
Compilation
For compilation, MainPage.g.h is included in MainPage.xaml.h, which is further included in MainPage.xaml.cpp. these files are compiled by the C++ compiler to produce MainPage.obj. (This compilation is represented by the red lines in the above diagram.) MainPage.obj, along with the other obj files that are available at this stage are passed through the linker with the switch /WINMD:ONLY to generate the Windows Metadata (WinMD) file for the project. This process is denoted in the diagram by the orange line. at this stage we are not linking the final executable, only producing the WinMD file, because MainPage.obj still contains some unresolved externals for the MainPage class, namely any functions which are defined in MainPage.g.h (typically the InitializeComponent and Connect functions). these definitions were generated by the XAML compiler and placed into MainPage.g.hpp, which will be compiled at a later stage.
MainPage.g.hpp, along with the *.g.hpp files for the other XAML files in the project, will be included in a file called XamlTypeInfo.g.cpp. This is for build performance optimization: these various .hpp files do not need to be compiled separately but can be built as one translation unit along with XamlTypeInfo.g.cpp, reducing the number of compiler invocations required to build the project.
Data Binding and XamlTypeInfo
Data binding is a key feature of XAML architecture, and enables advanced design patterns such as MVVM. C++ fully supports data binding; however, in order for the XAML architecture to perform data binding, it needs to be able to take the string representation of a field (such as “FullName”) and turn that into a property getter call against an object. in the managed world, this can be accomplished with reflection, but native C++ does not have a built-in reflection model.
Instead, the XAML compiler (which is itself a .NET application) loads the WinMD file for the project, reflects upon it, and generates C++ source that ends up in the XamlTypeInfo.g.cpp file. It will generate the necessary data binding source for any public class marked with the Bindable attribute.
It may be instructive to look at the definition of a data-bindable class and see what source is generated that enables the data binding to succeed. Here is a simple bindable class definition:
[Windows::UI::Xaml::Data::Bindable]
public ref class SampleBindableClass sealed {
public:
property Platform::String^ FullName;
};
When this is compiled, as the class definition is public, it will end up in the WinMD file as seen here:
This WinMD is processed by the XAML compiler and adds source to two important functions within XamlTypeInfo.g.cpp: CreateXamlType and CreateXamlMember.
The source added to CreateXamlType generates basic type information for the SampleBindableClass type, provides an Activator (a function that can create an instance of the class) and enumerates the members of the class:
if (typeName == L”BlogDemoApp.SampleBindableClass”)
{
XamlUserType^ userType = ref new XamlUserType(this, typeName, GetXamlTypeByName(L”Object”));
userType->KindOfType = ::Windows::UI::Xaml::Interop::TypeKind::Custom;
userType->Activator =
[]() -> Platform::Object^
{
return ref new ::BlogDemoApp::SampleBindableClass();
};
userType->AddMemberName(L”FullName”);
userType->SetIsBindable();
return userType;
}
Note how a lambda is used to adapt the call to ref new (which will return a SampleBindableClass^) into the Activator function (which always returns an Object^).
From String to Function Call
As I mentioned previously, the fundamental issue with data binding is transforming the text name of a property (in our example, “FullName”) into the getter and setter function calls for this property. This translation magic is implemented by the XamlMember class.
XamlMember stores two function pointers: Getter and Setter. these function pointers are defined against the base type Object^ (which all WinRT and fundamental types can convert to/from). A XamlUserType stores a map<String^, XamlUserType^>; when data binding requires a getter or setter to be called, the appropriate XamlUserType can be found in the map and its associated Getter or Setter function pointer can be invoked.
The source added to CreateXamlMember initializes these Getter and Setter function pointers for each property. these function pointers always have a parameter of type Object^ (the instance of the class to get from or set to) and either a return parameter of type Object^ (in the case of a getter) or have a second parameter of type Object^ (for setters).
if (longMemberName == L”BlogDemoApp.SampleBindableClass.FullName”)
{
XamlMember^ xamlMember = ref new XamlMember(this, L”FullName”, L”String”);
xamlMember->Getter =
[](Object^ instance) -> Object^
{
auto that = (::BlogDemoApp::SampleBindableClass^)instance;
return that->FullName;
};
xamlMember->Setter =
[](Object^ instance, Object^ value) -> void
{
auto that = (::BlogDemoApp::SampleBindableClass^)instance;
that->FullName = (::Platform::String^)value;
};
return xamlMember;
}
The two lambdas defined use the lambda ‘decay to pointer’ functionality to bind to Getter and Setter methods. these function pointers can then be called by the data binding infrastructure, passing in an object instance, in order to set or get a property based on only its name. Within the lambdas, the generated code adds the proper type casts in order to marshal to/from the actual types.
Final Linking and Final Thoughts
After compiling the xamltypeinfo.g.cpp file into xamltypeinfo.g.obj, we can then link this object file along with the other object files to generate the final executable for the program. This executable, along with the winmd file previously generated, and your xaml files, are packaged up into the app package that makes up your Windows Store Application.
A note: the Bindable attribute described in this post is one way to enable data binding in WinRT, but it is not the only way. Data binding can also be enabled on a class by implementing either the ICustomPropertyProvider interface or IMap<String^,Object^>. these other implementations would be useful if the Bindable attribute cannot be used, particularly if you want a non-public class to be data-bindable.
For additional info, I recommend looking at this walkthrough, which will guide you through building a fully-featured Windows Store Application in C++/XAML from the ground up. the Microsoft Patterns and Practices team has also developed a large application which demonstrates some best practices when developing Windows Store Applications in C++: project Hilo. the sources and documentation for this project can be found at http://hilo.codeplex.com/. (Note that this project may not yet be updated for the RTM release of Visual Studio.)
I hope this post has given you some insight into how user-edited files and generated files are compiled together to produce a functional (and valid) C++ program, and given you some insight into how the XAML data binding infrastructure actually works behind the scenes.


















