DotNet, WCF

I don’t want to be worry about WCF configuration on client side


I personally feels there is still too much configuration in setting up WCF service infact Microsoft has reduced in new .net frameworks.

If client application wants to consume WCF service then you need to create proxy class using Visual Studio and create configuration on Web/App config files (Visual Studio also generates many configuration). So if you are creating a WCF service and you want client should do minimum configuration setting, you can create proxy class your own which will encapsulate all configuration to connect WCF service and you can provide it sa DLL. It might not not relevant option for all scenarios because if your service would be consume by any clients type (.net,java,php etc.) then you might not need to provide it but this can be very useful if you know client applications are .Net client.

I am here taking an example of creating wcf service which is hosted on console application with tcp/ip bindings and consume by .net client application.

I structured server components in three projects

  • ServiceHostApp: Console self hosting application for WCF service
  • MarketDataProviderService: WCF project which has business logic and implements service contracts.
  • MarketApi: project which encapsulate DataContract, ServiceContract and channel creation code. This dll should deliver to client side so that all the service contract can accessed in client application.

Project: MarketApi

image

IMarketDataProvider.cs

It is service contract which has method GetMarketPrice.

 [ServiceContract]
    public interface IMarketDataProvider
    {
        [FaultContract(typeof(ValidationException))]
        [OperationContract]
        double GetMarketPrice(string symbol);

    }

ValidationException

It contains exception class which is using as fault contract in IMarketDataProvider.

  
    [DataContract]
    public class ValidationException
    {
        public ValidationException() { }
        [DataMember]
        public string ValidationError { get; set; }
    }

ServiceApi.cs

This class actually creating channels using factory class “ChannelFactory” provided by .net.

 
public class ServiceApi
    {
        public static T CreateServiceInstance(Binding binding,string endpoint)
        {
            var address = new EndpointAddress(endpoint);
            var factory = new ChannelFactory(binding,endpoint);
            return factory.CreateChannel();
        }

    }

CreateServiceInstance method is generic method which creates channels for any binding provided and endpoints.

Project: MarketDataProviderService

This project has implementation of service contract IMarketDataProvider.

 
public class MarketDataProvider : IMarketDataProvider
    {
        
       public double GetMarketPrice(string symbol)
        {
            //TODO: Fetch market price
            //sending hardcode value
            if (!symbol.EndsWith(".NSE"))
                throw new FaultException(
			new ValidationException { 
				ValidationError = "Symbol is not valid" 
				}, 
				new FaultReason("Validation Failed"));
           //send real price
            return 34.4d;
        }
    }

Project: Hosting Service

ServiceHostApp is console application which is hosting MarketDataProviderService.

 
 class Program
    {
        static void Main(string[] args)
        {
            using (var productHost = new ServiceHost(typeof(MarketDataProvider)))
            {
                ServiceEndpoint productEndpoint = productHost.AddServiceEndpoint(
			typeof(IMarketDataProvider), new NetTcpBinding(), 
			"net.tcp://localhost:8000/MarketService");
                productHost.Open();
                Console.WriteLine("The Market service is running and is listening on:");
                Console.WriteLine("{0} ({1})",
                  productEndpoint.Address.ToString(),
                  productEndpoint.Binding.Name);
                Console.WriteLine("\nPress any key to stop the service.");
                Console.ReadKey();
            }
        }
    }

ServiceHost class of System.ServiceModel namespace uses to host wcf service. You can add ServiceEndPoint to this class. Here I am running wcf service on tcp port 8000.

image

Now Let’s Create Client Application

Client application will not use proxy class generated by Visual studio, instead client application will use MarketApi.dll to communicate with Service.

  
 class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Connecting to Service..");
                var proxy = ServiceApi.CreateServiceInstance(
			new NetTcpBinding(), 
			"net.tcp://localhost:8000/MarketService");
                Console.WriteLine("MSFT Price:{0}",
			proxy.GetMarketPrice("MSFT.NSE"));
            }
            catch (FaultException ex)
            {
                Console.WriteLine("Service Error:" + ex.Detail.ValidationError);
            }
            Console.ReadLine();
        }

    }

Here CreateServiceInstance method create instance of IMarketDataProvider through NetTcpBinding on 8000 port.

proxy.GetMarketPrice method will call method on service. FaultException of validationException type is catched in catch block.

 

image

Raise FaultException

Now I want to test for if service sends fault exception if something goes wrong. In client application I am sending symbol which is not part of NSE exchange.

I am sending symbol as GOOG.NASDAQ to get market price. Service application will raise exception “Not valid symbol”.

 
 class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Connecting to Service..");
                var proxy = ServiceApi.CreateServiceInstance(
			new NetTcpBinding(), 
			"net.tcp://localhost:8000/MarketService");
                Console.WriteLine("MSFT Price:{0}",
			proxy.GetMarketPrice("MSFT.NSE"));
                Console.WriteLine("Getting price for Google");
                double price = proxy.GetMarketPrice("GOOG.NASDAQ");

                
            }
            catch (FaultException ex)
            {
                Console.WriteLine("Service Error:" + ex.Detail.ValidationError);
            }
            Console.ReadLine();
        }
    }

image

I have not used any other configuration like authentication, authorization etc. I just want to describe how we can create Api without configuration mess.

You can find source code of this example here.

https://skydrive.live.com/embed?cid=D5CF070E5761448A&resid=D5CF070E5761448A%21697&authkey=ANa5UmGIArTJJrs

Advertisements

One thought on “I don’t want to be worry about WCF configuration on client side

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s