WCF service client (Service References) to call Dynamics CRM 4 web service

1. change system.serviceModel configuration
2. Call web service

<system.serviceModel>
	<bindings>
		<basicHttpBinding>
			<binding name="CrmServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
				<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="163840" />
				<security mode="TransportCredentialOnly">
					<transport clientCredentialType="Windows" />
					<message clientCredentialType="UserName" algorithmSuite="Default" />
				</security>
			</binding>
		</basicHttpBinding>
	</bindings>
	<client>
		<endpoint address="http://dcbr03vrms01/MSCrmServices/2007/CrmService.asmx" binding="basicHttpBinding" bindingConfiguration="CrmServiceSoap" behaviorConfiguration="CrmBehavior" contract="CrmSdk.CrmServiceSoap" name="CrmServiceSoap" />
	</client>
	<extensions>
		<behaviorExtensions>
			<add name="CrmRemoveHeaderBehavior" type="ConsoleApplication2.CrmBehaviorExtensionElement, ConsoleApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
		</behaviorExtensions>
	</extensions>
	<behaviors>
		<endpointBehaviors>
			<behavior name="CrmBehavior">
				<CrmRemoveHeaderBehavior />
			</behavior>
		</endpointBehaviors>
	</behaviors>
</system.serviceModel>
using System;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //WcfCall(); 
            AsmxCall();
        }

        static void WcfCall()
        {
            /* 
             * <extensions>
             *     <behaviorExtensions>
             *         <add name="CrmRemoveHeaderBehavior" type="
             */
            var extensions_behaviorExtensions_add_type = typeof(CrmEndpointBehavior).AssemblyQualifiedName;

            CrmSdk.CrmServiceSoapClient service = new ConsoleApplication2.CrmSdk.CrmServiceSoapClient();

            //service.Endpoint.Behaviors.Add(new CrmEndpointBehavior()); 

            service.ClientCredentials.Windows.ClientCredential.Domain = "comcare.gov.au";
            service.ClientCredentials.Windows.ClientCredential.UserName = "zhou.zhongchen";
            service.ClientCredentials.Windows.ClientCredential.Password = "p@ssw0rd1";

            CrmSdk.CrmAuthenticationToken token = new ConsoleApplication2.CrmSdk.CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = "RMSDev";

            var aaa = service.Retrieve(token, null, null, CrmSdk.EntityName.contact.ToString(), new Guid("EF255982-CE4E-E011-A714-0050568B129A"), new CrmSdk.ColumnSet() { Attributes = new string[] { "address1_telephone3" } });
        }

        static void AsmxCall()
        {
            Sdk.CrmService service = new ConsoleApplication2.Sdk.CrmService();

            Sdk.CrmAuthenticationToken token = new ConsoleApplication2.Sdk.CrmAuthenticationToken();
            token.AuthenticationType = 0;
            token.OrganizationName = "RMSDev";

            service.CrmAuthenticationTokenValue = token;
            service.CallerOriginTokenValue = new ConsoleApplication2.Sdk.CallerOriginToken() { CallerOrigin = new Sdk.WebServiceApiOrigin() };
            service.CorrelationTokenValue = null;

            service.Credentials = System.Net.CredentialCache.DefaultCredentials;

            var aaa = service.Retrieve(CrmSdk.EntityName.contact.ToString(), new Guid("EF255982-CE4E-E011-A714-0050568B129A"), new Sdk.ColumnSet() { Attributes = new string[] { "address1_telephone3" } });
        }
    }
    public class CrmMessageInspector : IClientMessageInspector
    {
        #region IClientMessageInspector Members

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) 
        { 
        } 
        
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) 
        { 
            request.Headers.RemoveAll("CallerOriginToken", "http://schemas.microsoft.com/crm/2007/WebServices"); 
            request.Headers.RemoveAll("CorrelationToken", "http://schemas.microsoft.com/crm/2007/WebServices"); 
            return null;
        }
        
        #endregion
    }
    public class CrmEndpointBehavior : IEndpointBehavior
    {
        #region IEndpointBehavior Members

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 
        { 
        } 
        
        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) 
        {
            clientRuntime.MessageInspectors.Add(new CrmMessageInspector()); 
        }
        
        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) 
        {
        } 
        
        public void Validate(ServiceEndpoint endpoint) 
        { 
        }
        
        #endregion
    }

    public class CrmBehaviorExtensionElement : BehaviorExtensionElement 
    {
        public override Type BehaviorType 
        { 
            get 
            { 
                return typeof(CrmEndpointBehavior); 
            } 
        }
        
        protected override object CreateBehavior() 
        { 
            return new CrmEndpointBehavior(); 
        }
    }
}
Advertisements

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