Tuesday, October 20, 2009

Silverlight Web Services deployment

One of the usual issues a newbie developer has with silverlight is with the webservice deployment. Everything would work fine when the services are developed along with the silverlight application but it won't work when it gets deployed to the target server.


The usual reason for this is the url references of the application won't be updated when the deployment is done. In order to make sure that this issue doesn't repeat every time, we can invoke the web services in the silverlight app in such a way that it never needs updating the urls.


A sample snippet of how to do this is as below. We use the Application.Current.Host.Source.AbsoluteUri variable which holds the value of the abolute path of the uri being accessed.



int index = Application.Current.Host.Source.AbsoluteUri.IndexOf(Application.Current.Host.Source.AbsolutePath);
String myCurrentHostUrl = Application.Current.Host.Source.AbsoluteUri.Remove(index + 1);

myCurrentHostUrl contains the value of the website where I am hosting this. Now I can invoke my webservice with this url.



BasicHttpBinding basicHttp = new BasicHttpBinding();
EndpointAddress endPoint = new EndpointAddress(myCurrentHostUrl + @"WebServices/MyWebService.svc");
MyWebServiceClient client = new MyWebServiceClient(basicHttp, endPoint);

We can simply put this code in a reusable function and keep using this as and when needed. Hope this helps.