Using the WebClient Class

Silverlight's WebClient class is located in the System.Net namespace and acts much like its big brother found in the full version of the .NET Framework. It allows asynchronous requests to be made to Web resources and provides a way to specify a callback method to process response data. It's arguably the easiest way to initiate a request and handle a response in Silverlight since it doesn't require knowledge of stream objects or the process of converting byte arrays into strings. In fact,...

Figure Wwg

Now assume that your company has strict rules on branding, meaning that the text used in this and all other forms must match or closely match the company standard of Times New Roman in size 12. This requirement entails setting both the FontFamily and FontSize properties of each control on your form that will display text content, as shown in the following XAML Text Enter your Username FontFamily Times New Roman FontFamily Times New Roman Text Enter your password FontFamily Times New Roman...

Using a Web Service Proxy to Make Asynchronous Calls

After running the Add Service Reference tool to create a proxy, a SOAP client class will be generated that can be used to call an ASP.NET Web Service. As with WCF calls, ASP.NET Web Services calls are made asynchronously. When data from the service returns to the Silverlight application, a callback method is invoked to process the data and bind it to controls. An example of using a class named ProductServiceSoapClient to call an ASP.NET Web Service asynchronously is shown next. Looking through...

Polygon Objects

Asp Net Polygon

The Polygon class enables you to draw an enclosed shape comprised of multiple lines. You use the Points property to specify a series of Point objects that each defines the corner or connecting points of your Polygon shape to draw. Consider a simple example, that of drawing a triangle. To draw a triangle, three points need to be specified. The following XAML shows how to draw a triangle whose three points are specified as 50, 50 , 400, 200 , and 25, 200 . The triangle is red. lt UserControl 6...

Timeline Markers

Timeline markers allow you to associate multiple specific points in a media file with any 'useful' information. They are typically used as a form of synchronization mechanism, for instance, to enable seeking through the media to a specific point, or even to allow you to synchronize the media with other items at set times advertising being a good example a car chase in a movie could signal via a timeline marker that it's time to show the BMW advert on the right-hand side . You could also use...

Summary Vgr

This chapter has taken the security surrounding a Silverlight application and sliced it up into some fairly chunky topics. These topics by and large are probably not new to you, but the way in which you tackle them might be. What you have seen discussed is the attacks likely to be made against your application, and how there are certain measures tackled within the Silverlight framework. Once you move past this foundational level of security, you are into the custom aspect of securing your...

Working with Data Repositories

Silverlight 2 allows you to access data from different places, but as in a sandboxed application, there are some limitations. We are going to present some techniques to access and store data in your application. There are two groups of repositories you can play with local ones and remote ones. You saw some of them in detail in other chapters. Here we give you a quick overview of how to get and save your data. Also check the Chapter 10 demos for accessing data if you want to copy and paste some...

Dynamically Loading XAML

As an ASP.NET developer, you're aware that there are many scenarios in which the HTML that makes up your pages can't just be created and edited at design time in Visual Studio or your tool of preference . For instance, providing different HTML for different users to cater for the individual look and feel of the user interface is not possible at design time only. Runtime decisions have to be made to alter the HTML to be output. It's almost certainly going to be a requirement in any advanced...

RadialGradientBrush

RadialGradientBrush allows you to specify how multiple colors are blended together using an ellipse as the axis, therefore specifying Offset 1.0 in a child GradientStop referring to the entire circumference of the axis. The default center GradientOrigin is set to 0.5, 0.5 . The following example leaves the GradientOrigin unchanged and blends blue and green together lt UserControl 6 xaml Width 400 Height 3 00 gt lt Grid x Name LayoutRoot Background White gt lt Rectangle Height 300 Width 3 00 gt...

Data Controls Namespaces

Beyond the assemblies and namespaces that Silverlight provides to handle data, there are also data presentation offerings that you can use to render the information and perform automatic binding therefore, it is important that you are aware of them. Some people have argued that Silverlight controls are very simple or not good enough for a serious application. In reality, many Microsoft partners are already developing controls that can provide a very rich experience for Silverlight 2....

DOM Manipulation

Every element that exists within the DOM is treated as a node in a hierarchical tree structure, with the document node forming the root. Consider a very basic HTML page lt title gt JavaScript Guide lt title gt lt head gt lt h1 gt JavaScript Guide lt h1 gt lt h2 gt Sibling node lt h2 gt lt body gt lt html gt You can see here that the lt head gt node has a single parent the lt html gt node and a single child the lt title gt node . The lt html gt node, though, has two direct children the lt head...

Binding

At this stage of the chapter you may have an initial understanding about how binding fits in the big picture. Next, we dig deeper into the binding world of Silverlight, understanding what it is, how it is implemented, and how to get the most out of it. Simply put, data binding is the connection between the user interface and the business objects that allows data to flow between one section and the other one. Figure 10-3 shows a graphical representation of the concept of binding. In Figure 10-3,...

Elements Parts

The elements parts allow you to define which object you are going to need to execute the logic of your control. This means that the visual template should incorporate them in order to get them at run time. Figure 11-18 shows the relationship when the control initializes. When the control initializes, it will look for the parts by name in the current instance. This will give you access to the controls in order to handle the events or to perform alteration to the properties, for example, to...

Navigation Challenges

One of the first challenges that you have when interacting with ASP.NET is the standard page transition. As each page is treated as an independent entity, the plug-in execution will be lost if you navigate to a new page. The Silverlight application runs independently on the previous page, but as soon as the user leaves that page, the content is disposed. When the user presses the back button on the browser history or another link to return to the previous page, the Silverlight application will...

Defining a WCF Service Contract

Once the data contract s used by the service is defined, the service contract can be created. Service contracts rely on .NET interfaces and WCF attributes. In its most basic form, a service contract defines what operations a service will perform using an interface. Services that implement the contract must, of course, implement all of the members defined in the contract interface. The following code demonstrates how to create a service contract and use the ServiceContract and OperationContract...

Silverlight CrossDomain Policy Files

The Flash cross-domain policy file format works well for restricting access to a server by domain, but it doesn't allow specific resources on a server to be locked down. In today's security comes first mentality, having more control over what resources can be accessed is a desirable feature. After all, if callers don't need access to every folder on a server, then why give them that level of access in the first place To help reduce the attack surface exposed to cross-domain callers, Microsoft...

ASPNET Media Server Control

The beauty of this control is that it allows you to embed your audio and video files directly into your web page without requiring any knowledge whatsoever of either client-side JavaScript or, indeed, XAML Silverlight. The control then takes care of generating all of the Silverlight markup and code behind required to get your media running. The control also supports skinning as well as allowing the inclusion of Chapters, Markers, and Captions. Once you have installed the ASP.NET Futures...

LinearGradientBrush

As well as the provision of painting with a single, solid color, you also have the option of painting an area with n different colors, each of which blends into the next as gradually or as suddenly as you dictate. LinearGradientBrush allows you to specify how multiple colors are blended into one another along a single straight axis, which runs from the top-left corner of the area being painted to the bottom-right corner of the area being painted by default. The different colors and their...

DownloadProgressChanged

Like BufferingProgressChanged, this event is more than likely to occur repeatedly during a progressive download and will fire whenever the total downloaded content increases by 0.05 or more. void MyMedia_DownloadProgressChanged object sender, RoutedEventArgs e Simply wire these events up in your XAML markup or in code if you really want to , and you're ready to roll. lt Our Media Object -- gt lt MediaElement x Name MyMedia AutoPlay False The handlers below do nothing more than output...

Windows Media File Editor

This handy tool comes with the Windows Media Encoder 9 installation package and allows you to open and edit media files that end with the .wmv, .wma, and .asf file extensions. When you run the application, you will be presented with the screen shown in Figure 13-10. The file you're going to see opened and edited in this example is, like the Butterfly.wmv that you've seen thus far, installed along with Windows Vista and is called Bear.wmv. Once the file is opened in Windows Media File Editor,...

Interacting with Silverlight from the Browser

In order to allow a scripting language in the hosting page to program against your Silverlight class, you first need to register the class in question as a scriptable object. This should be done in one of the initialization steps of your class, so the UserControl_Loaded event is a natural choice. Take a look at the code in SLFromDOM.aspx within the Chapter04 source directory, which contains the basic code required to host a Silverlight application. A Silverlight page called SLFromDOM.xaml can...

Using Sockets in a Siiveriight Client

Silverlight applications can connect directly to remote servers using socket classes available in the System.Net and System.Net.Sockets namespaces. Once connected, data can be pushed from the server to one or more clients without the need for client polling. Several classes such as DnsEndPoint, Socket, and SocketAsyncEventArgs can be used to connect to a remote server. The DnsEndPoint class is used to define the IP address of the target server as well as the port, while the Socket class defines...

The ListBox Control

The ListBox control provides a flexible way to display a collection of items vertically or horizontally within an application. Like many controls found in ASP.NET, the ListBox control relies on templates to determine how items are rendered. You'll typically use the ListBox control in data-binding scenarios. This section provides a quick introduction to the control and demonstrates how templates can be used. Later in the book, you'll see how items controls such as the ListBox can be bound to a...

Displaying Download Progress with the ProgressBar Control

It goes without saying that audio and video files can be large. The speed at which they download can vary greatly depending on the end-user's network connection, network latency, and other factors. Although you can write custom code to handle displaying the progress of a media file being downloaded, Silverlight provides a ProgressBar control that can be used to visually notify the user without writing a lot of code. The ProgressBar control acts much like the ProgressBar found in Windows Forms...

ImplicitStyleManager

While the default technique of defining and applying styles that you've seen so far works, it certainly can be a pain to add Style StaticResource YourStyleKey to all of the controls needing to pick up a specific style in an application. WPF provides a way to implicitly apply styles to controls, but unfortunately this functionality isn't available in Silverlight 2. Enter ImplicitStyleManager provided by the Silverlight Toolkit freely available for download from www.silverlight.net . By using...

Using the ASPNET Profile Provider

If, as is more likely, you'd like your Silverlight application to take into account a user's ASP.NET profile information, you need not worry. Silverlight enables you to hook into ASP.NET's built-in Profile properties system to retrieve information stored on a per-user basis if required. To do this, it's simply a matter of exposing access to the Profile Provider within your ASP.NET site via ASP.NET Application Services, which shipped as part of the .NET 3.5 release. Don't worry if you haven't...

The Security Model

There are many levels of security to consider when building an application. This section focuses on the security model offered by the .NET Framework. In the desktop implementation of the .NET Framework, there are two models you might be familiar with role-based security and code-access security. Role-based security is provided in the desktop Framework to allow for a developer to specify the role in which the calling user must be a member in order to execute a particular piece of code assembly,...

The TextBlock Control

Label controls are used frequently in development frameworks such as ASP.NET and Windows Forms. Although Silverlight doesn't provide a control named Label, it does provide a TextBlock control that performs the same function as a Label control. You can't use a TextBlock control to capture data, but it's frequently used with other user input controls such as TextBox, which is why it's included in the user input controls category. The TextBlock control defines a Text property that can be used to...

Introduction to Silverlight Controls

Silverlight 2 provides more than 25 controls that can be grouped into four general categories including user input controls, layout controls see Chapter 5 , items controls, and media controls. Figure 6-1 shows what some of these controls look like in the Visual Studio Toolbox. User input controls include common controls found in many other frameworks such as TextBox, Button, and CheckBox, as well as some nonstandard controls such as ToggleButton and RepeatButton. Layout controls include Canvas,...

Namespaces

The xmlns attribute isn't specific to XAML it's standard XML and is used to qualify the element it's applied to and the child elements contained within it. Don't bother trying to type these namespace values into your browser to see what's there, as there isn't usually anything there. XML namespace values are nothing more than arbitrary strings to help differentiate between elements with the same name, in much the same way as .NET namespaces are used to fully qualify the types declared within...

Summary Ecu

Silverlight provides several different options for requesting, receiving, and processing data from remote services and web sites. In this chapter, you've seen how Silverlight can be used to call WCF and ASP.NET Web Services using a proxy object and how classes like WebClient and HttpWebRequest can be used to request data from REST services. By using these classes along with related helper classes, you can retrieve data from services that have the proper cross-domain policy files in place. The...

Creating a WCF Service

Once the service contract has been defined, it must be implemented in order to be useful. When a class implements an interface, it must define all of the members in the interface. The same logic holds true for services that implement service contracts. WCF Services can be exposed using IIS or can be self-hosted in Console applications, Windows Services, or other types of .NET applications. When hosting services on IIS, the service file will have a .svc file extension rather than the .asmx...

Updating Silverlight

The DOM Integration section in this chapter talks about the Silverlight plug-in in quite a bit of depth, but there is a key area that it doesn't cover, and that is its role in upgrading the Silverlight run time. When you write your first Silverlight application, if you click your right-button within your browser window, over your Silverlight application region, you'll see the Silverlight Configuration option appear. This validates that you are clicking over the Silverlight Host plug-in within...

The CheckBox Control

Silverlight's CheckBox control derives from a base class named ToggleButton which, in turn, derives from ButtonBase that allows different states of a control to be tracked. Although a CheckBox is normally used to track True or False values as in ASP.NET, three states are supported in the Silverlight control including checked, unchecked, and indeterminate. CheckBox provides an isChecked property of type Nullable lt bool gt that can be used to set the state of the control and determine if it's...

The Layout Process

The layout process in Silverlight is essentially the same as that in WPF, using a two-stage measure-and-arrange algorithm to calculate the size and position of elements within the top-level parent panel container. Whenever the user interface needs to be drawn or redrawn , the first operation that takes place is the measure operation. This involves the layout system iterating recursively through the child elements that make up the UI, measuring each one in turn and evaluating its desired size....

JSON Fundamentals

Several REST APIs including the one provided by Flickr allow data to be returned as JSON. JSON delimits objects by using brackets and separates property names from values using a colon character. An example of using JSON to pass photo data from Flickr to a client is shown next server 2226, farm 3, title Camp Chihuahua Class In Session, ispublic 1, isfriend 0, isfamily 0 This JSON fragment specifies where photo data starts and ends using and characters, separates property names and values using...

MediaElement

MediaElement derives from FrameworkElement, which, in turn, derives from UIElement. These two classes provide derived controls with their layout abilities, including input keyboard, mouse, and stylus and focusing characteristics as well as sizing information via Width and Height properties. Of course, as well as the standard input, visual and layout abilities, MediaElement adds a host of properties, methods, and events that are used to select and control media within your application, the...

The Silverlight Interaction Context

As you are now developing in the Silverlight world, you need to understand the differences and similarities that the model offers. During the previous chapters, you have learned about the architecture and controls that are published from the plug-in. Now you are going to use that knowledge in order to explore the interaction between the application and the ASP.NET world. Silverlight applications run in a sandbox environment, but this does not prevent you from interacting with the external world...

Using the XmlSerializer Class

You've seen how the XmlReader class can parse XML data node by node in a forward-only manner. While it can be used to map XML data to CLR objects, there's another option available that's designed to simplify the process of mapping XML data to objects. Silverlight provides an XmlSerializer class located in the System.Xml.Serialization namespace that can act as the middleman between an XML document and an object. It's capable of deserializing XML data into objects and serializing objects into XML...

The Stylus and Touch Screens

Silverlight 2 supports a new concept in the ASP.NET world, which is the interaction with the stylus pen and touch screen commonly found in Tablet PCs. The interaction with them is very similar to the mouse interaction, but there are new elements that play an important role in the interaction. If you explore the event arguments, you will find the property StylusDevice that will provide information about the points captured by the stylus and the Inverted property. Inverted This is an interesting...

LINQ Namespaces

Finally but not least important, Silverlight provides a wide support of LINQ functionality under this namespace. System.Linq includes the base classes for the integrated query language that will allow you to query objects using LINQ in your Silverlight applications. LINQ is also implemented in order to query XML under System.Xml.Linq. You may find references on the Web to XLINQ. Most of the functionality has been ported from the full .NET implementation except for the following features...

Presentation Core

With Silverlight 1.0, you were given the presentation core and a control to host it in. As an end-user you could receive a very rich-looking application. Behind the scenes as a developer, the only API that was exposed to you was an unmanaged interface, which you would typically develop against using JavaScript. Even for a very apt JavaScript developer, it had many shortcomings historically poor IDE support, error-prone, difficult to debug, inefficient, poor code reusability, and the list goes...

Dynamic Generation of XAML from the Server

Possibly one of the less-obvious integration points between your Silverlight application and your standard ASP.NET web application is that you have the ability to dynamically generate and manipulate XAML on the server before it is shipped off to the client's machine as part of the application life cycle. The idea behind this is that in the page where you create your Silverlight host, you add in a reference to an ASP.NET page rather than the standard XAML file. All you have to do then is to make...

Visual State Parts

In this example, you have seen how you can obtain resources and trigger changes based on the control logic. But there is a more elegant way to perform these operations that will give the designer better control over how each state should look. Providing visual states allows the designer to override completely how the control looks in each state. To define the different states, you need to add the visual state parts. These parts are defined using attributes in this case, you are not using...

Creating a Silverlight Duplex Polling Receiver Class

Calling and receiving data in Silverlight requires a fair amount of code to be written. Before showing the code to interact with a polling duplex service, it's important to understand the general steps involved. Here's a synopsis of what you need to do to send and receive data in a Silverlight client 1. Reference assemblies and namespaces. 1a. Reference System.ServiceModel.dll and System.ServiceModel .PollingDuplex.dll in your Silverlight project. 1b. Import the System.ServiceModel and...

Using Templates

As it turns out, creating a new ControlTemplate is done by following the same process as creating a predefined style You use a Setter object to pass your ControlTemplate value to the Template property. The following XAML uses a PathGeometry object to describe a star shape and uses this as the new shape for the Button lt UserControl 6 xaml presentation Width 400 Height 3 00 gt lt Grid x Name LayoutRoot Background White gt lt Grid.Resources gt lt Style TargetType Button x Key StarButton gt lt...

OnDemand XAP Loading

In an Internet environment, being able to get your Silverlight application up and running as fast as possible is a must-have goal. Therefore, in the case of a rich and functionally complex Silverlight application, having all the libraries packaged and loaded into a single XAP file will directly violate this goal, as the entire XAP file and all functionality will need to be downloaded before the application can start. Obviously, if not all this functionality is needed immediately or even not at...

Handling Control Events Programmatically

In addition to declaring events declaratively, you can also hook events to event handlers dynamically in code using the C operator or the VB.NET AddHandler keyword. This won't come as news to .NET developers since it's the standard way to programmatically work with events. An example of hooking up a Silverlight UserControl's Loaded event and a Button control's Click event to event handlers is shown next public partial class Page UserControl this.Loaded new RoutedEventHandler Page_Loaded...

RSS and ATOM Syndication Feeds

RSS and ATOM both rely on a simple metadata format to exchange data between publishers and subscribers. RSS describes data using item elements, while ATOM uses entry elements. RSS is available in several different versions ranging from .91 to 2.0, although RSS 2.0 is the predominant version used on today's web sites and blogs. ATOM was created to fill in some of the perceived holes in RSS 2.0 and is currently at version 1.0. ATOM adds features that aren't found in RSS 2.0 such as the ability to...

Using WCF Polling Duplex Services to Communicate over HTTP

In the previous sections, you saw how data can be pulled from Web Services and RESTful services and even pushed from servers to Silverlight clients using sockets. Silverlight 2 provides another way to push data from a server to a client using WCF and HTTP. WCF's support for duplex service contracts makes this possible and opens up unique opportunities for pumping data to Silverlight applications. Many of the WCF services that are created follow the simple request response mechanism to exchange...