Specifying relative URLs to Silverlight WCF EndPoints

Posted on 5/17/2009 @ 5:20 PM in #SharePoint by | Feedback | 4056 views

This is a ridiculous problem that is especially pertinent in SharePoint, since, SharePoint’s Visual Studio experience is so much fun, I avoid it as much as I can. I code as much as I can outside of SharePoint, and then move in the pieces as indicated in my Deploying WCF EndPoints as solutions in SharePoint 2007 article.

As you know, best practice dictates that when you code stuff, don’t hardcode URIs in code. But in Silverlight, when you give a reference to a Hardcoded URI in code as below ---

   1: EndpointAddress address = new EndpointAddress("/_wcf/ListItemsSvc.svc");

… you get a UriFormatException as below -

   1: System.UriFormatException was unhandled by user code
   2:   Message="Invalid URI: The format of the URI could not be determined."
   3:   StackTrace:
   4:        at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
   5:        at System.Uri..ctor(String uriString)
   6:        at System.ServiceModel.EndpointAddress..ctor(String uri)
   7:        at SLTreeBrowse.Page..ctor()
   8:        at SLTreeBrowse.App.Application_Startup(Object sender, StartupEventArgs e)
   9:        at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
  10:        at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
  11:   InnerException: 

dangit!! (eh? for Canadians!)

Okay, here is how you fix it.

Simply change your code to this -

   1: EndpointAddress address = new EndpointAddress(
   2:     (new Uri(Application.Current.Host.Source, "/_wcf/ListItemsSvc.svc").AbsoluteUri
   3:     ))
   4:     ;

Sound off but keep it civil:

Older comments..

On 5/18/2009 3:14:24 AM Isaac said ..
Thanks, much easier than the method I was using before.

On 5/18/2009 2:50:13 PM Mifko said ..
I believe it should be enough to specify UriKind.RelativeOrAbsolute...

On 5/18/2009 9:58:10 PM Sahil Malik said ..
Crap! Thats right! Mifko, yeah you can just do UriKind .. thanks for pointing this out!


On 6/1/2009 1:27:41 PM Sahil Malik said ..
Sorry, I spoke too soon. UriKind.relative gives the same error! :-/