Monthly Archives: October 2011

Building Windows 8 Metro Apps in C# and XAML

Quick tour around what Metro programming means for .NET programmers. Example for WPF and SL changes and how to integrate your app in the Windows 8 Metro Style Apps.

METRO

Metro is the new name of application name to run on Windows 8. Applications are Touch UI enabled, full screen (also called immersive). Microsoft provides a user interface guidelines. Windows 8 can run on samll cpu/memory/disk. It exists an application store. Security aspect is part of the game. Planning to migrate WPF applications to Metro need a lot of work.

XAML and Codebehind

Built-in controls are build using XAML. Extended Application Model Language. It covers elemnts and properties, also event handlers. It exists user controls. XAML uses namespaces. Elements correspond to objects. XAML is a tree description of objects. Metro and WPF is defferent. In WPF, XAML elements are .NET objects ; in Metro, XAML elements are WinRT objects, the new native API. For C# developpers, CLR just make use of RCW (runtime com wrappers) to make .NET types to WinRT objects. So XAML are usable from C++ or JS and C#. WinRT objects are esay to use in C#.

Asynchronous APIs

Metro applications must be highly responsive : fast and fluid. They should be responsiveness. Motion should be natural and fluid. Metro starting screen enables to user to scrool. Sliding applications requires performance. The motion should be smooth and it is hard to achieve. Repainting moving items is frequent. The natural feeling of motion should be guaranted. WinRT allows this with an animation system. WinRT avoid blocking APIs. Example, reading a file is not ablocking operation like ReadFile or fread() because it blocks the UI thread. Instead there are non blocking alternatives and APIs must return in less than 50 ms (<50 ms). WinRT asynchronous patterns is provided throught C# async and await keywords.

Example via new Geolocator()

IAsyncOperation interfaces are transposed into async C# pattern. Private async void Button_Click… objGeoposition = locator.GetGeopositionAsync(); C# and await keyword do the job easy. It is easy to do multiple operations without pain, but don’t disconnect your brain. It is a language extension support.

Files and Networking

A classical windows application has access to files and network resources on the current users. Computer subverting occurs sometimes like command&control servers. Metro has changed the model. The application have acces to limited resources like a local application folder; Fo the others, it requires “capabilities”. Example are Documents, Music, library acess, removable storage, outbound internet access, local network, user credentials, inbound connections, devices, location. Applications need to request for capabilities. It is linked with the installation features provided by the store : requested and granted at installation. There are few documentation about this for the moment. Runtime failure will occur if an application try to use something not previously declared.

Visual Studio 11 Dev Preview

Package.appxmanifest file enable to declare capabilities. There checkboxes for each capabilities. When the user accepts and let your app to be installed, it can later, disable some features requested. Be carefull of that.

Integration with Win8 UI

The start screen shows application icon. Application can share data. Metro offers a way to do sharing. Users can also search inside application if they have declared a contract. Contracts are for Share, search, etc. Application bar is a minimal menu with commands. Part of the Win8 application development is to integrate with the new metro style UI. Snapping allows applications to be sticked, flipped and switched and then, application layout is changed. Applications views are differents and are provided by the application.

WinRT and .NET

Built-ins XAML objects. WinRT objets are easy to use with .NET. Types are automatically mapped to .NET world. Collections are mapped with familiar interfaces. But something it differs ; examples are streams witch are not wrapped automatically. WinRT is completely asynchronous. Wrappers and located in System.Runtime.WindowsRuntime.dll. It exists synchronous APIs but be carefull not to use theses blocking methods in the UI thread because your app will be terminated by Metro… WinRT exposes buffers. Objects lifecycle is managed via COM and reference counting and not with a garbage collector. Be aware of circular references. .NET GC will release COM references. WinRT provide method like Marshal.ReleaseComObject. Some .NET features are reduced or missing. You should look to the WinRT equivalence to .NET methods. Porting existing .NET code to Metro is a major challenge.

C++ Renaissance (the Channel9 talk)

C++ Renaissance

http://channel9.msdn.com/Shows/Going+Deep/Craig-Symonds-and-Mohsen-Agsen-C-Renaissance

Craig Symonds: Lead PM on Visual C++, 20 years at Microsoft

Mogen Agsen: C++ Team and Experience Team, 20 years at Microsoft

In 2011, let’s talk about C++.

I think we are going to a renaissance. It is a language that was important. There is a resurgence of the native developers. We have carefully selected our job. The conditions are starting to happened. Things are happening in that space, passion. We are in a reengagement, inside and outside Microsoft. Native developers have not gone away. There are busy people. Microsoft is making a re-engagement with the community. C++ is used in line of business, in mobile, in servers, game development, everywhere. We think the community is smaller over the years but it grows. It is always bigger the way we think.

Even inside Microsoft, managed code was the next big thing. But, all the major products, Windows, Office, SQL Server is made using C and C++. C++ is a very low-level and high level language. Some guys told C++ was unsecure, unsafe. C++ gives full power. Microsoft used to do C with classes and now, modern C++. C++ is done in such a way that power and performance is provided by default in C++. C++ can do the same fast things C developers used to do, but you can use safe types and OO programming. It gives the performance – look at the generated assembly code. It is amazing. COM programming was pointer and vtable way to do this. In modern COM, it is built with smart pointers. ATL introduced that, it is bind using smart pointers and it is safe. Compared to .NET, C++ is made for super performance and it Is also very high level. We focus on values and others languages love to mix code with C++.

Performance is always non negotiable.

C++ compilers and optimizers use CPU register and it rocks. C++ is type safe.

C++ gives you first access the ability to innovation as soon it is available. It can be a market advantage. We talk a lot about productivity but the key impact is immediate access to innovation. C++ allows that.

Native productivity is different that managed productivity.

In C++, you don’t have to be object oriented or to use classes. You can but you can’t just use functions.

C++ and templates meta programming is made for esoteric audience. It is surprising to see template meta programming. You can’t think at a different think but it is always C++. The transition from C programming could be large but it is part of the C++ shape.

Concurrency is next major topic for the past 15 last years.

Garbage collection and C++.

C++ is not made for classic garbage generation. It does not work.

C++ brings diversity. There are many memory management systems. Some apps brings their own memory management system, using OS API or STL usage.

The problem is not that an app leaks, the fact is that it starts fast. This is what is important.

In game development, the application pre-allocates a large bloc of memory, build partitions it and use it.

GC is fantastic for AI and managed languages.

In C++, shared pointers do a better job for objects lifecycle. The tradeoffs are important. There are a lot of techniques in C++ world. In .NET, there is only one way to allocate memory.

If you want to be fast and small, GC is not the way to go.

In 90’s, it was write once, run everywhere rules. C++ is more than a language, it is coupled with libraries, like C runtime and C++ STL. Library can be generic and portable, example for a math library. Also, UI can be portable. C++ can be low level and high level. C++ developers are very sophisticated to understand what can be portable and what can be platform dependent. Sophistication is one thing we are fascinated.

There is no one size fits all in C++. You need to think what part of the platform you have to call. C++ has an eco system.

C++ language has so much features elegant like template and not elegant like macros. C++ has so unique attributes in the language and C++ is bound to software development excellence. C++ is native and the platform is native so it is much and much easier to achieve such superior power and performance.

C++ known as unsafe and unsecure is a myth and is wrong. It is provided by marketing guys.

In Channel9, there will be more and more videos about C++. Visual Studio will bring unique features and some C++ only tools and designers. Visual C++ has been the first language for MSDEV. It became now, the central place for C#, VB, HTML and C++ and in a near future, JavaScript. There are a lot of things that look equal among languages. But C++ compiler is far complicated versus others so Visual Studio could be dominated by C++ superiority but is not oriented like that. Visual C++ and Visual Studio fit very well together. Target audience is diversified. The value added by Visual Studio, example productivity, designers and ALM tools is shared for all languages. VS is multi role environment and the goal is not to replicate tools with equality for all languages. Differences in VS11 will be more important.

VS dot not ship every 6 months. Microsoft read a backlog for Visual C++ and Visual Studio. They want to hear from the community. What do you want new and more ? There a lot of future plans. Diego D. (community Pm for Visual C++) want the community to help the Visual C++ Team, by sorting its internal backlog.

Don’t be surprised if in the future, new designers and tools address C++ first. And on the opposite, ther will be specific tools for specific language. These are existing scenarios in VS11.

Christophe Pichaud | Visual C++ user since VC1.52c in 1992

C++ Renaissance

C++ Renaissance

C++ est dans l’O.S et pas seulement dans Windows, C++ est dans le navigateur web et pas seulement Internet Explorer. La communauté C++ se réduit mais au travers des universités, c’est la plateforme la plus populaire, avec .NET, Java et PHP.

C++ veut dire développement natif. C++ permet d’accéder à toutes les fonctionnalités sous-jacentes du système d’exploitation. C’est une caractéristique unique. Ce n’est pas le cas des langages managé comme C# ou Java qui dépendant d’un framework et lorsque la fonctionnalité n’est pas exposée au travers du framework et de ses classes de bases, l’appel au code natif est la seule possibilité.

La nouvelle génération d’application appelle le développement natif. Native UI.

L’autre argument est la puissance et la performance qu’apporte C++ et il n’y a pas d’équivalents. Un très haut degré d’abstraction mais sans compris sur la performance.

C++ a évolué et les extensions TR1 et C++ 11, anciennement nommé C++ 0X en sont la preuve.

Avant, le code C++ utilisait des appels à new et le code pouvait produire des fuites mémoires. Avec les shared_ptr<T>, il est possible de complètement s’affranchir des problèmes liés à la restitution de la mémoire. Bjarne Stroutrup, inventeur du C++ déclare à propose de C++, entre autre que « C++ is the best language for garbage collection principally because it creates less garbage ». A traduire.

Le manager de Visual C++ (Ale Contenti) préfère cette maxime « C++ brings Power and Performance without comprise». A traduire.

Le code natif est très naturel car la plupart du temps, le code a une relation simple avec la mémoire. Le programme interagit en direct.

Le monde C++ est indissociable du monde des librairies. La symbiose entre le langage et les librairies est totale. Le monde C++ existe depuis plus de 20 ans et donc il existe des centaines de librairies.

C++ permet d’avoir du code « clean » et « secure » malgré tous les slogans marketing que l’on a pu entendre à propose des langages évolués comme C# ou Java. La librairie STL par exemple apporte un niveau de maturité et de stabilité exceptionnel qui rend le code plus fort, plus lisible et sans compris sur la performance. En C++, chaque programmeur a un jour essayé de coder sa propre classe String et finalement, après des heures de conception et après avoir essayé de gérer son propre buffer, le constructeur par copie ou la surcharge de l’opérateur d’affectation, on arrive à la conclusion que l’implémentation standard std::string fournit dans la STL fait le job de manière bien plus efficace !

C++ code that rocks !

Visual C++ introduces PPL (Parallel Pattren Library) to provide a clean and safe way to do parallel programming.
Exemple, by the code….

// ProjectBuild.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "..\..\concrtextras\ppltasks.h"
using namespace std;
using namespace Concurrency::samples;
struct Project
{
string Name;
};
int Build(const Project&amp; project)
{
printf("Start building project '%s'\n", project.Name.c_str());
Sleep(1000);
printf("End building project '%s'\n", project.Name.c_str());
return 0;
}
void main()
{
Project A = {"A"}; // A B
Project B = {"B"}; // / \ /
Project C = {"C"}; // C D
Project D = {"D"}; //
task&lt;void&gt; a([=]() {
Build(A);
});
task&lt;void&gt; b([=]() {
Build(B);
});
// Build C after A
auto c = a.continue_with([=]() {
Build(C);
});
// Build D after both A and B
auto d = (a &amp;&amp; b).continue_with([=]() {
Build(D);
});
(c &amp;&amp; d).wait();
}

Christophe Pichaud | .NET Rangers
MCSD, MCSD.NET, MCTS .NET 2.0

CPP day in France

MS and Intel have done a full day about C++ modern programming and parallel topics. Very cool.

Power and Performance == C++