Setting Up the Sockets Client
Now that your server is all set, you need to create a client. To do this, you can copy the XAML from the duplex HTTP sample into a new Sockets.xaml user control. Then, in the code-behind, you need to set up some stuff. This is where, if you ask me, sockets are easier than duplex HTTP it feels like far fewer methods and far less trouble to accomplish the same scenario. So first, adding the following namespace includes using System.Threading using System.Net.Sockets using System.Text...
Silverlight Runtime and SDK
Finally, for developers who want to use a different IDE or prefer a more lightweight development environment, Microsoft does allow you to download the different Silverlight development components individually. To do this, begin by downloading and installing the Silverlight 3 Developers Runtime, using this URL The standard Silverlight 3 run time is highly optimized in order to keep the download size of the player to an absolute minimum. This comes at some cost to developers because part of the...
Silverlight XAML Basics
XAML is a case-sensitive declarative language, based on XML that lets you design the user interface of a Silverlight application in descriptive markup. Similar to the way ASP.NET or Windows Forms work with the concept of a code-behind file, XAML files map to managed-code partial classes where you can write in your language of choice. XAML is important for the evolution of how you create the user interface because the user interface is separate from the code files. This means that a designer...
Network Access Security Model
By default, Silverlight applications can only access the server that they were deployed to and downloaded from , a.k.a., their site of origin. If you don't do anything special, this is the extent of the communication allowed, much as in AJAX applications however, Silverlight 3 also has the capability to make cross-domain calls, that is, calls to servers in other domains, which is essential for enabling mashups. To do this, Silverlight has a security policy system. This means that calls using...
Simulating Video Reflections
It's likely you've seen Silverlight media samples that simulate reflected video. This technique is easy and fast to achieve once you know the basics. You can apply this same technique to any other element in your Page as well. To achieve the effect, we'll use Two MediaElements, both using the same Source First, start by creating two MediaElements and set their Source property to the same video. Then, position them one on top of the each other as shown in Figure 10-10. You can use whatever...
EndUser Customization
The StateButton custom control now fully supports some select Visual States. As with Template Parts, the actual rendering used to represent the distinct Visual States and the transitions that are applied between them can be configured in XAML through the Control Template property. Here, we include a StateButton in an application to check out its behavior lt UserControl x Class Wrox.Silverlight3 6 xaml presentation 6 xaml 0.CustomControls.StateButton Width 400 Height 300 gt lt Grid x Name...
Checking for Application Updates
To check for and retrieve an update to OOBA, you can call the CheckAndDownloadUpdateAsync method and handle the event. In order for the updated application to be used, you can check the UpdateAvailable property in this event handler, and if it returns true, you can prompt the user to restart the application. In the case where an update is available, but the update is using a newer version of Silverlight, the UpdateAvailable will return false, and the update will not download. Note that OOBA...
Viewing and Compiling Shaders with Shazzam and the DirectX SDK
Start by downloading and installing the latest version of the DirectX SDK. Be warned, it's a fairly hefty 400 MB download. Once you've installed the SDK, install and run Shazzam. The first time you run Shazzam, you'll probably need to update its settings to ensure that it knows the correct location of the DirectX FX compiler. Do this by expanding the Settings panel and clicking on the Change Path button, shown expanded in Figure 9-39 gt I Samplei I Sample Sampled J Sampled Sample5 gt I Samplei...
Identifying Visual States for a Control
The TemplateVisualState class attribute is used to identify what Visual States a control supports. Each state is defined by two strings, representing the unique state name and what logical group the state belongs to. Groups are used to identify Visual States that are mutually exclusive. A control can be in two logical states as long as those states are in different StateGroups. The following shows a new StateButton custom control with several states relating to mouse interaction...
Detecting Download Progress
Just as you can detect the amount of video that has been buffered, you can detect the amount of the total video that has been downloaded. The MediaElement's DownloadProgress property represents the percentage of video that has been downloaded in the value range of 0 to 1. As the value of this property increases by 0.05, the DownloadProgressChanged event is raised by the MediaElement. The following XAML demonstrates how to specify an event handler for the DownloadProgressChanged event Width 320...
Sizing Video and Setting the Stretch Behavior
The MediaElement control does not have to be the same size as the source video. Just like any element in your VisualTree, you are in charge of its positioning and size. Just like the Image and Path control that we examined in Chapter 9, the MediaElement control has a Stretch property that dictates the way the underlying video is drawn as its container MediaElement control is sized and resized. The following values can be set on MediaElement.Stretch Fill The video is stretched both vertically...
Code Access Security Model
Silverlight 3 completely rips out the familiar .NET Code Access Security CAS model and replaces it with a straightforward, invisible model. Because it is targeted strictly at web applications and runs in the browser, it more or less inherits the browser AJAX security model in terms of what it allows applications to do. So, in a sense, the burden of security, particularly code security, is removed from the developer no worrying about attributes, asserts, demands, and that sort of thing. Under...
Handling Scripted Events from Managed Code
Handling JavaScript events in managed code is pleasantly easy. Continuing on from the last example, first add an HTML Button to the test page, just inside the body tag lt button id myHtmlButton gt Click Me HTML lt button gt Now, inside of our Page type constructor, add the code to attach to that button's Click event HtmlElement btn btn.AttachEvent onclick, HtmlButton_Click First you just use the Document.GetElementByld much as you would in HTML to get a reference to the HTML element. There is...
Authorization
Authorization is about ensuring that an actor usually a person user is authorized to do something. ASP.NET carries forward the concept of role-based authorization. This is superior to the common level-based authorization e.g., user, superuser, admin because it allows for more fine-grained control, based on the role that a user is in. It is somewhat similar to groups in NT file access security, although there is no built-in grouping of other roles. Role-based authorization is limited, though,...
Responding to Video Markers
Windows Media files can be encoded with Markers throughout their timelines that can represent either text or some type of script at a specified point on the timeline. You can use these markers to create a higher level of interactivity with the media currently playing. For example, consider a recorded presentation that includes a set of coordinating slides. As the video plays, you would like to change the active slide at different points in the video to coincide with the appropriate narration....
Clipping Video
Again, just like any FrameworkElement-derived object, the MediaElement can be clipped using a clipping path. To clip the MediaElement, you set the Clip property using the same path data syntax you were introduced to in Chapter 9. Blend makes creating clipping paths easy. Simply define a path using the Blend drawing tools, and then size and position the path over the MediaElement you want to clip. Once you have the path where you want it, select both the Path and the MediaElement hold down the...
Text Input
Silverlight 3 includes a TextBox control, which provides the same basic text input capabilities you are used to receiving from the HTML lt input gt element. The control offers single-format, multiline input capabilities with automatic text wrapping, as well as integration with the clipboard. An undo redo stack is also included. The following code demonstrates using the TextBox lt UserControl 6 xaml presentation 6 xaml Width 400 Height 300 gt lt Grid x Name LayoutRoot Background White gt lt...
Cryptography
Silverlight 3 provides a subset of the .NET Framework's cryptography capabilities, which is likely more than enough for most Silverlight applications. With these, you can do both symmetric and asymmetric encryption, handle hashes, and generate random numbers. The thing is that, in most cases, you'll want to do your cryptography on the server because there's no terribly safe place to keep things like keys on the client. One possible work-around for that would be to require the user to...
Custom Panels
As was stated earlier in the chapter, the layout system included in Silverlight is not only highly flexible but also very extensible. It is quite easy to leverage the layout system to create your own custom layout panels that contain your own unique layout logic. In order to show this, this section demonstrates how to create a simple Wrap Panel control. The layout logic for the Wrap Panel will stack its child elements from left to right, starting in the upper-left corner of the panel. When the...
Detecting Network State
The OOBA experience wouldn't be completely useful unless there was a way to detect whether the local application was online. Checking the results of the method in the NetworkChange.NetworkAddressChanged event, you can check the state of the current network connection. if NetworkInterface .GetIsNetworkAvailable At the application level, in the App.Xaml.Cs file, you can determine whether an application is running outside the browser by checking the IsRunningOutOfBrowser property if
StaticResource Markup Extensions
The StaticResource markup extension is used to set the x Key attribute on an object that is defined in a ResourceDictionary object. lt Style x Key MainButton TargetType Button gt lt Setter Property Width Value 80 gt The x Key attribute is applied to the Style object to give it the unique name MainButton. This Style object is in a ResourceDictionary, which in Silverlight is normally the outermost XAML element of your XAML file lt Style x Key MainButton TargetType Button gt lt Setter Property...
Raising and Handling Managed Events in Script
If you've done any .NET development, you're already familiar with handling managed events, so here we're going to focus on two things raising managed events and handling those events in JavaScript. Of all of this, the only particularly Silverlight-specific feature is handling them in JavaScript, so we're going to focus on that mainly. First, though, we'll talk about raising managed events. There is a well-known pattern for this that holds true in Silverlight. I'm not talking about the Observer...
IValueConverter
The IValueConverter interface defines two straightforward methods to enable conversion Convert and ConvertBack. As their names suggest, they allow conversion back and forth between two types. If all that you need to support is OneWay binding, the ConvertBack method is not invoked. Here, you see a basic implementation of IValueCOnverter that adjusts the way that a DateTime object is converted to a String Class for converting between DateTime and string objects public class DateConverter...
Object or Content Element Syntax
Most elements are created using the object or content element syntax, which is used in the Introducing XAML section earlier in this chapter to create the TextBlock object lt TextBlock gt Hello World lt TextBlock gt lt ObjectName gt lt ObjectName gt where ObjectName is the name of the object that you are trying to instantiate. The following example uses object element syntax to declare a Canvas Some objects, such as Canvas, can contain other objects, such as Rectangle or TextBlock lt TextBlock...
XAML Hierarchy
When you add XAML objects to the Silverlight control, you are defining a hierarchical tree structure with a root object. All XAML files have a root element. In Silverlight, the root element is always the container that has the x Class attribute. The following XAML example creates an object hierarchy containing a root UserControl object in the SilverlightApplication6 namespace Page class. When the XAML is parsed by the player, the Canvas object, which has Rectangle and TextBlock elements, is...
Silverlight and JavaScript Marshaling
A note on marshaling types between script and managed code while the basic scenarios and even not-so-basic ones should go off without a hitch following the principles illustrated here, there are actually a lot of sticky details in terms of how stuff gets sent back and forth between script and managed code. If you're going to do a lot of this, you should consult the MSDN documentation on this topic. The basic rules are Managed types are wrapped by reference to JavaScript. This is why, for...
Other Inputs Ink
Although this section is called Other Inputs, essentially the only other user-initiated inputs that Silverlight handles are ink-related. While you may have other hardware devices that a user may use, they will need to translate to mouse, keyboard, or ink to work in Silverlight. So in this last user-interactivity section, we'll focus on ink stuff. As noted in the mouse section, ink information is attached to mouse event arguments. This is important because you can use the mouse for basic ink...
Font Embedding
If you've selected a TextBlock in Blend, you'll see these default fonts listed at the top of the FontFamily dropdown see Figure 9-29 . The blue Silverlight logo next to these fonts indicates that they are embedded. If you want to use a font other than one of the defaults, you'll have to embed that font in your project or a referenced assembly . This is easy in Blend, simply select the font you wish to apply and check the Embed box in the Text properties panel. Blend will automatically create a...
Silverlight Tmf
Jason Beres Grant Hinkson Devin Rader Joseph Croney Silverlight 3 Programmer's Reference Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright 2009 by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN 978-0-470-38540-1 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 Library of Congress Cataloging-in-Publication Data is available from the publisher. No part of this publication may be...
Silverlight PlugIn Sizing and Position
As has been described in the book, at its core, Silverlight is a browser plug-in, which is added to the page using a standard HTML lt object gt tag. This means that when mixed into a page that contains other HTML, CSS, and JavaScript, the specific way the browser renders this content can have significant influence over how the Silverlight plug-in is sized and positioned. To control the size of the browser plug-in, you can set a height and width attribute on the object tag in HTML, as shown in...
Common Mouse Scenarios
OK, so now you have a good overview of what Silverlight gives you in terms of mouse events, and it is time to apply that knowledge in meaningful ways. The following are common scenarios that you'll likely need to deal with while building interactive applications. Hovering is when the mouse cursor is over an element. On the Web today, in HTML, hovering is often used to provide visual feedback to indicate that an action is available such as the mouse cursor changing to a hand if a link can be...
HTML Bridge Scenarios
Here are a few more interesting scenarios to think about that are enabled thanks to this truly advanced HTML bridge Silverlight to Silverlight You can have two instances of Silverlight on one page and communicate between them using the bridge or the new Local Connection API. This could be useful in scenarios in which you need to coordinate data between them such as multiple Silverlight Web Parts in a portal as well as situations in which you need more advanced layering than is supported...
Silverlight Tour
Silverlight 3 continues the improvements that Silverlight 2 delivered over Silverlight 1.0. In the next section, we'll look at some of the more important features of Silverlight 3, including Throughout the book, you will learn about each of the items listed in much more detail. The following sections are designed to set the stage for what's to come as you explore the full capability of Silverlight 3. If you are not familiar with WPF, you are probably not familiar with XAML. Since the dawn of...
Using Embedded Fonts
As discussed earlier in the chapter, Silverlight natively supports 10 Western language fonts and 31 East Asian fonts, but the world of fonts is vast, and designers should not be limited to this tiny handful. Thankfully, Silverlight includes support for embedding fonts in the application, allowing designers to use any font they wish in their application design. To use an embedded font with the TextBlock, you simply provide the FontFamily property with a special font URI that tells Silverlight...
Interacting with the Browser Object Model BOM
The Browser Object Model BOM is the set of objects that allow applications to understand and manipulate browser facilities such as window-, location-, navigator-, and frames-related functionality. It also provides access to the currently loaded document, which gets you into the Document Object Model and is usually the object that receives the most focus and efforts of DHTML development. In terms of browser-level interaction, Silverlight provides a few facilities. First, there is the HtmlPage...
Text Decorations
TextBlock also allows you to supply a text decoration. Text decorations are visual ornaments that can be applied to text such as underline, overline, or strike-through. Whereas in WPF you can apply any of these different types of text decorations, in Silverlight you are limited to only the underline text decoration. To apply the decoration, simply use the TextDecorations property and provide it with a value of Underline, as shown in the following sample lt TextBlock
Setting Up the Policy Server
Now, because sockets require a call access security file even for site-of-origin calls , you first need to set up a policy server listener. To do this, add a new class file to your console application, calling it PolicyServer. You'll need to use a few namespaces to make things more manageable Most of the socket's functionality you'll need will, of course, be in System.Net.Sockets. We have I O included because we want to read the policy XML file from the local filesystem, as you'll see shortly....
Key Features of ASX
The following are a few key features of the ASX playlist that may help you decide between SSPL and ASX Server Independent ASX files do not require a Windows Media Server. They are stand-alone files that can reside loosely on a server or as part of your Silverlight project. Dynamic Generation ASX files can be created either statically or, more attractively, dynamically. This means you can serve up a dynamic playlist based on a user's authentication level or the time of day the playlist is being...
Measure Then Arrange
The basis of the Silverlight layout system is to measure, arrange, and then draw elements. Every element that can be drawn in Silverlight is included as part of the application's visual tree. When the application begins a layout pass, it uses the visual tree as a map, enumerating the leaves in the tree to first measure, then arrange, and finally draw the UI element. The first pass of the system, the Measure pass, asks each element in the visual tree to determine how much space it would like to...
Figure 1
The TextBlock control also includes a Text property, shown in the following sample, that you can use to provide the element's content lt TextBlock Text Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Fusce porttitor, tellus id tristique viverra, ligula pede pulvinar purus, nec hendrerit urna justo et nulla. Cras condimentum nulla at ipsum. Nullam nulla. Sed elit lectus, hendrerit rhoncus, gravida id, tristique quis, justo. Vivamus et enim. Nunc accumsan. Curabitur ultrices dui ac...
Creating a Custom Shader Effect
With the custom shader tweaked and compiled, it's now time to create a custom ShaderEffect class that can be consumed by our Silverlight applications. Shazzam has already taken a lot of the guesswork out of the process by compiling the .fx shader and generating a starter effect class for us. We now have to add the compiled effect to our Visual Studio project and customize the starter class for Silverlight. Shazzam currently generates WPF code. Add the Compiled Shader to Visual Studio Select...
Sockets
Like the HTTP-based duplex communication just covered in the previous section, sockets are likely going to appeal to a limited audience, but they're very useful for those who need them. Silverlight's sockets implementation uses Windows Sockets Winsock on Windows and BSD UNIX's sockets on OS X to provide a standard, managed interface. If you need true, real-time duplex communication and can use TCP, then this is your solution in Silverlight. The challenge, of course, is that it uses ports...
Silverlight Controls Toolkit
In addition to the controls that Microsoft includes in the Silverlight SDK, it offers an additional set of controls through the Silverlight Controls Toolkit. These controls are made available outside the Silverlight release cycle and are made available with full source code via the Microsoft Codeplex web site www.codeplex.com Silverlight. Having a separate set of controls outside of Silverlight allows Microsoft to release new controls more frequently and at differing levels of quality that are...
Enabling GPU Hardware Acceleration
When rendering high-definition video or any video for that matter , you may want to enable hardware acceleration to offload the processing to your GPU. You first have to enable this at the plug-in level. The following ASPX enables this on the ASP Silverlight component lt asp Silverlight ID Silverlight1 EnableGPUAcceleration true runat server Width 100 Height 100 gt You can also set these parameters using the lt param gt tag when using an lt object gt instead of the Silverlight ASP control lt...
Interacting with the Document Object Model DOM
In the previous section, you saw the facilities for interacting with BOM in this section, you'll see the facilities provided for interacting with the DOM, which is what you'll want to do if you need to control or get information about visual elements in the browser that are outside the Silverlight instance. The first, and most obvious, way to get at the DOM is through the Document object itself, and Silverlight provides a super-easy way to do that The Document property gets you an HtmlDocument...
Alerts Confirms and Prompts Oh Dear
In the following sections, you'll see how to use standard JavaScript user message input facilities. For alerts that are triggered from the server, Silverlight 3 introduces the MessageBox class, which provides a static Show method that you can use to display a message in a simple dialog box. The dialog box is modal and provides an OK button. There is an overload of the Show method that enables you to specify a title bar caption and an optional Cancel button. If you display a Cancel button, you...
Property Resolution
When defining and applying a custom Style to a control, it's important to understand how the values defined in that style are resolved with local values set on the control itself and with values set in the default Style for the control. When a custom Style is applied, the property settings in the custom style are combined with the property settings of both the default style and the local control instance. Each property set in a custom Style overrides the default value defined in the control's...
Referencing the Image in XAML
Use the same syntax as you used with XAP File Images, adding a forward slash to the URI lt MediaElement Width 320 Height 240 HorizontalAlignment Left VerticalAlignment Bottom Margin 50,50,0,0 gt XAP size is reduced faster page load time . Media is not loaded at page load instead, it loads asynchronously after the XAP is downloaded. Use this scenario when you want to create a very lightweight, quick-loading application. The media will begin streaming from the server to the MediaElement control...
Timeline Controls
The timeline and transport controls appear directly beneath a video once it is selected. The interface is broken into six key regions, highlighted in Figure 10-16 The Timeline is where you will trim the beginning and ending of your video, cut segments from your video, and add media markers. You navigate the Timeline by dragging the playhead orange box icon to a desired position. As you drag or scrub, as it's also known , the position indicator and video preview will update see Figure 10-17 ....
Adjusting for Time Zones
The main tool for working with specific points in time, where differences in time zone matter, is DateTimeOffset. You can use TimeZoneInfo, but it is basically limited to Local and Utc which just might be enough . If you need more, though, DateTimeOffset is the tool to use. For example, let's say that you have a server in a different time zone and you want to know what that time zone is and potentially adjust for it to let the user know what time it is in terms of his time zone. This is a...












