Creating an IronRuby Silverlight Application
IronRuby is an implementation of the Ruby programming language that is currently being developed by Microsoft. Using IronRuby, developers can implement Ruby code as the client-side language for Silverlight applications. Using Ruby to code Silverlight applications allows developers to use already existing Ruby applications to provide rich functionality to the Silverlight application. The first step in creating an IronRuby Silverlight application is to create a folder for the application. Inside...
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,...
Combining Shapes with GeometryGroup
The simplest way to combine geometries is to use the GeometryGroup and nest the other Geometry-derived objects inside. Here's an example that places an ellipse next to a square lt Path Fill Yellow Stroke Blue Margin 5 Canvas.Top 10 Canvas.Left 10 gt lt Path.Data gt lt GeometryGroup gt lt RectangleGeometry Rect 0,0 lt EllipseGeometry Center 150,50 RadiusX 35 lt GeometryGroup gt lt Path.Data gt lt Path gt The effect of this markup is the same as if you supplied two Path elements, one with the...
What exactly is DataBinding
How do we automatically write data to the TextBlock Manning Publications Co. Please post comments or corrections to the Author Online forum One way to accomplish this would be to have the code behind updating the TextBlock when the temperature changes. Ignore for the purposes of this example how the code behind would get that information If the application described were truly a thermostat instead of simply a thermometer, there must be a way for the user to enter text and have the value picked...
Cueballs in code and text replace below with cueballs
If the dog is entering anything but the Moving state we set its velocity to zero 1 and set the time to wait based on the game's current Delay value 2 . Otherwise the dog is entering the Moving state and we need to figure out where it is moving to and how long it will take to get there. This is done by calling the SetNextTarget method 3 . I don't think we have one of those yet. That's right so let's vreate it now. Here is the body of our SetNextTarget method double speed game.Speed double...
Writing a Custom HTTP Handler
Every resource processed by ASP.NET is processed by an actor called an HTTP handler. For example, web pages with the extension .aspx are processed by a page handler, while stand-alone web services with the extension .asmx are processed by a SOAP handler. All these classes are implementations of the IHttpHandler interface. When you associate your custom file type with the ASP.NET runtime, as shown in the previous section, you have to tell ASP.NET how to process this resource. The way to do this...
Customized ToolTips
If you want to supply more ambitious tooltip content, such as a combination of nested elements, you need to break the ToolTipService.ToolTip property out into a separate element. Here's an example that sets the ToolTip property of a button using more complex nested content lt Button Content I have a fancy tooltip gt lt ToolTipService.ToolTip gt lt StackPanel gt lt TextBlock Margin 3 Text Image and text gt lt TextBlock gt lt Image lt TextBlock Margin 3 Text Image and text gt lt TextBlock gt lt...
The Pythagorean theorem
The final topic we're going to cover in this chapter is the Pythagorean theorem. The theorem deals once again with the measurement of triangles, and looks like this Let's take another look at our right triangle, shown in Figure 6-32. An illustration of the theorem is shown in Figure 6-33. If you calculate the area of the squares on each leg of the triangle and add them together, you will get the area of the square on the hypotenuse. Figure 6-32. A triangle with sides labeled Figure 6-33. An...
Media Video and Audio
The System.Windows.Controls.MediaElement control provides media playback capability in Silverlight 2. It can handle both audio and video in a variety of formats. These are the supported video formats WMVA Windows Media Video Advanced Profile non-VC-1 WMVC1 Windows Media Video Advanced Profile VC-1 ASX Advanced Stream Redirector files extension might be .asx, .wax, .wvx, .wmx, or .wpl Silverlight 3 has enhanced media management supporting high-quality and secured multimedia streaming. The...
Adding an Overlay 1
Adding an overlay to a video can be a great way to give an identity to such a file, for example, with a company logo. However, don't forget that everything you're doing here will be burned into the video file. It might not be an appropriate way to display a message that must change often, such as an advertisement. In that case, a better solution would be to set your Silverlight 242 CHAPTER 13 Progressing with Videos application so that the advertisement is displayed on top of the media element...
Creating an HTTP Handler for NonHTML Content
Some of the most interesting HTTP handlers don't generate HTML. Instead, they render different types of content, such as images. This approach gives you the flexibility to retrieve or generate your content programmatically, rather than relying on fixed files. For example, you could read the content for a large ZIP file from a database record and use Response.BinaryWrite to send it to the client. Or, you could get even more ambitious and use your HTTP handler to dynamically create a ZIP archive...
Querying Data in an Asynchronous Page
The data source controls don't have any asynchronous support. However, many of the underlying ADO.NET classes, including SqlCommand and SqlDataReader, have asynchronous support. The following page takes advantage of the BeginReader and EndReader methods of the SqlDataReader. To allow the asynchronous query, you need to explicitly enable it in the connection string, as shown in the following snippet from the web.config file lt add name NorthwindAsync connectionString Data Source localhost...
System Design 1
BI 2.0 system design is actually a lot simpler than BI 1.0 design at a higher level. BI 2.0 systems tend to leverage existing enterprise services for data, business algorithms, or visualizations. Furthermore, BI 2.0 implementations have a higher level of quality, as more mature software engineering concepts are applied to the design of these systems. Leveraging services allows BI 2.0 software to be highly flexible. Changes in the service algorithms can automatically propagate down through the...
Adding load and error events to Silverlight at initialization time
The events parameter allows you to specify functions that are executed on certain events during the Silverlight application initialization. Currently, Silverlight allows you to register handlers for onLoad and onError events. The following code snippet creates a Silverlight object that implements onLoad and onError event handling lt script Silverlight.createObjectEx source Page.xaml, parentElement id SilverlightControl, properties width 400, height 400, version 1.1, background 1111FF onLoad...
Other DataBound Controls
In addition to the simple bound controls, ASP.NET includes several more complex controls . They work very much like the simple bound controls in that you attach a data source to them and they render automatically. However, these controls differ by displaying the data in more elaborate ways . These controls include the GridView, the FormView, the DetailsView, and the DataList. The best way to understand the nature of these controls is to work through a couple of examples . First, the GridView....
The Resources panel
The Resources panel, shown in Figure 2-57, contains a list of all resources of your application. Remember the ResourceDictionaryl.xaml file you created It shows up in this list, and inside of it, the Brushl resource color gradient you created is shown. You can use the Resources panel to actually apply the resources, which you'll do now by following these steps 1. Select the Rectangle tool and create a Rectangle in the workspace. Figure 2-57. The Resources panel, which contains all resources...
Converting the DataSet to XML
Using the XML methods of the DataSet is quite straightforward, as you'll see in the next example. This example uses two GridView controls on a page. The first DataSet is filled directly from the Employees table of the Northwind database. The code isn't shown here because it's similar to what you've seen in the previous chapters. The second DataSet is filled using XML. Here's how it works once the DataSet has been created, you can generate an XML schema file describing the structure of the...
The RadioButton
The RadioButton also derives from ToggleButton and uses the same IsChecked property and the same Checked, Unchecked, and Indeterminate events. Along with these, the RadioButton adds a single property named GroupName, which allows you to control how radio buttons are placed into groups. Ordinarily, radio buttons are grouped by their container. That means if you place three RadioButton controls in a single StackPanel, they form a group from which you can select just one of the three. On the other...
ASPNET Login Controls
Earlier in this chapter, you handcrafted a couple of different login pages . During the heyday of ASP.NET 1 .1, that's exactly what you had to do to get Forms Authentication to work . Later versions of ASP.NET add a number of login controls that perform the most common login scenarios you might need for your site . These controls include the Login, LoginView, PasswordRecovery, LoginStatus, LoginName, ChangePassword, and CreateUserWizard controls . Here's a summary of what each control does...
Converting vectors to angles
To see this code in action, visit the vectorAngleConversion project. This is a simple project that sets up a Point object that contains a vector and a variable called angle private Point vectorLength new Point private double angle A value that represents a vector is assigned to the vectorLength variable, and the angle of the vector is calculated and output to a TextBlock vectorLength.X 5 vectorLength.Y 5 double radians Math.Atan2 vectorLength.Y, vectorLength.X angle Convert.ToIntl6 l80 Math.PI...
FrameBased Animation
Along with the property-based animation system, Silverlight provides a way to create frame-based animation using nothing but code. All you need to do is respond to the static CompositionTarget.Rendering event, which is fired to get the content for each frame. This is a far lower-level approach, which you won't want to tackle unless you're sure the standard property-based animation model won't work for your scenario for example, if you're building a simple side-scrolling game, creating...
Common Properties
The Common Properties bucket of the Properties panel, shown in Figure 2-51, contains properties common to all UI elements or controls. Here you can set properties such as What cursor an object will display when the mouse is over it by specifying a value in the Cursor field Whether the object can detect hits by enabling the IsHitTestVisible option Whether the object will display a tooltip and what it will read by specifying text in the ToolTip field Figure 2-51. The Common Properties bucket of...
A Browser History Example
Using the techniques you've just learned about, you can tackle a true Silverlight challenge integrating your application with the history list in the web browser. Ordinarily, Silverlight content exists inside a single page. Thus, no matter what takes place in that page the browser history list never changes. This can confuse users, who often expect that clicking the back button will bring them back to the previous visual in your Silverlight application, whereas it will actually end the current...
Defining Custom Attributes for Each Node
Another way to extend your Web application's navigation is to define custom attributes for the site nodes in web . sitemap and retrieve them at run time. Imagine that you want to associate a specific image with each page in your site. To accomplish this, just create a new attribute and specify it in the siteMapNode element in the site map data. ASP.NET site map navigation support makes it very easy to add arbitrary attributes to each node. In this example, you add JPEG URLs to the site map...
Concurrency
Update errors can be caused by all the usual factors a timeout waiting for a connection, a network error, and so on but the most common update error is a concurrency problem. By default, update commands use optimistic concurrency, which attempts to match every value. This runs into immediate trouble when two users make overlapping changes. If you attempt to update a record, and that record no longer has the initial set of values you retrieved, the update fails with an...
Adding dynamic XAML using managed JavaScript
You can use managed JavaScript code to dynamically add XAML objects that are rendered to the browser in the Silverlight application. This is one of the most powerful features of the DLR because it allows you to employ the strengths of the scripting language to create a content-rich interface for the user. One of the biggest strengths of the DLR is that almost every Silverlight object has a constructor. You can use that constructor rather than having to use CreateFromXaml or a XamlReader to...
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...
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...
Agile Software Development Life Cycle Model
The topic of the Agile SDLC model is vast enough for an entire book. However, for the purposes of this book, a summary of the Agile SDLC will suffice. To support the dynamic nature of the market, it would be challenging for organizations to follow the traditional waterfall SDLC model to implement IT solutions. In order to provide faster, cheaper, and better products delivering high business value, organizations have to implement an optimized, diversified, agile, and cohesive IT organization...
Type Editors
So far you've seen how type converters can convert various data types to strings for representation in the Properties window. But some data types don't rely on string editing at all. For example, if you need to set an enumerated value such as BorderStyle , you can choose from a drop-down list of all the values in the enumeration. More impressively, if you need to set a color, you can choose from a drop-down color picker. And some properties have the ability to break out of the Properties window...
Discovering the ButtonBase
What do a Button, Checkbox, and RadioButton have in common When you click on them something happens. This is enough to make them share a base class the ButtonBase. This class defines one important event the Click event. By handling this event, you define what the reaction of the application must be. ButtonBase derives from ContentControl. All subclasses get a Content property that is of type object. You can store anything in the Content property, for example, a string which will become the text...
ASPNET Controls That Use Silverlight
As you saw in Chapter 1, it's easy to build a simple ASRNET web application that includes Silverlight content. You simply need to create a website that includes an HTML or an .aspx test page. Although this approach allows you to place Silverlight and ASRNET pages side by side on the same website, they aren't in any way integrated. You can navigate from one page to another for example, use a link to send a user from an ASRNET web form to a Silverlight entry page , but there's no interaction...
Text Selection
As you already know, you can select text in any text box by clicking and dragging with the mouse or holding down Shift while you move through the text with the arrow keys. The TextBox class also gives you the ability to determine or change the currently selected text pro-grammatically, using the SelectionStart, SelectionLength, and SelectedText properties. SelectionStart identifies the zero-based position where the selection begins. For example, if you set this property to 10, the first...
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...
Testing the Web Method
Now that you've added the code to your solution, you'll want to test out the Service to make sure it works. To test out the code 1. Change the SPSite value to your own SharePoint default site if you didn't use the GetContextSite method and add a list called Survey to SharePoint with two fields called Question and Answer. To do this, navigate to your SharePoint site, click ''View All Site Content,'' and click Create. Under Custom Lists, click ''Custom List,'' and provide a name and description...
A File Browser
Using the concepts you've learned so far, it's quite straightforward to put together a simple file-browsing application. Rather than iterating through collections of files and directories manually, this example handles everything using the GridView and some data binding code. Figure 12-1 shows this program in action. f. Untitled Page - Windows Internet Explorer k - - - gj htt jbo tl0a WtM4FfcftnHV,a K X Pi' Movs Up I Qrrr nnV ivirwDj.Jprej rW ASF fiFTn V MOB pm ISWVfT Movs Up I Qrrr nnV...
Creating a manifest for the managed JavaScript Silverlight application
With the XAML file in place, you should create an XML file named AppManifest.xml. Although this file is created automatically by Chiron, Chiron does not automatically add all of the assembly libraries you need. Listing 11.10 shows an example of an AppManifest.xml file for a managed JavaScript Silverlight application. This manifest file includes the standard Silverlight assemblies, the assemblies for managed JavaScript, and the assemblies to implement the Silverlight 2 controls. Example...
The background Parameter
This sets the color of the Silverlight application's background. This color will be visible only if you set the windowless parameter to true as explained in the next section. The background parameter is a XAML color, not an HTML color. It means that you can also set the Alpha channel, as we saw in Chapter 5. In addition to these generated parameters, you can create additional ones as discussed in the following sections. The windowless Parameter This parameter is tricky. To keep it simple, let's...
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...
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...
Packaging Images and Media
While you can download images and media file by file, sometimes an application requires a collection of related images or other media before it can start. One example of this is a game that might need a number of images to display scenes, characters, and the background. You can package these resources into a single ZIP archive and download it. After downloading the ZIP file, using the WebClient class perhaps, you can save its stream. Let's revisit the image browser from earlier in the chapter...
Template Bindings
Although the revised button template respects the content of the button, it ignores most other properties. For example, consider this instance that uses the template lt Button Template StaticResource ButtonTemplate Content A Templated Button Margin 10 This markup gives the button a Margin value of 10 and a Padding of 20. The element that holds the button is responsible for paying attention to the Margin property. However, the Padding property is ignored, leaving the contents of your button...
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...
The Source
When you set the Source property of a MediaElement, Silverlight decides what kind of source you have and creates an appropriate source object. For example, if your path starts with mms , Silverlight assumes that your source is a streaming source from a Windows Media Server. If the source property points to a simple WMV file, a MPEG4 file, or an audio file, Silverlight assumes that you have a progressive download source in your application. In all cases, Silverlight creates an object that is...
Custom Expression Builders
One of the most innovative features of expressions is that you can create your own expression builders that plug into this framework. This is a specialized technique that, while impressive, isn't always practical. As you'll see, custom expressions make the most sense if you're developing a feature that you want to use to extend more than one web application. For example, imagine you want a way to create a custom expression builder that allows you to insert random numbers. You want to be able to...
Listing Core field type class continued
using Microsoft.SharePoint.Security Guid 1b6 64652-3 97c-4cb6-93 5c-1c088694afe4 public class LikertScaleField SPFieldText public LikertScaleField SPFieldCollection fields, string fieldName base fields, fieldName public LikertScaleField SPFieldCollection fields, string typeName, string displayName base fields, typeName, displayName public override BaseFieldControl FieldRenderingControl ObjectModel true BaseFieldControl fieldControl new LikertScaleFieldControl fieldControl.FieldName...
Encoding Metadata in the Media File
The biggest benefit to developers using Expression Encoder to encode audio and video is the ability to encode metadata into the output file. Using Silverlight, that metadata can be extracted later and used to implement rich features in the video playback for example, displaying chapter titles and embedding script commands that trigger application events at specific points in the media playback. Metadata can be added to media files in Expression Encoder by clicking the Metadata tab, as shown in...
Accessing the HTML Page From NET 1
In Chapter 14, we talked about the Silverlight HtmlPage class as a gateway to the HTML page hence the name containing the application. We talked about the HtmlPage.Window property and used it to get JavaScript object instances, and to call the Alert, Confirm, and Prompt methods. Another handy property of the HtmlPage class is the Document. This is the exact equivalent of calling document in JavaScript. Using the well-known methods GetElementById and GetElementsByTagName, you can access any HTML...
Creating the navigation buttons
Next, you will next create a series of Rectangles in a Canvas that you will then use as your navigation buttons. Before you do that, however, it would be good for you to understand the differences between WPF and Silverlight. As you know, WPF has many built-in controls such as the Button control. Silverlight, however, does not have very many built-in controls at all, for example, it does not even include a Button control. In fact, if you look in the Asset Library and select Show All, you will...
The DockPanel
The DockPanel, as its name implies, allows you to dock its content to the top, bottom, left, or right of the control. You'll create a DockPanel now 1. Select the DockPanel tool from the toolbar. 2. In Row 0 Column 0, draw out a DockPanel. 3. Hold down the Pen tool and select the Pencil tool. 4. Draw four squiggly shapes in the DockPanel. By default, the DockPanel will dock all of its content to the left of the panel, as shown in Figure 5-12. You can change where these objects are docked in the...












