Title: Deep Dive into Silverlight 2
1Deep Dive into Silverlight 2
2Agenda
- DOM integration
- File I/O and isolated storage
- Networking
- Controls and templates
- Styles
3DOM Integration
- System.Windows.Browser namespace contains classes
for accessing browser DOM - HtmlPage, HtmlWindow, and others
- Managed -gt unmanaged
- Access DOM from managed code
- Call JavaScript functions from managed code
- Unmanaged -gt managed
- Call managed code from JavaScript
- Process DOM events with managed code
4Alerting the User
HtmlPage.Window.Alert ("Error!")
5Processing DOM Events in C
ltselect id"Options" ltoption value"0"
selectedgtOnelt/optiongt ltoption
value"1"gtTwolt/optiongt ltoption
value"2"gtThreelt/optiongt lt/selectgt
HtmlElement elem HtmlPage.Document.GetElementByI
d("Options") elem.AttachEvent("onchange",
new EventHandlerltHtmlEventArgsgt(OnSelectionChanged
)) . . . protected void
OnSelectionChanged(object sender, HtmlEventArgs
e) // TODO Respond to the event
6Accessing DOM Elements from C
string text HtmlElement options
HtmlPage.Document.GetElementById("Options") fore
ach (HtmlElement option in options.Children)
if (String.Compare(option.GetAttribute("selected"
), "true", true) 0) text
option.GetAttribute("value")
7DOM Integration
8File I/O
- General-purpose file I/O not permitted
- OpenFileDialog can be used to open files
- User interaction constitutes permission needed to
safely open files - No SaveFileDialog in Beta 1
- Isolated storage can be used to persist data
locally subject to quotas
9OpenFileDialog
// Display an image selected by the
user OpenFileDialog ofd new OpenFileDialog() o
fd.Filter "JPEG Files (.jpg.jpeg).jpg
.jpegAll Files (.)." ofd.FilterIndex
1 if ((bool)ofd.ShowDialog()) using
(Stream stream ofd.SelectedFile.OpenRead())
BitmapImage bi new BitmapImage()
bi.SetSource(stream) MyImage.Source
bi // MyImage is a XAML Image object
10Isolated Storage
- System.IO.IsolatedStorage contains classes for
safe, secure, per-user local storage - Ideal for personalization settings
- Virtualized (physical location hidden)
- Scope can be per-app or per-site, but
- Storage per-user is max 1 MB per domain
- IsolatedStorageFile.IncreaseQuotaTo method
increases quota if user approves
11Writing to Isolated Storage
using (IsolatedStorageFile store
IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream stream
new IsolatedStorageFileStream("Settings.xml"
, FileMode.Create, store))
using (StreamWriter writer new
StreamWriter(stream)) //
TODO Write to stream with StreamWriter
12Reading from Isolated Storage
Caution Throws IsolatedStorageException if file
doesn't exist
using (IsolatedStorageFile store
IsolatedStorageFile.GetUserStoreForApplication())
using (IsolatedStorageFileStream stream
new IsolatedStorageFileStream("Settings.xml"
, FileMode.Open, store))
using (StreamReader reader new
StreamReader(stream)) //
TODO Read from stream with StreamReader
13Isolated Storage
14Networking
- Silverlight 2 has rich networking support
- SOAP/XML Web services via WCF proxies
- HTTP services (POX, REST, RSS, ATOM) via
HttpWebRequest and WebClient classes - Socket support, asset downloads over HTTP,
syndication classes, and more - Cross-domain access supported using
Flash-compatible or Silverlight XML policy files
15Cross-Domain Network Calls
- Allowed if target domain has XML policy file in
place permitting calls from other domains - Crossdomain.xml Requires domain"" allowing
calls from any domain - Clientaccesspolicy.xml Can restrict access to
certain domains only - Policy file must be located at domain root
http//msdn2.microsoft.com/en-us/library/cc197955(
VS.95).aspx
16Sample Policy File
lt?xml version"1.0"?gt lt!DOCTYPE
cross-domain-policy SYSTEM "http//www.macromedi
a.com/xml/dtds/cross-domain-policy.dtd"gt ltcross-do
main-policygt ltallow-access-from domain""
/gt lt/cross-domain-policygt
Allow access from all domains
17WebClient
- Event-based HTTP networking API
- Commonly used to download assets
- DownloadStringAsync - String
- OpenReadAsync Stream (binary)
- Can also be used to perform uploads
- Fires progress and completion events and supports
cancellation of pending requests - Event handlers execute on UI thread
18Downloading Binary Assets
WebClient wc new WebClient() wc.DownloadProgres
sChanged new DownloadProgressChangedEventHa
ndler(OnProgressChanged) wc.OpenReadCompleted
new OpenReadCompletedEventHandler(OnDownloadCo
mpleted) wc.OpenReadAsync(new Uri("Assets/Flight.
wmv", UriKind.Relative)) ... void
OnDownloadCompleted(object sender,
OpenReadCompletedEventArgs e) Stream result
e.Result // TODO Use result
19HttpWebRequest
- Delegate-based HTTP networking API
- Supports asynchronous operation only
- Provides control over wire format
- GET/POST/PUT/DELETE (REST)
- Customization of HTTP headers
- Completion methods called on background threads
20Calling a REST Service
HttpWebRequest request (HttpWebRequest)
HttpWebRequest.Create (new Uri("http//contoso
.com/weather/98052")) request.BeginGetResponse
(new AsyncCallback(OnGetResponseCompleted),
request) ... private void OnGetResponseComplete
d(IAsyncResult ar) HttpWebRequest request
(HttpWebRequest)ar.AsyncState
HttpWebResponse response
(HttpWebResponse)request.EndGetResponse(ar)
using (StreamReader reader new
StreamReader(response.GetResponseStream()))
string result reader.ReadToEnd()
...
21Networking
22Controls
- More than 20 built-in controls
- Canvas, StackPanel, Grid, and GridSplitter
- Button, CheckBox, HyperlinkButton, RepeatButton,
RadioButton, and ToggleButton - TextBox, ListBox, and DataGrid
- TabControl, Slider, and MultiScaleImage
- Border, Calendar, DatePicker, and more!
- Support styles, templates, and data binding
23Button Control
ltButton Width"256" Height"128" FontSize"24"
Content"Click Me" Click"Button_Click" /gt
private void Button_Click(object sender,
RoutedEventArgs e) ...
24ListBox Control
ltListBoxgt ltListBoxItem Content"B-25 Mitchell"
/gt ltListBoxItem Content"BVM BobCat" /gt
ltListBoxItem Content"F4U Corsair" /gt
ltListBoxItem Content"F-18 Hornet" /gt
ltListBoxItem Content"P-40 Warhawk" /gt
ltListBoxItem Content"P-51 Mustang" /gt lt/ListBoxgt
25Control Customization
- ContentControl derivatives support deep
customization via Content property - Button
- ListBoxItem
- DataGridCell
- TabItem and more
- Use property element syntax to assign non-trivial
values to Content property
26Button with Custom Content
ltButton Width"256" Height"128"
Click"Button_Click"gt ltButton.Contentgt
ltStackPanel Orientation"Horizontal"
HorizontalAlignment"Center"gt ltEllipse
Width"75" Height"75" Margin"10"gt
ltEllipse.Fillgt ltRadialGradientBrush
GradientOrigin"0.25,0.25"gt
ltGradientStop Offset"0.25" Color"White" /gt
ltGradientStop Offset"1.0" Color"Red" /gt
lt/RadialGradientBrushgt
lt/Ellipse.Fillgt lt/Ellipsegt ltTextBlock
FontSize"24" Text"Click Me" VerticalAlignment"C
enter" /gt lt/StackPanelgt lt/Button.Contentgt lt/
Buttongt
27ListBox with Custom Items
ltListBoxgt ltStackPanel Orientation"Horizontal"gt
ltImage Source"Images/B-25.jpg" Margin"5"
/gt ltTextBlock Text"B-25 Mitchell"
Margin"5" HorizontalAlignment"Center"
VerticalAlignment"Center" /gt lt/StackPanelgt
... lt/ListBoxgt
28Control Templates
- Redefine a controls entire visual tree
- Perform extreme customization without changing
basic behavior of control - Exposed through control's Template property
(inherited from Control base class) - Use TemplateBinding to flow property values
from control to template - Use ContentPresenter and ItemsPresenter to flow
content and items to template
29Elliptical Button
ltButtongt ltButton.Templategt ltControlTemplate
TargetType"Button"gt ltGridgt
ltEllipse Width"256" Height"128"gt
ltEllipse.Fillgt ltRadialGradientBrush
GradientOrigin"0.25,0.25"gt
ltGradientStop Offset"0.25" Color"White" /gt
ltGradientStop Offset"1.0" Color"Red"
/gt lt/RadialGradientBrushgt
lt/Ellipse.Fillgt lt/Ellipsegt
ltTextBlock FontSize"24" Text"Click Me"
HorizontalAlignment"Center" VerticalAlignment"C
enter" /gt lt/Gridgt lt/ControlTemplategt
lt/Button.Templategt lt/Buttongt
30TemplateBinding
ltButton Width"256" Height"128" FontSize"24"
Content"Click Me"gt ltButton.Templategt
ltControlTemplate TargetType"Button"gt
ltGridgt ltEllipse Width"TemplateBinding
Width" Height"TemplateBinding
Height"gt ltEllipse.Fillgt
ltRadialGradientBrush GradientOrigin"0.25,0.25"gt
ltGradientStop Offset"0.25"
Color"White" /gt ltGradientStop
Offset"1.0" Color"Red" /gt
lt/RadialGradientBrushgt lt/Ellipse.Fillgt
lt/Ellipsegt ltContentPresenter
FontSize"TemplateBinding FontSize"
Content"TemplateBinding Content"
HorizontalAlignment"Center"
VerticalAlignment"Center" /gt lt/Gridgt
lt/ControlTemplategt lt/Button.Templategt lt/Buttongt
31Elliptical Button with Custom Content
ltButton Width"256" Height"128" FontSize"24"gt
ltButton.Contentgt ltStackPanel
Orientation"Horizontal" HorizontalAlignment"Cent
er"gt ltCheckBox /gt ltTextBlock
FontSize"24" Text"Click Me" VerticalAlignment"C
enter" /gt lt/StackPanelgt lt/Button.Contentgt
ltButton.Templategt ltControlTemplate
TargetType"Button"gt ltGridgt
ltEllipse Width"TemplateBinding Width"
Height"TemplateBinding Height"gt
ltEllipse.Fillgt ltRadialGradientBrush
GradientOrigin"0.25,0.25"gt
ltGradientStop Offset"0.25" Color"White" /gt
ltGradientStop Offset"1.0" Color"Red"
/gt lt/RadialGradientBrushgt
lt/Ellipse.Fillgt lt/Ellipsegt
ltContentPresenter FontSize"TemplateBinding
FontSize" Content"TemplateBinding
Content" HorizontalAlignment"Center"
VerticalAlignment"Center" /gt lt/Gridgt
lt/ControlTemplategt lt/Button.Templategt lt/Buttongt
32Styles
- Styles provide level of indirection between
visual properties and their values - Define style as XAML resource
- Apply style using StaticResource markup
extension - Can be scoped globally or locally
- Combine styles and templates to stylize
controls with custom visual trees
33Defining and Using Styles
Prevents style from being applied to non-Buttons
Style name
ltStyle xKey"ButtonStyle" TargetType"Button"gt
ltSetter Property"Width" Value"256" /gt ltSetter
Property"Height" Value"128" /gt ltSetter
Property"FontSize" Value"24" /gt lt/Stylegt
... ltButton Style"StaticResource ButtonStyle"
... /gt ltButton Style"StaticResource
ButtonStyle" ... /gt ltButton Style"StaticResourc
e ButtonStyle" ... /gt ltButton Style"StaticResou
rce ButtonStyle" Width"128" ... /gt
Explicit property value overrides style property
value
34Combining Styles and Templates
ltStyle xKey"EllipticalButton"
TargetType"Button"gt ltSetter Property"Template"
gt ltSetter.Valuegt ltControlTemplate
TargetType"Button"gt ltGridgt
ltEllipse Width"TemplateBinding Width"
Height"TemplateBinding Height"gt
ltEllipse.Fillgt ltRadialGradientBrush
GradientOrigin"0.25,0.25"gt
ltGradientStop Offset"0.25" Color"White" /gt
ltGradientStop Offset"1.0" Color"Red"
/gt lt/RadialGradientBrushgt
lt/Ellipse.Fillgt lt/Ellipsegt
ltContentPresenter Content"TemplateBinding
Content" HorizontalAlignment"Center"
VerticalAlignment"Center"
FontSize"TemplateBinding FontSize" /gt
lt/Gridgt lt/ControlTemplategt
lt/Setter.Valuegt lt/Settergt lt/Stylegt
... ltButton Style"StaticResource
EllipticalButton" Content"Click Me"
Width"256" Height"128" FontSize"24"
Click"Button_Click" /gt
35Controls, Templates, and Styles
36Discussion