Thursday, December 20, 2007

Supporting Full Screen Mode with Silverlight

One of the nice features that Silverlight supports is the ability to go "full screen" and effectively take over the entire screen of a computer (hiding everything else from sight - including the browser frame). This can be very useful when building immersive UI experiences, games, rich video players, etc.
For a nice example of this feature in action, make sure to check out the Fox Movies Sample on www.silverlight.net:

Once the page loads and the movie starts playing, double-click on the video surface in the middle to switch into full-screen mode (note: the screen-shot above is not in full-screen but rather browser mode). You can then hit the escape key to switch back into normal browser viewing.
How to Implement Full Screen Mode with Silverlight 1.1 using .NET
One of the questions I've seen a few people ask is "how can you implement full screen-mode when building Silverlight applications using .NET?" The good news is that the answer is actually pretty easy:
1) First add an input driven event handler to your application (for example: a mouse down or keyboard event handler). For security reasons Silverlight doesn't allow developers to switch an application into full-screen mode on first application load (you don't want an application to spoof you). So you'll instead need to trigger full-screen mode in response to a user action.
2) Within your input event handler set the BrowserHost.IsFullScreen property to true (note: the BrowserHost class lives within the System.Windows.Interop namespace). This will cause Silverlight to switch into full screen mode. Setting this property to false will return it back to normal browser mode.
Simple Full Screen Mode Sample
You can download a simple Silverlight full screen-mode sample I put together written in C# here.
When you run the sample it will load a super simple Silverlight application within the browser and display a text message prompting you to click it to switch into full-screen mode:

When you switch into full-screen mode, Silverlight will display a user message blurb that will pop-up on the screen for a few seconds and instruct the user that they can press the escape key to switch back into browser mode. After a few seconds this message will disappear and only your content will be visible. In my sample above I also allow the user to click on the "Click to Return to Browser" text and switch back into browser mode as well.
Walkthrough the Simple Full Screen Mode Code
The code to implement the above sample is pretty simple.
To begin with we can open and edit the root .XAML file for the application, and add a UI element to it that we want to use to trigger the full-screen mode. In the sample above I used a control that I named "MyMessage". Below is all of the XAML for the entire application:

Within the application's Page_Loaded() event handler above I am wiring up two event handlers:
MyMessage_MouseLeftButtonDown - This event handler will execute anytime a user clicks on the TextBlock message control I added into my XAML file. Within this event handler I'm simply toggling the BrowserHost.IsFullScreen property to true or false depending on whether or not it is already in full screen mode.
BrowserHost_FullScreenChange - This event handler will execute anytime Silverlight switches between full screen and browser mode. It provides a good place to add logic to update the UI when this happens. In the example above I am changing the text on the TextBlock control. I could also have optionally resized controls and/or moved them around the screen to new coordinate positions. Currently the Silverlight 1.1 Alpha doesn't have layout manager support, so controls won't automatically re-position unless you write code to manage this yourself (don't worry - layout manager controls for Silverlight like in the desktop WPF version are coming).
In addition to the IsFullScreen property, BrowserHost class has a number of additional properties and events that are very useful:

Silverlight Tutorial - Color Animations

In this tutorial, I'm going to show you how to use Silverlight's Storyboard and ColorAnimation XAML tags to create custom color animations. Color animations are commonly used on input controls like buttons to give visual feedback that the cursor is over the control or when the button has been pressed. This tutorial will show a couple of simple examples that can easily be extended to complex controls and animations.

The examples in this post were built using Visual Studio 2008 beta 2, Silverlight 1.1 Alpha Refresh, and C#. For information on where to download these, please visit our previous tutorial Getting Started With Silverlight.

We'll start by defining the XAML for the rectangle.

Here we've defined a very simple red rectangle. Since we want the color to change when the user enters or leaves the control with the cursor, we've defined event handlers for each of these. The code inside these event handlers is located in the C# code behind and will be explained a little later. Now that we have the rectangle defined, let's create an animation to change the color of the rectangle when the user enters it with the mouse cursor.

The first thing you might notice here is the tag. This tag holds a collection of Storyboards and is located directly after the opening Canvas tag. Inside this tag is where we'll be placing the Storyboards that will control our color animations. The first Storyboard we're going to make will change the color of the rectangle when the user enters the control with the mouse. In order to control the Storyboard from the C# code-behind, you'll have to first give it a name. I named mine "mouseEnter". Next we add a ColorAnimation inside the Storyboard. The first attribute we set is Duration, which is how long the animation will run - in this case, 1 second. Next, we set the end result of the animation. I want my rectangle to fade from red to black, so I set To to "#000000". The next thing we set is the Storyboard.TargetName, which is the name of the object we want to modify. This has to be set to the same thing that we named the rectangle, in this case "myRectangle". Storyboard.TargetProperty is the property the animation will be changing, which in this case is the fill color. It might seem like a complicated way to address the rectangle's fill color, but it's necessary. If we expanded out the rectangle to use a SolidColorBrush it might make a little more sense:

So in the attribute , "(Shape.Fill)" refers to and "(SolidColorBrush.Color)" is the Color attribute of . All right, the storyboard and animation are done and ready to be run. Let's create some C# code that will handle the events.
private void MyRectangleMouseEnter(object sender, EventArgs e){ this.mouseEnter.Begin();}
If you remember, we added a MouseEnter event to our XAML code and told it to execute the method MyRectangleMouseEnter. All this function does is to start the Storyboard we named "mouseEnter". If you build and preview your project, you should get something that looks like the following:
If you ask me, that's not very interesting. Let's add in the XAML code to make the rectangle fade back to red when the mouse leaves the control.

To make the rectangle fade back to red, I simply added another Storyboard to the canvas resources. The only thing different from the previous ColorAnimation is that To is now set to red (#FF0000), instead of black (#000000). Just like with the previous storyboard, we'll going to need some C# code to run the animation. This time, the function is hooked up to the rectangle's MouseLeave event.
private void MyRectangleMouseLeave(object sender, EventArgs e){ this.mouseLeave.Begin();}
That's it. Now we have a rectangle that fades to black when the mouse enters it and fades back to red when the mouse leaves.
We've only barely touched the surface for the possibilities of what a color animation is capable of - but hopefully this tutorial will provide you with a launching point for your own complex (and much more interesting) animations.

Silverlight and Javascript Interaction

Silverlight is a relatively new client side technology released by Microsoft, but already people are finding the need to communicate between their Silverlight applications and Javascript. This tutorial will go through all the code required to call Javascript functions from Silverlight and vice-versa.
All the Silverlight code and examples were created using the 1.1 Alpha Refresh. Before you can use the example application below, you'll need to download the runtime (if you haven't already). If you're new to Silverlight, check out our introductory tutorial for information on what to download and how to get started.

Before we jump into code, let's look at an example of some communication between Silverlight and Javascript. The application on the left was created using Silverlight, the one on the right was made using HTML and CSS. When one of the buttons on the left is clicked, a message will be displayed on the right indicating that. The same thing happens when a button on the right is clicked.

So let's see how something like this is done. We'll start with the hard one - calling a Javascript function from Silverlight. There's no direct way (that I know of) to simply call a Javascript function directly from the Silverlight code behind. What we have to do is create events and attach to them from the Javascript code. This isn't a lot of work, but being able to call them directly would be a nice feature to have. So let's look at some
C# code behind that creates the events.


using System;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Browser;namespace SilverlightJavascript{ [Scriptable] public partial class Page : Canvas { [Scriptable] public event EventHandler ButtonAClicked; [Scriptable] public event EventHandler ButtonBClicked; [Scriptable] public event EventHandler ButtonCClicked; public void Page_Loaded(object o, EventArgs e) { // Required to initialize variables InitializeComponent(); WebApplication.Current.RegisterScriptableObject( "SilverlightApp", this); } }}

Since my Silverlight application has three buttons, I created three events - one for each button. They're created and used exactly like they are in an ordinary C# Windows application. One difference I'm sure you noticed is the [Scriptable] attribute above the definition of the class and each event. This lets Silverlight know that this class and these events should be accessible from the Javascript code. The next thing you might have noticed is the RegisterScriptableObject call. With this function we're telling Silverlight to make this class accessible via scripts by the name "SilverlightApp". Now whenever I want to use this object in Javascript, I'll reference it by the name "SilverlightApp". We'll see how this works later. Now that everything is setup, let's look at some C# code to fire our newly created events.

void ButtonA(object sender, MouseEventArgs e){ if (ButtonAClicked != null) ButtonAClicked(this, e);}void ButtonB(object sender, MouseEventArgs e){ if (ButtonBClicked != null) ButtonBClicked(this, e);}void ButtonC(object sender, MouseEventArgs e){ if (ButtonCClicked != null) ButtonCClicked(this, e);}

In my XAML code I hooked up a MouseLeftButtonUp event to each of my buttons. Now when a button is clicked, one of these functions will be called. As you can see, firing the events is no different than a C# application. You should always make sure to check that an event is not null before firing it - otherwise things tend to crash. An event will be null if nothing has attached to it. That's all the code required on the Silverlight side to call Javascript functions. Now let's look at how to make Javascript listen for these events. The first thing we need to do is attach Javascript functions to each event. We'll do this as soon as the Silverlight application is done loading. So now you're probably wondering, how do we know when the Silverlight is done loading? There's an event we can listen for that is called as soon as it's finished. In order to get this event we need to modify the Javascript that Visual Studio generated as part of the test code. In my solution, the .js file is named TestPage.html.js. It might be different for you depending on how you set it up.

// JScript source code//
contains calls to silverlight.js, example below loads Page.xamlfunction createSilverlight(){ Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById( "SilverlightControlHost"), id: "SilverlightControl", properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: {onLoad: OnLoaded} }); // Give the keyboard focus to the Silverlight // control by default document.body.onload = function() { var silverlightControl = document.getElementById('SilverlightControl'); if (silverlightControl) silverlightControl.focus(); }}

This should look very similar to what Visual Studio has created for you. The addition we have to make is in the events: {} section. We need to add an event for onLoad. With this addition, we're telling Silverlight to call the Javascript function OnLoaded as soon as it's finished loading. The OnLoaded function is where we're going to be attaching Javascript functions to our Silverlight events. So let's see how that's done.

function OnLoaded(sender, args)
{
sender.Content.SilverlightApp.ButtonAClicked = ButtonAClicked; sender.Content.SilverlightApp.ButtonBClicked = ButtonBClicked; sender.Content.SilverlightApp.ButtonCClicked = ButtonCClicked;}function ButtonAClicked(){ //The Silverlight A button has been clicked
}
function ButtonBClicked(){ //The Silverlight B button has been clicked }function ButtonCClicked(){
//The Silverlight C button has been clicked
}

The OnLoaded event is automatically passed in the Silverlight object and some event arguments. Here's where we use the "SilverlightApp" name we created above. With those assignments, we're telling Silverlight to execute a Javascript function whenever one of those events is fired. So now, whenever the event ButtonAClicked is fired from the Silverlight Application, the Javascript function ButtonAClicked will be executed. That's it for calling Javascript functions from Silverlight. Now let's look at how to call Silverlight functions from Javascript. This process is much easier than calling Javascript from Silverlight. The first thing we need is a C# function we want called.
Let's add one to our Silverlight code behind.

Scriptable]public void HTMLButtonAClicked(){ //The HTML A button has been clicked}

There nothing special about this function except for the [Scriptable] attribute which makes it accessible by our Javascript code. All that's left is to call this function from the Javascript code.


var slApp = document.getElementById('SilverlightControl');slApp.Content.SilverlightApp.HTMLButtonAClicked();

As you can see, this is much easier than the other way around. The first thing we need to do is get the Silverlight object. You're probably wondering where the "SilverlightControl" id came from which is passed into getElementById. This is set back in the .js file that Visual Studio created for you. All that's left to do is access the class we named "SilverlightApp" and call the HTMLButtonAClicked function. Once that's done, the function we wrote in the C# code behind will be executed. I hoped you enjoyed this tutorial on Silverlight and Javascript interaction. Post a comment if you have any questions.



Communicate Between Flex and Silverlight using Javascript


If Flex can communicate with Javascript and Silverlight can communicate with Javascript, it seems like there should be some sort of transitive rule that lets Flex communicate with Silverlight. Well there is, and this tutorial is going to show you how to use Javascript to communicate directly between a Flex application and a Silverlight application.
You're probably asking yourself, why would I ever want to do that? To be honest, we haven't thought of a great reason yet. Maybe Silverlight can do something Flex can't, or Flex has a feature Silverlight doesn't, and you want combine both into one all-powerful web page. Well now you can.



Depending on whether or not you have all the required plugins installed, you should see an example of Flex/Silverlight communication on the right. The sliders on the top and left were created using Flex. The sphere in the middle was created using Silverlight. When you drag the sliders, the sphere will roll around accordingly. You can also click and drag the sphere, which will move the sliders.
If you can't see the above example, it either means you don't have Flash 9 or the Silverlight 1.1 Alpha Refresh Runtime.
This tutorial isn't going to go into the specifics of how Silverlight and Flex communication with Javascript. For detailed information on how to accomplish that, check out our previous two tutorials: Silverlight and Javascript Interaction and Flex & Javascript Tutorial - Simple Interaction.
We'll start by looking at what happens when one of the sliders is moved.

function MoveBallX(val){ var silverlightControl = document.getElementById('SilverlightControl'); silverlightControl.Content.SilverlightApp.MoveBallX(val);}
function MoveBallY(val){ var silverlightControl = document.getElementById('SilverlightControl'); silverlightControl.Content.SilverlightApp.MoveBallY(val);}
When the horizontal slider is moved, the Flex application calls the Javascript function MoveBallX and passes in the current value of the slider. This function then calls the C# function MoveBallX in the Silverlight application. Silverlight then positions the ball to the new X position. The same thing happens when the vertical slider is moved, but now MoveBallY is called. That is all the Javascript code required to move the sphere when one of the Flex sliders is moved.
Now let's look at what happens when the drags the sphere.

function xChanged(){ var silverlightControl = document.getElementById('SilverlightControl'); xPos = silverlightControl .Content.SilverlightApp.GetXValue(); getFlexApp('HorizontalSilverlightMover').setXValue(val);}
function yChanged(){ var silverlightControl = document.getElementById('SilverlightControl'); yPos = silverlightControl.Content.SilverlightApp.GetYValue(); getFlexApp('VerticalSilverlightMover').setYValue(val);}
function getFlexApp(appName) { if (navigator.appName.indexOf ("Microsoft") !=-1) { return window[appName]; } else { return document[appName]; }}
Again, there's not a lot of Javascript code required to keep the two applications synchronized. The functions xChanged and yChanged are hooked up to events in the Silverlight application and are called whenever a user moves the ball in either the X or Y direction. The first thing these functions do is get the new position from the Silverlight application by calling either GetXValue or GetYValue. It then simply calls setXValue or setYValue to set the horizontal or vertical slider to its new position. The function getFlexApp is explained in details in the earlier Flex and Javascript tutorial, but it basically acquires a reference to the Flex application depending on what type of browser is currently being used.

As you can see, the actual code to do Flex/Silverlight communication is very simple. This tutorial was meant to let everyone know that the possibility existed. As a reminder, please refer to Silverlight and Javascript Interaction for detailed information on how to communicate between Silverlight and Javascript. Also refer to Flex & Javascript Tutorial - Simple Interaction for information on how to communicate between Flex and Javascript.

How To Embed Silverlight Into a Webpage

Since we've started posting Silverlight tutorials, I've had to figure out how to get Silverlight applications embedded into our blog. Needless to say, I found the process a lot harder than it should be. Visual Studio provides a test page as part of a default Silverlight project, but what if you want to take the Silverlight application and put it in a blog post like we do? This tutorial will go through all code changes, files needed, and new code required to easily embed your Silverlight apps into existing webpages.

If you're new to Silverlight, I would strongly recommend reading our earlier tutorial, Getting Started With Silverlight. All of the examples in this tutorial were created using Visual Studio 2008 beta 2 and Silverlight 1.1 Alpha Refresh.

Required Files
Let's start by figuring out what files are needed for a Silverlight application. When you create a new Silverlight project with Visual Studio, it creates all sorts of files - most of which aren't needed to display Silverlight. At a minimum, the only two files you'll need are the XAML file and your code behind file. I use C# for my code behind so I'll have a DLL. If you used Javascript, you'll have a JS file. When you build the Silverlight project, Visual Studio is going to put the the code behind in a folder named "ClientBin" inside your project directory.

The Javascript
Javascript makes up the bulk of getting Silverlight into a webpage. You'll notice that Visual Studio also outputs a file named "Silverlight.js". You only need one of these files for each webpage - even if you have multiple Silverlight apps on a single page. You'll want to put this in a script tag somewhere in your webpage - preferably up in the head. If you don't have access to the head tag - like in a blog post - just stick the script tag at the top of the post.


<script type="text/javascript" src="Silverlight.js"></script>

The other Javascript file Visual Studio makes for you is the one for the test page. We don't need everything in there, so let's just strip out the function that matters.

function createSilverlight(){ Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById("SilverlightControlHost"), id: "SilverlightControl", properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: {} });}This function will only work for one Silverlight control per page, so let's modify it to work for multiple applications.
function createSilverlight(source, parent, id){ Silverlight.createObjectEx({ source: source, parentElement: document.getElementById(parent), id: id, properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: {} });}

Now the source, parentElement, and id are passed in as parameters instead of being hard coded inside the function.

Modify the XAMLDepending on where you're putting your files, you might have to modify the XAML file to point to the correct location of the code behind file. The default page.xaml file that Visual Studio generates will look something similar to this.

<Canvas x:Name="parentCanvas" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Loaded="Page_Loaded" x:Class="EmbedSilverlight.Page; assembly=ClientBin/EmbedSilverlight.dll" Width="640" Height="480" Background="White" >
</Canvas>


The part of this that probably needs modified is x:Class. The assembly portion of x:Class will need to changed to point to wherever you put the code behind on your webserver. Remember, this path is relative to the location of the parent webpage and not the location of the XAML file.
The HTMLWe've got the necessary files, the Javascript, and we've made the change to our XAML file. We are now ready to create some HTML code to actually display our Silverlight applications. I'm going to reuse a small Silverlight app that was created for an earlier tutorial.
In order to embed Silverlight into a website, we first need a parent element to stick it in - a div. Each parent element will need a unique id.

<div id="Example1Host" style="width:120px;height:44px;"> <script type="text/javascript"> createSilverlight("/pathToSilverlight/Page.xaml", "Example1Host", "Example1"); </script></div>Here's the output of the above HTML code using my example application.


So what if you want two of these? All you need to do is duplicate the above code, but with a different id.


<div id="Example1Host" style="width:120px;height:44px;"> <script type="text/javascript"> createSilverlight("/pathToSilverlight/Page.xaml", "Example1Host", "Example1"); </script></div><div id="Example2Host" style="width:120px;height:44px;"> <script type="text/javascript"> createSilverlight("/pathToSilverlight/Page.xaml", "Example2Host", "Example2"); </script></div>

Silverlight Tutorial - Animating HTML Elements


Animation! And more animation! We sure do seem to love animation here at Switch On The Code - and really, I have no idea why. But as long as we keep coming up with cool concepts that deal with animation, we will continue to write about them. Today we are going to take a look at something a little bit weird - we are going to animate HTML elements using Silverlight. Thats right, you read that correctly - HTML elements, the stuff you would normally animate with some plain old javascript - perhaps even the Generic Animation javascript code. Why would you want to do this? I don't have any good reasons at the moment. But it does show off some of the capabilities of silverlight, and that is a good enough reason to write about it.
One thing to note before we get started - you will need the
Silverlight 1.1 Alpha Refresh in order for the examples on this page to work. If you don't have it installed, you probably won't see any notification of that fact. This is because, unlike most silverlight apps, the silverlight on this page has no display - so there is no place for the usual "Get Silverlight" image and link to appear. So if the examples on this page fail to work, I would suggest checking out some of our other silverlight tutorials to make sure that your silverlight 1.1 install is working. So below we have the classic animation example that we use here at Switch On The Code. This time, however, the "Go!" button is not hooked to a javascript function, it is hooked to an function in the silverlight code-behind. And if you set some values in the text boxes and click "Go!", silverlight will move and resize the red box to the values given in the given amount of time.

How to Use Custom User Controls in Silverlight

Since Microsoft hasn't released an official library of controls for Silverlight, making and using your own is very important. This tutorial is going to show you how to import and add a custom control to your Silverlight application.

The code and examples in this post have been written using Silverlight 1.1 Alpha. This tutorial won't cover how to make user controls - just how to use them. Just like a classic cooking show, I've prepared a user control earlier that we'll be using. I've created a replica of the default Windows XP WPF button. The DLL that holds this control can be downloaded
here - feel free to use the button for whatever you want.

Let's start by adding the button using nothing but XAML. The first thing we need to do is get the namespace into the XAML code.

<Canvas x:Name="parentCanvas" xmlns="http://schemas.microsoft.com/client/2007" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="clr-namespace:SOTCSilverlightControls; assembly=ClientBin/SOTCSilverlightControls.dll" Loaded="Page_Loaded" x:Class="SilverlightControlsTestApp.Page; assembly=ClientBin/SilverlightControlsTestApp.dll" Width="640" Height="480" Background="White" >
</Canvas>


This is the code from a default Silverlight application. I've added the following attribute to the canvas, which will let us reference the DLL containing our user controls.

xmlns:controls="clr-namespace:SOTCSilverlightControls; assembly=ClientBin/SOTCSilverlightControls.dll"
What you put after "xmlns", in this case "controls", is what you will use to reference the namespace. This can be anything you want (as long as it doesn't already exist).
The only control in that assembly is a Button, so let's put one of those on our canvas.