CrmServiceClient 总是返回 null 组织服务
CrmServiceClient is always returning null Organization Service
我有以下代码可以连接到 Dynamics 365 Online 组织。它在 orgService.Execute(new WhoAmIRequest());
上抛出空引用异常,错误日志在代码下方。我已经在两台装有不同控制台应用程序的机器上试过了。我已经尝试了 8.2 和 8.0 SDK DLL。如果我使用 CrmConnection
和 7.x SDK DLL 重写它,一切正常。我可以使用相同的凭据浏览到该组织(剪切并粘贴以确保没有拼写错误。)
连接字符串格式取自 https://msdn.microsoft.com/en-us/library/mt608573.aspx:
中的示例
Named account using Office 365
<add name="MyCRMServer"
-connectionString="AuthType=Office365;Username=jsmith@contoso.onmicrosoft.com;
Password=passcode;Url=https://contoso.crm.dynamics.com"/>
基本代码。
var connectionString = @"Url=https://ORGNAME.crm.dynamics.com; Username=username@ORGNAME.onmicrosoft.com; Password=43JF##$j#@Ha; Authype=Office365;";
var client = new CrmServiceClient(connectionString);
var orgService = (IOrganizationService)client.OrganizationWebProxyClient ?? client.OrganizationServiceProxy;
orgService.Execute(new WhoAmIRequest());
错误日志输出:
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Information: 8 : Discovery URI is = https://ORGNAME.crm.dynamics.com:443/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Information: 8 : DiscoverOrganizations - Initializing Discovery Server Object with https://ORGNAME.crm.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Verbose: 16 : DiscoverOrganizations - attempting to connect to CRM server @ https://ORGNAME.crm.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Source : System.ServiceModel
Method : Retrieve
Date : 2/13/2017
Time : 5:42:37 PM
Error : Metadata contains a reference that cannot be resolved: 'https://ORGNAME.crm.dynamics.com/_common/error/errorhandler.aspx?BackUri=&ErrorCode=&Parm0=%0d%0a%0d%0aتفاصيل الخطأ: The service '%2fXRMServices%2f2011%2fDiscovery.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'Microsoft.Crm.Site.Services%2c Version%3d8.0.0.0%2c Culture%3dneutral%2c PublicKeyToken%3d31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..&RequestUri=%2fXRMServices%2f2011%2fDiscovery.svc%3fwsdl%26sdkversion%3d8.1&user_lcid=1025'.
Stack Trace : at System.ServiceModel.Description.MetadataExchangeClient.MetadataRetriever.Retrieve(TimeoutHelper timeoutHelper)
at System.ServiceModel.Description.MetadataExchangeClient.ResolveNext(ResolveCallState resolveCallState)
at System.ServiceModel.Description.MetadataExchangeClient.GetMetadata(MetadataRetriever retriever)
at System.ServiceModel.Description.MetadataExchangeClient.GetMetadata(Uri address, MetadataExchangeClientMode mode)
at Microsoft.Xrm.Sdk.Client.ServiceMetadataUtility.RetrieveServiceEndpointMetadata(Type contractType, Uri serviceUri, Boolean checkForSecondary)
at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1..ctor(Uri serviceUri, Boolean checkForSecondary)
at Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory.CreateManagement[TService](Uri serviceUri, Boolean enableProxyTypes, Assembly assembly)
at Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory.CreateManagement[TService](Uri serviceUri)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.CreateAndAuthenticateProxy[T](IServiceManagement`1 servicecfg, Uri ServiceUri, Uri homeRealm, ClientCredentials userCredentials, ClientCredentials deviceCredentials, String LogString)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.DiscoverOrganizations(Uri discoveryServiceUri, Uri homeRealmUri, ClientCredentials clientCredentials, ClientCredentials deviceCredentials)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.DiscoverOrganizations(Uri discoveryServiceUri, Uri homeRealmUri, NetworkCredential networkCredential)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.InitCRM2011Service()
======================================================================================================================
Inner Exception Level 1 :
Source : System.Runtime.Serialization
Method : ThrowXmlException
Date : 2/13/2017
Time : 5:42:37 PM
Error : CData elements not valid at top level of an XML document. Line 1, position 3.
Stack Trace : at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
at System.Xml.XmlUTF8TextReader.Read()
at System.ServiceModel.Description.MetadataExchangeClient.MetadataLocationRetriever.GetXmlReader(HttpWebResponse response, Int64 maxMessageSize, XmlDictionaryReaderQuotas readerQuotas)
at System.ServiceModel.Description.MetadataExchangeClient.MetadataLocationRetriever.DownloadMetadata(TimeoutHelper timeoutHelper)
at System.ServiceModel.Description.MetadataExchangeClient.MetadataRetriever.Retrieve(TimeoutHelper timeoutHelper)
======================================================================================================================
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : OrganizationWebProxyClient is null
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : OrganizationServiceProxy is null
您是否尝试过将参数直接传递给 CrmServiceClient 而不是连接字符串?
我可以使用以下方法成功连接到 Dynamics365
public CrmServiceClient(string crmUserId, SecureString crmPassword, string crmRegion, string orgName, bool useUniqueInstance = false, bool useSsl = false, OrganizationDetail orgDetail = null, bool isOffice365 = false);
我是这样申请的
var pwd = ConvertToSecureString("userpassword");
CrmServiceClient client = new CrmServiceClient("user@mail.com", pwd, "NorthAmerica", "orgname", isOffice365: true);
下面是将密码转换为安全字符串的方法
private System.Security.SecureString ConvertToSecureString(string password)
{
if (password == null)
throw new ArgumentNullException("missing pwd");
var securePassword = new System.Security.SecureString();
foreach (char c in password)
securePassword.AppendChar(c);
securePassword.MakeReadOnly();
return securePassword;
}
根据 Microsoft 的最新建议,我们不应使用“AuthType=Office365”。
我们可以使用应用程序帐户(客户端 ID 和密钥)生成令牌并访问 Dynamics CRM 组织服务。但是,如果您想使用用户 ID 和密码,请使用 (AuthType = OAuth)
示例代码:
string connectionString = "AuthType = OAuth; Url = 'https://*****.crm.dynamics.com'; 用户名 = '';密码 = ''; AppId = 51f81489-12ee-4a9e-aaae-a2591f45987d; RedirectUri = app://58145B91-0C36-4500-8554 -080854F2AC97;登录提示=从不”;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
CrmServiceClient crmServiceClient = new CrmServiceClient(connectionString);
WhoAmIResponse whoAmIResponse = crmServiceClient.Execute(new WhoAmIRequest()) as WhoAmIResponse;
注意:尝试从 Azure 函数使用它时出现以下错误:
- 从身份验证上下文请求令牌时出错需要非空权限
- 出现一个或多个错误。 => 发送请求时发生错误。 => 底层连接已关闭:发送时发生意外错误。 => 无法从传输连接读取数据:现有连接被远程主机强行关闭。 => 现有连接被远程主机强制关闭错误从身份验证上下文中请求令牌
- CurrentAccessToken = 'crmServiceClient.CurrentAccessToken' 引发了 'System.NullReferenceException'
类型的异常
只需添加一行即可轻松解决这些问题:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
参考 URL : https://support.microsoft.com/en-us/help/4051700
Microsoft Dynamics 365 Customer Engagement(在线)要求使用 TLS 1.2 进行连接
如果您遇到任何其他问题,请告诉我。
谢谢,
峰会
我遇到了错误
Unable to login to Dynamics CRM, Error was :
Data[0] = "The provided uri did not return any Service Endpoints!
我在尝试使用 AuthType=ClientSecret 的连接字符串连接到 Dynamics 时收到此错误。以前我使用用户名和密码以及形式为
的连接字符串成功连接
"Url={dynamicsConnectionString};Username={username};Password={password};AuthType=Office365;"
连接字符串已更改为
形式
"AuthType=ClientSecret;RequireNewInstance=false;Url={CrmDynamicsPrivatePrimaryConnection};ClientId={CrmDynamicsPrivateClientId};ClientSecret={CrmDynamicsPrivateClientSecret};LoginPrompt=Never;"
发生错误是因为我使用的是 Microsoft.CrmSdk.XrmTooling.CoreAssembly
的过时版本。我使用的是版本 9.0.2.27
,根据网络报告,连接 ClientSecret 需要版本 9.1.0.13
。我使用 NuGet 更新到 9.1.0.68
版本,Dynamics 连接正常。
我一直在努力解决这个问题,因为除了安装 Microsoft.CrmSdk.XrmTooling.CoreAssembly 的更高版本(在 MS 文档上他们也没有提到这一点)之外,我所做的一切都是因为较低此 dll 版本不支持 ClientSecret 身份验证。
我有以下代码可以连接到 Dynamics 365 Online 组织。它在 orgService.Execute(new WhoAmIRequest());
上抛出空引用异常,错误日志在代码下方。我已经在两台装有不同控制台应用程序的机器上试过了。我已经尝试了 8.2 和 8.0 SDK DLL。如果我使用 CrmConnection
和 7.x SDK DLL 重写它,一切正常。我可以使用相同的凭据浏览到该组织(剪切并粘贴以确保没有拼写错误。)
连接字符串格式取自 https://msdn.microsoft.com/en-us/library/mt608573.aspx:
中的示例Named account using Office 365
<add name="MyCRMServer" -connectionString="AuthType=Office365;Username=jsmith@contoso.onmicrosoft.com; Password=passcode;Url=https://contoso.crm.dynamics.com"/>
基本代码。
var connectionString = @"Url=https://ORGNAME.crm.dynamics.com; Username=username@ORGNAME.onmicrosoft.com; Password=43JF##$j#@Ha; Authype=Office365;";
var client = new CrmServiceClient(connectionString);
var orgService = (IOrganizationService)client.OrganizationWebProxyClient ?? client.OrganizationServiceProxy;
orgService.Execute(new WhoAmIRequest());
错误日志输出:
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Information: 8 : Discovery URI is = https://ORGNAME.crm.dynamics.com:443/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Information: 8 : DiscoverOrganizations - Initializing Discovery Server Object with https://ORGNAME.crm.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Verbose: 16 : DiscoverOrganizations - attempting to connect to CRM server @ https://ORGNAME.crm.dynamics.com/XRMServices/2011/Discovery.svc
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Source : System.ServiceModel
Method : Retrieve
Date : 2/13/2017
Time : 5:42:37 PM
Error : Metadata contains a reference that cannot be resolved: 'https://ORGNAME.crm.dynamics.com/_common/error/errorhandler.aspx?BackUri=&ErrorCode=&Parm0=%0d%0a%0d%0aتفاصيل الخطأ: The service '%2fXRMServices%2f2011%2fDiscovery.svc' cannot be activated due to an exception during compilation. The exception message is: Could not load file or assembly 'Microsoft.Crm.Site.Services%2c Version%3d8.0.0.0%2c Culture%3dneutral%2c PublicKeyToken%3d31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified..&RequestUri=%2fXRMServices%2f2011%2fDiscovery.svc%3fwsdl%26sdkversion%3d8.1&user_lcid=1025'.
Stack Trace : at System.ServiceModel.Description.MetadataExchangeClient.MetadataRetriever.Retrieve(TimeoutHelper timeoutHelper)
at System.ServiceModel.Description.MetadataExchangeClient.ResolveNext(ResolveCallState resolveCallState)
at System.ServiceModel.Description.MetadataExchangeClient.GetMetadata(MetadataRetriever retriever)
at System.ServiceModel.Description.MetadataExchangeClient.GetMetadata(Uri address, MetadataExchangeClientMode mode)
at Microsoft.Xrm.Sdk.Client.ServiceMetadataUtility.RetrieveServiceEndpointMetadata(Type contractType, Uri serviceUri, Boolean checkForSecondary)
at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1..ctor(Uri serviceUri, Boolean checkForSecondary)
at Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory.CreateManagement[TService](Uri serviceUri, Boolean enableProxyTypes, Assembly assembly)
at Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory.CreateManagement[TService](Uri serviceUri)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.CreateAndAuthenticateProxy[T](IServiceManagement`1 servicecfg, Uri ServiceUri, Uri homeRealm, ClientCredentials userCredentials, ClientCredentials deviceCredentials, String LogString)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.DiscoverOrganizations(Uri discoveryServiceUri, Uri homeRealmUri, ClientCredentials clientCredentials, ClientCredentials deviceCredentials)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.DiscoverOrganizations(Uri discoveryServiceUri, Uri homeRealmUri, NetworkCredential networkCredential)
at Microsoft.Xrm.Tooling.Connector.CrmWebSvc.InitCRM2011Service()
======================================================================================================================
Inner Exception Level 1 :
Source : System.Runtime.Serialization
Method : ThrowXmlException
Date : 2/13/2017
Time : 5:42:37 PM
Error : CData elements not valid at top level of an XML document. Line 1, position 3.
Stack Trace : at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
at System.Xml.XmlUTF8TextReader.Read()
at System.ServiceModel.Description.MetadataExchangeClient.MetadataLocationRetriever.GetXmlReader(HttpWebResponse response, Int64 maxMessageSize, XmlDictionaryReaderQuotas readerQuotas)
at System.ServiceModel.Description.MetadataExchangeClient.MetadataLocationRetriever.DownloadMetadata(TimeoutHelper timeoutHelper)
at System.ServiceModel.Description.MetadataExchangeClient.MetadataRetriever.Retrieve(TimeoutHelper timeoutHelper)
======================================================================================================================
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : Unable to Login to Dynamics CRM
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : OrganizationWebProxyClient is null
Microsoft.Xrm.Tooling.Connector.CrmServiceClient Error: 2 : OrganizationServiceProxy is null
您是否尝试过将参数直接传递给 CrmServiceClient 而不是连接字符串?
我可以使用以下方法成功连接到 Dynamics365
public CrmServiceClient(string crmUserId, SecureString crmPassword, string crmRegion, string orgName, bool useUniqueInstance = false, bool useSsl = false, OrganizationDetail orgDetail = null, bool isOffice365 = false);
我是这样申请的
var pwd = ConvertToSecureString("userpassword");
CrmServiceClient client = new CrmServiceClient("user@mail.com", pwd, "NorthAmerica", "orgname", isOffice365: true);
下面是将密码转换为安全字符串的方法
private System.Security.SecureString ConvertToSecureString(string password)
{
if (password == null)
throw new ArgumentNullException("missing pwd");
var securePassword = new System.Security.SecureString();
foreach (char c in password)
securePassword.AppendChar(c);
securePassword.MakeReadOnly();
return securePassword;
}
根据 Microsoft 的最新建议,我们不应使用“AuthType=Office365”。
我们可以使用应用程序帐户(客户端 ID 和密钥)生成令牌并访问 Dynamics CRM 组织服务。但是,如果您想使用用户 ID 和密码,请使用 (AuthType = OAuth)
示例代码:
string connectionString = "AuthType = OAuth; Url = 'https://*****.crm.dynamics.com'; 用户名 = '';密码 = ''; AppId = 51f81489-12ee-4a9e-aaae-a2591f45987d; RedirectUri = app://58145B91-0C36-4500-8554 -080854F2AC97;登录提示=从不”;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
CrmServiceClient crmServiceClient = new CrmServiceClient(connectionString); WhoAmIResponse whoAmIResponse = crmServiceClient.Execute(new WhoAmIRequest()) as WhoAmIResponse;
注意:尝试从 Azure 函数使用它时出现以下错误:
- 从身份验证上下文请求令牌时出错需要非空权限
- 出现一个或多个错误。 => 发送请求时发生错误。 => 底层连接已关闭:发送时发生意外错误。 => 无法从传输连接读取数据:现有连接被远程主机强行关闭。 => 现有连接被远程主机强制关闭错误从身份验证上下文中请求令牌
- CurrentAccessToken = 'crmServiceClient.CurrentAccessToken' 引发了 'System.NullReferenceException' 类型的异常
只需添加一行即可轻松解决这些问题:ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
参考 URL : https://support.microsoft.com/en-us/help/4051700
Microsoft Dynamics 365 Customer Engagement(在线)要求使用 TLS 1.2 进行连接
如果您遇到任何其他问题,请告诉我。
谢谢, 峰会
我遇到了错误
Unable to login to Dynamics CRM, Error was :
Data[0] = "The provided uri did not return any Service Endpoints!
我在尝试使用 AuthType=ClientSecret 的连接字符串连接到 Dynamics 时收到此错误。以前我使用用户名和密码以及形式为
的连接字符串成功连接"Url={dynamicsConnectionString};Username={username};Password={password};AuthType=Office365;"
连接字符串已更改为
形式"AuthType=ClientSecret;RequireNewInstance=false;Url={CrmDynamicsPrivatePrimaryConnection};ClientId={CrmDynamicsPrivateClientId};ClientSecret={CrmDynamicsPrivateClientSecret};LoginPrompt=Never;"
发生错误是因为我使用的是 Microsoft.CrmSdk.XrmTooling.CoreAssembly
的过时版本。我使用的是版本 9.0.2.27
,根据网络报告,连接 ClientSecret 需要版本 9.1.0.13
。我使用 NuGet 更新到 9.1.0.68
版本,Dynamics 连接正常。
我一直在努力解决这个问题,因为除了安装 Microsoft.CrmSdk.XrmTooling.CoreAssembly 的更高版本(在 MS 文档上他们也没有提到这一点)之外,我所做的一切都是因为较低此 dll 版本不支持 ClientSecret 身份验证。