Pages

Wednesday, August 21, 2013

Initializing WCF client programmatically


Usually, developers follow the practice of making use of Web.config to set all the configuration values for a WCF client. But in some cases, that approach is not always applicable.

For example, if we are trying to call a WCF service through some SharePoint page which was deployed using a feature, in this case, the Web.config resides at a different location and hence the code would not be able to fetch this data.

The more desired approached is to initialize it through your code itself.

Below is the code which I had used to initialize a WCF Client for a service which uses Custom Binding and SOAP 1.2

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;

public static CustomBinding GetBinding()
{
   CustomBinding binding = new CustomBinding();
   binding.Name = "Name_of_your_binding";
   binding.CloseTimeout = TimeSpan.Parse("00:05:00");
   binding.OpenTimeout = TimeSpan.Parse("00:05:00");
   binding.ReceiveTimeout = TimeSpan.Parse("00:10:00");
   binding.SendTimeout = TimeSpan.Parse("00:10:00");
   binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap12, System.Text.Encoding.UTF8));
   HttpsTransportBindingElement hbe = new HttpsTransportBindingElement();
   hbe.RequireClientCertificate = true;
   hbe.AllowCookies = false;
   hbe.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
   hbe.BypassProxyOnLocal = false;
   hbe.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
   hbe.KeepAliveEnabled = true;
   hbe.ManualAddressing = false;
   hbe.MaxBufferPoolSize = Convert.ToInt64(int.MaxValue);
   hbe.MaxBufferSize = int.MaxValue;
   hbe.MaxReceivedMessageSize = Convert.ToInt64(int.MaxValue);
   hbe.ProxyAuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
   hbe.Realm = "";
   hbe.TransferMode = TransferMode.Buffered;
   hbe.UnsafeConnectionNtlmAuthentication = false;
   hbe.UseDefaultWebProxy = true;
   binding.Elements.Add(hbe);
   return binding;
}


public static EndpointAddress GetEndpointAddress()
{
   EndpointAddress endpoint = new EndpointAddress(<URL_string>);
   return endpoint;
}


public static void Main(string[] args)
{
   CustomBinding binding = GetBinding();
   EndpointAddress endpoint = GetEndpointAddress();
   <Proxy_Client_Name> client = new <Proxy_Client_Name>(binding, endpoint);
}

Above, Proxy_Client_Name denotes the name specified for your Client Class in the WCF Service Proxy file which you might have generated from your WSDL or must have been handed over to you by the WCF service providers.

One of the drawbacks of using this approach is that you cannot change the configuration settings at run-time. Apart from that, I would personally suggest all of you to go ahead with it :) ...  

1 comment: