Service Binding in Code

By | August 16, 2011

I like to initialize services in code. The settings once defined they rarely change. This way I implement access to web services in a factory class that serves instances for all the services being consumed by any client assembly.

This is how you would go about creating an instance of the CRM 2011 service. You can download a class with the implementation of this code here.

public static IOrganizationService GetOrganizationService()
{

CustomBinding customBinding = null;
ChannelFactory factory = null;
IOrganizationService orgService = null;
HttpTransportBindingElement httpTransport = null;
SecurityBindingElement securityElement = null;
TextMessageEncodingBindingElement textMessageEncoding = null;

httpTransport = new HttpTransportBindingElement();
httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
securityElement = SecurityBindingElement.CreateSspiNegotiationBindingElement(true);
textMessageEncoding = new TextMessageEncodingBindingElement();
textMessageEncoding.MaxReadPoolSize = 64;
textMessageEncoding.MaxWritePoolSize = 16;
textMessageEncoding.WriteEncoding = Encoding.UTF8;

customBinding = new CustomBinding(securityElement, textMessageEncoding, httpTransport);
customBinding.OpenTimeout = new TimeSpan(0, 0, 120);
customBinding.ReceiveTimeout = new TimeSpan(0, 0, 120);
customBinding.SendTimeout = new TimeSpan(0, 0, 120);

factory = new ChannelFactory(customBinding, new EndpointAddress(ConfigurationManager.AppSettings[“OrgURL“]));
factory.Endpoint.Behaviors.Add(new ProxyTypesBehavior());
orgService = factory.CreateChannel();

return orgService;

}

With this code all I need is a configuration setting containing the URL to the CRM service Organization.svc (see here how to obtain it) which can be stored in the application configuration file or in the registry. In the case of the code above the setting is called OrgURL and is stored in the application configuration file.

This code will also work with a proxy class generated with the crmsvcutil.exe tool. See the line in bold. This line of code is required if you are going to work with the proxy class otherwise you will get all sort of serialization errors.

 

Leave a Reply