15 July 2009

Calling a service relative to the Silverlight XAP

This post is deprecated and left here for link reference only. See this post or a better way to do this. A small tidbit that I developed when I was following a training by Dennis van der Stelt of Class-A. One of the assigments was to consume a service and display data. The lab contained a string with a hard coded path. I thought of the following, IMHO much cleaner solution. I also discovered that WCF services are defined in a ServiceReferences.ClientConfig that contains a full path to the service. That is not nice on deployment time. This may have been caused by the fact I hosted the Silverlight App in an Azure project, I am not sure yet. But anyhow, I made an extension method to the Silverlight System.Windows.Controls.Control like this
using System;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;

namespace LocalJoost.Utilities.Silverlight
{
  public static class UserControlExtensions
  {
    public static EndpointAddress GetRelativeEndpointAdress(
      this UserControl control, string path)
    {
      var clientbinLocation = 
          Application.Current.Host.Source.ToString().Substring(0,
          Application.Current.Host.Source.ToString().LastIndexOf("/"));
      return new EndpointAddress(new Uri(string.Format("{0}/{1}",
        clientbinLocation.Substring(0,
        clientbinLocation.LastIndexOf("/")), path)));
    }
  }
}
If you now want to call a service that is sitting in the root of your web application that is hosting you can call it like this:
var client = new CloudMapperDataServiceClient();
client.Endpoint.Address = 
 this.GetRelativeEndpointAdress("CloudMapperDataService.svc");
Substitute "CloudMapperDataServiceClient" by your own client proxy class and "CloudMapperDataService.svc" by your own svc and you are ready to roll. Seeing this again while I blog it I think it might be even better to get the name of the svc from the original Endpoint.Address setting. Well, that's something for later

No comments: