building silverlight applications using .net (part 2 of 2)
Post on 18-Oct-2014
2.066 views
DESCRIPTION
This session demonstrates building a rich interactive application (RIA) using Silverlight. We cover how to use Microsoft Visual Studio to create applications, how to create UI using XAML markup and code, how to build a custom control, how to retrieve data from a Web service, znc how to manipulate data with XML and LINQ. (This is the second in a two-part series.)TRANSCRIPT
Building Silverlight Applications using .NET (Part 1 & 2)Jamie Cool.NET Framework TeamMicrosoft [email protected]
Nick Kramer.NET Framework TeamMicrosoft [email protected]
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 RIAWeb deployment
Need 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 + SilverlightHighly productive development Framework
Multi-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
LegendV1.1
LegendV1.0
.NET for Silverlight
XAML
Pres
enta
tion
Cor
e
Networking
JSON
REST POXRSS
DataLINQ XLINQ
DLRRuby Python
WPFExtensible Controls
BCLGenerics Collections
InputsKeyboardMouse Ink
MediaVC1 WMA MP3
Browser Host
MS AJAX LibraryDOM
Integration
UI Core
ImagesVector Text
Animation
DRMMedia
ControlsLayout Editing
CLR Execution Engine
Deploy
Friction-Free InstallerAuto-
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 FrameworkThe shared apis & technologies are the same The tools are the same
Highly compatibleMinimal changes needed to move from Silverlight to DesktopHowever, not binary compatible by default
The SandboxAll apps run in the sandbox
Conceptually similar to the HTML DOM sandboxApps 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 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.htmScript load files - CreateSilverlight.js & Silverlight.jsA 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 1Zip package support planned
Getting Starteddemo
Working with UI
XAML (rhymes with Camel)XAML = eXtensible Application Markup LanguageFlexible XML document schema
Examples: WPF, Silverlight, Workflow FoundationMore 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>
Hello world
Markup = Object Model
<TextBlock FontSize="32" Text="Hello world" />
TextBlock t = new TextBlock();t.FontSize = 32;t.Text = "Hello world";
=
CanvasIs 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>
The CanvasThe 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 (3)<Canvas> <Rectangle/></Canvas>
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 rectangle = new Rectangle();rectangle.SetValue(Canvas.TopProperty, 25);rectangle.SetValue(Canvas.LeftProperty, 25);
=
Fantasy Baseballdemo
TransformationsAll 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>
Hello World
Property ElementsProperty 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 block = new TextBlock;RotateTransform transform = new RotateTransform();Transform.Angle = 45;block.RenderTransform = transform;
=
<ScaleTransform>demo
Common EventsMouseMoveMouseEnterMouseLeaveMouseLeftButtonDownMouseLeftButtonUp
KeyUpKeyDownGotFocusLostFocusLoaded
Silverlight Event Example<Canvas xmlns="…" xmlns:x="…" MouseEnter="OnMouseEnter"> </Canvas>
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>
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>
void OnMouseEnter(object sender, MouseEventArgs e) { …}
x:NameName your xaml element so you can use it in code
<Rectangle x:Name=“rect”/>
void OnMouseEnter(object sender, MouseEventArgs e) { rect.Height = 75;}
Custom Elements in XAMLCustom 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 controlsDerive from Control
Eg, public class MyControl : ControlDefine the look of the control in xamlCall InitializeFromXaml(xaml)Remember the return value
XAML-able Custom ControlsHave a public parameterless constructor
Eg, public MyControl()Create public propertiesCreate public events
Custom Controldemo
Feature comparison – 1.0 vs 1.1In terms of graphics/UI/XAML:
v1.1 =v1.0+ managed code (CLR)+ XAML extensibility+ Control class (user control)+ sample controls
Feature comparison – Controls1.1 alpha 1.1 thinking WPF
Button 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 WPF
TreeView No No YesAccordion No No 3rd partyDataGrid No No 3rd partyUserControl Yes Yes Yes
Feature comparison -- Layout1.1 alpha 1.1 thinking WPF
Canvas Yes Yes YesGrid (table) No Yes YesStackPanel No Yes YesViewbox No Yes Yes
Feature comparison -- other1.1 alpha 1.1 thinking WPF
Mouse events
Partial Yes Yes
Keyboard events
Partial Yes Yes
<.Resources>
Partial Yes Yes
Data binding No Yes Yesstyling No Yes Yes
Feature comparison -- other1.1 alpha 1.1 thinking WPF
3D 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 2HTTP Networking + XMLWeb ServicesLINQHTML IntegrationRounding it outResources
HTTP Networking + XML
Browser based HTTP networking stack
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();
Make the HTTP Request
Process the response
XmlReader & XmlWriter
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");
Initialize the reader
Find a node & read it’s value
HTTP Networking + XMLdemo
Web Services
Web Services
[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();
The Web Service to Call
Call the Web Service from the client
Async SupportSync & Async web services supported in the AlphaGeneral purpose RAD async support coming
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 Servicesdemo
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;
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
LINQSupports 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 LINQdemo
HTML Integration
Access the HTML DOM from ManagedHTML 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 ScriptMark a property, method or event as Scriptable:
WebApplication.Current.RegisterScriptableObject("BaseballData", this);
[Scriptable]public void Search(string Name) { … }
var control = document.getElementById("Xaml1");control.Content.BaseballData.Search(input.value);
Register a scriptable object:
Access the managed object from script:
HTML IntegrationOther interesting HTML integration scenarios:
Persisent linksFwd/Back Integration
Notes:Simple type marshalling only in the AlphaComplex type support on the way
HTML Integrationdemo
MAC Debugging
MAC DebuggingEnables 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 Debuggingdemo
Other .NET Related Features of Note…Dynamic Languages
Javascript, 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 ActionGive us feedback
Features you like?Features you don’t?What do you want to build?What existing code & skills will you leverage?
Backup
PowerPoint GuidelinesFont, size, and color for text have been formatted for you in the Slide MasterUse the color palette shown belowSee next slide for additional guidelines
Sample Fill
Sample Fill
Sample Fill
Sample Fill
Sample Fill
Sample Fill
Demo Title
NameTitleGroup
demo
Video Titlevideo
Partner Title
NameTitleGroup
partner
Customer Title
NameTitleGroup
customer
Announcement Titleannouncing
Please fill out your evalevaluation
© 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.
Backup
Silverlight V1.1 ComponentsSilverlight
.NET Framework
Execution Engine
HTML BridgeWPF
XML DLR (Ruby,
Python)
App Model & Services
Friction-free Installer & Updater
Presentation and Media Runtime
UI Core (Text, Vector, Animation)
Media (VC1, WMA, MP3)Inputs (Key, Mouse, Ink)
Controls
Framework Libraries
Browser
Hosting
BCLNETLINQ
V1
V1.1
Factored CLR Execution engine
Full type system (generics, collections, etc..)
Factored Framework librariesLeightweight subset of .NET for web applications
Extensible PlatformUpdater denables a model for agile evolutoin of the platformSandboxed assemblies can be deployed with the application