Tags: | Categories: Blog Posted by admin on 3/9/2009 5:57 PM | Comments (5)

Posted on dotenetslackers on Published: 19 Nov 2007

Al Pascual shows how to create a Silverlight 1.1 web application that leverages Ajax.

Introduction

The job of a software engineer shouldn't end on the road home from a long day at the office. The hardest job has just started. Every year there's newly emerging technology that we need to learn if we want to be the one to get the new project that sooner or later our company will want to secure. There is no need to learn something new every day. However if you are, for example, a .NET programmer, it's very important to keep abreast of new versions and improvements each year. Adopting these in the early stages will allow you to be prepared when your company decides to upgrade. Being flexible allows you to keep up in this fast-moving market.

By now you should be very familiar with ASP.NET 2.0 and have already moved from the basic 1.1. It does not matter if you are using C# or VB.NET, but it is a great idea to learn both languages. They both compile to the IL, and with both languages you can achieve the same results. Of course, if you happen to come from VB you will be more familiar with VB.NET; and if your background is in from the areas of C/C++/Java, C# will naturally be your language of choice.

Thanks to the Internet, teaching yourself has become easier and cheaper. You can find videos, blogs, articles, and even the tools necessary to use those new technologies for free. Microsoft always releases the new tools for free when they are still in Beta. If your excuse is that you don't install Beta software, get ready to find yourself a brand new excuse. I am not telling you to use those tools for production software; I'm saying that you should install them for self-teaching purposes. To do so, it's always a good idea to have your own computer at home, rather than simply relying on your machine at the office.

What Are Silverlight and Ajax?

Silverlight is the answer that is emerging from Microsoft to compete against Macromedia Flash and Flex. It's a browser plug-in that renders graphics, just as Flash and Flex are client-side technologies that render graphics on the browser using a plug-in. The object is downloaded and runs on the client computer. Many people believe that it's part of the ASP.NET platform. I will show in this article that both Silverlight and Ajax work together to accomplish client-side and serve-side communication. However, it is important to understand that Silverlight is not rendered from the server like ASP.NET.

ASP.NET uses postbacks to connect to the server. Silverlight 1.0 and 1.1 cannot use postbacks; instead, they use Microsoft ASP.NET AJAX or the asynchronous download class to talk to the server. Since Silverlight can call any AJAX, you do not have to use Microsoft ASP.NET AJAX 1.0. You could put together some code to write another AJAX. You could also use the class download with Silverlight to make asynchronous calls. I found it easier to create an AJAX service using the template provided by Microsoft.

What tools and setup do you need?

What you need to get started working with Silverlight is all provided, right now, for free by Microsoft. All the required tools are still in Beta, and after Microsoft releases those tools all of the Beta products will expire. By then you should have learned the new technology, and maybe a few things will even be added or changed by the time of the release version. Either way, the practice and time spent will have paid off already.

You have two options in using Silverlight as of right now - either use Silverlight 1.0 or Silverlight 1.1. "What's the difference?", you might ask. First of all, Silverlight 1.0 works using Visual Studio 2005. You'll also write the control using Javascript. However, with Silverlight 1.1 you are going to need to use Visual Studio 2008 Beta version and C# to write the controls. In this article I will show you how to write a Silverlight 1.1 control. In a future article I intend to show you how to use Silverlight 1.0. I personally believe that you should always utilize the latest version. In this case, Microsoft made the right decision with version 1.1 when adding C# rather than Javascript. If you think about it, that was an enormous change, since Silverlight is a completely client-sided application, and C# programmers are accustomed to using libraries for server-side controls.

When using Silverlight 1.1 with C# you will find that Microsoft rewrote all the libraries that have server-side classes and namespaces. So, let's start setting up the computer to write a Silverlight 1.1 control.

Download the Silverlight plug-in for the browser for Windows. Make sure to restart the browser after installation and test it by going to the Silverlight website and testing a few online controls.

Download the Visual Studio 2008 Beta version. VS2008 works side by side with VS2005. You should also install the Professional or Team version. As I said earlier, it's a free download from Microsoft; you may as well take advantage of it to learn the most comprehensive version possible. VS2008 will not affect your ASP.NET AJAX 1.0 installation either. Do not install the Express version, since it does not work with Silverlight.

Download the Alpha tools for Silverlight and the Visual Studio template. Both are needed to start a project with Silverlight 1.0.

Download Expression Blend. Right now, Expression Blend is still in Beta, but is required to create controls and edit existing controls. Expression Blend edits only files with the .xaml extension. You can edit the file manually by editing the XML; however this can be a very difficult task that Expression Blend already does quite well. What you will in fact be missing so far - as tools are concerned - are the standard controls that you could normally expect to find in an editor. You will need to create this by hand, using rectangles, canvas, textboxes, dropdown boxes, etc… It's actually easier to add those controls to the page manually as opposed to adding them into the Silverlight control. If you are used to Macromedia Flash you will find this new tool somewhat familiar; however if you are accustomed to VS2005/VS2008 you may feel lost for awhile. Make sure you install this tool after VS2008 to enable the editing of XAML files within VS2008.

You can download the documentation with examples or you can use the online website for that.

Creating the Silverlight Control.

I highly recommend that before you even attempt to begin creating a Silverlight control, you download a few samples and play around with them by making a few modifications of your own. You can find many examples on the Silverlight website as well as other people's blogs. Scott Guthrie keeps a list of Silverlight controls and each month he adds more links to various useful resources and controls.

The best idea at this point is to start Visual Studio 2008 and then open the template called Create Silverlight Control. In the project you'll find a XAML file with an associated xaml.cs file and a default.html page. Notice that you cannot find any .aspx page and you cannot add any at this time. This project will only allow you to edit the control with Expression Blend and render it on the HTML page.

By right clicking on the .xaml file, you will display the menu. You will find a menu item entitled Open with Expression Blend..., which lets you edit the control if you have already installed the tool.

Now you will create a "hello world" program in Expression Blend. You will discover that it is actually quite simple. After compiling and running the program, you will find the control on the browser. What I am attempting to demonstrate is the method used to create a control that uses server-side code with Microsoft ASP.NET AJAX 1.0. To test this, you should add an image in Expression Blend and then add the code on the picture.xaml.cs file in order to handle the picture.

Figure 1: Expression Blend Logo

fig00.jpg

Note: If you've already used VS2008, you can skip this section. Otherwise, please continue reading to get up to speed on this new and improved editor. First, you'll find that you have a new tab to split the designer vew. Previously, in VS2005 you had only Design and HTML. Now you'll be getting the best of both worlds. Splitting the view will allow you to see the screen split into two separate sections - design and HTML. When creating the project, you'll find a dropdown that allows you to use different versions of the framework. You have the option to select from versions 2.0, 3.0, or 3.5. If you cannot find the correct template, then change the dropdown, since there might be only one of the versions available. Other than that, VS2008 looks much like VS2005. Although, in my opinion, there are still a few bugs needing to be fixed, the program is still generally useful.

Attaching AJAX to the Control

There are two ways to attach AJAX to the control. First, you can use the download class to download an image from the internet.

  1. var downloader = new Downloader();  
  2.             downloader.Completed += new EventHandler(downloader_Completed);  
  3.             downloader.DownloadFailed += new ErrorEventHandler(downloader_DownloadFailed);  
  4.             downloader.Open("GET", photo);  
  5.             downloader.Send();  

var downloader = new Downloader(); downloader.Completed += new EventHandler(downloader_Completed); downloader.DownloadFailed += new ErrorEventHandler(downloader_DownloadFailed); downloader.Open("GET", photo); downloader.Send();

There are 2 events you will need to handle - one when the picture finishes downloading and another if the picture fails to download. If completed properly, you can attach it to the picture on your Silverlight control.

  1. private void downloader_Completed(object sender, EventArgs e)  
  2. {  
  3.      var downloader = sender as Downloader;  
  4.      _image.Source = downloader.Uri;  
  5. }  

private void downloader_Completed(object sender, EventArgs e) { var downloader = sender as Downloader; _image.Source = downloader.Uri; }

In case the download fails, you can always change some text on the control. This download call can also be used to download more than just images. You can return other data and handle it if you know what data you will receive. That is what makes the Downloader class very limited and an AJAX Web service should be used to accomplish this.

Creating a Proxy Website or the AJAX Web Service

This is, in my opinion, the best way to have communication between the client (Silverlight 1.1) and the server running ASP.NET 3.5. First, open your VS2008 and choose Create a new Website. Then, select framework 3.5 from the dropdown menu as well as the ASP.NET Futures AJAX Web Site. Download the template ASP.NET AJAX Futures Web Service from the Microsoft website Silverlight.net GetStarted. You will need to download this template if you did not do it earlier while setting up the environment (or if you do not see it when creating a new website.)

Figure 2: Website template for Visual Studio 2008

fig01.jpg

VS2008 will create an ASP.NET 3.5 website. Now, add a Web Service (.asmx file).

Figure 3: Add New Item menu in VS2008

fig02.jpg

Open the WebService.cs file and, on top, uncomment the code below to allow AJAX to use the web service:

  1. // To allow this Web Service to be called from script, using ASP.NET AJAX, 
  2. uncomment the following line.   
  3. // [System.Web.Script.Services.ScriptService]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService]

On the default page you'll find the script manager. Add the service you want to use between the Script Manager open and closing tags.

  1. <asp:ScriptManager ID="ScriptManager1" runat="server">
  2. <Services>
  3. <asp:ServiceReference Path="webservice.asmx" />
  4. </Services>
  5. </asp:ScriptManager>

<asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="webservice.asmx" /> </Services> </asp:ScriptManager>

Now you need to set up the default page and add the Silverlight control. Any page that has a Silverlight control needs to call this JavaScript method:

  1. <script type="text/javascript">  
  2.         createSilverlight();  
  3. </script>  

<script type="text/javascript"> createSilverlight(); </script>

Now you can drag and drop the Silverlight control you created. By right clicking on the project and selecting Add Silverlight link...your project will be completed and ready to start using server-side calls. However, the way to avoid problems is to copy the .xaml and .xaml.cs files into that project and use it. If you do this, you will not have to link to another project; and the control together with the Web Service will be in the same project.

Putting It All Together

After you have successfully accomplished all of the above steps, this should be the simplest part. On your WebService.cs file, you want to add a method for each server-side functionality.

  1. [WebMethod]  
  2. public string HelloWorld()  
  3. {  
  4. return "Hello World at " + DateTime.Now.ToString();  
  5. }  

[WebMethod] public string HelloWorld() { return "Hello World at " + DateTime.Now.ToString(); }

Silverlight can now access methods such as calling a web service. The only difference is that with Downloader you need to specify two methods for callbacks - one for success and the other in case of failure.

Summary

This straightforward article will allow you to create your first Silverlight project. At first it may sound as if there are too many steps necessary to generate a simple solution. But I am confident that once you have finished creating your first project, each subsequent project will be painless for you. There are numerous ways to begin a project, and if you do not need server-side code, you will not need to use the template previously discussed.

There are many resources available to you on the web. You can download samples, but make sure they are Silverlight 1.1 rather than version 1.0. You'll also find only client-side projects and projects with AJAX web services. Remember - I highly recommend that you always attempt to utilize the latest version available.

Posted from http://weblogs.asp.net/albertpascual

blog comments powered by Disqus