Skip to main content

A Beginner's Guide to Silverlight with PHP Article

By Jordan Knight



Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

In recent years, web developers have been moving increasingly towardsthe development of so-called RIAs, or Rich Internet Applications. These canbe built using any of a number of different technologies, but what they havein common is their goal of recreating a desktop application experienceinside a web browser. Microsoft entered the RIA space in late 2007 withSilverlight. For the uninitiated, Silverlight is a client-side technologypowered by the .NET Framework. This means that .NET developers can utilizetheir existing skillset to create Silverlight-based applications with arelatively easy learning curve. Silverlight runs on Windows and Mac in mostmodern browsers.It’s worth noting that Silverlight is a client-side technology, whichmeans it’s not tied to any particular server-side platform. It can be hostedregardless of whether your site is built in plain HTML, ASP.NET, or evenPHP. You might think that it would be more difficult to use Silverlight in aPHP application, but it’s actually quite simple; you can leverage JSON, XML,or any number of communication technologies to pass data from Silverlight tothe PHP backend. However, in this article, we’re choosing to go with a SOAPWeb Service. I’ll first show you how to start developing with Silverlight,then cover how you set up the web service in PHP, and finally demonstratehow to access the service from your Silverlight application.To follow along, you’ll need Visual Studio, Silverlight Tools, and PHP5. I’ll be showing you how to install Visual Studio with the SilverlightTools, but I’m going to assume you already have a web server set up withPHP. Otherwise, it’s very simple to set up using Microsoft’s Web PlatformInstaller, and you can find instructions for doing that in a previousSitePoint article. You should be familiar with object-orientedprogramming concepts, though it’s unnecessary to know any C# or VB.NET, asI’ll be showing you all the required code.To follow along with the samples in this article, you can downloadanarchive of all the source files. Within that download, theSampleApplication directory contains all the source forthe Visual Studio project, and the silverlightdirectory contains the finished PHP site including the compiled Silverlightapplication.When you’re finished with the tutorial, be sure to head over and testyour learnings in our ArticleQuiz, sponsored by Microsoft.

Starting Out with Silverlight

Silverlight applications are built using Visual Studio for the code,and the Expression Studio suite of tools for the user interface. ShaneMorris has a greatarticle here detailing the use of Expression Studio to design aSilverlight UI. In this article, we’ll focus instead on the developmentside.Preparing to build Silverlight applications is quite simple. First,you’ll need Visual Studio. Microsoft has a free Express version of thissoftware available, so head over to the Silverlightwebsite and download the Web Platform Installer. It will guide youto download Visual Web Developer and the Silverlight tools. If you doalready have Visual Studio, you can download the Silverlight toolsdirectly.

warning: Versions

For the purpose of this tutorial, the sample application was builtand tested using Visual Studio 2008 and the Silverlight 3 Tools.However, it should work fine with Visual Studio 2010 and Silverlight 4if you’re using the latest and greatest.

Once you have the Silverlight tools installed, there will be newoptions available in Visual Studio to create Silverlight applications.Start by selecting New Project from the File menu. Browse toSilverlight, and selectSilverlight Application. Enter a name and alocation to save your new project, and clickOK.

note: C# or VB.NET?

The Silverlight option is available both in the Visual C# and inthe VB.NET categories in the New Project screen. Which one you choosewill depend on which language you’re more comfortable programming with.For the examples in this tutorial, I’ll be working with C# code, so ifyou want to follow along that’s what you should select.

Figure 1. Creating a new Silverlight application

Creating a new Silverlight application

The next screen allows you to choose how you want your applicationto be hosted. For the purposes of this tutorial, just leave the defaultsettings and click OK.You will be presented with two projects in the Visual StudioSolution Explorer—one for the Silverlight project and one for an ASP.NETsite. Even though we’re planning to use PHP for the server-side code,we’ll be able to take some generated code from the ASP.NET site to makeour job easier.

Figure 2. The two new projects shown in the Solution Explorer

The two new projects shown in the Solution Explorer

Creating a Simple Silverlight Application

Before we jump in and integrate Silverlight with PHP, let’s create abasic Silverlight application to become familiar way it works. Start byopening MainPage.xaml in your Silverlightapplication. It’s an XAML file, which stands for eXtensible ApplicationMarkup Language, and is how the Silverlight (and WPF) user interface isbuilt. It’s quite similar to HTML, so you’ll be able to pick it upquickly.Let’s start simple by adding a text box and a button to the screen.With your cursor placed inside the <Grid> element, enter the following XAML:<StackPanel></StackPanel>. A StackPanel is a kind of layout control inSilverlight. It will force the controls you enter inside it to stackeither vertically or horizontally.Next, we’ll add a TextBox and aButton inside the StackPanel, likethis:

Example 1. MainPage.xaml (excerpt)

<Grid x:Name="LayoutRoot">  <StackPanel>    <TextBox Text="Joe Citizen" x:Name="txtName"/>    <Button Content="Click Me!"/>  </StackPanel></Grid>

Pressing F5 will run the application. You shouldsee a button and text box appear on the screen.

Figure 3. Our sample application viewed in a browser

Our sample application viewed in a browser

Clicking the button will achieve nothing at this stage. Let’s fixthat.Stop the application by closing the browser. Back in Visual Studio,locate the button in the XAML file and add an attribute called Click. Typing Click="" willcause Visual Studio to prompt you with <New EventHandler>. Select this option by pressingEnter. You can then right-click the text that was addedand select Navigate to Event Handler. This willtake you into the “code behind.” The code behind is the area that’s usedto enter C# (or VB.NET) code—the guts of the application is written incode behind.Let’s make the application show the text from the text box in amessage dialog.First, add using System.Windows.Browser; to thearea at the top of the page where you see a list ofusing statements:

Learn PHP for free!

Make the leap into server-side programming with a comprehensive cover of PHP & MySQL.

Normally RRP $11.95 Yours absolutely free

Example 2. MainPage.xaml.cs (excerpt)

using System.Windows.Shapes;using System.Windows.Browser;namespace PHPTutorialFirst{

This code imports a namespace. Namespaces allow the very large .NETframework class library to be split into smaller, manageable parts. Thisparticular namespace includes the alert functionality we’re after.Next, enter the following code inside theButton_Click function to show the popup:

Example 3. MainPage.xaml.cs (excerpt)

private void Button_Click(object sender, RoutedEventArgs e){  HtmlPage.Window.Alert(txtName.Text);}

This will show the contents of the text box on the screen. You mayremember that back in the XAML file you added an attribute to the TextBlock called x:Name. This name is how we reference theelement in our code: txtName.Now that you’ve written a basic application, you’re ready to gofurther and start consuming a web service. But before we do we’ll look athow to insert our Silverlight application into our HTML files or PHPtemplates.

Including the Silverlight Application in a Page

The first step to integrating Silverlight with your PHP applicationis to include the application itself in the pages generated by PHP. Thereare a couple of ways that Silverlight can be instantiated. The firstoption is to dynamically add new Silverlight applications usingJavaScript. I won’t go into detail here, but you can find out moreinformation in the MSDN Silverlight.jsreference document.The second option is to use the <object> HTML tag. The <object> tag is a way to tell a browser to loadan external object like an image or a plugin. Most plugins like Flash andSilverlight now use this tag.To help you out, Visual Studio makes a sample page for you when youcreate a new Silverlight project. You can find it in the web project youcreated earlier called [applicationname]TestPage.html. So, for our sample application, the file inquestion is SampleApplicationTestPage.html.Create a new directory in your server’s web root for your newapplication (in our examples we’ll be calling itsilverlight), and make a newindex.php page inside it. Copy the contents of thetest page that Visual Studio created into that file, and copySilverlight.js from the web project to your newdirectory.Now you have a PHP file that includes an <object> tag pointing to a Silverlightapplication, and an accompanying JavaScript file with some necessaryutilities. But, if you examine the object element, you’ll see that its src attribute is ClientBin/SampleApplication.xap. Looking backat the web project Visual Studio created for you, you’ll see that it doesindeed contain a ClientBin directory with aSampleApplication.xap file.Silverlight applications are compiled into what is known as a XAP(pronounced “zap”) package, which is what’s then included in the page withthe help of the <object> tag. So youjust need to copy the ClientBin directory into yourapplication’s directory, and your index.php page should now correctlydisplay your Silverlight application. You can rename or move the XAP file;you just need to remember to adjust the object’s src accordingly. Remember that if you modifyyour Silverlight application, you’ll need to copy theClientBin directory file again. During development,it’s probably easier to run your Silverlight applications from VisualStudio, and copy them over to the PHP directory when you’re done.Your silverlight directory should now look asshown in Figure 4, “The contents of the silverlightdirectory”, with theindex.php file containing the contents of thegenerated SampleApplicationTestPage.html from yourVisual Studio web project.

Figure 4. The contents of the silverlightdirectory

The contents of the silverlight directory

Jordan is a Senior Consultant at Readify, Silverlight MVP and has been developing web applications on the .NET platform for the last eight years. He especially enjoys client side development like JavaScript and Silverlight. Jordan runs the SDDN Australia's only dedicated Silverlight user group.

New books out now!

Learn valuable skills with a practical introduction to Python programming!

Give yourself more options and write higher quality CSS with CSS Optimization Basics.