Wednesday, June 6, 2012

WCF endpoint issue fixed

In silverlight when we you add refrenece to a WCF service it added a configuration file servicereference.config.

This file contains endpoint of the service and Binding information of the service. When you publish the website and put on server everytime you need to change the end point of service in servicerefernece.config file before publishing it. I have go a very simple solution for this issue.

Add this class as a service helper class

 public class ServiceProxy
    {
        private Uri _baseUri;
        private EndpointAddress _endpointAddress;
        private CustomBinding _binding;
        private T _client;

        public ServiceProxy(String serviceUri)
        {
            _baseUri = new Uri
                (Application.Current.Host.Source.ToString().Substring(0, Application.Current.Host.Source.ToString().IndexOf("ClientBin")));
            //("http://localhost/GacOil");
            _endpointAddress = new EndpointAddress(new Uri(_baseUri, serviceUri), null);

            HttpTransportBindingElement transport = new HttpTransportBindingElement();
            transport.MaxBufferSize = int.MaxValue;
            transport.MaxReceivedMessageSize = int.MaxValue;
            transport.TransferMode = TransferMode.Buffered;
         
            /*Please use the same binding as your service use here if BasicHttpBinding then use BasicHttpBinding only here*/
         
            _binding = new CustomBinding(
               new HttpCookieContainerBindingElement(),
                new BinaryMessageEncodingBindingElement(),
                 transport
            );

            _binding.OpenTimeout = _binding.ReceiveTimeout = _binding.SendTimeout = _binding.CloseTimeout = new TimeSpan(0, 5, 0);

            _client = (T)Activator.CreateInstance(typeof(T), new object[] { _binding, _endpointAddress });
        }

        public T Client
        {
            get
            {
                return _client;

            }
        }
    }


Now you are all set to use this wrapper class to call WCF service.

ServiceProxy mProxy = new ServiceProxy< TestServiceClient >("Services/TestService.svc");

Where TestServiceClient is the Service client class and TestService.svc is under Services folder of your root directory. No you don't have to worry about changing end point everytime you pubish it on server.

Let me know if you any questions/doubts regarding this.

Regards
Vinod

1 comment:

Anonymous said...

solve my issue great explaination

Post a Comment

Send us your comment related to the topic mentioned on the blog