RIA Development Center
FeaturesTipsEventsVideosSilverlight GallerySilverlight Hosting Resources
Brad Abrams gives a brief overview of what Microsoft .NET RIA Services is and how it's going to make your life simpler. Read more
See more tips
Which platform do you use most often?
(Check one)
AIR
AJAX
Flash
JavaFX
Silverlight
Other

View Results
Get regular email alerts when we publish new features!
DevX RIA Development Update

More Newsletters
Leveraging Silverlight 2 with SQL Server and XML (cont'd)

Building a WCF Web Service
The mechanism we selected for saving customer designs into the SQL Server database was a WCF Web Service hosted on our web server. The model for building this WCF Service was another excellent tutorial by Jesse Liberty.

Following the recognized best practice, our Service Contract is contained in an Interface. The Operation Contracts include a method for saving design parameters, retrieving design information by UserID and by a design ID (AutoID).

 
[ServiceContract]
public interface ICustomerDesigns
{
    [OperationContract]
    List<CustomerWeddingImprintDesign> GetDesignsByUserId(string UserId);

    [OperationContract]
    int InsertNewCustomerWeddingImprintDesign
     (CustomerWeddingImprintDesign cstIDesign);

    [OperationContract]
    List<CustomerWeddingImprintDesign> GetDesignByAutoId(int AutoID);
}

Although the process of creating a WCF Web Service seems very daunting and complicated involving an enormous amount of code, much of it will be automatically generated for you by Visual Studio. One part, however, which you will have to write yourself is the implementation code for your Service Contract.

#region ICustomerDesigns Members


public List<CustomerWeddingImprintDesign> GetDesignsByUserId(string UserId)
{
    try
    {
        DBAccessDataContext dc = new DBAccessDataContext();
        var matchingDesigns = from CustomerWeddingImprintDesigns 
in dc.CustomerWeddingImprintDesigns
                              where CustomerWeddingImprint
                              Designs.UserID.Equals(UserId) 
                             select CustomerWeddingImprintDesigns;
        return matchingDesigns.ToList();
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
        return null;
    }
}

public List<CustomerWeddingImprintDesign> 
GetDesignByAutoId(int AutoID)
{
   DBAccessDataContext dc = new 
DBAccessDataContext();
    var matchingDesigns = from CustomerWeddingImprintDesigns 
in dc.CustomerWeddingImprintDesigns
                          where 
CustomerWeddingImprintDesigns.AutoID.Equals(AutoID)
                          select CustomerWeddingImprintDesigns;
    return matchingDesigns.ToList();
}

public int InsertNewCustomerWeddingImprintDesign
(CustomerWeddingImprintDesign custIDesign)
{
    try
    {
        DBAccessDataContext dc = new 
DBAccessDataContext(); 
        dc.CustomerWeddingImprintDesigns.InsertOnSubmit(custIDesign);                
        // Insert count of changes to be made to the database
        System.Data.Linq.ChangeSet changes = dc.GetChangeSet();
        dc.SubmitChanges();
        return changes.Inserts.Count;
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
        return 0;
    }
}


#endregion}

In this case the required implementation simply consists of LINQ queries to save and retrieve data to/from the database. Since .NET datatypes and SQL Server datatypes are not identical, it is critical when using LINQ to SQL that the datatypes you do use at each end of the conversation are compatible. Moreover, since Beta 2 now requires when calling the SetValue method that all parameters must be of the exact correct data type, (implicit conversions previously were permitted), care must also be taken to conform to this requirement.

When a Silverlight application is running on the same server as a WCF service, no Cross-Domain policy file is needed. However, if you wish to run or debug a locally running Silverlight application that references a remote WCF service, or if the Silverlight application is hosted on a server that has multiple base addresses, a Cross-Domain policy file is needed. The required format for Cross-Domain policy files changed between Beta 1 and Beta 2, so you will need to exercise special caution to select the correct one if you are copying any sample text from the Internet. For more information on Cross-Domain policy files read the section titled "Configuring a Cross-Domain Policy File (clientaccesspolicy.xml)" at www.wpflearningexperience.com.

Implementation Issues
Joe has put together an excellent blog article describing a number of implementation problems which we encountered while deploying this application at our web host. Since a detailed explanation of these issues is available elsewhere, we'll describe only those which relate to the code contained in this project.

One of the limitations of WCF Web Services hosted on IIS is that each service can have only a single base address. Unfortunately, under some hosting configurations multiple base addresses can exist, thereby confusing WCF. An example of multiple identities would be domain.com and www.domain.com. If, as is often the case, a modification of the hosting configuration is not an option, a relatively simple workaround can trick WCF into only seeing a single base address. This workaround involves creating a custom service factory and overriding the CreateServiceHost() method so that it returns only the first base address reported by IIS. Blog articles by Rob Zelt and Rob Reynolds can provide additional helpful details.

Silverlight 2 Creating a Custom Service Factory

protected override ServiceHost CreateServiceHost(Type serviceType, Uri 
[] baseAddresses)
{ 
// If more than one base address exists then return the second 
// address, otherwise return the first address
 (protected override ServiceHost CreateServiceHost
(Type serviceType, Uri[] baseAddresses)
{                       
    // If more than one base address exists then return the second 
    // address, otherwise return the first address
    //(You might be wondering why we're picking the second address here 
    //rather than the first.
    //For us, the second address holds the correct address for our deployment domain
    //www.silverlightblend.com. You may need to modify this code to return 
    //a different/custom base address depending on your IIS server configuration. 
    if (baseAddresses.Length > 1)
    {
        return new ServiceHost(serviceType, baseAddresses[1]);
    }
    else
    {
        return new ServiceHost(serviceType, baseAddresses[0]);
    }            
}

The appropriate location for this Custom Host Factory is in the ServiceName.svc.cs file as a sister class to your Service Contract (Interface). Another minor modification required is to add "Factory="YourNamespaceName.CustomHostFactory" to your ServiceName.svc file as shown in the following code:

<% @ ServiceHost 
Language="C#" Debug
="true" Service="DMSL2WeddingImprints_Web.CustomerDesigns" 
Factory="DMSL2WeddingImprints_Web.CustomHostFactory" 
CodeBehind="CustomerDesigns.svc.cs" %>

Finally, don't forget that your web server (not limited to IIS) must have the necessary Silverlight MIME types, particularly one for the .xap files used by Silverlight 2. (xap application/x-silverlight-app) If your web host uses IIS 6, this MIME type must be set administratively. If it uses IIS 7, in some cases this MIME type can be set via a web.config file. For a more detailed explanation of these issues see Joe's blog article.

Recommended Resources
Some resources you'll need as you develop your Silverlight 2 application are:

Silverlight 2 is unquestionably a major advance over Silverlight 1.0. For an experienced C# developer, it is much more comfortable and productive writing code behind in C# instead of JavaScript. And even though not all controls are yet available in Beta 2 (and not all of the ones which are present are completely finished either), the ones that are promised will make developers that much more productive. Silverlight 2 technology allows developers to design and deploy features which previously would have taken teams of people to do. By pulling together these components, Silvelight will make you more productive and (potentially) release your creativity.

* This article was commissioned by and prepared for Microsoft Corporation. This document is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.


Previous Page: Design Parameter Storage and Retrieval  
Page 1: Getting Started with Silverlight 2—the StepsPage 3: Design Parameter Storage and Retrieval
Page 2: Control Data Binding vs. Event HandlingPage 4: Building a WCF Web Service
Rate This Content:
Low     High
3 after 4 ratings