Dynamically creating a Sharepoint Web-Service proxy instance

In my current code, I find myself accessing many Sharepoint web services. In one run of code I can access 5-6 different web services on dozens of different sites, not necessarily even on the same server. Given that I find myself writing a lot of boilerplate code looking like this:

using (SiteData siteDataWS = new SiteData())
{
   siteDataWS.Credentials = CredentialsCache.DefaultNetworkCredentials;
   siteDataWS.Url = currentSite.ToString() + “/_vti_bin/SiteData.asmx”;

   // Do something with the WS.
}

Seeing as this is quite wearisome, I’ve decided to go an genericize it. Given also that the name of the ASMX file for all Sharepoint services is the same as the name of the class to be instantiated, it gets even shorter:

1:  public static WSType CreateWebService (Uri siteUrl) where WSType : SoapHttpClientProtocol, new()
2: {
3:    WSType webService = new WSType();
4:    webService.Credentials = CredentialCache.DefaultNetworkCredentials;

5:    string webServiceName = typeof(WSType).Name;
6:    webService.Url = string.Format(“{0}/_vti_bin/{1}.asmx”, siteUrl, webServiceName);

7:    return webService;
8: }

Line 1: Define a generic method that receives the type of Web Service and returns an instance of it. Note the generic constraints – the type must be a Web Service Proxy (SoapHttpClientProtocol) and must be instantiable. The last one is necessary for line 3 to compile.

Line 5: Get the name of the type – for our example above it would be “SiteData” – and build the URL based on the site URL and the web service name.

Now I can transform the above snippet to this:

using (SiteData siteDataWS = WebServiceHelper.CreateWebService(currentSite))
{
   // Do something with the WS.
}

Drastic change? No, not really. But it keeps things clean.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.