Browser Integration

Silverlight 2 is a web browser-hosted control that runs in Internet Explorer, Firefox 2, and Safari or Firefox on the Macintosh. As such, there will be scenarios where developers need to customize how the control is configured. There will also be cases where developers need to modify the web browser Document Object Model DOM from Silverlight as well as situations where developers need to modify the Silverlight application from the DOM. Note Any performance or functionality differences that...

Listing Value Converter Converting Spending to Bar Width

using System using System.Windows using System.Windows.Data using System.Windows.Shapes namespace Ch04_DataBinding.Recipe4_4 public class SpendingToBarWidthConverter IValueConverter public object Convert object value, Type targetType, object parameter, System.Globalization.Culturelnfo culture verify validity of all the parameters if value.GetTypeQ typeof double targetType typeof double parameter null parameter.GetTypeQ typeof SpendingCollection return null cast appropriately double Spending...

Listing RecipejsFile

Preference name MicrosoftAjax.js function getDataUsing avaScriptAjaxAsync lt summary gt This method makes a web request to obtain an XML file lt summary gt lt returns type String gt req.set_userContext user's context function OnWebRequestCompleted executor, eventArgs if executor.get_responseAvailable var xmlString executor.get_responseData Call Managed Code method to pass back data - Covered in Recipe 6.6 Although this book does not focus onASP.NETAJAX, we will cover the highlights of Listing...

The Code Str

In this code sample, we add an SSPL and a CSPL to the mix of media that we then play through the player we developed in Recipes 8-2 and 8-3. Figure 8-20 shows the new items added to the menus that enable you to test the features. Figure 8-20. Items added to the On-Demand left and Broadcast right menus Figure 8-20. Items added to the On-Demand left and Broadcast right menus To play the SSPL, we create two new publishing points named SSPLBroadcast of type broadcast and SSPLOnDemand of type...

The Code Lnz

For this recipe's sample code, we start out by expanding the size of the default Silverlight application to 800 X 600 and divide the Grid into two rows and two columns. In Grid.Column 0 and Grid.Row 0, we place a Border with a simple gradient and place an InkPresenter inside the Border to provide an appearance of a drawing or writing surface. As we mentioned earlier, you must use the events and methods of InkPresenter in order to process and collect strokes. The important events are...

Listing A DataTemplate Declared and Used in Place

lt ContentControl x Name cntctrlEmployee HorizontalAlignment Stretch Grid.Column 0 Background Yellow Margin 5,5,5,5 Height 200 gt lt ContentControl.ContentTemplate gt lt DataTemplate gt lt TextBlock x Name tblkFirstName Text Binding FirstName TextWrapping Wrap FontSize 14 FontWeight Bold Foreground White Margin 3,0,0,0 gt lt DataTemplate gt lt ContentControl.ContentTemplate gt lt ContentControl gt In Listing 4-5 we define and associate a DataTemplate to the ContentControl.ContentTemplate...

Listing Recipe Pagexaml File 1

lt UserControl Height 216 Width 334 gt lt UserControl.Resources gt lt ScaleTransform ScaleX l ScaleY l x Key ReduceScaleTransform gt lt UserControl.Resources gt lt ScaleTransform ScaleX l ScaleY l x Name ScaleToFullScreen gt lt UserControl.RenderTransform gt lt Border CornerRadius 13,13,13,13 Margin 4 x Name MediaPlayerFrame gt lt Border.Background gt lt RadialGradientBrush SpreadMethod Reflect gt lt GradientStop Color FF28D7A4 Offset 0.5 gt lt GradientStop Color FF70ElBF Offset l gt lt...

The Policy Server

The policy server is similarly implemented as a console program that listens on all available IP addresses, bound to a well-known port 943. Listing 7-27 shows the code for the policy server. Listing 7-27. Implementation for the PolicyServer type using System using System.IO using System.Net using System.Net.Sockets using System.Text namespace Ch07_Networking.Recipe7_5.PolicyServer Socket ListenerSocket get set SocketAsyncEventArgs sockEvtArgs null valid policy request string public static...

How It Works Vyz

The OpenFileDialog class displays a standard Windows, Macintosh, or Linux open file dialog depending on the platform that allows users to browse to files anywhere on their system. The OpenFileDialog class has a Filter and a Filterlndex property, which allow you to set the file filter in much the same way a .NET developer would do in a Windows Presentation Foundation or Windows Forms application. You can specify what types of files you wish to open by specifying Filter like this fileDlg.Filter...

The Code

When you create a new Silverlight application project, type a name, select the project location, and then click OK, the Add Silverlight Application dialog appears, as shown in Figure 1-2. To run a Silverlight application, it needs to be hosted in an HTML Web page. How do you want to host this Silverlight application Add a new Web to the solution for hosting the control Q Dynamically generate an HTMLtest pageto host Silverlight within this project Q Link this Silverlight control into an existing...

Listing DockedUndockedViewjs File

System.Gadget.onDock dockStateChanged System.Gadget.onUndock dockStateChanged System.Gadget.Flyout.file FlyoutView.html System.Gadget.settingsUI SettingsView.html change size depending on state if System.Gadget.docked document.body.style.width 130px document.body.style.height 200px document.body.style.width 400px document.body.style.height 290px In loadGadget for the Docked Undockedview, we assign the event handler dockStateChanged to the gadget events onDock and onllndock. When this JavaScript...

Listing Data Entry UI XAML

lt UserControl mc Ignorable d Width 400 lt UserControl.Resources gt lt -- Employee collection Data source -- gt lt local EmployeeCollection lt -- Data template to be used for the Employee type -- gt lt DataTemplate x Key DT_Employee gt lt StackPanel Orientation Horizontal gt lt TextBlock Text Binding FirstName gt lt TextBlock Text Binding LastName Margin 5,0,0,0 gt lt StackPanel gt lt DataTemplate gt lt UserControl.Resources gt lt Grid x Name LayoutRoot Background White Margin 10,10,10,10 gt...

Encoding Markers Using Expression Encoder

A full coverage of Expression Encoder is beyond the scope of the book, and we encourage you to download the trial version and try out the different features. You can download a trail version from Once you import a media file into Expression Encoder, you can navigate to the Metadata tab to add markers to the content. To add a marker, you move the thumb along the media timeline to the time point where you want to add the marker, and then click the Add button in the Markers pane. This adds a...

The Code Dlq

There are two ways to approach this recipe using an HTML page or using an ASP.NET page. The plain-old HTML page can be used as a guide for configuring Silverlight for non-Microsoft platforms. For the HTML page, we'll use the default test page created by Visual Studio 2008. We'll also add a button to the HTML test page and a script reference to a JavaScript file that will load the XAML in this case one named Recipe2.4.js in the js folder . For the HTML page, the Silverlight 2 plug-in is...

How It Works Wga

As you create UIs that are data bound to various controls in a TwoWay binding so that users of your application can edit the data, you often have the need for those edits to pass validation checks. And in the event one or more of those validations fail, you may want to capture the errors and display them to your users in a meaningful way. There is built-in support for notification of validation errors in the data-binding subsystem within Silverlight. Every Silverlight control exposes an event...

How It Works Ank

The term stroke when talking about ink refers to the process of putting a pen or stylus to a touch screen, moving it across the screen by either writing or making annotations, and then lifting it off the screen. Each stylus-down, move-across-the-screen, stylus-up cycle is an ink stroke. For computers that do not have a touch screen, clicking the mouse button, holding the mouse button down, moving across the screen, and then releasing the mouse button creates an ink stroke. Tip Note that using a...

Listing XAML for the Page

lt UserControl mc Ignorable d Width 400 Height 300 gt lt local Company x Key CLRDS_Company gt lt UserControl.Resources gt lt Grid x Name LayoutRoot Background White DataContext StaticResource CLRDS_Company Margin 8,8,8,8 gt lt Grid.ColumnDefinitions gt lt ColumnDefinition Width 0.38 gt lt ColumnDefinition Width 0.032 gt lt ColumnDefinition Width 0.238 gt lt ColumnDefinition Width 0.028 gt lt ColumnDefinition Width 0.322 gt lt Grid.ColumnDefinitions gt lt Grid.RowDefinitions gt lt RowDefinition...

Listing Extension to ProductHeader Type to Include a Dirty Flag

public partial class ProductHeader Referring back to Listing 7-7, you will see that to use the Dirty flag appropriately, we handle the BeginningEdit event on the ProductHeaderDataGrid. This event is raised whenever the user starts to edit a cell. In the handler, we set a flag named InEdit to indicate that an edit process has started. We also handle the CurrentCellChanged event, which will be raised whenever the user navigates away from a cell to another one. In this handler, we see if the cell...

The Chat Server

The chat server is implemented as a console program. The functionality is divided into two primary classes the ConnectionListener, which accepts incoming client connections, hands them over to a ServerConnectionManager instance, and continues to listen for more connections, and the ServerConnectionManager, which manages and processes messages for each connected client, and then routes messages between clients. Listing 7-25 shows the ConnectionListener class that we use in the server program to...

Silverlight Gotostate Gridview Togglebutton

The code sample implements an Expander custom control with a header and body area, each with their own content and content template options. The default template also defines a Systems. used to expand and contract the body of the Expander. The ToggleButton type is the base class for multistate buttons like CheckBox and RadioButton and exposes Checked and Unchecked states. Listing 5-29 shows the control implementation for Expander. using System.Windows.Controls.Primitives namespace...

Setting Up Publishing Points

Publishing points define the endpoints of a WMS 2008 installation to which a client connects to receive media. A publishing point could be defined to serve a media file stored on disk, a playlist that defines an ordered collection of media files to be played in sequence, or media that is being acquired real time from a capture device, such as encoder software connected to a camera. The publishing point abstracts the actual source of the media and provides the client with a URL to which the...

Setting Up WMS

Once you have Windows Server 2008 installed on your server, you can download WMS 2008 at Full instructions on installing WMS 2008 can be found at http support.microsoft.com kb 934518. When you install WMS on a server that has a web server running and listening on port 80, WMS will not enable the HTTP server control protocol during installation. Once you have installed WMS 2008, you will need to enable this to allow Silverlight to work with WMS. To do that, open the Windows Media Services...

Silverlight Generateelement

The framework ships with a few prebuilt DataGrid column types for handling some of the standard data types. DataGridTextColumn is one of the most useful ones, and can be used to view and edit any data that can be converted to a meaningful text representation. DataGridCheckBoxColumn is another one that can be used to view and edit a Boolean value as a CheckBox and with the current value mapped to its checked state. There may be situations where you want to implement custom logic to handle a...

How It Works Rtv

POX-style message exchange can be an attractive alternative to the more structured SOAP-based message exchange in many ways. It does not impose any of the specific format requirements of SOAP, and there is much more freedom as to how the messages get structured. Consequently, it requires fewer infrastructural requirements, benefits from more implementation options, and can be consumed by almost any XML-aware runtime environment. The downside of such loose-format messaging, however, is that very...

How It Works Awr

The Border control inherits from FrameworkElement and is a container control. It can contain exactly one child element. However, the child element can be a Panel such as a Grid, StackPanel, or Canvas, which can contain additional controls. When you add a Border to an application, the Background property is transparent by default. You can apply a solid color or gradient brush to provide a background for the Border. You can also set the CornerRadius property to provide a rounded corner, as shown...

The Sockets API in Silverlight

All socket functionality in Silverlight works asynchronously, thus avoiding any blocking calls that would prevent the main thread from blocking execution waiting for any such call completion. This is in line with other networking and web services APIs that we have studied in earlier recipes in this chapter. However, the design pattern for the Socket's asynchronous APIs is somewhat different from the previously discussed Begin-End pattern, as you will see in a moment. The life of a socket...

The Code Rmw

In this code sample, we will build a layout container extending the Panel type that can arrange its children in either a horizontal orientation in rows or a vertical one in columns . It also automatically wraps all its children into successive rows or columns based on available space. We have named the implementing type WrapPanel, and Listing 5-21 shows the code. Listing 5-21. WrapPanel Implementation Orientation dependency property DependencyProperty OrientationProperty typeof Orientation ,...

I

Figure 6-12. Recipe 6-8 initial Silverlight gadget web project layout We also go to the project properties for the Silverlight2RecipesGadget project and add the 6-8 Embed Silverlight within a Vista Gadget project to the Silverlight tab. We do not create test pages in the Add Silverlight Application wizard because we don't need them in this project. Completing the wizard will automatically copy the output from our Silverlight application to the ClientBin folder for the gadget each time the...

Listing ConnectionListener Class

namespace Ch07_Networking.Recipe7_5.ChatBroker the socket used for listening to incoming connections Socket ListenerSocket get set SocketAsyncEventArgs sockEvtArgs null new server connection manager ServerConnectionManager ConnManager new ServerConnectionManager run the connection listener create a new IP endpoint at the specific port, and on any available IP address IPEndPoint ListenerEndPoint new IPEndPoint IPAddress.Any, Port create the listener socket ListenerSocket new Socket...

How It Works Abu

The Silverlight 2 browser control is configurable with any web server-side technology such as ASP. NET, ASP classic, JSP, Ruby, or PHP because it is configured using the standard HTML lt object gt tag. Note For ASP.NET we cover the lt asp Silverlight gt server control in Recipe 6-2. When you create a new Silverlight application, you have the option of having the project wizard create two test pages for the new Silverlight application, an .aspx test page, and an .html test page. These pages...

Listing Sample Implementation of INotifyPropertyChanged

public class Notifier INotifyPropertyChanged implementing INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged utility method to raise PropertyChanged if PropertyChanged null PropertyChanged this, e string OldVal _SomeBoundProperty compare with new value if different, set property _SomeBoundProperty value and raise PropertyChanged RaisePropertyChanged new Change Notification for Collection Types The INotifyCollectionChanged interface also has a single event, named...

VideoBrush

MediaElement renders video by default in a rectangular shape determined by the Height and the Width properties of the MediaElement. However, you may need to implement more complex designs, such as rendering video bounded by a shape like a Rectangle or a control like the Border. Silverlight defines a type called VideoBrush that can be connected to a MediaElement instance and then used to fill a shape or a control in the XAML with video. This XAML snippet shows an example lt Border CornerRadius...

The Code Emk

For this code sample, we bind a DataGrid to product data sourced from the AdventureWorks WCF service. Each row, in addition to the bound columns, also displays some row details data, including an image of the product, some inventory information, a product description, and another DataGrid displaying the cost history records of the product demonstrating a master-detail arrangement. Figure 5-19 shows the DataGrid with the row details of a row expanded. Figure 5-19. Bound DataGrid using a...

The Code Dxv

For this recipe, we demonstrate using the ScaleTransform with a twist. We employ an overall Scale-Transform to scale up the UI when in full-screen mode, butwe also applyanother ScaleTransform to limit how large the buttons get when in full-screen mode. Figure 6-4 shows the UI for the application before implementing full-screen mode. The application includes a Border, a MediaElement, and a few Button controls to control the content playback. We set a RectangleGeometry on the MediaElement.Clip...

The Code Yfg

The code sample in this recipe creates a custom column type named DataGridDateColumn for editing DateTime types using the DatePicker control. Listing 5-12 shows the code for DataGridDateColumn. Listing 5-12. DataGridDateColumn Class using System using System.ComponentModel using System.Windows using System.Windows.Controls using System.Windows.Data using System.Windows.Media public class DataGridDateColumn DataGridBoundColumn public DateTime DisplayDateStart get set public Binding...

The Code Sdo

The sample code for this recipe has a button that allows the user to select files in the local file system, including with Multiselect set to true. The files that were selected are listed in a ListBox control. When the user clicks the Select Files button in the test application, an Open dialog appears with a filter configured for TIFF files, as shown in Figure 2-12. Figure 2-13 shows the test application UI after the user clicks the Open button in the dialog. Figure 2-13. Recipe 2-7 test...

The Code Fvh

The simplest Silverlight application that uses a dynamic language consists of an HTML or ASPX file to host the application just as in a compiled Silverlight application, and an app.xaml file that defines the Silverlight UI, much as page.xaml does for a compiled Silverlight application. The code-behind for app.xaml in a dynamic language application can be one of the following, depending on the language app.py IronPython code-behind file app.rb IronRuby code-behind file app.jsx Managed JScript...

The Code Fst

The sample application for this recipe includes three images that have been configured to be an embedded resource. The UI for the recipe has a simple gradient for the root Grid Background, a Button named RetrieveResourceNames to retrieve the resource names of embedded resources that are available, and a ListBox control named ResourceNames to display the names. The application also has a Border control to provide a color outline for a nested Image control, which is where the embedded resources...

How It Works Lem

There are situations where you may want to store data to the client's computer such as user-specific settings or application state information. However, it is not possible to use the regular file system of the operating system from a web browser application because native file system operations require full trust but web-based applications run in a partial-trust isolated sandbox. Isolated storage provides a safe client-side storage area for partial-trust applications to persist information on a...

The Code Bjr

The sample application for this recipe contains a Retrieve XML and Load button that when clicked fires the event RetrieveXMLandLoad_Click. This event creates an HttpWebRequest object that points to the location where Recipe 2-9's ApressBooks.xml file was copied. new WebRequest request HttpWebRequest.Create location request.BeginGetResponse When the asynchronous web request completes, the code in the callback method RetrieveXmlCompleted executes. The following code retrieves the XML document...

The Code Eqf

The code sample for this recipe illustrates the basic custom control concepts by implementing a ProgressBar control. Note The Silverlight control framework includes a ProgressBar control, and we in no way claim that you should use this implementation over the framework-supplied one. We chose this purely as a way to show you how to write a custom control, and we hope that purpose will be served here. Listing 5-25 shows the generic.xaml for the ProgressBar control default UI. Listing 5-25....

The Code Wwx

For the code in this recipe, we take everything we covered earlier and apply it to TextBox controls to provide a nice rounded appearance. We also use a Border to highlight an editing region with plain TextBox controls, resulting in a nice appearance. Figure 3-40 shows the output. Figure 3-40. Recipe 3-10 Sample code output Figure 3-40. Recipe 3-10 Sample code output Figure 3-40 shows two TextBox controls and two TextBlock controls, one inside a Border control and a plain version of each...

Using the DataContractJsonSerializer

Silverlight provides the DataContractJsonSerializer type in System.Runtime.Serialization.Json that allows you to serialize or deserialize JSON data to and from CLR types decorated with the DataContract attribute. To use the DataContractSerializer, you create a new instance of it, and initialize it with the type of the CLR object you want to serialize DataContractJsonSerializer jsonSer new To deserialize some JSON data, you pass in a reference to the stream containing the JSON data to the...

Silverlight Eap

In this recipe's sample code, we modify the default test web pages, adding an additional instance of the Silverlight plug-in of the same Silverlight application so both plug-in instances point to the Ch06_BrowserIntegration.Recipe6_7.xap file. In both the .aspx page and the .html page, we ensure that both Silverlight plug-in controls as well as their parent lt div gt containers have unique IDs in the page. We also modify the test pages so that the height and width on all of the controls isn't...

How It Works Oyc

The Silverlight 2 SDK includes two ASP.NET server controls the MediaPlayer control and the Silverlight control that exist in the System.Web.Silverlight namespace. The lt asp Silverlight gt ASP.NET server control encapsulates the functionality discussed in Recipe 6-1 into a configurable server control that integrates a Silverlight application contained in an .xap as well as supporting JavaScript functions to create a rich Internet application. The lt asp Silverlight gt server control...

Listing CodeBehind for the Page 1

namespace Ch07_Networking.Recipe7_5.ChatClient public partial class Page UserControl public ClientConnectionManager ConnManager get set initialize the ClientConnectionManager ConnManager new ClientConnectionManager ParentPage this set the data context to the ClientConnetionManager LayoutRoot.DataContext ConnManager private void btnHoin_Click object sender, RoutedEventArgs e private void btnLogoff_Click object sender, RoutedEventArgs e private void btnTalk_Click object sender, RoutedEventArgs e...