Dynamically calling a web service without a web reference in C#

Adding a web reference to your C# project and keeping it up to date, especially in times where many changes are being made, can be very tiresome. It occurred to me the other day that it must be possible to call a service on the fly in C# code using refection. Surely this functionality is included in the .Net framework. I was correct, it is, but it is not too well documented (Probably because it is slower at executing when compared with using a web reference – reflection etc…). However sometimes flexibility is more important than speed so I decided to look into implementing a solution.

Initially I had tired to read in the service’s WSDL via the ServiceDescription and parse it, however this proved to be very problematic and slow. Then in my travels around the many useless Google results I came across and Article on CodeProject.com by Ehsan Golkar. In this article Ehsan uses the ServiceDescription but loads the output into a ServiceDescriptionImporter. This then allows the creation of a compiled assembly into memory that will interface with the web service. Ehsan code seemed rather hard wired to his UI so I have taken the liberty to create a class that makes its operation much more generic.

Here is my Visual Studio solution which includes a test web service and a win forms application with uses ServiceInspector to call the test web service.

VS 2012 Solution Files for ServiceInspector

Changing C# Dataset (XSD) Connection Strings

One thing that I have often found I have needed to do when programming is to change the connection string properties of an dataset table adapter or queries table adapter. Allowing changes to the connection to be made programmatically can be very beneficial. For example time-outs can be controlled and the database or SQL server instance can be changed on the fly.

The usual way of accessing the connection is the make a partial class on the adapter that exposes the properties that you want to have access to. While this method does work it is not very generic and requires partial classes to be made and maintained. This is OK if you have a small set but can become an unnecessary overhead if you have a large collection of adapters. As such having a generic method of solving this issue was required.

The first thing we have to do is make connection and connection modifier properties on the adapter public because by default they are set to internal.

XSD Connection Moddifier

Next we need to make use of the .Net reflection library. This will allow us to make a generic method that will work over all of the XSDs strongly typed datasets. Due to the way the table adapters and query table adapters are generated I created two methods, however if required I’m sure they could be combined.

Hopefully this code will be helpful to some people as I could find very little online on how to do this.