Click to Rate and Give Feedback
MSDN
MSDN Library

  Switch on low bandwidth view
How to: Build a Service for Silverlight Clients

Silverlight applications frequently need to access some data or functionality on the back-end server. For example, if you are writing a customer management application, the server may contain a database of customers that your Silverlight application will need to retrieve. If you are writing a game, the server may contain high-score information that your Silverlight application will need to update. In many cases, the best way to make functionality on the server available to Silverlight is to create a Web service, as described in this topic.

This topic describes how to add a Silverlight-enabled service to an existing server-side project. Typically, this will be the default Web application that is included by Visual Studio 2008 in your Silverlight solution. For example, if you are building an application called SilverlightApplication1, you will see a Web application called SilverlightApplication1_Web in Solution Explorer. But you can add a service to any other Web site, Web application, or even create an entirely new WCF service application project.

This procedure assumes that you are using Visual Studio 2008 for your development environment. For convenience, the first few steps describe how to generate the default Web application when creating a Silverlight solution. If you are using another project to host the service, you can skip these steps.

For a procedure that outlines how to access the service created in this topic from a Silverlight client, see How to: Access a Service from Silverlight using Visual Studio.

To add a Silverlight-enabled WCF service to an existing Web site or Web application

  1. From the File menu, select New, then Project, then Silverlight from the Project types, and then select Silverlight Application from the Visual Studio installed templates. Accept the default Name SilverlightApplicaton1 and click OK.

  2. In the Add Silverlight Application wizard that pops up, accept the three defaults. These are Add a new Web to the solution for hosting the control, the Web Application Project as the Project Type, and the Name SilverlightApplication1Web for the application. Then select OK.

  3. To add a Silverlight-enabled Windows Communication Foundation (WCF) service to the default Web application generated, right-click the SilverlightApplication1Web project in the Solution Explorer and select Add, then New Item…. Select Silverlight from the Categories, then select the Silverlight-enabled WCF Service from the Visual Studio installed templates, change the name of the service to CustomerService.svc in the Name box, and add click Add.

  4. To define and implement the CustomerService contract, replace the GetData method in the CustomerService class (already defined in the CustomerService.svc.cs file) with the operations you want the service to support. In this example, we will add two operations that will allow the Silverlight client to retrieve the number of users in a database, and to retrieve each individual user’s information.

    [OperationContract]
    public int CountUsers()
    {
        return 2;
    }
    [OperationContract]
    public User GetUser(int id)
    {
      if (id == 1)
      {
      return new User() { IsMember = true, Name = "Paul", Age = 24};
      }
      else
      {
      return new User() { IsMember = false, Name = "John", Age = 64};
      }
    }
    
    

    Do not forget to apply the OperationContractAttribute attribute to each operation. The service you are defining is based on the Windows Communication Foundation (WCF) technology – a powerful platform for building distributed applications. This topic only shows basic WCF features – for more information, refer to the WCF documentation, and specifically the topic Designing and Implementing Services.

  5. Types that are used in services need to follow certain rules. The simplest way to create a valid type is to make sure it is public, has public members and a public constructor that does not require any parameters. For example, the User type in the GetUser operation may be implemented as follows.

    public class User
    {
    
        public bool IsMember { get; set; }
    
        public string Name { get; set; }
    
        public int Age { get; set; }
    }
    

    You can use the DataContractAttribute and DataMemberAttribute , along with some other mechanisms, to customize how data is transferred between the service and the client. For full details on the types that can be used in services, see Types Supported by the Data Contract Serializer.

  6. (Optional) When using services to access databases, it is convenient to use types automatically generated from a database using the ADO.NET Entity Framework. These generated types are fully compatible with services intended for Silverlight use. It is also frequently convenient to use LINQ in service implementation. For example, assuming you have a database with a Users table and have generated a MyDatabaseEntities entity model from your database, an operation to find users by name could be implemented as follows.

    [OperationContract]
    public IEnumerable<Users> GetUsersByName(string nameToSearch)
    {
        MyDatabaseEntities e = new MyDatabaseEntities();
        return (from user in e.Users where user.Name.Contains(nameToSearch) select user);
    }
    
  7. To test the service implementation in Visual Studio, select the CustomerService.svc file in Solution Explorer, right-click and select View in Browser (or press Ctrl + F5) to display a test page for the service. You should see the CustomerService Service test page, which confirms the service is available.

Additional Considerations when Creating Services

There are certain restrictions on the types of services that Silverlight can access. If you are creating your WCF service without using the Silverlight-enabled WCF Service template, you must make sure that the WCF service is configured with the BasicHttpBinding for it to be supported. Note that other WCF bindings are not available as they require features not supported by the Silverlight client. WSHttpBinding for example requires sessions and transactions, which are not supported. For more information about Silverlight 2 restrictions when accessing SOAP services, including ones not created using WCF or even .NET, see Accessing SOAP Services.

When creating a service anywhere other than on the Web site that hosts your Silverlight application, cross-domain issues can arise. Cross-domain calls between Silverlight applications and services present a security vulnerability and must be specifically enabled by an appropriate cross-domain policy. For procedures that describe how to implement such a policy, see Making a Service Available Across Domain Boundaries.

This situation frequently arises when debugging several separate Web application projects in Visual Studio, because a different port number is assigned to each web application. For example, your Silverlight application may be hosted on http://localhost:1111, and your service may be hosted on http://localhost:2222. Even though the machine name is the same (localhost), the difference in port numbers is sufficient to create a cross-domain situation that you must deal with as described in the topic mentioned and linked to above.

When you use the Silverlight-enabled WCF Service template, your Web.config file is automatically modified to turn on ASP.NET Compatibility Mode, to make it easier to integrate your service-backed Silverlight application with the ASP.NET security model. It would enable you, for example, to restrict access to certain services to authenticated users, or only to users in a certain Role. Any WCF services present in the same project must be configured to allow the ASP.NET compatibility mode by using the AspNetCompatibilityRequirements attribute. This is done automatically for any services added using the Silverlight-enabled WCF Service template, but you must do this manually for any other WCF services you may have in the same project. An alternative to this is to turn off ASP.NET Compatibility Mode in Web.config if none of your services require it.

Example

The following samples summarize the code in the CustomerService.svc.cs file after completing the preceding procedure.

//CustomerService.svc.cs
using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace SilverlightApplication1Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CustomerService
    {
        [OperationContract]
        public int CountUsers()
        {
            return 2;
        }
        [OperationContract]
        public User GetUser(int id)
        {
            if (id == 1)
            {
                return new User() { IsMember = true, Name = "Paul", Age = 24 };
            }
            else
            {
                return new User() { IsMember = false, Name = "John", Age = 64 };
            }
        }
    }

    [DataContract]
    public class User
    {
        [DataMember]
        public bool IsMember { get; set; }

        [DataMember]
        public string Name { get; set; }

        [DataMember]
        public int Age { get; set; }
    }

}

See Also

Change Date History Reason

11/4/2008

Added comments explaining why only the BasicHttpBinding is supported for accessing added a WCF service.

Responding to customer question: “Why not support the WSHttpBinding too?”

Send comments about this topic to Microsoft.

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker