Jamie Cool.NET Framework Team Microsoft Corporation jamiec@microsoft.com Nick Kramer.NET Framework...

Preview:

Citation preview

Building Silverlight Applications using .NET (Part 1 & 2)Jamie Cool.NET Framework TeamMicrosoft Corporationjamiec@microsoft.com

Nick Kramer.NET Framework TeamMicrosoft Corporationnkramer@microsoft.com

Agenda – Part 1

Part 1Silverlight + .NET OverviewGetting StartedWorking with UIBuilding custom controls

Part 2HTTP Networking + XMLWeb ServicesLINQHTML IntegrationRounding it out

Tons of stuff – 2+ talks worth!

Characteritics of an RIA

Web deploymentNeed a ubiquitous platformNeed a secure sandboxed environment

Rich UI experiences beyond server generated HTML

Need a highly capable UI model

Signifigant client-side application logicNeed a highly productive development environment

.NET + Silverlight

Highly productive development FrameworkMulti-language support, like C# & VBContains the latest innovation from Microsoft (ex. LINQ)AJAX integration

Great tools with Visual Studio & Expression

Cross-platform & cross-browser pluginWorks with Safari, Firefox and IE on MAC & WindowsFast, easy install process

Legend

V1.1Legend

V1.0

.NET for Silverlight

XAML

Pre

sen

tati

on

Core

Networking

JSON

REST POXRSS

DataLINQ XLINQ

DLRRuby Python

WPFExtensible Controls

BCLGenerics Collections

InputsKeyboardMouse Ink

MediaVC1 WMA MP3

Browser Host

MS AJAX Library

DOM Integration

UI Core

Images

Vector Text

Animation

DRM

Media

ControlsLayout Editing

CLR Execution Engine

Deploy

Friction-Free Installer

Auto-Updater

ApplicationServices

SOAP

.NET for Silverlight & the Desktop

.NET for Silverlight is a factored subset of full .NETDesktop ~50 MB (Windows only)

Silverlight + .NET Alpha ~ 4 MB (cross platform)

Additional pieces of .NET available in a pay-for-play model

Same core development FrameworkThe shared apis & technologies are the same

The tools are the same

Highly compatibleMinimal changes needed to move from Silverlight to Desktop

However, not binary compatible by default

The Sandbox

All apps run in the sandboxConceptually similar to the HTML DOM sandbox

Apps run just like HTML pages – just click a URLNo elevation prompts. No way to get out of the sandbox

Includes some additional functionality:Safe isolated storageClient based file upload controlsCross domain support in-work

Getting Started with .NET on Silverlight

What You'll Need:

Install the following: Silverlight V1.1 AlphaVisual Studio “Orcas” Beta 1Silverlight Tools Alpha for Visual Studio "Orcas" Beta 1Expression Blend 2 May PreviewASP.NET Futures

Everything you need is at www.silverlight.net Links to downloads & docsVS object browser a great way to view APIs

What makes up a .NET Silverlight appA .NET silverlight app includes at least:

A root html file - Default.htm

Script load files - CreateSilverlight.js & Silverlight.js

A root xaml & assembly - YourApp.xaml & YourApp.dll

A .NET Silverlight app is also likely to include:Other application libraries (your's, Microsoft's or 3rd parties)

Application resources (ex. xaml) – optionally embedded in assembly

PackagingLoose file support in Alpha 1

Zip package support planned

Getting Started

demo

Working with UI

XAML (rhymes with Camel)

XAML = eXtensible Application Markup LanguageFlexible XML document schema

Examples: WPF, Silverlight, Workflow Foundation

More compact than codeEnables rich tooling support

While still preserving good readability and hand-coding within text editors

XAML Sample

<Canvas xmlns="http://schemas.microsoft.com/client/2007" > <TextBlock FontSize="32" Text="Hello world" /></Canvas>

<Canvas xmlns="http://schemas.microsoft.com/client/2007" > <TextBlock FontSize="32" Text="Hello world" /></Canvas>

Hello world

Markup = Object Model

<TextBlock FontSize="32" Text="Hello world" /><TextBlock FontSize="32" Text="Hello world" />

TextBlock t = new TextBlock();t.FontSize = 32;t.Text = "Hello world";

TextBlock t = new TextBlock();t.FontSize = 32;t.Text = "Hello world";

=

Canvas

Is a Drawing SurfaceChildren have relative positions:

<Canvas Width="250" Height="200">

<Rectangle Canvas.Top="25" Canvas.Left="25" Width="200" Height="150" Fill="Yellow" />

</Canvas>

<Canvas Width="250" Height="200">

<Rectangle Canvas.Top="25" Canvas.Left="25" Width="200" Height="150" Fill="Yellow" />

</Canvas>

The Canvas

The Rectangle

Canvas (2)

Position relative to first Canvas parent:<Canvas Background="Light Gray"> <Canvas Canvas.Top="25" Canvas.Left="25" Width="150" Height="100" Background="Red">

<Ellipse Canvas.Top="25" Canvas.Left="25" Width="150" Height="75" Fill=“White" /> </Canvas></Canvas>

<Canvas Background="Light Gray"> <Canvas Canvas.Top="25" Canvas.Left="25" Width="150" Height="100" Background="Red">

<Ellipse Canvas.Top="25" Canvas.Left="25" Width="150" Height="75" Fill=“White" /> </Canvas></Canvas>

Canvas (3)

<Canvas> <Rectangle/></Canvas>

<Canvas> <Rectangle/></Canvas>

Canvas canvas = new Canvas();Rectangle rectangle = new Rectangle();canvas.Children.Add(rectangle);

Canvas canvas = new Canvas();Rectangle rectangle = new Rectangle();canvas.Children.Add(rectangle);

=

Attached Properties

<Canvas> <Rectangle Canvas.Top="25"/></Canvas>

Top property only make sense inside a CanvasWhen we add new layouts, do we add new properties to Rectangle?

Solution: attached properties!

Attached Properties (2)

<Rectangle Canvas.Top="25" Canvas.Left="25"/><Rectangle Canvas.Top="25" Canvas.Left="25"/>

Rectangle rectangle = new Rectangle();rectangle.SetValue(Canvas.TopProperty, 25);rectangle.SetValue(Canvas.LeftProperty, 25);

Rectangle rectangle = new Rectangle();rectangle.SetValue(Canvas.TopProperty, 25);rectangle.SetValue(Canvas.LeftProperty, 25);

=

Fantasy Baseball

demo

Transformations

All elements support themTransform Types

<RotateTransform /><ScaleTransform /><SkewTransform /><TranslateTransform />

Moves

<MatrixTransform />Scale, Skew and Translate Combined

Transformations (2)

<TextBlock Text="Hello World"> <TextBlock.RenderTransform> <RotateTransform Angle="45" /> </TextBlock.RenderTransform></TextBlock>

<TextBlock Text="Hello World"> <TextBlock.RenderTransform> <RotateTransform Angle="45" /> </TextBlock.RenderTransform></TextBlock>

Hello World

Hello World

Property Elements

Property values can be complex objectsUse “property elements” to represent them in XML

<SomeClass.SomeProperty>

Property Elements (2)

<TextBlock> <TextBlock.RenderTransform> <RotateTransform Angle="45" /> </TextBlock.RenderTransform></TextBlock>

<TextBlock> <TextBlock.RenderTransform> <RotateTransform Angle="45" /> </TextBlock.RenderTransform></TextBlock>

TextBlock block = new TextBlock;RotateTransform transform = new RotateTransform();Transform.Angle = 45;block.RenderTransform = transform;

TextBlock block = new TextBlock;RotateTransform transform = new RotateTransform();Transform.Angle = 45;block.RenderTransform = transform;

=

<ScaleTransform>

demo

Common Events

MouseMoveMouseEnterMouseLeaveMouseLeftButtonDownMouseLeftButtonUp

KeyUpKeyDownGotFocusLostFocusLoaded

Silverlight Event Example

<Canvas xmlns="…" xmlns:x="…" MouseEnter="OnMouseEnter"> </Canvas>

<Canvas xmlns="…" xmlns:x="…" MouseEnter="OnMouseEnter"> </Canvas>

Canvas canvas = new Canvas();canvas.MouseEnter += OnMouseEnter;

// or more explicitly:canvas.MouseEnter += new MouseEventHandler(OnMouseEnter);

Canvas canvas = new Canvas();canvas.MouseEnter += OnMouseEnter;

// or more explicitly:canvas.MouseEnter += new MouseEventHandler(OnMouseEnter);

=

Silverlight Event Example (VB)<Canvas xmlns="…" xmlns:x="…" Height="100" Width="100" Background="Red" x:Name=“canvas” /> </Canvas>

<Canvas xmlns="…" xmlns:x="…" Height="100" Width="100" Background="Red" x:Name=“canvas” /> </Canvas>

Private Sub something _ (ByVal o As Object, ByVal e As MouseEventArgs) _ Handles canvas.MouseEnter rectangle.Fill = New SolidColorBrush(Colors.Green) End Sub

Private Sub something _ (ByVal o As Object, ByVal e As MouseEventArgs) _ Handles canvas.MouseEnter rectangle.Fill = New SolidColorBrush(Colors.Green) End Sub

Silverlight Event Example

<Canvas xmlns="…" xmlns:x="…" Height="100" Width="100" Background="Red" MouseEnter="OnMouseEnter" /> </Canvas>

<Canvas xmlns="…" xmlns:x="…" Height="100" Width="100" Background="Red" MouseEnter="OnMouseEnter" /> </Canvas>

void OnMouseEnter(object sender, MouseEventArgs e) { …}

void OnMouseEnter(object sender, MouseEventArgs e) { …}

x:Name

Name your xaml element so you can use it in code

<Rectangle x:Name=“rect”/><Rectangle x:Name=“rect”/>

void OnMouseEnter(object sender, MouseEventArgs e) { rect.Height = 75;}

void OnMouseEnter(object sender, MouseEventArgs e) { rect.Height = 75;}

Custom Elements in XAML

Custom Element = custom class (Markup = object model)

Use XML namespaces<prefix:CustomClass/>

XML namespace declaration tells where to find class

xmlns:prefix="clr-namespace:SomeNamespace;assembly=SomeAssembly.dll"

<custom:Button>

demo

Writing custom controls

Derive from ControlEg, public class MyControl : Control

Define the look of the control in xamlCall InitializeFromXaml(xaml)Remember the return value

XAML-able Custom Controls

Have a public parameterless constructorEg, public MyControl()

Create public propertiesCreate public events

Custom Control

demo

Feature comparison – 1.0 vs 1.1

In terms of graphics/UI/XAML:

v1.1 =v1.0

+ managed code (CLR)

+ XAML extensibility

+ Control class (user control)

+ sample controls

Feature comparison – Controls

1.1 alpha 1.1 thinking WPFButton Sample Yes YesTextBox (edit)

No Yes Yes

Scrollbar Sample Yes YesSlider Sample Yes YesListBox Sample Yes YesCheckBox No Yes YesRadioButton No Yes YesComboBox No Yes Yes

Feature comparison – Controls (2)

1.1 alpha 1.1 thinking WPFTreeView No No YesAccordion No No 3rd partyDataGrid No No 3rd partyUserControl Yes Yes Yes

Feature comparison -- Layout

1.1 alpha 1.1 thinking WPFCanvas Yes Yes YesGrid (table) No Yes YesStackPanel No Yes YesViewbox No Yes Yes

Feature comparison -- other

1.1 alpha 1.1 thinking WPFMouse events

Partial Yes Yes

Keyboard events

Partial Yes Yes

<.Resources>

Partial Yes Yes

Data binding No Yes Yesstyling No Yes Yes

Feature comparison -- other

1.1 alpha 1.1 thinking WPF3D No No YesHardware acceleration

No No Yes

Out of browser

No No Yes

Off-line No No YesCross-platform

Yes Yes No

Intermission

Agenda – Part 2

HTTP Networking + XMLWeb ServicesLINQHTML IntegrationRounding it outResources

HTTP Networking + XML

Browser based HTTP networking stack

StreamReader responseReader = new StreamReader(response.GetResponseStream());string RawResponse = responseReader.ReadToEnd();

StreamReader responseReader = new StreamReader(response.GetResponseStream());string RawResponse = responseReader.ReadToEnd();

Browser based headers/cookies passed with requestRestricted to same domain access in the AlphaCross-domain coming

Uri dataLocation = new Uri("http://localhost/playerdata.xml");BrowserHttpWebRequest request = new BrowserHttpWebRequest(dataLocation);HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Uri dataLocation = new Uri("http://localhost/playerdata.xml");BrowserHttpWebRequest request = new BrowserHttpWebRequest(dataLocation);HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Make the HTTP Request

Process the response

XmlReader & XmlWriter

XmlReader xr = XmlReader.Create(new StringReader(RawResponse));XmlReader xr = XmlReader.Create(new StringReader(RawResponse));

Core XML reading & writing capabilities in the alphaRAD XLINQ support coming

xr.ReadToFollowing("Player");string playerNodeText = xr.Value;string playerNameAttribute = xr.GetAttribute("Name");

xr.ReadToFollowing("Player");string playerNodeText = xr.Value;string playerNameAttribute = xr.GetAttribute("Name");

Initialize the reader

Find a node & read it’s value

HTTP Networking + XML

demo

Web Services

Web Services

[WebMethod]public List<Player> GetPlayerList() { ... }[WebMethod]public List<Player> GetPlayerList() { ... }

VS based Proxy Generator enables strongly typed accessASP.NET JSON services supported in the AlphaWCF & SOAP support coming

baseballService = new BaseballData();playerList = baseballService.GetPlayerList().ToList();baseballService = new BaseballData();playerList = baseballService.GetPlayerList().ToList();

The Web Service to Call

Call the Web Service from the client

Async Support

Sync & Async web services supported in the AlphaGeneral purpose RAD async support coming

baseballService.BeginGetPlayerList(new AsyncCallback(OnPlayerDataLoaded), null);

baseballService.BeginGetPlayerList(new AsyncCallback(OnPlayerDataLoaded), null);

private void OnPlayerDataLoaded(IAsyncResult iar){

playerList = baseballService.EndGetPlayerList(iar).ToList();}

private void OnPlayerDataLoaded(IAsyncResult iar){

playerList = baseballService.EndGetPlayerList(iar).ToList();}

Start the async web service call

Handle the web service completion event

Web Services

demo

Works with any Web serverOnly requirement is to serve Silverlight files to the browserEx. xaml, assemblies, resources

ASP.NET is a great platform for Silverlight applications

Use ASP.NET & WCF services from SilverlightIntegrate Media into an ASPX pageIntegrate Silverlight content into an ASPX pageLeverage ASP.NET AJAX Extensions and ASP.NET Futures (May 2007)Other integration points under way…

Silverlight on the server

LINQ

LINQ

var filteredPlayers = from p in players where p.HomeRuns > 20 orderby p.HomeRuns descending select p;

var filteredPlayers = from p in players where p.HomeRuns > 20 orderby p.HomeRuns descending select p;

Return all players with 20+ home runs, sorted

LINQ = Language INtegrated Query Allows query expressions to benefit from compile-time syntax checkking, static typing & IntellisenseWorks on any IEnumerable<T> based info source

LINQ

Supports querying on in memory datasourcesOther LINQ technologies forthcoming:

XLINQ = LINQ for XMLQuery, parse, create XML

DLINQ = LINQ for relational dataQuery, edit, create relational data

Using LINQ

demo

HTML Integration

Access the HTML DOM from ManagedHTML access availble in new namespace

HtmlPage.Navigate("http://www.microsoft.com");String server = HtmlPage.DocumentUri.Host;HtmlPage.Navigate("http://www.microsoft.com");String server = HtmlPage.DocumentUri.Host;

using System.Windows.Browser;using System.Windows.Browser;

HtmlElement myButton = HtmlPage.Document.GetElementByID("myButtonID");myButton.AttachEvent("onclick", new EventHandler(this.myButtonClicked));

private void myButtonClicked(object sender, EventArgs e) { ... }

HtmlElement myButton = HtmlPage.Document.GetElementByID("myButtonID");myButton.AttachEvent("onclick", new EventHandler(this.myButtonClicked));

private void myButtonClicked(object sender, EventArgs e) { ... }

Static HtmlPage class provides entry point

Hookup events, call methods, or access properties

Access Managed Code from ScriptMark a property, method or event as Scriptable:

WebApplication.Current.RegisterScriptableObject("BaseballData", this); WebApplication.Current.RegisterScriptableObject("BaseballData", this);

[Scriptable]public void Search(string Name) { … }[Scriptable]public void Search(string Name) { … }

var control = document.getElementById("Xaml1");control.Content.BaseballData.Search(input.value);var control = document.getElementById("Xaml1");control.Content.BaseballData.Search(input.value);

Register a scriptable object:

Access the managed object from script:

HTML Integration

Other interesting HTML integration scenarios:Persisent links

Fwd/Back Integration

Notes:Simple type marshalling only in the AlphaComplex type support on the way

HTML Integration

demo

MAC Debugging

MAC Debugging

Enables debugging of Silverlight code on the MACRequires a proxy client installed on the MACProxy & setup instructions can be found at:

C:\Program Files\Microsoft Visual Studio 9.0\Silverlight\MacIntel\ Proxy must be running prior to browser activation

MAC Debugging

demo

Other .NET Related Features of Note…

Dynamic LanguagesJavascript, Python, Ruby

Application ServicesIsolated StorageSafe File Open

ASP.NET Integration

Find out more about these technologies in upcoming sessions…

Related talks…

Talk TimeJust Glue It! Dynamic Languages in Silverlight Tues – 11:45

Developing ASP.NET AJAX Controls with Silverlight Tues – 11:45

Deep Dive on Silverlight Media Integration Tues - 2:15

Extending the Browser Programming Model with Silverlight

Wens – 9:45

Building Rich, Interactive E-commerce Applications Using ASP.NET and Silverlight

Wens – 11:30

Call to Action

Give us feedbackFeatures you like?Features you don’t?What do you want to build?What existing code & skills will you leverage?

© 2007 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.

Recommended