49
1 Building Silverlight Applications using .NET Matt Gibbs Development Manager [email protected]

Building Silverlight Applications using - TechTargetajaxexperience.techtarget.com/images/Presentations/Gibbs_AJAX...Building Silverlight Applications using .NET ... VC1 WMA MP3 Browser

Embed Size (px)

Citation preview

1Building Silverlight Applications

using .NET

Matt GibbsDevelopment [email protected]

Agenda

2

Tons of stuff Tons of stuff –– 2+ talks worth!2+ talks worth!

§ Silverlight + .NET Overview§ Getting Started§ Working with UI§ Building custom controls§ HTTP Networking + XML§ Web Services§ LINQ§ HTML Integration

3

Characteristics of a RIA

§ Web deployment§ Need a ubiquitous platform§ Need a secure sandboxed environment

§ Rich UI experiences beyond server generated HTML§ Need a highly capable UI model

§ Signifigant client-side application logic§ Need a highly productive development environment

.NET + Silverlight

4

¨ Highly productive development Framework¤Multi-language support, like C# & VB¤Contains the latest innovation from Microsoft (ex.

LINQ)¤ AJAX integration

¨ Great tools with Visual Studio & Expression

¨ Cross-platform & cross-browser plugin¤Works with Safari, Firefox and IE on MAC &

Windows¤ Fast, easy install process

Legend

V1.1Legend

V1.0XAML

Networking

JSON

REST POXRSS

Data

LINQ 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 .NET¤ Desktop ~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 Framework¤ The shared apis & technologies are the same ¤ The tools are the same

¨ Highly compatible¤ Minimal changes needed to move from Silverlight to Desktop¤ However, not binary compatible by default

The Sandbox

¨ All apps run in the sandbox¤Conceptually similar to the HTML DOM sandbox

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

¨ Includes some additional functionality:¤ Safe isolated storage¤Client based file upload controls¤Cross domain support in-work

Getting Started with .NET on Silverlight

What You'll Need:

¨ Install the following: ¤ Silverlight V1.1 Alpha¤ Visual Studio “Orcas” Beta 1¤ Silverlight Tools Alpha for Visual Studio "Orcas"

Beta 1¤ Expression Blend 2 May Preview¤ ASP.NET Futures

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

What makes up a .NET Silverlight app

¨ A .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¨ Packaging¤ Loose file support in Alpha 1¤ Zip package support planned

Working with UI

XAML (rhymes with Camel)

¨ XAML = eXtensible Application Markup Language¨ Flexible XML document schema

¤Examples: WPF, Silverlight, Workflow Foundation

¨ More compact than code¨ Enables 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" ><Canvas xmlns="http://schemas.microsoft.com/client/2007" ><TextBlock FontSize="32" Text="Hello world" /><TextBlock FontSize="32" Text="Hello world" />

</Canvas></Canvas>

Hello world

Markup = Object Model

<TextBlock FontSize="32" Text="Hello world" /><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();TextBlock t = new TextBlock();t.FontSize = 32;t.FontSize = 32;t.Text = "Hello world";t.Text = "Hello world";

==

Canvas

¨ Is a Drawing Surface¨ Children 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"><Canvas Width="250" Height="200">

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

</Canvas></Canvas>

The CanvasThe Canvas

The RectangleThe 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=“Black" />

</Canvas></Canvas>

<Canvas Background="Light Gray"><Canvas Background="Light Gray"><Canvas Canvas.Top="25" Canvas.Left="25"<Canvas Canvas.Top="25" Canvas.Left="25"

Width="150" Height="100" Width="150" Height="100" Background="Red">Background="Red">

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

</Canvas></Canvas></Canvas></Canvas>

Canvas (3)

<Canvas><Rectangle/>

</Canvas>

<Canvas><Canvas><Rectangle/><Rectangle/>

</Canvas></Canvas>

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

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

==

Attached Properties

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

¨ Top property only make sense inside a Canvas¨ When 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 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 rectangle = new Rectangle();rectangle.SetValue(Canvas.TopProperty, 25);rectangle.SetValue(Canvas.TopProperty, 25);rectangle.SetValue(Canvas.LeftProperty, 25);rectangle.SetValue(Canvas.LeftProperty, 25);

==

Transformations

¨ All elements support them¨ Transform Types¤<RotateTransform />¤<ScaleTransform />¤<SkewTransform />¤<TranslateTransform />n Moves

¤<MatrixTransform />n Scale, Skew and Translate Combined

Common Events

¨ MouseMove¨ MouseEnter¨ MouseLeave¨ MouseLeftButtonDown¨ MouseLeftButtonUp

§ KeyUp§ KeyDown§ GotFocus§ LostFocus

Silverlight Event Example

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

</Canvas>

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

</Canvas></Canvas>

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

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

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

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

==

Silverlight Event Example (VB)<Canvas xmlns="…" xmlns:x="…"

Height="100" Width="100" Background="Red"

x:Name=“canvas”/>

</Canvas>

<Canvas xmlns="<Canvas xmlns="……" xmlns:x="" xmlns:x="……""Height="100" Width="100" Height="100" Width="100"

Background="Red" Background="Red" x:Name=x:Name=““canvascanvas””

/> /> </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 _Private Sub something _(ByVal o As Object, ByVal e As (ByVal o As Object, ByVal e As

MouseEventArgs) _MouseEventArgs) _Handles canvas.MouseEnterHandles canvas.MouseEnter

rectangle.Fill = New rectangle.Fill = New SolidColorBrush(Colors.Green)SolidColorBrush(Colors.Green)End SubEnd Sub

x:Name

¨ Name your xaml element so you can use it in code

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

void OnMouseEnter(object sender, MouseEventArgs e) {

rect.Height = 75;}

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

rect.Height = 75;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"

Writing custom controls

¨ Derive from Control

¤Eg, public class MyControl : Control¨ Define the look of the control in xaml¨ Call InitializeFromXaml(xaml)¨ Remember the return value

XAML-able Custom Controls

¨ Have a public parameterless constructor

¤Eg, public MyControl()¨ Create public properties¨ Create public events

Feature comparison – 1.0 vs 1.1

¨ In terms of graphics/UI/XAML:

¨ v1.1 =n v1.0n + managed code (CLR)n + XAML extensibilityn + Control class (user control)n + sample controls

Feature comparison – Controls

1.1 alpha

1.1 thinking

WPFButton Sample Yes YesTextBox (edit)

No Yes YesScrollbar 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 YesKeyboard events

Partial Yes Yes

<.Resources> Partial Yes YesData binding No Yes Yesstyling No Yes Yes

Feature comparison -- other

1.1 alpha

1.1 thinking

WPF

3D No No YesHardware acceleration

No No Yes

Out of browser No No YesOff-line No No YesCross-platform Yes Yes No

HTTP Networking + XML

Browser based HTTP networking stack

¨ Browser based headers/cookies passed with request¨ Restricted to same domain access in the Alpha¨ Cross-domain coming

StreamReader responseReader = newStreamReader(response.GetResponseStream());

string RawResponse = responseReader.ReadToEnd();

StreamReader responseReader = StreamReader responseReader = newnewStreamReader(response.GetResponseStream());StreamReader(response.GetResponseStream());

stringstring RawResponse = responseReader.ReadToEnd();RawResponse = responseReader.ReadToEnd();

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

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

Make the HTTP RequestMake the HTTP Request

Process the responseProcess the response

XmlReader & XmlWriter

¨ Core XML reading & writing capabilities in the alpha

¨ RAD XLINQ support coming

XmlReader xr = XmlReader.Create(newStringReader(RawResponse));XmlReader xr = XmlReader.Create(XmlReader xr = XmlReader.Create(newnewStringReader(RawResponse));StringReader(RawResponse));

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

xr.ReadToFollowing("xr.ReadToFollowing("PlayerPlayer");");stringstring playerNodeText = xr.Value;playerNodeText = xr.Value;stringstring playerNameAttribute = playerNameAttribute = xr.GetAttribute("xr.GetAttribute("NameName");");

Initialize the readerInitialize the reader

Find a node & read itFind a node & read it’’s values value

Web Services

Web Services

¨ VS based Proxy Generator enables strongly typed access¨ ASP.NET JSON services supported in the Alpha¨ WCF & SOAP support coming

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

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

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

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

The Web Service to CallThe Web Service to Call

Call the Web Service from the clientCall the Web Service from the client

Async Support¨ Sync & Async web services supported in the

Alpha¨ General purpose RAD async support coming

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

baseballService.BeginGetPlayerList(baseballService.BeginGetPlayerList(newnew AsyncCallback(OnPlayerDataLoaded), AsyncCallback(OnPlayerDataLoaded), nullnull););

private void OnPlayerDataLoaded(IAsyncResult iar){

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

privateprivate voidvoid OnPlayerDataLoaded(IAsyncResult iar)OnPlayerDataLoaded(IAsyncResult iar){{

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

Start the async web service callStart the async web service call

Handle the web service completion eventHandle the web service completion event

Silverlight on the server

¨ Works with any Web server¤Only requirement is to serve Silverlight files to the

browser¤ Ex. xaml, assemblies, resources

¨ ASP.NET is a great platform for Silverlight applications¤Use ASP.NET & WCF services from Silverlight¤ Integrate Media into an ASPX page¤ Integrate Silverlight content into an ASPX page¤ Leverage ASP.NET AJAX Extensions and ASP.NET

Futures (May 2007)

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("HtmlPage.Navigate("http://www.microsoft.comhttp://www.microsoft.com");");StringString server = HtmlPage.DocumentUri.Host;server = HtmlPage.DocumentUri.Host;

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

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

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

HtmlElement myButton = HtmlElement myButton = HtmlPage.Document.GetElementByID("HtmlPage.Document.GetElementByID("myButtonIDmyButtonID");");myButton.AttachEvent("myButton.AttachEvent("onclickonclick", ", newnewEventHandler(EventHandler(thisthis.myButtonClicked));.myButtonClicked));

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

Static HtmlPage class provides entry point Static HtmlPage class provides entry point

Hookup events, call methods, or access propertiesHookup events, call methods, or access properties

Access Managed Code from Script

Mark a property, method or event as Scriptable:

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

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

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

Register a scriptable object:Register a scriptable object:

Access the managed object from script: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 Alpha¤Complex type support on the way

MAC Debugging

MAC Debugging

¨ Enables debugging of Silverlight code on the MAC

¨ Requires a proxy client installed on the MAC¨ Proxy & setup instructions can be found at:¤C:\Program Files\Microsoft Visual Studio

9.0\Silverlight\MacIntel\¤ Proxy must be running prior to browser activation

Other .NET Related Features of Note…

¨ Dynamic Languages¤ Javascript, Python, Ruby

¨ Application Services¤ Isolated Storage¤ Safe File Open

¨ ASP.NET Integration

Call to Action

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

Building Silverlight Applications using .NET

Matt GibbsDevelopment [email protected]