nobe123
nobe123

Reputation: 73

Soap Error connecting to hosted CRM online 2011

I have been trying to troubleshoot this error for a long time. "An error occurred when verifying security for the message" I did some research, people said this is because the time difference between the server and the client. This anyone else have the same problem? Below is the detail of my error

    System.ServiceModel.FaultException was caught
  Message=An error occurred when verifying security for the message.
  Source=mscorlib
  StackTrace:
    Server stack trace: 
       at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]: 
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at WindowsFormsApplication1.CrmSdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
       at WindowsFormsApplication1.CrmSdk.Discovery.DiscoveryServiceClient.Execute(DiscoveryRequest request) in WindowsFormsApplication1\Service References\CrmSdk.Discovery\Reference.cs:line 723
       at WindowsFormsApplication1.Form1.DiscoverOrganizationUrl(String organizationName, String discoveryServiceUrl) in Form1.cs:line 110
  InnerException: 

Here is the code i used to access the hosted CRM online webservice

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web;
//using System.ServiceModel;
//using System.ServiceModel.Description;


namespace WindowsFormsApplication1
{
    using CrmSdk;
    using CrmSdk.Discovery;
    using System.Net;
    using System.Globalization;
    using LocalServices;
    using System.ServiceModel;
    using System.Web.Services.Protocols;

    public partial class Form1 : Form
    {
        ///hosted CRM online
        private const string DiscoveryServiceUrl = "https://disco.crm.dynamics.com/XRMServices/2011/Discovery.svc";


        private IOrganizationService _service;

        private string fetchXML =
                                     @"
                                         <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                          <entity name='account'>
                                            <attribute name='name' />
                                            <attribute name='address1_city' />
                                            <attribute name='primarycontactid' />
                                            <attribute name='telephone1' />
                                            <attribute name='accountid' />
                                            <order attribute='name' descending='false' />
                                            <filter type='and'>
                                              <condition attribute='ownerid' operator='eq-userid' />
                                              <condition attribute='statecode' operator='eq' value='0' />
                                            </filter>
                                            <link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
                                              <attribute name='emailaddress1' />
                                            </link-entity>
                                          </entity>
                                        </fetch>                        


                                    ";

        public Form1()
        {
            InitializeComponent();
            //GetDataFromCRM();

            GetDataFromCRM2();

        }
        private void GetDataFromCRM2()
        {

        private string DiscoverOrganizationUrl(string organizationName, string discoveryServiceUrl)
        {
            using (CrmSdk.Discovery.DiscoveryServiceClient client = new CrmSdk.Discovery.DiscoveryServiceClient("CustomBinding_IDiscoveryService", discoveryServiceUrl))
            {
                //ApplyCredentials(client, credentials);

                client.ClientCredentials.Windows.ClientCredential.UserName = UserName;
                client.ClientCredentials.Windows.ClientCredential.Password = Password
                client.ClientCredentials.Windows.ClientCredential.Domain = Domain

                CrmSdk.Discovery.RetrieveOrganizationRequest request = new CrmSdk.Discovery.RetrieveOrganizationRequest()
                {
                    UniqueName = organizationName
                };

                try
                {
                    CrmSdk.Discovery.RetrieveOrganizationResponse response = (CrmSdk.Discovery.RetrieveOrganizationResponse)client.Execute(request);
                    foreach (KeyValuePair<CrmSdk.Discovery.EndpointType, string> endpoint in response.Detail.Endpoints)
                    {
                        if (CrmSdk.Discovery.EndpointType.OrganizationService == endpoint.Key)
                        {
                            Console.WriteLine("Organization Service URL: {0}", endpoint.Value);
                            return endpoint.Value;
                        }
                    }

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture,
                        "Organization {0} does not have an OrganizationService endpoint defined.", organizationName));

                }
                catch (FaultException e)
                {
                    MessageBox.Show(e.Message);
                    throw;
                }

                catch (SoapHeaderException e)
                {
                    MessageBox.Show(e.Message);
                    throw;
                }
                catch (SoapException e)
                {
                    MessageBox.Show(e.Message);
                    throw;
                }
                return null;
            }

        }
        //private static void ApplyCredentials<TChannel>(ClientBase<TChannel> client, ICredentials credentials)
        //    where TChannel : class
        //{
        //    client.ClientCredentials.Windows.ClientCredential = credentials.Windows.ClientCredential;
        //}
        private void ExecuteFetch(string serviceUrl)
        {
            using (OrganizationServiceClient client = new OrganizationServiceClient("CustomBinding_IOrganizationService", new EndpointAddress(serviceUrl)))
            {
                client.ClientCredentials.Windows.ClientCredential.UserName = UserName;
                client.ClientCredentials.Windows.ClientCredential.Password = Password;
                client.ClientCredentials.Windows.ClientCredential.Domain = Domain;

                _service = (IOrganizationService)client;

                FetchExpression expression = new FetchExpression();

                expression.Query = 
                         @"
                                         <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                          <entity name='account'>
                                            <attribute name='name' />
                                            <attribute name='address1_city' />
                                            <attribute name='primarycontactid' />
                                            <attribute name='telephone1' />
                                            <attribute name='accountid' />
                                            <order attribute='name' descending='false' />
                                            <filter type='and'>
                                              <condition attribute='ownerid' operator='eq-userid' />
                                              <condition attribute='statecode' operator='eq' value='0' />
                                            </filter>
                                            <link-entity name='contact' from='contactid' to='primarycontactid' visible='false' link-type='outer' alias='accountprimarycontactidcontactcontactid'>
                                              <attribute name='emailaddress1' />
                                            </link-entity>
                                          </entity>
                                        </fetch>      
                          ";

                EntityCollection result = _service.RetrieveMultiple(expression);
                DataTable temp =  ConvertEntityToTable(result);

            }
        }
        /// Convert Entity To datatable 
        private DataTable ConvertEntityToTable(EntityCollection result)
        {
            DataTable dt = new DataTable();
            int rowCount = result.Entities.Count();
            try
            {
                for (int i = 0; i < rowCount; i++)
                {
                    DataRow dr = dt.NewRow();
                    Entity currentEntity = (Entity)result.Entities[i];
                    var keys = currentEntity.Attributes.Count();

                    for (int j = 0; j < keys; j++)
                    {
                        string columName = currentEntity.Attributes[j].Key;
                        string value = currentEntity.Attributes[j].Value.ToString();

                        if (dt.Columns.IndexOf(columName) == -1)
                            dt.Columns.Add(columName, Type.GetType("Sysem.String"));
                        dr[columName] = value;
                    }
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch (Exception exp)
            {
                throw;
            }
        }
    }
}

app.config

<bindings>
   <customBinding>
    <binding name="CustomBinding_IDiscoveryService">
     <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
      messageVersion="Default" writeEncoding="utf-8">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
       maxBytesPerRead="4096" maxNameTableCharCount="16384"  />
     </textMessageEncoding>
     <httpsTransport manualAddressing="false" maxBufferPoolSize="524288"
      maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
      bypassProxyOnLocal="false" decompressionEnabled="true" hostNameComparisonMode="StrongWildcard"
      keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
      realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
      useDefaultWebProxy="true" requireClientCertificate="false" 

                         />

    </binding>

It throw the error at FaultException Thanks for all the help

Upvotes: 0

Views: 1347

Answers (1)

Jason Lattimer
Jason Lattimer

Reputation: 2848

The general consensus appears to be that besides the actual time, the timezone and daylight savings time settings appear to be the cause of this error. The client and server need to be in sync with each other.

Upvotes: 0

Related Questions