devxlogo

SharePoint Applied: SharePoint 2007 with WCF and Silverlight

SharePoint Applied: SharePoint 2007 with WCF and Silverlight

ilverlight 2 just went RTM. This product is unique because for the first time in the Microsoft world, you have .NET running cross platform, in a secure way, and without all the deployment hassles. It has the ability to bring rich UI, right to the browser?much like Flash, but with more capabilities and a .NET heart.

So, what does this mean to you as a SharePoint developer? Well, as I elucidated in my previous article, developing rich UIs in SharePoint 2007 isn’t exactly my idea of a good time! In fact, it is a bit like a three-year old playing drums on your head all night long while his seven-year old sister is sticking chewing gum in your hair as you are trying to sleep because you have an early morning 7:00 AM morning meeting in a recessionary economy. Take heart! The thin .NET 3.5 development model makes it all easier.

In this article, I will illustrate an example that builds a Silverlight front-end to SharePoint functionality. The Silverlight control will work within the SharePoint context, and will thus allow you to access the SharePoint object model from the restricted Silverlight CLR. Throughout this article, I will focus on illustrating the specific development steps I follow to make my development of Rich UIs within SharePoint a whole lot easier. Let’s begin with defining the problem first.

Problem Definition

I find the calendar list in SharePoint quite useful. In this article, I will build a Silverlight UI that shows me appointments for today while remaining under the current user’s context. These appointments will be stored in the calendar list and will be rendered in a rich Silverlight UI. At the very onset, this seems to tell me that the Silverlight UI running inside SharePoint would need to have full access to the SharePoint context. How in the world would I achieve that in the restricted Silverlight CLR?

In order to achieve this, I will need to write:

  1. A Silverlight .xap file. I will have to work with Visual Studio 2008 SP1 (with Silverlight tools installed), and Expression Blend 2 SP1 to craft this UI.
  2. A WCF service. This service will work in-context, retrieving the appointments under the security context of the currently logged-in user. The Silverlight UI will consume the service using basicHttpBinding.
  3. A contract. This contract specifies how the Silverlight application will talk to the WCF service. This is the same as the WCF contract.

The first step is to define the WCF contract, shown below:

   [ServiceContract]   public interface IAppointments   {      [OperationContract]      List GetAppointments();   }

In the preceding code, BO.Appointment is a custom business object defined as follows:

   [DataContract]   public class Appointment   {      [DataMember]      public DateTime AppointmentTime {          get; set; }      [DataMember]      public string Title { get; set; }   }

With the contract defined, you can write up the pieces around the contract.

Editor’s Note: This article was first published in the March/April 2009 issue of CoDe Magazine, and is reprinted here by permission.

Writing the Silverlight Application

The nice thing about the thin .NET 3.5 development model is that as long as you have a contract ironed out, you can take SharePoint completely out of the picture, along with:

  • The virtual machine
  • The process of attaching to W3WP.exe
  • That pesky GAC DLL version whose breakpoint never seems to get hit
?
Figure 1. The Silverlight Project Structure: The figure shows the sample files and projects in the Visual Studio Solution Explorer pane.

I’ll simply stub out the project on my Vista development machine as shown in Figure 1.

I created the project shown in Figure 1 using the Silverlight tools for Visual Studio 2008 SP1, and a WCF service library that I added to the project. As you can see, the MyServices class library is a WCF service library, which hosts a service in Appointments.cs that implements the contract defined earlier. Because you’re not yet running inside SharePoint, you can simply stub out fake appointments as shown below:

   public List GetAppointments()   {      List toReturnAppts =          new List();      toReturnAppts.Add(new BO.Appointment {          Title = "First Appointment",          AppointmentTime = DateTime.Now });      toReturnAppts.Add(new BO.Appointment {          Title = "Second Appointment",          AppointmentTime = DateTime.Now });      toReturnAppts.Add(new BO.Appointment {          Title = "Third Appointment",          AppointmentTime = DateTime.Now });      return toReturnAppts;   }

The preceding code is terse because it uses a concept called “Object and Collection Initializers” introduced with C# 3.0.

Next, I’ll start crafting the UI of my Silverlight application. I need a UI to which I can bind the results of the WCF service call. This snippet below shows how to implement it:

      

The “ShowTime” static resource is a DataTemplate defined as a resource:

                              

For the eagle-eyed among you, the ContentControl that points to a StaticResource is another application-level resource?it’s just a ControlTemplate that takes a DateTime and renders a good looking Analog Clock. You can download the source code for the clock ControlTemplate.

That’s it, the UI is done (and it’s really that easy). Now, you need to bring it to life with some data, so you can see it running and in action.

?
Figure 2. The Silverlight Application: Here’s the Silverlight application running in Safari.

The Silverlight UI will get its data from the WCF service using basicHttpBinding. To do that, you need to add a WCF service reference to the Silverlight application.

With the reference added, you can use the WCF service proxy to get Appointments data, and bind the appointments to the Silverlight UI (see Listing 1).

An important thing to note in Listing 1 is that you should always call WCF services from Silverlight UIs asynchronously. Failing to do so could lock up the browser?and your end users won’t be happy about that!

When you compile and run the above application above, you’ll see a UI similar to Figure 2.

You may have noticed that I haven’t even touched SharePoint yet. Technically, this entire application could have been developed by a non-SharePoint developer. But at this point, with the UI and WCF service skeleton done, you can work SharePoint into the picture.

Enter SharePoint: Authoring the WCF Service

Earlier, you saw some stub code that substituted for the WCF service?creating mock objects suitable for testing the UI. To make this work inside SharePoint, you need only two simple steps:

  1. You need to configure SharePoint to support WCF, which you can achieve by activating the feature you will find at www.codeplex.com/SPWCFSupport.
  2. You’ll have to edit the WCF service code to extract actual appointments under the security context of the currently logged in user. In other words, you’ll need to replace the dummy WCF service you saw earlier with a real WCF service that extracts appointments, obeying the currently logged in user’s security context.

Because the first step is self-explanatory if you follow the link, I’ll focus on the second in this article. The key phrase here is “obeying the currently logged in user’s security context.”

Now, you could run the WCF service completely out of SharePoint, and thus on a different domain than your Silverlight application. But in that case you would have to set a cross-domain policy that allowed cross-domain calls to work. If you host the WCF service within SharePoint on the same domain, you don’t need to worry about that.

Author’s Note: If you’re interested in learning more about cross-domain policy, you should watch this video.

WCF, by default, works outside of ASP.NET, and thus outside of SharePoint. That’s reasonable, because WCF’s scope is much larger than just ASP.NET. But WCF does have an ASP.NET compatibility mode, which allows a WCF service to get a reference to HttpContext.Current, and SPContext.Current. You can read the background and implementation details here.

So let’s get this straight: A beautiful Silverlight UI running on MacOS/Safari can now talk to a WCF service that fully participates in the SharePoint object model, uses the current SharePoint context, and the current security context?all with no deployment issues, either! That makes me more excited than a five-year old in a candy store with no parents around to police. The possibilities are clearly immense.

With the current context in hand and a little SPQuery magic, I modified the WCF service implementation code as shown below:

   [AspNetCompatibilityRequirements(RequirementsMode =       AspNetCompatibilityRequirementsMode.Required)]   public class Appointments : IAppointments   {   #region IAppointments Members      public List GetAppointments()      {         List toReturnAppts =             new List();         SPWeb web = SPContext.Current.Site.OpenWeb();         SPList appointmentsList = web.Lists["Appointments"];         SPListItemCollection items = appointmentsList.GetItems(            new SPQuery(         appointmentsList.Views["Current Events"]));         IEnumerable todaysAppts =            from item in items.OfType()            select new BO.Appointment            {               Title = item[3].ToString(),               AppointmentTime = Convert.ToDateTime(item["Start Time"])            };         toReturnAppts.AddRange(todaysAppts);         return toReturnAppts;      }   #endregion   }

I then updated my endpoint address to the relevant SharePoint address and rebuilt the .xap file, which I will then place in my SharePoint .wsp solution package so I can deploy it along with the other files.

Deploying Everything in SharePoint

Let me make this section really simple. You should deploy everything as a solution, and the easiest way to create solutions is WSPBuilder. Here are the high-level portions to deploy:

?
Figure 3. Solution Structure: The figure shows the files in the deployable Silverlight + WCF solution.
  1. The WCF service deployed as a part of the solution as described here. Note that in this case the WCF Service will need to run under the ASP.NET compatibility mode.
  2. The same solution also deploys the .xap file in a document library using the tag in the relevant elements.xml. You could also deploy the .xap as a physical file if you wish.
  3. Finally, the same solution also deploys an application page, and creates a custom action menu item for it.

In short, the class library from which WSPBuilder creates a solution looks like Figure 3.

When you activate the feature, and browse to the application page, you’ll see a Silverlight application running in the browser, with full access to the SharePoint context, under my (the currently logged in user) security context, in a nice looking UI (see Figure 4).

?
Figure 4. Silverlight in SharePoint: Here’s the sample Silverlight application running inside SharePoint.

Although this example shows the Silverlight application running in a SharePoint application page, it could just as easily run inside a Web Part, or anything else.

And there you have it, folks. This article demonstrated how the thin .NET 3.5 development model simplifies SharePoint development, making the platform more appealing than ever. The bulk of this project was developed outside of SharePoint, and incrementally deployed to SharePoint as it was completed. This has the following significant advantages:

  1. A better development experience. I did most of the difficult development outside of the virtual machine that runs SharePoint on a Vista OS.
  2. Leverage talent. You have the ability to scale out and leverage different skill sets in your team, rather than finding one superhero who is an expert at Silverlight, SharePoint, WCF and more?and is available at a reasonable price.
  3. Modular code. The developed code is modular. The SOA-based architecture ensures that this application doesn’t affect any others.
  4. Supports good development practices.This model lets you follow solid development practices, such as effective source control and effective unit testing.
  5. Maintainable results. Finally, and perhaps most important, crafting a modular solution means your product requires less effort to write and is more maintainable. When was the last time you both these advantages together?

My next article raises the bar by demonstrating how the thin .NET 3.5 development model helps you author rich HTML UIs, using concepts such as AJAX. Of course, the underlying theme is still developer productivity and maintainable code, working within the SharePoint 2007 platform.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist