Technology Corner

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

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

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Archives

RSS InfoQ Feeds

  • Article: Q&A on the Book "Humans vs Computers"
    Author Gojko Adzic has released a book, Humans vs Computers in which he tells stories about the impact of inflexible automation, edge cases and software bugs on the lives of real people. He explains the common mistakes built into the systems and provides advice on how to prevent these mistakes from being built into our systems in the first place. By Shane Ha […]
  • Q&A with Michael Coté on Devops Adoption and his Talk at DevOpsDays NZ
    Raf Gemmail talks to Pivotal’s Michael Coté about obstacles to DevOps adoption and his forthcoming talk at DevOpsDays NZ 2017 By Rafiq Gemmail
  • TensorFlow Serving 1.0 Release Detailed at Google I/O
    Google's Noah Fiedel details new programming model for TensorFlow Serving in a stable 1.0 release. Subject matter addresses common challenges with portability, servablility , and reproducibility improvements. By Dylan Raithel
  • First NetBeans Code Drop Lands at Apache
    Oracle has released the first of three NetBeans code drops to the Apache Incubator. By Matt Raible
  • Article: The Top 10 Adages in Continuous Deployment
    On the basis of discussions at the Continuous Deployment Summit, researchers derived 10 adages about continuous-deployment practices. These adages represent a working set of approaches and beliefs that guide current practice and establish a tangible target for empirical validation. By Chris Parnin
  • Podcast: Joshua Kerievsky and Heidi Helfand on High Performance via Psychological Safety
    In this podcast Shane Hastie, Lead Editor for Culture & Methods, spoke to Joshua Kerievsky, CEO of Industrial Logic, and Heidi Helfand, Director of Engineering Excellence at Procore Technologies and author of the book Dynamic Reteaming, about their talk High Performance via Psychological Safety. By Joshua Kerievsky
  • Spotify and Google Release Forseti GCP Security Tools
    Google has opened up Forseti Security, a set open source tools for GCP security, to all GCP users. The project is the result of a collaborative effort from both Spotify and Google, combining what was originally separate work together into a single toolkit. It aims to automate security processes for developers in order for them to develop more freely. By Andr […]
  • Article: Q&A on the Book SAFe Distilled
    The book SAFe Distilled breaks down the complexity of the framework into easily understood explanations and actionable guidance. It’s a resource for acquiring a deep understanding of the Scaled Agile Framework, and how to implement it successfully. By Ben Linders
  • String Interpolation in Entity Framework Raises Concerns
    One of the new features in Entity Framework Core 2 is the ability to automatically convert interpolated strings into parameterized SQL. Though designed to avoid problems with poorly written SQL, it is feared that it may actually lead to more SQL injection attacks. By Jonathan Allen
  • Podcast: Twitter's Yao Yue on Latency, Performance Monitoring, & Caching at Scale
    Yao Yue spent the majority of her career working on caching systems at Twitter. She created a performance team that deals with edge performance outliers often exposed by the enormous scale of Twitter. In this podcast, she discusses standing up the performance team, thoughts on instrumenting applications, and interesting performance issues (and strategies for […]

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

1 Comment

  1. […] You can read about how to create api or manual proxy class using channel factory here. […]

    Like

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

Blogs I Follow

%d bloggers like this: