Christophe Pichaud Microsoft Architect Sogeti France 3/31/2017 10:31 PM APP – SAC – TOOL Windows 8 BUILD Best-Of Christophe Pichaud Microsoft Architect Sogeti France © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Metro Apps Start, Suspend…
Process lifetime walkthrough App 1 App 2 App 3 App N Running … Apps suspend after a short delay Apps resume instantly from suspend Suspended App terminated under memory pressure without notification Terminated
Introducing suspend System resources focused on app user is interacting with in the foreground Inactive apps have no impact on battery life or responsiveness, they are suspended by the OS Enables instant switching between apps!
Apps do not get notified when they are getting terminated Termination happens System needs more memory User switch occurs System shutdown Apps crash Apps do not get notified when they are getting terminated
Process state transitions App gets 5s to handle suspend App is not notified before termination Running App suspending Suspended App Terminated App User Launches App Low Memory resuming Apps are notified when they have been resumed Splash screen Code gets to run No code runs App not running
Suspend under the hood Suspended apps are not scheduled by the NT Kernel No CPU, Disk or Network consumed All threads are suspended Apps remain in memory Kernel ensures apps are not suspended in critical sections that could cause system wide deadlocks Apps instantly resumed from suspend when brought to foreground
App Activation Through Contracts Apps are activated through contracts Launch, search, ShareTarget, etc. Apps need to initialize contract specific actions Context is provided Running App launch shareTarget activated kind search
App crash? Start over Apps that are stuck are no fun Your app can be terminated abruptly in any of these cases Too long to load Too long to suspend Stopped handling input messages (Blocking I/O on UI thread) Task manager Bring the user back home, and ignore saved user session state previousExecutionState is provided in activation event args
Use live tiles to appear running Your app’s tile is an opportunity to provide value to users even when they are not using your app Gives the user the sense that there is something going on with your app, and is an invitation to go back Two mechanisms available to update tiles on the Start screen
Lock screen apps Apps that can run in the background Designed for real-time communications apps (Mail, IM, VoIP) Maintain TCP sockets in the background Run code periodically Run code in response to system events (user login)
Metro Style Apps connected
Review app process lifetime Running App Suspended App Terminated App Suspending Low Memory Resuming
RTC trigger APIs for your apps OS VoIP IM Mail Network Trigger System Trigger Time Trigger Background Task Infrastructure
Key points Longer Battery Life Always Reachable Apps
Recap
WinRT APIs for Metro style apps User Interface HTML5 / CSS XAML DirectX Controls Data Binding SVG Tiles Input Accessibility Printing Devices Communications & Data Geolocation Printer NFC Contracts XML Web Sensors Portable Devices Networking Notifications Streams Media Local & Cloud Storage AtomPub Capture Visual Effects Background Transfer SMS PlayTo Transcoding Fundamentals App Lifetime Authentication Cryptography Globalization .NET Win32
APIs make it simple to build Metro style apps User Interface HTML5 / CSS XAML DirectX Controls Data Binding SVG Tiles Input Accessibility Printing Devices Communications & Data Geolocation Printer NFC Contracts XML Web Sensors Portable Devices Networking Notifications Streams Media Local & Cloud Storage AtomPub Capture Visual Effects Background Transfer SMS PlayTo Transcoding Fundamentals Authentication Cryptography Globalization .NET Win32 App Lifetime
APIs make it simple to build Metro style apps HTTP APIs RSS AtomPub IXHR HttpClient Atom WCF XHR HttpWebRequest Web services Data APIs Skydrive Live ID Json XML Streams Xbox Live Azure DataReader/DataWriter Information APIs Background APIs Network Information Cost Cost Download Upload RTC Push Notification Socket APIs TCP sockets UDP sockets SSL sockets Web Sockets Proximity sockets
Using DirectX in Metro style apps App initialization CoreApplication & CoreWindow Handling events Pointer, gestures, keyboard Resource creation GPU & CPU resources Rendering
What is the Windows Runtime?
Windows Kernel Services Metro style Apps Desktop Apps View XAML HTML / CSS HTML JavaScript Model Controller C/C++ C#, VB JavaScript (Chakra) C C++ C# VB Windows Runtime APIs Communication & Data Graphics & Media Devices & Printing System Services Application Model Internet Explorer Win32 .NET SL Kernel Windows Kernel Services
Windows Runtime Architecture Metro style app Language Support (CLR, WinJS, CRT) Language Projection Windows Metadata & Namespace UI Pickers Controls Media Web Host (HTML, CSS, JavaScript)) XAML Storage Network … Windows Runtime Core Runtime Broker Windows Core
Design Principles Major improvement to developer experience Great intellisense & tooling Responsive and Fluid Async APIs where they are needed App-Centric Platform Well managed app-to-app contracts Platform based Versioning Apps keep running on future Windows versions
Windows Metadata Concise, complete description of the Windows Runtime Generated natively from C++ or C#/VB Compiler Efficient binary format derived CLI Metadata Same structures, different meanings Rich enough to allow multi-language projection generation Full intellisense on statically known information
The Windows Namespace Windows.* Runtime objects are in a simple, unified, hierarchical namespace Great intellisense and browsing in Visual Studio One Clear type for each function Catalog is extensible but private Your apps can add objects (in C++/C#) Objects can be seen from JavaScript
Windows Runtime Basic Types Strings HSTRING Avoids copying in multiple languages Basic Types INT32, UINT64 * Pointers allowed in limited cases Enumerations enum AsyncStatus Flag or non-flag styles Structures struct Rect; Can contain strings, but not interfaces Simple Arrays INT32 [] For very basic collections Interfaces IInspectable Methods are defined in interfaces Generic Interfaces IVector<T> Type-generic interface Runtime Class Windows.Storage.StorageFile Binds interfaces to make a class
What is a Windows Runtime Object? Shell32.dll IInspectable IUnknown Object IStorageItemInformation IStorageItem FileInformation Runtime Class IStorageFile Interfaces Activation Store (Registry) Windows Metadata (Disk)
Projections IInspectable IUnknown Projection C++ App Projection Object Projection CLR C#/VB App Projection Chakra HTML App Windows Metadata
Object Creation Start App asks to create object Pass Name to RoActivateInstance Find DLL using Catalog Load DLL Call DllGet-ActivationFactory Object created by implementation code IInspectable returned Projection creates wrapper (using metadata) Object bound to wrapper Wrapper returned to App End App Projection WinRT Object Manager WinRT Object
Versioning IInspectable IInspectable IUnknown IUnknown Future Windows Object Object Windows Metadata v8 Projection App Windows Metadata v9 Projection App
Windows Runtime Patterns Collections IVector<T>, IVectorView<T>, IMap<T> Iterators, Collections and events cross-language Delegates delegate AsyncActionCompletedHandler Encapsulate the context to call back to an object Events IApplicationLayout::LayoutChanged Lists of callback recipients PropertySet interface IPropertySet Collection of items with varying types Async Interface ReceivePropertiesOperation A way to get a delayed result without blocking Contracts Windows.ApplicationModel. DataTransferManager Connect Apps to Windows Extension Points
Associative Collection Collections IInspectable STL-style Projection C++ App IUnknown Array IVector<T> IVectorView<T> IEnumerable (T) style Projection CLR C#/VB App IObservableVector<T> IInspectable Chakra JavaScript Projection HTML App IUnknown Associative Collection IMap<T> IMapView<T> IObservableMap<T>
Asynchronous Objects Basic requirement for Metro style apps Always responsive, ready “Long running” APIs must be delivered as async Simpler to allow apps to make synchronous calls But then bad apps can overwhelm quality of system Instead, build async into API shape And have language projections integrate it deeply
Threading Main UI Thread Threadpool App Code App Code App Code App Windows UI Object Windows Object Windows Object App Code App Code App Code
Windows Runtime Threading Three main types of object Thread bound – works only on the thread where it was created – most UI Thread flexible – works on any thread, uses locking if needed to control simultaneous access Brokered – out of process UI runs in single threaded environment that is not reentrant (“ Application STA”) Callbacks can only enter if they are related to an outgoing call Most non-UI runs in any thread
Brokered Objects IInspectable IUnknown Projection App RuntimeBroker.exe Proxy App Projection IInspectable IUnknown Windows Runtime Object
Inside WinRT
The Windows Runtime is fundamental to Metro style apps.
WinRT registration catalogs Install Extension Catalog Class Catalog Extension 1 Runtime Class “A” Launch Contract Extension 2 Runtime Class “B” Search Contract Extension 3 Runtime Class “C”
Extension Registrations WinRT registration Install Extension Registrations Several OS supported contracts Extensions are contract implementation Extensions map the abstract to the concrete Class Registrations Classes are concrete implementations Contains information to activate and run code
Deployment pipeline Install Application Manifest Deployment Engine Extension Catalog Application Manifest <Applications> <Application Id="App" StartPage="default.html"> <VisualElements DisplayName="Hello World" Logo="images\logo.png" Description="Hello_World" .... Deployment Engine Class Catalog
Tapping a tile Tap The OS stores the extension’s identification during install The OS queries the extension catalog to find the extension The OS activates the extension via WinRT
Finding the right extension Tap Explorer.exe Extension Catalog Query Activation System Class Catalog Investigate Activate
Activating the extension Tap Explorer.exe RPCSS Activation System Activate Application.exe Class Catalog DCOM Launch
Running the app Run RPCSS Register MTA Run Query Class Catalog Application.exe RPCSS Register MTA main() { ... } Run Query Class Catalog
Completing app activation Run Explorer.exe Complete Activation Activation System Instance Activate App RPCSS Application.exe Instance App Callback App Code
Application object Run MTA STA #1 Run Run STA #2 Activate Register Application.exe MTA STA #1 Application Code Application Code Run Run STA #2 Activate Application Code Register
WinRT APIs Foundations
Windows Runtime APIs Available to all programming languages JavaScript C#/VB C++ Available to all programming languages Requires a language neutral type system
Numeric types Behave differently in .NET/C++ compared to JavaScript C++/.NET - Signed, Unsigned; 8, 16, 32, 64 bit int; 32, 64 bit float JavaScript – double-precision 64-bit binary format IEEE 754 value Windows Runtime – Same as C++/.NET without signed 8-bit integer But… Operating system uses 64-bit integers in some places file sizes, position, etc. JavaScript number can only represent 53 bits of precision
Numeric types ECMAScript (ECMA-262) Standard Requires numbers treated as IEEE-754 64-bit floating point values JavaScript applications using the Chakra runtime cannot accurately determine the values of some 64-bit integers But such values can be received from and passed back to WinRT APIs Many (most) values will work fine Use caution with 64 bit values whose absolute value is greater than 2^53 (9,007,199,254,740,992)
Strings Immutable or mutable? Null Immutable – JavaScript, .NET; Mutable – C++ Null JavaScript: null is an object, string is a type C++: std::string has no 'null' semantics .NET System.String: reference type has a 'null' distinguished value Windows Runtime: string's immutable, no null representation
Structures Handled differently by languages As a result… C++/CLR: Structures are value types, can contain all types JavaScript: Has no structure construct but structures can be simulated Windows Runtime supports structures, with restrictions on content Can only contain numbers, strings or structures Windows Runtime structures cannot contain pointers Windows Runtime structures are value types As a result… Structure valued property behavior differs in languages
References & pointers Target languages handle pointers and references differently C++: All types can be passed by value or by reference .NET: Objects are passed by reference, value types by value JavaScript: Objects passed by reference, numbers passed by value Windows Runtime: Objects (Interfaces) passed by reference, all other types passed by value As a result… Method parameters are [in] or [out], never [in, out]
Arrays Reference or value types? Windows Runtime JavaScript, .NET, C++: Reference types Windows Runtime Arrays are value types so marshal by value ONLY WHEN they are marshaled!
Events Event syntax differs across languages Be aware… C++/CLR – Clients add events with += operator JavaScript – Clients add events with either the addEventListener function or by setting the “on<eventname>” property on the object. Be aware… JavaScript event name casing is all lowercase Assigning to the property implies one listener while addEventListener allows multiple listeners Misspelling the event name in either case silently fails
Collections Windows Runtime collections are relatively straightforward Vectors – similar to array, projected with array syntax Maps – key/value pairs, projected as dictionary to CLR apps Surprise… Because collection value accesses require a method call, they can be unexpected performance bottlenecks Can use the GetMany method for bulk retrieval
Method overloading Two criteria used when handling overloads Overload on number of params (arity) JavaScript, .NET, C++ all distinguish methods by arity Overload on parameter type .NET, C++ all distinguish methods by type of parameters JavaScript has a limited notion of type Windows Runtime methods Overload on arity but not on type
Asynchronous APIs Platform design goal that APIs cannot block the UI thread Guidance: Anything taking > 50 ms should be asynchronous Resulted in prevalent use of Async Pattern in platform Established a naming pattern: <verb>[<noun>]Async GetThumbnailAsync Return value mapped to a promise for a future result In .NET – await obj.GetThumbnailAsync() In JavaScript – obj.GetThumbNailAsync().then (func);
.NET parallel programming
TPL Dataflow Overview System.Threading.Tasks.Dataflow.dll Primitives for in-process message passing “Blocks” that can buffer and process data Used individually and/or linked together to create networks Inspired by Decades of computer science research/history Related Microsoft technologies Asynchronous Agents Library in Visual C++ 2010 Axum incubation project CCR from Microsoft Robotics
TPL Dataflow Dataflow Networks “Dataflow Blocks” implement interfaces IDataflowBlock, ITargetBlock<TInput>, ISourceBlock<TOutput> Linkable to form a network Data automatically propagated from sources to linked targets Enables building powerful parallel and asynchronous pipelines, e.g. ActionBlock, TransformBlock, JoinBlock, … Integrates with Task, IObservable, … TransformBlock<byte[],byte[]> Compress TransformBlock<byte[],byte[]> Encrypt data compressed and encrypted
Parallel Debugging Additions Parallel Watch Multi-process Pervasive Flagging
Concurrency Visualizer Shift-Alt-F5 Faster processing, faster loading Supports big traces Supports EventSource and custom markers Built-in support for TPL, PLINQ, Sync Data Structures, and Dataflow Built-in support for your own EventSource types Also provides Visual Studio markers API New visualizations e.g. defender view
C++ and XAML
XAML benefits For WPF, SL and Windows Phone developers Utilize current skills Reuse compatible assets For those new to XAML Powerful declarative programming model Separation of UI layer and application logic Expressive: Controls, layout, vector drawing Comprehensive : Styles, templates, data binding, animation Extensible : Custom controls
C++ for the Windows 8 runtime Set of language extensions and libraries to allow direct consumption and authoring of Windows runtime types. Strongly-typed system for Windows runtime Automatically reference counted Exception-based Deep integration with STL Well defined binary contract across module boundaries
C++: First class support for Metro style apps XAML designer C++ to access the Windows runtime Async nature of APIs IDE improvements Local, simulator and remote debugging Package your apps Code Analysis
Using Windows Runtime from C#
C# and Visual Basic influenced the Windows Runtime
Windows Runtime is designed to be used from object-oriented languages like C# and Visual Basic
Windows Runtime metadata files use an updated version of Windows Runtime metadata files use an updated version of .NET’s metadata format
Windows Runtime includes a XAML based framework for Metro style apps
Windows Runtime was expressly designed to work well with C# and Visual Basic
Most differences between Windows Runtime and Most differences between Windows Runtime and .NET are hidden from the managed developer
IIterable<T> ↔ IEnumerable<T> .NET automatically maps collection interfaces to their Windows Runtime equivalent IIterable<T> ↔ IEnumerable<T> IVector<T> ↔ IList<T> IVectorView<T> ↔ IReadOnlyList<T> IMap<K,V> ↔ IDictionary<K,V> IMapView<K,V> ↔ IReadOnlyDictionary<K,V>
A few places use extension methods to bridge between Windows Runtime and managed code
You can write your own Windows Runtime components in C# or Visual Basic
You should build a Windows Runtime component when you want your code to be used from JS, C++, C# and VB
API signatures must only use Windows Runtime types Structs can only have public data fields Inheritance can only be used for XAML controls, all other types must be sealed Only supports system provided generic types
Build your own managed Windows Runtime components Influenced by C# and VB Feels natural and familiar from C# and Visual Basic Build your own managed Windows Runtime components
Using Windows Runtime with C++
C++ in a Metro style World Overview Metro style Applications (Hybrid) HTML5 + JS front-end C++ components XAML UI Applications XAML interface C++ code behind Metro style Games DirectX & C++
C++ for Windows Runtime Overview Set of language extensions and libraries to allow direct consumption and authoring of Windows Runtime types. Strongly-typed system for Windows Runtime Automatically reference counted Exception-based Deep integration with STL Well defined binary contract across module boundaries
C++ Component Extensions (C++/CX) bindings to foreign type systems Key Bindings Feature Summary 1. Data Types ref class Reference type value class Value type interface class Interface property Property with get/set event “Delegate property” with add/remove/raise delegate Type-safe function pointer generic Type-safe generics 2. Allocation gcnew Garbage-collected allocation ref new Reference-counted allocation 3. Pointer & Reference ^ Strong pointer (“hat” or “handle”) % Strong reference
WinRT Types: For Cross-Language Use C/C++ External Surface for native callers/callees WinRT External Surface for WinRT callers/callees Module Internals written in C++
Lifetime Management Handle (^) is a pointer to a Windows Runtime object for which the compiler performs automatic reference counting ref new instantiates or activates a Windows Runtime class. Person^ p; { Person^ p2 = ref new Person(); // refcount = 1 p2->Name = “John”; // refcount = 1 p = p2; // refcount = 2 } // refcount = 1 p = nullptr; // refcount = 0; ~Person()
Runtime Class Defining Using public ref class Person { public: Person(String^ name, String^ email); void Greet(Person^ other); internal: ~Person(); void SetPassword(const std::wstring& passwd); }; ABI-safe cross-language class Public methods restricted to WinRT typed parameters Private/internal methods can use any legal C++ type parameters Using Person^ p = ref new Person(“John Surname”); p->Greet(ref new Person(“Jim Surename”);
Interface Defining Using Inheriting Implementing public interface class IAnimal { void Play(); }; Methods are implicitly public Using IAnimal^ animal = ref new Cat(); animal->Play(); Inheriting public interface class IFeline : IAnimal { void Scratch(); }; Implementing ref class Cat : IFeline { public: virtual void Play(); virtual void Scratch(); Public inheritance only
Automatic Lifetime (Stack, Member) Defining public ref class DatabaseConnection { public: ~ DatabaseConnection(); }; Using { DatabaseConnection db(); db.SetName( “Employees”); // … // … lots of queries, updates, etc. … } // ~DatabaseConnection()
Property Defining Trivial properties (with private backing store) public: property String^ Name; User defined properties public: property Person^ Sibling { Person^ get() { InitSiblings(); return _sibling; } void set(Person^ value) { _sibling = value; NotifySibling(); } } private: Person^ _sibling; Using Person^ p = ref new Person(“John”); p->Sibling = ref new Person(p->Name);
Delegate Declaring: like a function public delegate void PropertyChanged( String^ propName, String^ propValue ); Instantiating: like a class From lambda: auto p = ref new PropertyChanged( [](String^ pn, String^ pv) { cout << pn << ” = “ << pv; } ); From free-function auto p = ref new PropertyChanged( UIPropertyChanged ); From class-member auto p = ref new PropertyChanged( this, MainPage::OnPropertyChanged ); Invoking: like a function p( “Visible”, false );
Event Defining Trivial event (with private backing store) public: event PropertyChanged^ OnPropertyChanged; User defined event public: event PropertyChanged^ OnNetworkChanged { EventRegistrationToken add(PropertyChanged^); void remove(EventRegistrationToken t); void raise(String^, String^); } Using Subscribing person->OnPropertyChanged += propertyChangedDelegate; auto token = person->OnPropertyChanged::add(propertyChangedDelegate); Unsubscribing person->OnPropertyChanged -= token; person->OnPropertyChanged::remove(token);
Exception Signaling an error case: throw exception HRESULT Exception E_OUTOFMEMORY OutOfMemoryException E_INVALIDARG InvalidArgumentException E_NOINTERFACE InvalidCastException E_POINTER NullReferenceException E_NOTIMPL NotImplementedException E_ACCESSDENIED AccessDeniedException E_FAIL FailureException E_BOUNDS OutOfBoundsException E_CHANGED_STATE ChangedStateException REGDB_E_CLASSNOTREG ClassNotRegisteredException E_DISCONNECTED DisconnectedException E_ABORT OperationCanceledException Signaling an error case: throw exception throw ref new InvalidArgumentException(); throw ref new COMException(E_*); Handling an error case: catch exception try { … } catch (OutOfMemoryException^ ex) { … } Access HRESULT value via ex->HResult Notes on exceptions: catch (Platform::Exception^) catches all WinRT exceptions Exceptions don’t carry any state and don’t travel across modules Deriving from an exception class is ill-formed
Generics Defining Using Implementing generic<typename T, typename U> public interface class IPair { property T First; property U Second; }; Using IPair<String^, Uri^>^ uri = GetUri(); auto first = uri->First; // type is String^ auto second = uri->Second; // type is Uri^ Implementing ref class PairStringUri: IPair<String^, Uri^> { public: property String^ First; property Uri^ Second; };
Template Runtime Class Defining template<typename T, typename U> ref class Pair: IPair<T, U> { public: property T First; property U Second; Pair(T first, U second) { First = first; Second = second; } }; Using IPair<String^, Uri^>^ pair = ref new Pair<String^, Uri^>( “//BUILD/”, ref new Uri(“http://www.buildwindows.com”));
.winmd metadata .winmd files To consume a winmd file: Contain the metadata representation of WinRT types To consume a winmd file: Right click on project in Solution Explorer > References > Add New Reference… Or #using <Company.Component.winmd> Make sure the winmd and implementation dll is packaged together with your application To produce a .winmd file: Start from the “C++ WinRT Component Dll” template Define public types (ref classes, interfaces, delegates, etc.) Tip: C++ WinRT components can be consumed from C++, JS or C#
Partial Runtime Class Partial class definition Class definition private partial ref class MainPage: UserControl, IComponentConnector { public: void InitializeComponent(); void Connect() { btn1->Click += ref new EventHandler(this, &MainPage::Button_Click); } }; Class definition ref class MainPage MainPage() { InitializeComponent(); } void Button_Click(Object^ sender, RoutedEventArgs^ e);
Libraries
Vector and ObservableVector Instantiating using namespace Platform; Vector<String^>^ items = ref new Vector<String^>(); Adding elements items->Append(“Hello”); Returning a read-only view of the vector IVectorView<String^>^ GetItems () { return items->GetView(); } Getting notification for changes items->VectorChanged += ref new VectorChangedEventHandler<String^> (this, &MyClass::VectorChanged);
Map and ObservableMap Defining Adding elements using namespace Platform; Map<String^, Uri^> favorites = ref new Map<String^, Uri^>(); Adding elements favorites->Insert(“MSDN”, ref new Uri(“http://msdn.com”)); Checking and removing elements if (favorites->HasKey(“MSDN”)) favorites->Remove(“MSDN”);
Library Integration: STL STL Algorithms String has Begin()/End() member methods. For WinRT collections, collection.h defines begin() and end() functions. IVector<int>^ v = GetItems(); int sum = 0; std::for_each( begin(v), end(v), [&sum](int element) { sum += element; } ); Conversions String^ std::wstring (via wchar_t*) Vector std::vector std::vector<int> v; v.push_back(10); auto items = ref new Vector<int>(v); Vector std::vector Vector<int>^ items = …; std::vector<int> v = to_vector(items); Map std::map
WinRT and JavaScript Basics
JavaScript and C# WinRT component namespace CustomWinRTComponent { public interface IMoreMath { } public sealed class MoreMath : IMoreMath { public static double Sinh(double x) { return Math.Sinh(x); } // JavaScript var MoreMath = CustomWinRTComponent.MoreMath; var y = MoreMath.sinh(0.7);
C++ and Metro Style Apps
The C++ language extensions Read / write metadata Maps between C++ patterns (e.g. constructors) and WinRT interfaces Maps between output parameters and return values Automatic reference counting Casting Maps between exceptions and HRESULTs
Exception & return value wrapping HRESULT __stdcall Add( Calculator* this, int i, int j, int* result ) try { int i = Add(41, 1); } catch (OverflowException^ e) { printf("Too big"); int Add(int i, int j) { if (i+j < i) { throw OverflowException(); } return i + j; WinRT ABI Native to COM Wrapper COM to Native Wrapper HRESULT __stdcall __cli_Add(Calculator* calc, int i, int j, int* r) { try { *r = calc->Add(i, j); } catch (Exception^ e) { return e->HResult; return S_OK; }; inline int Add(int i, int j) { int res; HRESULT hr = __cli_Add(this, i, j, &res); if (hr != 0) { __throw_hr_as_exception(hr); // switch on hr & throw } return res; };
H^T A hat is a pointer to a pointer to an array of function pointers “It’s not okay to call me a carrot” A hat is a pointer to a pointer to an array of function pointers aka: Pointer to vptr to vtable Calculator::ICalculator vtable &Calculator::QueryInterface &Calculator::AddRef &Calculator::Release &Calculator::GetIids &Calculator::GetRuntimeClassName &Calculator::GetTrustLevel &Calculator::Add ref class Calculator IStorageCell vtable * vfptr1 ICalculator vtable * vfptr2 int _storage int _refcount ICalculator^ calc
H^T A hat is a pointer to a pointer to an array of function pointers “It’s not okay to call me a carrot” A hat is a pointer to a pointer to an array of function pointers aka: Pointer to vptr to vtable ^ provides automatic reference counting Similar to ComPtr<T> Adds ability to use casting.
C++ for Metro style apps C++ language extensions gives you the best of both C++ and WinRT The compiler understands the concepts natively, and will do the best job at optimizing While giving you a readable and natural syntax C++ and Win8: power and performance!
Brings existing C++ code into Metro Style Apps
Windows SDK for Metro style apps Desktop apps View XAML HTML / CSS HTML JavaScript Model Controller C C++ C# VB JavaScript (Chakra) C C++ C# VB WinRT APIs Communication & Data Graphics & Media Devices & Printing System Services Application Model Internet Explorer Win32 .NET / SL Core Windows Core OS Services
Windows SDK for Metro style apps Windows 8 introduces the concept of “app container” broker Access to a number of resources (files, devices, etc.) is controlled by the broker A large number for Win32 APIs are replaced by the WinRT library A good number of Win32 APIs will not be available E.g. GDI, Registry, MessageBox, etc. http://go.microsoft.com/fwlink/?LinkId=228532
Existing code Desktop apps Metro style apps Microsoft Libraries good Standard C++ Libs ppl (parallel patterns lib) Win32 ATL MFC 3rd party libs (boost, etc.) your code good WinRT + Win32 subset ATL subset no depends
Existing 3rd party libraries 3rd party Libraries will need to review their usage of existing Win32 APIs A few examples: boost: low usage of APIs not part of Windows SDK for Metro style apps Physics engines (e.g. Bullet): the core of the library have small usage of non-Metro style SDK APIs Math libraries (e.g. Deal.II, SciMath, etc.): very little usage (if any) of non-Metro style SDK APIs
Your code Basic steps to migrate your code to the Metro style environment Make sure you remove or replace the usage of non-Metro style SDK APIs Flagged by compiler errors #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) Flagged by Logo Verification Toolkit (if needed) Add a WinRT layer for smooth interoperability with any Metro style app
Metro style SDK partitioning // c:\Program Files (x86)\Windows Kits\8.0\Include\um\mmdeviceapi.h #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) // Metro style SDK APIs #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) */ #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) // Desktop SDK APIs, not available for Metro style apps #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
.NET Kernel
Quick Reminder – What Is The CLR Entity Frame-work ASP. NET WCF WPF Win Forms Work Flow And more! Base Class Libraries The CLR JIT & NGEN Garbage Collector Security Model Exception Handling Loader & Binder Profiling& Debugging APIs
Improvements to the Garbage Collector
Quick Reminder – GC Fundamentals Roots Heap Generation 1 Generation 0 New objects allocated as Generation 0 Accessible References Keep Objects Alive GC Compacts Referenced Objects Objects Promoted to Older Generation
Quick Reminder – GC Fundamentals 2 Modes: Client (default) and Server Heaps Collection Flavors Small Object Heap Large Object Heap Client GC One Server GC One per logical processor Gen0/Gen1 Gen2 Client GC Always blocking Can be non-blocking Server GC
Quick Reminder - Server Mode (4.0) 3/31/2017 10:31 PM Quick Reminder - Server Mode (4.0) (.NET 4.0) Maximizes application scalability © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
3/31/2017 10:31 PM Background GC For Server Mode (New in 4.5) Performance: Reduces pause times (Desktop apps) (.NET 4.5) Gen0/Gen1 collections can proceed during Gen2 GC © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Other GC Improvements Performance 3/31/2017 10:31 PM Other GC Improvements Performance (Server GC) Scalable Marking for full blocking GCs Large Object Heap Allocation Improvements Better use of free space on LOH (Server only) Balancing the LOH allocations across processors … And More! LEARN MORE http://blogs.msdn.com/b/clrteam/ “Enhancements to the CLR GC in .NET 4.5” © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Assembly Image Usage Logs 3/31/2017 10:31 PM Automatic NGen model App Execute (MyApp.exe) App Execute App Execute Native Image Cache Assembly Image Usage Logs MyApp.ni.exe MyApp.exe OtherApp.ni.exe Auto Ngen Maintenance Task © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Automatic NGen Windows 8 only .NET 3.5 – Framework Only .NET 4.5 3/31/2017 10:31 PM Automatic NGen Windows 8 only .NET 3.5 – Framework Only .NET 4.5 Desktop app – Only assemblies in the GAC Metro style app – All assemblies eligible © 2010 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Executed Methods Profile Multi-Core Background JIT Performance: Improves startup time (Desktop apps) First Launch Subsequent Launch Executed Methods Profile
C# Next
C# and VB evolution C# 5.0 + VB 11.0 Windows Runtime + Asynchrony Dynamic + Language Parity C# 3.0 + VB 9.0 Language Integrated Query C# 2.0 + VB 8.0 Generics C# 1.0 + VB 7.0 Managed Code
What’s new? C# 5.0 VB 11.0 Windows Runtime support Asynchronous programming Caller info attributes Windows Runtime support Asynchronous programming Caller info attributes Iterators
Asynchronous programming models Windows Runtime: IAsyncOperation<T> .NET Framework: Task<T> Javascript: Promises All are objects representing “ongoing operations” All use callbacks to signal completion of operation Challenge: Callbacks turn your code inside out Insight: Automatic transformation to callbacks is possible
The Roslyn project Compiler Compiler Meta-programming Class Field public Foo private string X Meta-programming Read-Eval-Print Loop Language Object Model DSL Embedding Compiler Compiler Source File .NET Assembly Source code Source code Source code Source code
Binding and Flow Analysis APIs Roslyn APIs Formatter Colorizer Outlining Navigate To Object Browser Completion List Find All References Rename Quick Info Signature Help Extract Method Go To Definition Edit and Continue Language Service Compiler APIs Parser Syntax Tree API Symbols Symbol API Binder Binding and Flow Analysis APIs Emit API IL Emitter Compiler Pipeline Metadata Import
Quick Recap WinRT Visual C++ Component Extensions
Windows Core OS Services Windows 8 APIs Metro style app WinRT Win32 (Desktop Subset) Win32 (Metro style Subset) Windows Core OS Services
Exception^ WinRT APIs throw exceptions deriving from Platform::Exception … really, it’s HRESULTs under the cover HRESULT Exception E_OUTOFMEMORY OutOfMemoryException E_INVALIDARG InvalidArgumentException E_NOINTERFACE InvalidCastException E_POINTER NullReferenceException E_NOTIMPL NotImplementedException E_ACCESSDENIED AccessDeniedException E_FAIL FailureException E_BOUNDS OutOfBoundsException E_CHANGED_STATE ChangedStateException REGDB_E_CLASSNOTREG ClassNotRegisteredException E_DISCONNECTED DisconnectedException E_ABORT OperationCanceledException
Collections
WinRT collections family Vector Map VectorView MapView IVector IMap IVectorView IMapView IIterable IObservableVector IObservableMap IIterator STL containers are the backing store see <collection.h>
Collections usage considerations Mix STL containers with WinRT collections STL containers are faster but don’t have observable behavior Use STL containers internally; use WinRT collections at the boundary Fire up a profiler where it matters! Use STL algorithms on WinRT collections No need to copy the WinRT collection into an STL container You can have STL containers of ^ types Use Vector not IVector most of the time Only use IVector the public API surface
Collections usage considerations (cont.) VectorView, MapView and Iterator get invalidated Copy if you plan to change the underlying Vector or Map Each iteration over collections is a virtual call Use bulk iteration (GetMany) when it makes sense Implementing IVector is tricky Use an underlying Vector
Async pattern
Async simplified Build on Parallel Patterns Library (PPL) tasks to implement async pattern Sample available here: http://go.microsoft.com/fwlink/?LinkId=228286 Using this technique, async code is cleaner and more maintainable
Win32
Windows SDK for Metro style apps Windows 8 introduces the concept of “app container” sandbox Access to a number of resources (files, devices, etc.) is controlled by the sandbox A large number for Win32 APIs are replaced by the WinRT library A good number of Win32 will not be available to Metro style apps Some Win32 APIs are still available directly to Metro style apps COM Core Direct2D File Systems Kernel Direct3D Globalization Accessibility DirectComposition Media Foundation Audio DirectManipulation Windows and Messages DirectWrite
C++ renaissance
Visual C++: The power and performance tool for Windows. C++ Renaissance Industry momentum for C++. Renewing our commitment to C++: New programming model for Windows 8. Get the full power of your CPU and GPU. Use Windows 8 hardware capabilities to the fullest. Build for ARM. Visual C++: The power and performance tool for Windows.
Recap
For more information Related sessions Documentation & articles PLAT-874T - Lap around the Windows Runtime APP-409T Fundamentals of Metro style apps: how and when your app will run TOOL-531T Using the Windows Runtime from C# and Visual Basic TOOL-532T Using the Windows Runtime from C++ TOOL-533T Using the Windows Runtime from JavaScript C++ Language extension summary The Windows Runtime Windows Runtime Design
Feedback and questions Team Park Windows 8 Dev Community thank you Feedback and questions Team Park Windows 8 Dev Community
3/31/2017 10:31 PM © 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION. © 2011 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.