Showing posts with label SIlverlight. Show all posts
Showing posts with label SIlverlight. Show all posts

29 November 2007

Silverlight in action – Part 2

New version of the sample

As I explained in the previous post on the subject, the sample’s code was to be opened and used with Visual Studio 2008 Beta 2. Now one week later I’m happy to inform you that the code can now be opened and used with Visual Studio 2008 RTM. It was seamlessly ported to the latest version as now the “Silverlight 1.1 Tools for Visual Studio 2008 RTM” free download is now available. You can download the latest code for the sample from here.

Silverlight basics

What I came across while explaining Silverlight to students and even more experienced developers, is that some of them did not realize quite how “the magic” works. First and most important thing to understand is that you can have Silverlight application running on your site no matter how that site is built. Whether it is pure html (no server side code), PHP driven, JSP, ASP or any other web platform used to create web sites. To the server that serves Silverlight enabled pages any Silverlight application is just a bunch of files that need to be streamed to the client. Surely, the application can be much more flexible and dynamic by using some server-side interaction but again that depends on specifics on the application. Applications are always executed on the client machine and depend only on whether the client has Silverlight plug-in installed.

Creating Silverlight objects

Created to run inside any HTML page, any Silverlight application need to be included inside a page where we want to use it. For this to happen, we need to do two things – first create the HTML page and create a hosting element for the application(some element that will contain the app in itself) and second, to actually create the application object. For our sample application the page is quite simple :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>

<title>PosterDemo</title>

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

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

<style type="text/css">

.silverlightHost {

height: 1500px;

width: 1000px;

}

</style>

</head>

<body>

<select id="posters" onchange="Changed()" >

</select>

<div id="SilverlightControlHost" class="silverlightHost">

<script type="text/javascript">

createSilverlight();

</script>

</div>

</body>

</html>

From top to bottom here is what it contains. First there are two JavaScript files included – Default_html.js and Silverligh.js. I’ll explain the first later, the second is given by Silverlight SDK and is obligatory for every Silverlight application. It allows cross-browser plug-in installation detection plus object creation objects and methods. Right after including the JavaScript files, there is some CSS styling added to expand the application host element as much as it’s needed.

The body of the page contains only two elements – one <select> that will hold universities names so that users can select other posters, and the other is the actual host for the application <div id="SilverlightControlHost"… . Inside that host there is a simple JavaScript added that calls a method createSilverlight();

This method is defined in the file I said I’ll show - Default_html.js. It is a custom added js file that holds this code:

function createSilverlight()

{

var controlID = "SilverlightControl";

Silverlight.createObjectEx({

source: "Page.xaml",

parentElement: document.getElementById("SilverlightControlHost"),

id: controlID,

properties: {

width: "100%",

height: "100%",

version: "1.1"

},

events: {}

});

// Give the keyboard focus to the Silverlight control by default

document.body.onload = function()

{

var silverlightControl = document.getElementById(controlID);

if (silverlightControl)

silverlightControl.focus();

}

}

function Changed()

{

var posters = document.getElementById("posters");

var posterName = posters.options[posters.selectedIndex].text

var control = document.getElementById("SilverlightControl");

control.Content.basic.ChangePoster(posterName);

}

As you can see there are two functions here – the first is used to create the application object, the second is called when selection inside universities dropdown is changed. I will focus on the first function as the second I will explain in future posts on the sample. So what does this function do? Here we create a variable that holds the string of application control id value – "SilverlightControl". Then there is a call to a static method of Silverlight class - createObjectEx. Both the class and the method are defined inside Silverlight.js file. This method is used to create the application – “the key to the tent”. Here are passed some parameters. More of them can be passed to customize the application if needed. As an alternative to this method there is another one – createObject. Both do the same thing and the result is the same – the difference is the way parameters are passed. I the method we used – we pass the parameters as JSON object, and so we name each property and assign a value to it – just as in C# 3.0 you can create objects from anonymous class. The second method receives all parameters as usual. You probably will ask - what parameters can you pass to this initializing method. I will not go into more details on this as there is a good article written in Visual Studio Magazine on the subject. Through this parameters you can pass not only property values but also function pointers that will be called on some events, startup parameters that can be used for application data and others.

I want to point out only one parameter – source. It is an obligatory parameter that needs to be passed to initialize the application. This parameters holds the path to XAML file with application’s main interface. As you probably realize, you can put this file anywhere you want in the site, have it automatically generated, streamed from an embedded resource or other way you like.

The final result

So what the hell happens when this “magical” method “createObjectEx” executes?! Well, this method dynamically generates HTML object and includes it inside the page’s DOM. To see what that method creates, you can use a browser plug-in that shows generated source. For IE you can use – IE Developer Toolbar. Here is the source that was generated for the sample application:

<DIV class="silverlightHost" id="SilverlightControlHost">

<OBJECT id="SilverlightControl" type="application/x-silverlight" height="100%" width="100%" data="data:,">

<PARAM value="Page.xaml" name="source" />

<PARAM value="__slLoad0" name="onLoad" />

<PARAM value="__slError0" name="onError" />

</OBJECT>

</DIV>

So what is the end result from calling “createObjectEx” method – it is an HTML object element with specific parameters assigned to it. When the Silverlight browser plug-in is installed such object elements are handled by it and the application is being executed on the client. Probably someone may be tempted to just put the <Object> html with proper parameters than to use Silverlight.js file. Yes you can do it like that but I guarantee you that it probably not run on all supported browsers and if the user does not have Silverlight installed it will fail to load and the user will not know how to have that working (where and how to install Silverlight).

For now I’ll stop here … Expect soon more details on other aspects of this demo application and Silverlight development in general.

P.S.: If you have any questions on the Demo or want just to send me a message you can comment or use Facebook messaging.

20 November 2007

Silverlight in action – Part 1

The Road Show

Recently, I participated in this autumn's Microsoft Academic Road-show around Bulgaria's universities. I was talking to the students about Silverlight and sharing my experience from Imagine Cup finals. To be honest I was expecting more people to have interest in the competition. Still I expect more competitors this year as more people now know about it compared to last year.

Lecturing about Silverlight, I realized that a few people in Bulgaria know about it. Gladly to say, now this has been corrected as a few hundred more students know what it is now and what it can do. For each presentation I gave, I was using Bookvar and build a map for the subject. The presentation can be found here in the form of a zip archive. Unzip it and use Bookvar to open the .bmm file.

Demonstrations

As part of the demonstration I used some sample Silverlight applications – Popfly and others from Silverlight.net. Additionally to that, I created a sample Silverlight application to show key features of the technology. It is an application that presents the program for the event in some university. Primarily I thought to make it for a single university but to be more generic I decided to make it customizable. Now data is supplied to the application from a service and thus it can be easily changed.

The PosterDemo App

It consists of two parts - one is a simple web service with only one method - GetPosters() that returns all available posters. This serves as the backend of the application and allows demonstrating the seamless integration with web services. The backend returns a list of objects from type Poster. Here all backend objects serve only to hold and transfer data. For this demo application the objects that are returned are dummy ones – not taken from a database – so that things are simpler. So the Poster class has the following properties:

public string Title { get; set; }
public string UniversityLogo { get; set; }
public DateTime EventDate { get; set; }
public DateTime EventEndTime { get; set; }
public bool IsEnabled { get; set; }
public List<ProgramItem> ProgramItems { get; set; }

Each one of them is self explanatory and I will skip explaining what they are for. The last property is a collection of type ProgramItem. It holds all items (meaning lectures) that are in the particular poster instance. Here are the properties of that class too:

public string Title { get; set; }
public string LecturerDetails { get; set; }
public DateTime StartTime { get; set; }
public string Color { get; set; }
public string LecturerImage { get; set; }
public string LectureDescription { get; set; }

To integrate a silverlight application with a web service is as easy as it is for standard .NET application (web or windows). For the alpha version that is available now the only different thing that you must do is put the ScriptService attribute to the web service so that the data is transferred in JSON instead of SOAP format. Eventually for version 1.1 the SOAP will also be supported for Silverlight. The application looks like this:

On the top of it there is a dropdown which lists all enabled posters for viewing. When you change the dropdown – details on it are changed. Everything on it (except the main image and the text "ПРОГРАМА") is dynamic. Key features that I wanted to show is simple animation creation with Blend as well as other – more "developer friendly" stuff.

One is LINQ support. The service as you saw does filter posters in any way. To filter only the enabled posters I've used a simple LINQ query:

private void FillInPosterNames()
{
var posterNames = from p in posters
where p.IsEnabled == true
select p.Title;
HtmlElement posterElements = HtmlPage.Document.GetElementByID("posters");
foreach (string title in posterNames)
{
HtmlElement option = HtmlPage.Document.CreateElement("option");
option.SetProperty("innerHTML", title);
posterElements.AppendChild(option);
}
}

After filtering, we take the dropdown html DOM element, create an option for each poster title and add it to the dropdown. Here also there is the way you can manipulate Html elements form C# code ;)

For the list of program items I have created a custom control ProgramList and for each item a control ProgramListElement. Each one of them has quite a number of specifics which I will start explaining in other posts.

Download it!

The whole sample can be downloaded from here. To be able to open and start it you will need Silverlight 1.1 Alpha Refresh and Visual Studio 2008 Beta 2 with Silverlight tools for Visual Studio 2008 Beta 2. Unfortunately, yesterday Visual Studio 2008 was officially released without Silverlight Tools for VS 2008. In a couple of weeks the tools are expected so then I'll be able to post an updated version.

What next …

In next few days I'll take care to explain more details on the demo that will uncover tricky parts while working with Silverlight.