Building Silverlight Application using .NET (ScottGu)

Views:
 
     
 

Presentation Description

No description available.

Comments

Presentation Transcript

Building Silverlight Applications using .NET (Part 1 & 2):

Building Silverlight Applications using .NET (Part 1 & 2) Scott Guthrie General Manager Microsoft Corporation scottgu@microsoft.com

Agenda:

Agenda Silverlight + .NET Overview Getting Started XAML Shapes Controls Layout Brushes and Transforms Events and Code Building Custom Controls HTML and Script Integration File Open Dialog HTTP Network Access Web Services Isolated Storage Lots of content – 2+ talks worth

Download Slides + Samples:

Download Slides + Samples http://weblogs.asp.net/scottgu

Silverlight + .NET Overview:

Silverlight + .NET Overview

Characteristics of an RIA:

Characteristics of an RIA Web deployment Broad client reach Secure sandboxed environment Rich UI experiences beyond server generated HTML Highly capable UI model Signifigant client-side application logic Highly productive development environment

.NET + Silverlight:

.NET + Silverlight Cross-platform & cross-browser plugin Works with Safari, Firefox and IE on MAC & Windows Fast, easy install process Highly productive development Framework Multi-language support – VB, C#, JavaScript, Python, Ruby Rich class library of functionality that can be used Great tools with Visual Studio & Expression

Silverlight Security Sandbox:

Silverlight Security Sandbox Silverlight applications run in a security sandbox Activation model just like HTML pages – just click a URL No user elevation or security prompts within the browser Applications prevented from doing malicious things Silverlight enables some additional browser scenarios: Safe isolated storage Client based file upload controls Cross domain support (future)

.NET for Silverlight & the Desktop :

.NET for Silverlight & the Desktop .NET for Silverlight is a subset of the full . NET Framework Targetted support for RIA and Media scenarios Common core .NET development model Common APIs across both browser and desktop scenarios Common WPF UI programming model across both Development and Designer tools are the same Highly compatible Minimal changes needed to move from Silverlight to Desktop

Getting Started with .NET on Silverlight :

Getting Started with .NET on Silverlight

What You'll Need::

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 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:

What makes up a .NET Silverlight app A .NET silverlight app always incluides: A html file that hosts a Silverlight control (for example: Test.htm) JavaScript load files - CreateSilverlight.js & Silverlight.js A root XAML file & assembly - YourA pp.xaml & YourApp.dll A .NET Silverlight app is also likely to include: Other application libraries (your's, Microsoft's or 3 rd parties) Application resources (ex. xaml) – optionally embedded in assembly

Loading a Silverlight Application…:

Loading a Silverlight Application …

Test.htm:

Test.htm createSilverlight() method called to load the control <html> <head> <script type=“text/ javascript ” src =“Silverlight.js”></script> <script type=“text/ javascript ” src =“CreateSilverlight.js”></script> </head> <body> < div id=" SilverlightControlHost "> <script type="text/ javascript "> createSilverlight (); </script> </ div > </body> </html>

CreateSilverlight.js:

CreateSilverlight.js Source: XAML file referencing app entry point Silverlight.js takes care of control install if Silverlight is not already installed on t he machine function createSilverlight () { Sys.Silverlight.createObjectEx ({ source: " Page.xaml ", parentElement : document.getElementById (" SilverlightControlHost "), id: " SilverlightControl ", properties: { width: "100%", height: "100%", version: "0.95", }, }); }

Page.xaml:

Page.xaml Every app has a root XAML file References code assembly & class entry point < Canvas xmlns ="http://schemas.microsoft.com/client/2007" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" x:Class=“ MyPage;assembly = ClientBin /MyApp.dll“ Loaded=" Page_Loaded " Width ="640" Height ="480" Background ="White “> < TextBlock x:Name=“ MyMessage ” /> </Canvas >

MyPage.xaml.cs:

MyPage.xaml.cs Code behind file for the parent XAML public partial class MyPage : Canvas { public void Page_Loaded (object o, EventArgs e) { InitializeComponent (); MyMessage.Text = “Hello World!”; } }

Running Application…:

Running Application …

Getting Started:

Getting Started demo

XAML, Shapes and Controls:

XAML, Shapes and Controls

XAML:

XAML XAML = eXtensible Application Markup Language Flexible XML document schema Example usages: WPF, Silverlight, Workflow Foundation Enables rich tooling support While still preserving readability & hand-coding with text editors

XAML Sample:

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

Markup = Object Model:

Markup = Object Model <TextBlock FontSize="32" Text="Hello world" /> TextBlock t = new TextBlock(); t.FontSize = 32; t.Text = "Hello world"; = Anything that can be expressed in XAML can be programmatically coded as well

<TextBlock />:

< TextBlock /> < TextBlock >Hello</ TextBlock > Hello < TextBlock FontSize ="18">Hello</ TextBlock > Hello < TextBlock FontFamily ="Courier New">Hello</ TextBlock > Hello < TextBlock TextWrapping ="Wrap" Width="100"> Hello there, how are you? </ TextBlock > Hello there, how are you? < TextBlock > Hello there,< LineBreak />how are you? </ TextBlock > Hello there, how are you?

Shapes:

Shapes <Rectangle /> <Ellipse /> <Line /> <Polygon /> < PolyLine /> <Path />

Controls (1):

Controls (1) Re-usable UI elements that encapsulate UI and behavior and enable re-use and composition < Scottgu:Button x:Name=“ MyButton ” Text=“Push Me” /> Button b = new Button(); b.Text = “Push Me";

Controls (2):

Controls (2) Controls are referenced in XAML using XML namespace that points to assembly containing implementation < Canvas xmlns ="http://schemas.microsoft.com/client/2007" xmlns:x ="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Scottgu =" clr-namespace:Scottgu;assembly = ClientBin /Scottgu.dll" x:Class =“ MyNamespace.MyPage;assembly = ClientBin /MyApp.dll“ Loaded=" Page_Loaded " Width ="640" Height =" 480“> < Scottgu:Button x:Name=“ MyButton ” Text=“Push Me” /> </Canvas >

Controls (3):

Controls (3) Silverlight 1.1 Alpha has very few built-in controls MediaElement, Image, Canvas, TextElement Rich set of controls will start appearing with later betas TextBox, CheckBox, RadioButton, ListBox, ComboBox, Button, Slider, ScrollBar, ListBox, GridView, etc. Separate sample download for Silverlight 1.1 Alpha provides simple Button, Slider, ListBox and ScrollBar implementation

Shapes and Control Basics:

Shapes and Control Basics demo

Layout:

Layout

Canvas:

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> The Canvas The Rectangle

Canvas (2):

Canvas (2) Position relative to immediate 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 (3):

Canvas (3) <Canvas> <Rectangle/> </Canvas> Canvas canvas = new Canvas(); Rectangle rectangle = new Rectangle (); canvas.Children.Add (rectangle); = Canvas container maintains collection of child elements:

Attached Property Syntax:

Attached Property Syntax <Canvas> <Rectangle Canvas.Top="25"/> </Canvas> Top property only make sense inside a Canvas When we add new container types, do we have to add new properties to Rectangle ? Solution: U s e attached properties to add flexible, container specific customization

Attached Properties (2):

Attached Properties (2) <Rectangle Canvas.Top="25" Canvas.Left="25"/> Rectangle rectangle = new Rectangle(); rectangle.SetValue(Canvas.TopProperty, 25); rectangle.SetValue(Canvas.LeftProperty, 25); =

Canvas Layout Basics:

Canvas Layout Basics demo

Layout Managers (1):

Layout Managers (1) Silverlight 1.1 Alpha only supports Canvas Positioning Makes it hard to support flexible flow management WPF supports concept of layout managers Flexible containers that provide positioning and re-sizing support Future Silverlight 1.1 builds adding layout manager support Will include built-in Grid and StackPanel layout controls

Layout Managers (2):

Layout Managers (2) < StackPanel Orientation="Vertical"> <Button>Button 1</Button> <Button>Button 2</Button> </ StackPanel >

Layout Manager Prototype:

Layout Manager Prototype demo

Brushes:

Brushes

Brushes:

Brushes Determines how objects are painted For painting objects (e.g. Fill) For painting of lines (e.g. Stroke) Brush options include: Solid color brushes Gradient brushes Image brushes Video brushes

Brushes (2):

Brushes (2) < SolidColorBrush /> Support creation by name 141 named colors supported (e.g. Blue, Red, Green) Supports #FFFFFF or #FFFFFFFF syntax as well <Rectangle Width="200" Height="150" > < Rectangle.Fill > < SolidColorBrush Color="Black" /> </ Rectangle.Fill > </Rectangle> <Rectangle Width="200" Height="150" Fill="Black" /> <Rectangle Width="200" Height="150" Fill="#FFFFFF" />

Brushes (3):

Brushes (3) < LinearGradientBrush /> Start and Stop are to set angle as numbers Gradient Stops are the different color points <Rectangle Width="200" Height="150 "> < Rectangle.Fill > < LinearGradientBrush StartPoint ="0,0" EndPoint ="1,1"> < LinearGradientBrush.GradientStops > < GradientStop Color =“Blue" Offset ="0" /> < GradientStop Color="Black" Offset ="1" /> </ LinearGradientBrush.GradientStops > </ LinearGradientBrush > </ Rectangle.Fill > </ Rectangle>

Brushes (4):

Brushes (4) < RadialGradientBrush /> Gradient Stops are same syntax as Linear Gradient <Rectangle Width="200" Height="150" > < Rectangle.Fill > < RadialGradientBrush > < RadialGradientBrush.GradientStops > < GradientStop Color="Red" Offset="0" /> < GradientStop Color="Black" Offset="1" /> </ RadialGradientBrush.GradientStops > </ RadialGradientBrush > </ Rectangle.Fill > </Rectangle>

Brushes (5):

Brushes (5) < ImageBrush /> Gradient Stops are same syntax as Linear Gradient <Ellipse Width="200" Height="75" > < Ellipse.Fill > < ImageBrush ImageSource ="http://.../XBox360Logo.jpg" /> </ Ellipse.Fill > </Ellipse>

Brushes (6):

Brushes (6) < VideoBrush /> Enables using moving video as a Brush on an object < MediaElement x:Name=“ MyVideo ” Source=“Video.wmv” IsMuted =“true”/> < Ellipse Width="200" Height="75" > < Ellipse.Fill > < VideoBrush SourceName =“ MyVideo ”/> </ Ellipse.Fill > </Ellipse>

Brushes:

Brushes demo

Transformations:

Transformations All elements support them Transform Types <RotateTransform /> <ScaleTransform /> <SkewTransform /> <TranslateTransform /> Moves <MatrixTransform /> Scale, Skew and Translate Combined

Transformations (2):

Transformations (2) < TextBlock Text="Hello World"> < TextBlock.RenderTransform > < RotateTransform Angle="45" /> </ TextBlock.RenderTransform > </ TextBlock > Hello World

Transformations (3):

Transformations (3) <Canvas x:Name="Content" Width="500" Height="500"> < TextBlock FontSize ="24“>Button still works!</ TextBlock > < scottgu:Button Text="Push Me" Canvas.Top ="50" /> < Canvas.RenderTransform > < TransformGroup > < RotateTransform Angle="45"/> < SkewTransform AngleX ="45"/> </ TransformGroup > </ Canvas.RenderTransform > </Canvas>

Property Element Syntax:

Property Element Syntax Property values can be complex objects Use “property elements” to represent them in XAML <SomeClass.SomeProperty>

Property Elements (2):

Property Elements (2) <TextBlock> <TextBlock.RenderTransform> <RotateTransform Angle="45" /> </TextBlock.RenderTransform> </TextBlock> TextBlock block = new TextBlock; RotateTransform transform = new RotateTransform(); Transform.Angle = 45; block.RenderTransform = transform; =

Transforms:

Transforms demo

Events:

Events

x:Name:

x:Name Name your XAML element so you can use it in code Visual Studio automatically declares field for all x:name elements < TextBlock x:Name=“ MyMessage ”/> public void Page_Loaded (sender , MouseEventArgs e) { MyMessage.Text = “Hello World!”; }

Page_Loaded Event:

Page_Loaded Event First opportunity to run code after Silverlight application has been downloaded and loads within browser Fires after all assets within root .XAML file have been downloaded and are ready to run within the browser If you want to run code immediately and not block on this, consider loading assets in the background programmatically

UIElement Base Class Events:

UIElement Base Class Events MouseMove MouseEnter MouseLeave MouseLeftButtonDown MouseLeftButtonUp KeyUp KeyDown GotFocus LostFocus Loaded Note: All shapes and controls derive via UIElement , which means they all have the above 10 events

Wiring Up Event Handlers:

Wiring Up Event Handlers Event handlers can be wired up declaratively in XAML: Or explictly within the code-behind file VB – using th e "Handles" keyword C# -- programmatically within the Page_Loaded event handler <Rectangle x:Name=“ MyRect ” MouseEnter =“ MyRect_MouseEnter " > </Rectangle> public void MyRect_MouseEnter (object sender, MouseEventArgs e) { // todo : add code }

Events:

Events demo

Writing Custom Controls:

Writing Custom Controls

Writing custom controls:

Writing custom controls Derive from Control Eg , public class MyControl : Control Full encapsulation model for composing UI controls Can use shapes, controls, brushes, transforms, etc. to build a control's UI, and then expose your own object model to outside pages/controls that consume your control Can optionally use XAML to define the look of a control Call InitializeFromXaml ( xaml )

XAML-able Custom Controls:

XAML-able Custom Controls Have a public parameterless constructor Eg, public MyControl() Create public properties Create public events

Custom Control:

Custom Control demo

Missing WPF UI Features Today:

Missing WPF UI Features Today Some important infrastructure features missing from Silverlight alpha today: Layout Managers Styles / Templates (think CSS-like external stylesheets) Databinding and DataTemplates Support for these will be coming in the future

HTML Integration:

HTML Integration

Access the HTML DOM from Managed:

Access the HTML DOM from Managed HTML access availble in new namespace HtmlPage.Navigate (" http://www.microsoft.com "); String server = HtmlPage.DocumentUri.Host ; using System.Windows.Browser ; 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 Script:

Access Managed Code from Script Mark a property, method or event as Scriptable: WebApplication.Current.RegisterScriptableObject (“ FootballData ", this ); [Scriptable] public void Search( string Name) { … } var control = document.getElementById (" Xaml1 "); control.Content.FootballData.Search ( input.value ); Register a scriptable object: Access the managed object from script:

HTML Integration:

HTML Integration Other interesting HTML integration scenarios: Persisent links Fwd/Back Integration Notes: Simple type marshalling only in th e Alpha Complex type support on the way

HTML and Script Integration:

HTML and Script Integration demo

Open File Dialog Support:

Open File Dialog Support

OpenFileDialog:

OpenFileDialog Silverlight supports ability to prompt for local files Developers can then work with file contents locally without having to first upload them to the server OpenFileDialog openFileDlg = new OpenFileDialog (); openFileDlg.EnableMultipleSelection = false; openFileDlg.Filter = "Text files (*.txt;*.xml)|*.txt;*.xml"; openFileDlg.Title = "Select an image to upload"; if ( openFileDlg.ShowDialog () == DialogResult.OK ) { // Do something with the file or files }

OpenFileDialog Security Constraints:

OpenFileDialog Security Constraints Silverlight does not allow developer to control or access the origional file path on the local machine Silverlight does not allow direct file access without first going through the OpenFileDialog

OpenFileDialog:

OpenFileDialog demo

HTTP Networking Stack:

HTTP Networking Stack

Browser based HTTP networking stack:

Browser based HTTP networking stack StreamReader responseReader = new StreamReader ( response.GetResponseStream ()); string RawResponse = responseReader.ReadToEnd (); Browser based headers/cookies passed with request Restricted to same domain access in the Alpha Cross-domain coming in the future 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

HTTP Networking:

HTTP Networking demo

Web Services:

Web Services

Web Services:

Web Services [ WebMethod ] public List<Player> GetPlayerList () { ... } VS based Proxy Generator enables strongly typed access ASP.NET JSON services supported in the Alpha WCF & SOAP support coming footballService = new FootballData (); playerList = footballService.GetPlayerList (). ToList (); The Web Service to Call Call the Web Service from the client

Async Support:

Async Support Sync & Async web services supported in the Alpha baseballService.BeginGetPlayerList ( new AsyncCallback ( OnPlayerDataLoaded ), null ); private void OnPlayerDataLoaded ( IAsyncResult iar ) { playerList = baseballService.EndGetPlayerList ( iar ). ToList (); } Start the async web service call Handle the web service completion event

Web Services:

Web Services demo

Isolated Storage:

Isolated Storage Stream based access to a private file/directory structure Will have easier accessors in following iterations Patterned after .NET Framework IsolatedStorage classes Read and write string or binary data For Alpha you get an iso-store per Source attribute c ontoso.com/foo.xaml and contoso.com/bar.xaml each get a different isostore 1MB limit per iso-store Same iso-store is across browsers

Summary:

Summary Silverlight provides an incredibly powerful client platform Easy to deploy applications Easy to create great looking applications Easy to create fast and responsive applications All enabled cross platform and cross browser Still many more features coming Big missing features today: Layout, Styles, DataBinding Future alphas and betas coming this year …

Learn More:

Learn More http://weblogs.asp.net/scottgu

PowerPoint Presentation:

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

authorStream Live Help