WinRT Holy COw

45
www.buildwindows.com WinRT Holy Cow Eugene Zharkov Silverlight MVP

description

Based on build conference

Transcript of WinRT Holy COw

Page 1: WinRT Holy COw

www.buildwindows.com

WinRT Holy Cow

Eugene ZharkovSilverlight MVP

Page 2: WinRT Holy COw

www.buildwindows.com

Windows has always provided compelling capabilities for developers to build upon

Windows has not always made it straightforward for you to use

these capabilities from C# or VB

Page 3: WinRT Holy COw

[DllImport("avicap32.dll", EntryPoint="capCreateCaptureWindow")]static extern int capCreateCaptureWindow( string lpszWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hwndParent, int nID);

[DllImport("avicap32.dll")] static extern bool capGetDriverDescription( int wDriverIndex, [MarshalAs(UnmanagedType.LPTStr)] ref string lpszName, int cbName, [MarshalAs(UnmanagedType.LPTStr)] ref string lpszVer, int cbVer);

// more and more of the same

The C# code you have to write today…

Page 4: WinRT Holy COw

www.buildwindows.com

Traditional Windows API

Your Managed Code

Manually Generated

Interop Code

Page 5: WinRT Holy COw

The C# code you get to write on Windows 8

using Windows.Media.Capture;

var ui = new CameraCaptureUI();ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);

var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (file != null) { var bitmap = new BitmapImage() ; bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read)); Photo.Source = bitmap;}

Page 6: WinRT Holy COw

www.buildwindows.com

Windows Runtime Architecture

Windows Metadata & Namespace

Language Projection

Windows Core

Windows Runtime Core

XAML Storage …Network

UI Pickers MediaControls

Metro style app

Runtime Broker

Language Support (CLR, WinJS, CRT)

Web Host (HTML, CSS, JavaScript))

Page 7: WinRT Holy COw

www.buildwindows.com

Your Managed Code

Windows Runtime

Windows 8 API

Page 8: WinRT Holy COw

www.buildwindows.com

You already have the skills to build Metro style apps

with C# and VB

Page 9: WinRT Holy COw

www.buildwindows.com

Agenda

• The relationship between .NET and the Windows Runtime

• Using Windows Runtime APIs from C# and Visual Basic

• Building Window Runtime Components in C# and Visual Basic

Page 10: WinRT Holy COw

C# and Visual Basic influencedthe Windows Runtime

Page 11: WinRT Holy COw

www.buildwindows.com

Windows Runtime is designed to be used from object-oriented

languages like C# and Visual Basic

Page 12: WinRT Holy COw

www.buildwindows.com

Windows Runtime metadata files use an updated version of .NET’s

metadata format

Page 13: WinRT Holy COw

www.buildwindows.com

Viewing Windows Metadata Files

demo

Page 14: WinRT Holy COw

www.buildwindows.com

Windows Runtime includes a XAML based framework for Metro style

apps

Page 15: WinRT Holy COw

www.buildwindows.com

Many of the Windows Runtime design guidelines

came from the .NET design guidelines

Page 16: WinRT Holy COw

www.buildwindows.com

Windows Runtime was expressly designed

to work well with C# and Visual Basic

Page 17: WinRT Holy COw

Using the Windows Runtime feels natural and

familiar from C# and Visual Basic

Page 18: WinRT Holy COw

www.buildwindows.com

Using the Windows Runtime from C#

demo

Page 19: WinRT Holy COw

Most WinRT types map directly to C#/VB

var ui = new CameraCaptureUI();ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);

var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (file != null) { var bitmap = new BitmapImage() ; bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read)); Photo.Source = bitmap;}

Page 20: WinRT Holy COw

www.buildwindows.com

Primitives(strings, numbers, etc)

Interfaces

Enums

Structs

Static Members

Properties

EventsDelegates

Classes

Constructors

Methods

Almost everything maps directly between

the Windows Runtime and .NET

Page 21: WinRT Holy COw

www.buildwindows.com

Most differences between Windows Runtime and

.NET are hidden from the managed developer

Page 22: WinRT Holy COw

Exceptions from HRESULTs

try{

var ui = new CameraCaptureUI();ui.PhotoSettings.CroppedAspectRatio = new Size(16, 9);

}catch (Exception e){ //Exception handling code}

ComException

Page 23: WinRT Holy COw

Calling WinRT Async Operation from C#

var picker = new FileOpenPicker();picker.FileTypeFilter.Add("*");var files = await picker.PickMultipleFilesAsync();foreach (var file in files){ lbFiles.Items.Add(file.FileName);}

PickMultipleFilesOperation PickMultipleFilesAsync();

public sealed class PickMultipleFilesOperation : IAsyncOperation<IReadOnlyList<StorageFile>>, IAsyncInfo

Page 24: WinRT Holy COw

Accessing a WinRT Collection from C#

var picker = new FileOpenPicker();picker.FileTypeFilter.Add("*");var files = await picker.PickMultipleFilesAsync();foreach (StorageFile file in files){ lbFiles.Items.Add(file.FileName);}

System.Collections.Generic.IReadOnlyList <Windows.Storage.StorageFile>

Page 25: WinRT Holy COw

Accessing a WinRT Collection from C#

var picker = new FileOpenPicker();picker.FileTypeFilter.Add("*");var files = await picker.PickMultipleFilesAsync();foreach (StorageFile file in files){ lbFiles.Items.Add(file.FileName);}

System.Collections.Generic.IReadOnlyList <Windows.Storage.StorageFile>

Windows.Foundation.Collections.IVectorView <Windows.Storage.StorageFile>

Page 26: WinRT Holy COw

www.buildwindows.com

IIterable<T> ↔ IEnumerable<T>

IVector<T> ↔ IList<T>

IVectorView<T> ↔ IReadOnlyList<T>

IMap<K,V> ↔ IDictionary<K,V>

IMapView<K,V> ↔ IReadOnlyDictionary<K,V>

.NET automatically maps collection interfaces to their Windows

Runtime equivalent

Page 27: WinRT Holy COw

www.buildwindows.com

A few places use extension methods to bridge between Windows Runtime and managed code

Page 28: WinRT Holy COw

Streams Code Sample

FileOpenPicker picker = new FileOpenPicker();picker.FileTypeFilter.Add("*");

StorageFile file = await picker.PickSingleFileAsync();

Windows.Storage.Streams.IInputStream inputStream = await file.OpenForReadAsync();

System.IO.Stream stream = inputStream.AsStream();System.IO.StreamReader reader = new StreamReader(stream);

string contents = reader.ReadToEnd();

Page 29: WinRT Holy COw

IBuffer Code Sample

internal async void ProtectBytes(byte[] data, BinaryWriter output){ DataProtectionProvider dpp = new DataProtectionProvider();

IBuffer result = await dpp.ProtectAsync(data.AsBuffer()); byte[] protectedData; int start = 0; if (result.TryGetUnderlyingData(out protectedData, out start)) output.Write(protectedData); else throw new InvalidOperationException();}

Page 30: WinRT Holy COw

You can write your own Windows Runtime components

in C# or Visual Basic

Page 31: WinRT Holy COw

www.buildwindows.com

You should build a Windows Runtime component when you want

your code to be used fromJS, C++, C# and VB

Page 32: WinRT Holy COw

Traditional COM in Managed Code

[ComVisible(true), Guid("06D7901C-9045-4241-B8A0-39A1AC0F8618")]public interface IWindowsApiSample{ string HelloWorld();}

[ComVisible(true), [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(IWindowsApiSample))]public class WindowsApiSample : IWindowsApiSample{ public string HelloWorld() { return "Hello, World!"; }}

Page 33: WinRT Holy COw

Windows Runtime in managed code Sample

public sealed class MyClassLibrary{ public string HelloWorld() { return "Hello, World!"; }}

Page 34: WinRT Holy COw

www.buildwindows.com

By adhering to a few simple rules, you can build

a managed Windows Runtime component

that projects into C++ or JavaScript

Page 35: WinRT Holy COw

www.buildwindows.com

Only the public types and members

in your managed Windows Runtime component project need to follow

the simple rules

Page 36: WinRT Holy COw

www.buildwindows.com

API signatures must only use Windows Runtime types

Inheritance can only be used for XAML controls,

all other types must be sealedOnly supports system provided generic types

Structs can only have public data fields

Page 37: WinRT Holy COw

public sealed class ManagedLibrary{ public List<int> GetNumbers() { List<int> numbers = new List<int>(); numbers.AddRange(new int[] {0,1,1,2,3}); return numbers; }}

Authoring Collection Code

Page 38: WinRT Holy COw

public sealed class ManagedLibrary{ public IList<int> GetNumbers() { List<int> numbers = new List<int>(); numbers.AddRange(new int[] {0,1,1,2,3}); return numbers; }}

Authoring Collection Code

Page 39: WinRT Holy COw

private async Task<string> GetTweetTaskAsync(){ string url = "http://api.twitter.com/1/statuses/" + "user_timeline.xml?screen_name=bldwin"; var http = new HttpClient(); var resp = await http.GetAsync(url); var xml = XDocument.Load(resp.Content.ContentReadStream); var str = xml.Descendants("text") .Select(x => x.Value).First(); return str;}

Authoring Managed Async Method

Page 40: WinRT Holy COw

Authoring Windows Runtime Async Method

public IAsyncOperation<string> GetTweetAsync(){ return AsyncInfoFactory.Create( () => this.GetTweetTaskAsync());}

Page 41: WinRT Holy COw

www.buildwindows.com

Visual Studio has built-in support for managed

Windows Runtime component projects

Page 42: WinRT Holy COw

www.buildwindows.com

Building Windows Runtime Components in C#

demo

Page 43: WinRT Holy COw

www.buildwindows.com

You already have the skills to build Metro style apps

with C# and VB

Page 44: WinRT Holy COw

Influenced by C# and VB

Feels natural and familiar from C# and Visual Basic

Build your own managed Windows Runtime components

Page 45: WinRT Holy COw

www.buildwindows.com

[email protected]

• @2j2e

thank you