Coder Social home page Coder Social logo

microsoft / powerplatform-dataverseserviceclient Goto Github PK

View Code? Open in Web Editor NEW
269.0 56.0 50.0 2.79 MB

Code Replica for Microsoft.PowerPlatform.Dataverse.Client and supporting nuget packages.

License: MIT License

C# 100.00%
cdsserviceclient cds microsoft powerplatform dynamics dataverse dataverse-serviceclient

powerplatform-dataverseserviceclient's Introduction

NOTICE Project renamed to Microsoft.PowerPlatform.Dataverse.Client.*

Please see project rename for more information

Change Log

Current release notes and change log:

Microsoft.PowerPlatform.Dataverse.Client

Microsoft.PowerPlatform.Dataverse.Client.Dynamics

This nuget package has been deprecated (for now) Microsoft.Dynamics.Sdk.Messages

Overview

This repository contains the code for the Microsoft.PowerPlatform.Dataverse.Client and its supporting assemblies and classes.

IMPORTANT NOTES

The Dataverse ServiceClient cannot be built outside of Microsoft This is due to a set of dependencies on nuget packages that are internally available only. At some point in the future, we will expose the supporting nuget packages when we have updated our server infrastructure to support plugin development on .net core.

This encompasses the contents of the following nuget packages:

Microsoft.PowerPlatform.Dataverse.Client

Microsoft.PowerPlatform.Dataverse.Client.Dynamics

This nuget package has been deprecated (for now) Microsoft.Dynamics.Sdk.Messages

This library is and its supporting assemblies are a revision and update of the Microsoft.Xrm.Tooling.Connector.CrmServiceClient and the underlying Microsoft.Xrm.Sdk.Client libraries.

We encourage you to read the release notes we provide with each nuget packages. As with most of our Nuget packages that are intended as tools or for developer consumption, we extensively comment in release notes.

At this time: (06/13/2022) The Client SDK libs supports the following and has the following notices:

  • VS 2022 + .net 6 is required to build this project currently. see: global.json for current requirements.
  • .net full framework 4.6.2, 4.7.2, 4.8 and .net core 3.0, 3.1, 5.0, 6.0
  • We now support all authentication types from CrmServiceClient for .net framework, ( Client\Secret, Client\Cert, UID\PW Noninteractive, UID\PW interactive.)
  • We support the following authentication types from CrmServiceClient for .net core: Client\Secret, Client\Cert, UID\PW interactive.
  • Plugin Development using this Client is NOT supported at this time.

From a scenario point of view, we are particularity interested in any issues or challenges when using these library in either Asp.net Core, Azure Functions, and Linux based scenarios.

Note: We provide support for these nuget packages primarily via GitHub and Microsoft Support.
Github Issues is the preferred venue at this time as the development team is actively working on this library. A number of our dev's and PM's do monitor this channel and can respond to questions and feedback.

While we are monitoring the community forums, you are encouraged to open issue here

Samples / Docs

If you are transitioning from Microsoft.XrmTooling.CrmServiceClient to Microsoft.PowerPlatform.Dataverse.Client.ServiceClient Please start here: Transition apps to Dataverse ServiceClient.

Samples and such will be continually updated overtime on the PowerApps Samples GitHub Site. Dataverse ServiceClient Samples can be found here: Samples

For connections strings, docs on supported patterns are here: Connection String Docs. This link will be updated as Dataverse Specific connection string documentation comes online.

Microsoft Documentation root for Dataverse ServiceClient can be found here: Dataverse ServiceClient Docs

Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com.

When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

License

MIT

powerplatform-dataverseserviceclient's People

Contributors

allantargino avatar filcole avatar iammva avatar mattb-msft avatar microsoftopensource avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

powerplatform-dataverseserviceclient's Issues

client.Execute(new AddMemberListRequest() throwing Deserialize exception

The folllowing throws exception that it cant deserialize, but the action is carried out by CDS.

            client.Execute(new AddMemberListRequest()
            {
                EntityId = contact.Id,
                ListId = campaign.First().dca_telemarketinglist.Id
            });
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://schemas.microsoft.com/xrm/2011/Contracts/Services:ExecuteResult. The InnerException message was 'Error in line 1 position 371. Element 'http://schemas.microsoft.com/xrm/2011/Contracts/Services:ExecuteResult' contains data from a type that maps to the name 'http://schemas.microsoft.com/crm/2011/Contracts:AddMemberListResponse'. The deserializer has no knowledge of any type that maps to this name. Consider changing the implementation of the ResolveName method on your DataContractResolver to return a non-null value for name 'AddMemberListResponse' and namespace 'http://schemas.microsoft.com/crm/2011/Contracts'.'.  Please see InnerException for more details.
   at System.Runtime.Serialization.XmlObjectSerializerReadContext.InternalDeserialize(XmlReaderDelegator reader, String name, String ns, Type declaredType, DataContract& dataContract)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserializeWithSurrogate(XmlReaderDelegator xmlReader, Type declaredType, DataContract surrogateDataContract, String name, String ns)
   at System.Runtime.Serialization.XmlObjectSerializerReadContextComplex.InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, String name, String ns)
   at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
   at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlDictionaryReader reader, Boolean verifyObjectName)
   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.PartInfo.ReadObject(XmlDictionaryReader reader, XmlObjectSerializer serializer)
   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.PartInfo.ReadObject(XmlDictionaryReader reader)
   at System.ServiceModel.Dispatcher.DataContractSerializerOperationFormatter.DeserializeParameterPart(XmlDictionaryReader reader, PartInfo part, Boolean isRequest)

[Question] Any ETA please?

Hi

Now that it's been a few months, are you seeing any ETA for GA? Any plans? We are desperate to use this in our Azure functions to connect to CDS,

Thank you
-Srikanth

System.ArgumentNullException: 'Value cannot be null. (Parameter 'input')' when registering the CdsServiceClient on Startup

Hello everyone,

Trying to figure out why I am getting this error: System.ArgumentNullException: 'Value cannot be null. (Parameter 'input')'.

I noticed that this happens when I am actively debugging the code and then just stop the app, the next time I run my asp.net core project I run into this issue. Each time, I had to change the ssl port I use on IISExpress and sometimes run a disk cleanup.
Wondering if you have and Idea. Here is the service registration sequence:

			serviceCollection
				// CRM CLIENT
				.AddScoped<IOrganizationService, CdsServiceClient>(serviceProvider => new CdsServiceClient(
						serviceProvider.GetService<IConfiguration>()["ConnectionStrings:CRM"]
					)
				);

The connection string is properly formatted and is not null. Bellow is the call stack

 	System.Private.CoreLib.dll!System.Version.Parse(string input)	Unknown
 	System.Private.CoreLib.dll!System.Version.Version(string version)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.ConnectAndInitCdsOrgService(Microsoft.Xrm.Sdk.Discovery.OrganizationDetail orgdata, bool IsOnPrem, System.Uri homeRealmUri)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.DoDirectLogin()	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.InitCdsService()	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.GetCachedCDSService(out Microsoft.PowerPlatform.Cds.Client.CdsConnectionService ConnectionObject = null)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.IntilizeService(out Microsoft.PowerPlatform.Cds.Client.CdsConnectionService ConnectionObject = null)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.DoLogin(out Microsoft.PowerPlatform.Cds.Client.CdsConnectionService ConnectionObject = null)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.CreateCdsServiceConnection(object externalOrgServiceProxy = null, Microsoft.PowerPlatform.Cds.Client.AuthenticationType requestedAuthType = ClientSecret, string hostName = "", string port = "", string orgName = HIDDEN, System.Net.NetworkCredential credential = null, string userId = "", System.Security.SecureString password = {System.Security.SecureString}, string domain = "", string Geo = "CAN", string claimsHomeRealm = "", bool useSsl = true, bool useUniqueInstance = true, Microsoft.Xrm.Sdk.Discovery.OrganizationDetail orgDetail = null, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier user = null, string clientId = ********, System.Uri redirectUri = null, Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior promptBehavior = Never, string tokenCachePath = "", Microsoft.Xrm.Sdk.WebServiceClient.OrganizationWebProxyClient externalOrgWebProxyClient = null, string certificateThumbPrint = null, System.Security.Cryptography.X509Certificates.StoreName certificateStoreName = My, System.Security.Cryptography.X509Certificates.X509Certificate2 certificate = null, System.Uri instanceUrl = {System.Uri}, bool isCloned = false, bool useDefaultCreds = false)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.ConnectToCdsService(string cdsConnectionString = HIDDEN)	Unknown
 	Microsoft.PowerPlatform.Cds.Client.dll!Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.CdsServiceClient(string cdsConnectionString = HIDDEN)	Unknown
>	*****.Core.dll!*****.Core.Extensions.ServiceCollectionExtensions.RegisterClients.AnonymousMethod__1_0(System.IServiceProvider serviceProvider = {Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope}) Line 54	C#
 	Microsoft.Extensions.DependencyInjection.dll!Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryCallSite factoryCallSite = {Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryCallSite}, Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext context = {Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext})	Unknown
 	Microsoft.Extensions.DependencyInjection.dll!Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext, object>.VisitCallSiteMain(Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceCallSite callSite = {Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryCallSite}, Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext argument = {Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext})	Unknown
 	Microsoft.Extensions.DependencyInjection.dll!Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceCallSite callSite = {Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryCallSite}, Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext context = {Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext}, Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope serviceProviderEngine = {Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope}, Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverLock lockType = Scope)	Unknown
 	Microsoft.Extensions.DependencyInjection.dll!Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceCallSite singletonCallSite = {Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryCallSite}, Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext context = {Microsoft.Extensions.DependencyInjection.ServiceLookup.RuntimeResolverContext})	Unknown

System.DllNotFoundException : Unable to load shared library 'Rpcrt4' on Ubuntu 18.04.4

Hi! Amazing work on this new nuget package!

I've only come across this error which is thrown on linux (Ubuntu 18.04) when trying to call .SaveChanges() straight after a .AddObject(). Same code works fine on a Windows 10 machine.

       //service here implements IOrganizationService
        using (var ctx = new XrmServiceContext(service))
        {
            ctx.AddObject(new Account() { Name = "Test account" });
            ctx.SaveChanges();

            var account = ctx.CreateQuery<Account>()
                        .ToList()
                        .FirstOrDefault();
        }

System.DllNotFoundException : Unable to load shared library 'Rpcrt4' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libRpcrt4: cannot open shared object file: No such file or directory Stack Trace: at Microsoft.Xrm.Sdk.Client.NativeMethods.UuidCreateSequential(Guid& ptrGuid) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.CreateSequentialGuid() at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SetNewId(Entity entity) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.TraverseEntityGraph(Entity entity, Action1 onEntity, Action3 onLink, IEnumerable1 path)+MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.GetSaveChangesResult(SaveChangesResultCollection results, Entity entity) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.GetChangeRequestsFromChangedTree(SaveChangesResultCollection results, Entity entity, IEnumerable1 path, IList1 circularLinks)+MoveNext() at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.GetChangeRequests(SaveChangesResultCollection results, Entity entity)+MoveNext() at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges(SaveChangesOptions options) at Microsoft.Xrm.Sdk.Client.OrganizationServiceContext.SaveChanges()

This library is not usable unless/until CDS plugins properly support it

All of my CDS-based projects (i.e all projects of my company, since we exclusively provide CDS-based solutions, which I love) look like this:

 - MyProject.Model
 - MyProject.BusinessLogic
 - MyProject.Plugins
 - MyProject.Api
 - Etc...

The Model project will contain early-bound entities which derive from Microsoft.Xrm.Sdk.Entity. Then, the BusinessLogic layer contains all business logic for the entire project, which uses the entities defined above. Then the rest of the solution will consume these 2.

But now I have 2 versions of Microsoft.Xrm.Sdk.Entity, from 2 different assemblies, that I need to derive from depending on whether I'll be using them for a plugin or for an external component such as a Web API, Azure WebJob or Function, etc. This effectively means that I now have 2 different, incompatible set of entities, which completely destroy all possibilities of reusing anything or having a common base layer.

In an ideal scenario (apart from running the entire CDS platform on .NET Core, which seems far fetched), this library should target .NET Standard 2.0 and be compatible with both .NET Framework 4.x assemblies (which can then be used for plugins) AND .NET Core 3.0, for any usage anywhere outside the CDS platform, such as Azure Functions and so on.

CdsServiceClient Authorization Timing out after App Is Idle for long time

I am using CdsServiceClient in Azure Function and if we send a request which basically needs to connect to Dynamics 365 using CdsServiceClient then it is throwing exception with Authentication is Anonymous but with subsequent retry it works. Below is code for initializing CdsClient

    public CdsServiceClient Create(string connectionString)
    {
        _logger.TraceVerbose("Creating CrmServiceClient");
        CdsServiceClient client = new CdsServiceClient(connectionString);

        if (!client.IsReady)
        {
            _logger.TraceError("CrmServiceClient is not ready! Please check your connection string in your \"App.config\"");
        }

        _logger.TraceVerbose("Connected To CRM");
        return client;
    }

upload

CDS calls are made with two different user agents

Seems like there may be a mix of logging as most services have 2 versions of User Agent, with and without the CdsSvcClient info. We would need to consolidate useragent value so CDS can monitor traffic (and for our own usage as well).

Examples:
Some calls are made with useragent "ServiceName", some with useragent "ServiceName (CdsSvcClient:0.0.2.25)".

Could this be due to the fact that CdsServiceClient splits the calls between SOAP and REST endpoints?

Impersonation does not seem to work on a Cloned client instance

Using the CdsServiceClient does not seem to apply any impersonation while running in a web context. (ASP.Net Core)

I've set both CallerAADObjectId and CallerId on the client and neither one make a difference. Data requests are issued as the Application User without any impersonation applied. (The Application User has the Delegate role in Dynamics)

I used the exact same code in a console app and the impersonation works without issue.

My configuration for the CdsServiceClient is the same for both the web application and the console app. (Actually a LinqPad query)

Update: After some experimentation, I discovered that if you clone the CdsServiceClient, then the impersonation does not work. Reproduced it my the console app.

An item with the same key has already been added. Key: msdyn_iotalert.msdyn_customerasset

We have Azure function where we are creating IoT Alert Entity record in Dynamics CRM.

Code Snippet to Create Record

Entity newAlert = new Entity("msdyn_iotalert");
newAlert["msdyn_alertdata"] = JsonConvert.SerializeObject(Data);
newAlert["msdyn_alerttime"] = DateTimeOffset.Parse(ActiveTime, CultureInfo.CurrentCulture);
newAlert[msdyn_alerttype] = 192350000;
newAlert[msdyn_description] = Name;
newAlert["statecode"] = 0;
newAlert["statuscode"] = 1;
newAlert["msdyn_CustomerAsset"] = new EntityReference("msdyn_customerasset", assetId);
Guid alertId = this.cdsServiceClient.Create(newAlert);

Earlier I have raised bug regarding Lookup field Entityreference issue which was fixed so updated our code to use Schema name in upper case letter. #44

Error Log
[
{
"parsedStack":[
{
"assembly":"System.Private.CoreLib,Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw",
"level":0,
"line":0
},
{
"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+d__21.MoveNext",
"level":1,
"line":338,
"fileName":"C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs"
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw",
"level":2,
"line":0
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess",
"level":3,
"line":0
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral,PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification",
"level":4,
"line":0
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.CompilerServices.TaskAwaiter1.GetResult", "level":5, "line":0 }, { "assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", "method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+<TryExecuteAsyncCore>d__18.MoveNext", "level":6, "line":123, "fileName":"C:\\projects\\azure-webjobs-sdk-rqm4t\\src\\Microsoft.Azure.WebJobs.Host\\Executors\\FunctionExecutor.cs" } ], "severityLevel":"Error", "outerId":"0", "message":"Exception while executing function: CreateAlertFromIconicsFault", "type":"Microsoft.Azure.WebJobs.Host.FunctionInvocationException", "id":"12012676" }, { "parsedStack":[{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException", "level":0, "line":0 }, { "assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Collections.Generic.Dictionary2.TryInsert",
"level":1,
"line":0
},
{
"assembly":"Microsoft.PowerPlatform.Cds.Client, Version=0.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.PowerPlatform.Cds.Client.MetadataUtility.GetAttributeMetadata",
"level":2,
"line":0
},
{
"assembly":"Microsoft.PowerPlatform.Cds.Client, Version=0.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.PowerPlatform.Cds.Client.Utilities.ToExpandoObject",
"level":3,
"line":0
},
{
"assembly":"Microsoft.PowerPlatform.Cds.Client, Version=0.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.CdsCommand_WebAPIProcess_Execute",
"level":4,
"line":0
},
{
"assembly":"Microsoft.PowerPlatform.Cds.Client, Version=0.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.ExecuteCdsOrganizationRequestImpl",
"level":5,
"line":0
},
{
"assembly":"Microsoft.PowerPlatform.Cds.Client, Version=0.0.2.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.Create",
"level":6,
"line":0
},

{
"assembly":"dynamics-connector,Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"method":"DynamicsConnector.Dynamics.Services.DynamicsEntityService.CreateAlert",
"level":7,
"line":58,
"fileName":"D:\ConnectorProject\Workspace\Repo\fieldservice_240\fieldservice\src\azure\dynamics-connector\dynamics-connector\Dynamics\Services\DynamicsEntityService.cs"
},
{
"assembly":"dynamics-connector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"method":"DynamicsConnector.Functions.CreateAlertFromIconicsFault+d__10.MoveNext",
"level":8,
"line":100,
"fileName":"D:\ConnectorProject\Workspace\Repo\fieldservice_240\fieldservice\src\azure\dynamics-connector\dynamics-connector\Functions\CreateAlertFromIconicsFault.cs"
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw",
"level":9,
"line":0
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess",
"level":10,
"line":0
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification",
"level":11,
"line":0
},
{
"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e",
"method":"System.Runtime.CompilerServices.TaskAwaiter.GetResult",
"level":12,
"line":0
},
{
"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.Azure.WebJobs.Host.Executors.VoidTaskMethodInvoker2+<InvokeAsync>d__2.MoveNext", "level":13, "line":20, "fileName":"C:\\projects\\azure-webjobs-sdk-rqm4t\\src\\Microsoft.Azure.WebJobs.Host\\Executors\\VoidTaskMethodInvoker.cs" }, { "assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","level":14,"line":0}, {"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","level":15,"line":0}, {"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","level":16,"line":0}, {"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.CompilerServices.TaskAwaiter1.GetResult","level":17,"line":0},
{"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
"method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker2+<InvokeAsync>d__10.MoveNext","level":18, "line":52,"fileName":"C:\\projects\\azure-webjobs-sdk-rqm4t\\src\\Microsoft.Azure.WebJobs.Host\\Executors\\FunctionInvoker.cs"}, {"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","level":19,"line":0}, {"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","level":20,"line":0}, {"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","level":21, "line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e", "method":"System.Runtime.CompilerServices.TaskAwaiter1.GetResult","level":22,"line":0},{"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+d__29.MoveNext","level":23,"line":589,"fileName":"C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs"},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","level":24,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","level":25,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","level":26,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.GetResult","level":27,"line":0},{"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+d__28.MoveNext","level":28,"line":537,"fileName":"C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs"},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","level":29,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","level":30,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","level":31,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.GetResult","level":32,"line":0},{"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+d__27.MoveNext","level":33,"line":481,"fileName":"C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs"},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","level":34,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess","level":35,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","level":36,"line":0},{"assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e","method":"System.Runtime.CompilerServices.TaskAwaiter.GetResult","level":37,"line":0},{"assembly":"Microsoft.Azure.WebJobs.Host, Version=3.0.19.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35","method":"Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor+d__21.MoveNext","level":38,"line":290,"fileName":"C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs"}],"severityLevel":"Error","outerId":"12012676","message":"An item with the same key has already been added. Key: msdyn_iotalert.msdyn_customerasset","type":"System.ArgumentException","id":"22757684"}]

Issue setting a Date field to a null value.

With the change to Web API, updates to set a Date/Time field to null are failing. For example, this code throws an exception with an error response from the Web API.

var entity = new Entity("entity", guid)
entity["new_datetimefield"] = null;

service.Update(entity);

Error:

DateTime is less than minumum value supported by CrmDateTime. Actual value: 01/01/0001 00:00:00, Minimum value supported: 01/01/1753 00:00:00"

This was working on 0.2.1, but is failing on 0.2.5+

Operation return invalid status code 'Bad Request' : Microsoft.Powerplatform.Cds.Client -Version 0.2.16-Alpha

So, we got the following package which provide supports in .net core azure function
Microsoft.Powerplatform.Cds.Client -Version 0.2.16-Alpha

Let me include few details about our implementation:

  1. We have used Dynamics connection string - ClientSecret Authentication types

  2. Following things working fine with the above connection string.

  • Retrieve records from Entities - Working fine.

  • Insert/Update operation in Entity which doesn't contain EntityReference type (Lookup) - Working fine.

  1. When we perform Insert/update operation in Entity which contains EntityReference type (Lookup), it gives error
    Operation return invalid status code 'Bad Request'

Let me attach some code which we implemented in console application:
Entity newIOTAlert = new Entity("msdyn_iotalert");
//Map Fault Name from Iconic to Description field in IOT Alert in Dynamics
newIOTAlert["msdyn_description"] = messageObject["FaultName"].ToString();
//Map Fault Json data from Iconic to Alert Data field in IOT Alert in Dynamics
newIOTAlert["msdyn_alertdata"] = faultData;
newIOTAlert["msdyn_CustomerAsset"] = new EntityReference("msdyn_customerasset", customerDeviceId);
Guid alertId = cdsClient.Create(newIOTAlert);

Exception has occurred: CLR/Microsoft.Rest.HttpOperationException
An unhandled exception of type 'Microsoft.Rest.HttpOperationException' occurred in Microsoft.PowerPlatform.Cds.Client.dll: 'Operation returned an invalid status code 'BadRequest''
at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.Create(Entity entity)

'Object reference not set to an instance of an object' while performing upsert requests.

I'm getting 'Object reference not set to an instance of an object' while using upserts.

This is example code.

  var entity = new Microsoft.Xrm.Sdk.Entity("account", "rkv_ctscode", "11111");
  entity["name"] = "test";

  client.Execute(new UpsertRequest { Target = entity });

Stack:
at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.Execute(OrganizationRequest request)
at ConsoleApp2.Program.Main(String[] args) in C:\xxxs\ConsoleApp2\Program.cs:line 19

When viewing the request in fiddler everything looks OK.

image

BUG: EntityReference UpdateReguest bad URL translation

Doing an update request against an entity that uses an lookup alternate key results in a bad URL:

Case: Contact Entity has a lookup field to related Entity SocialSecurityNo on field ka_cpr.

The patch reguest generated when adding a alternate key to the EntityReference:
https://demolap.api.crm4.dynamics.com/api/data/v9.1/contacts(_ka_cpr_value='(00000000-0000-0000-0000-000000000000)')

It uses the empty Id of the entity reference and not the keycollection.

However i have not figured out how the URL should be manual either yet.
Somthing like?
https://demolap.api.crm4.dynamics.com/api/data/v9.1/contacts(_ka_cpr_value='socialsecuritynos(dca_socialsecurityno='xxxxxxxxxx')')

Key Attribute Support missing for Entity Reference fields when using CdsServiceClient

I noticed that CdsServiceClient does not support setting a lookup field using Key Attributes, it seems that the support for that is missing in Utilities.ToExpandoObject. The functionality still works if you are using the OrganizationWebProxyClient.

An example is:

KeyAttributeCollection lookupKeys = new KeyAttributeCollection();
lookupKeys.Add(new KeyValuePair<string, object>("tickersymbol","AMZN"));
someContact["parentcustomerid"] = new EntityReference("account", lookupKeys};

I found that key support does exist for referencing the primary entity (someContact in my sample above), https://github.com/microsoft/PowerPlatform-CdsServiceClient/blob/bd5dee5c8ecef545b2cede3fcaedc0fff0fa7abf/src/GeneralTools/CDSClient/Client/CdsServiceClient.cs#L4983

I put together a quick sample of how it could be implemented in ToExapandoObject (although really it should probably it's own method in Utilities just for formatting Entity Reference identifier).

https://github.com/microsoft/PowerPlatform-CdsServiceClient/blob/bd5dee5c8ecef545b2cede3fcaedc0fff0fa7abf/src/GeneralTools/CDSClient/Client/Utils/Utils.cs#L354

string entRefIdentifier;

if (entityReference.KeyAttributes?.Any() == true)
{

	string keycollection = string.Empty;
	foreach (var itm in entityReference.KeyAttributes)
	{
		if (itm.Value is EntityReference er)
		{
			keycollection += $"_{itm.Key}_value='{er.Id.ToString("P")}',";

			//IEnumerable<string> keys = cReq.KeyAttributes.Select(s => $"_{s.Key}_value='{((EntityReference)s.Value).Id.ToString().Replace("'", "''")}'");
			//keycollection += $"{EntityData.EntitySetName}({string.Join("&", keys)})";

			//if (cReq.Id != Guid.Empty)
			//{
			//    var s2 = EntityData.EntitySetName + cReq.Id.ToString("P");
			//}


			//// Add support for ER for KEY. 
			//keycollection += $"{itm.Key}@odata.bind='{$"/{metadataUtlity.GetEntityMetadata(Xrm.Sdk.Metadata.EntityFilters.Entity, er.LogicalName).EntitySetName}({er.Id})"}',";
		}
		else 
		{
			keycollection += $"{itm.Key}='{itm.Value}',";
		}
	}
	entRefIdentifier = keycollection.Remove(keycollection.Length - 1); // remove trailing , 
}
else
{
	entRefIdentifier = $"{entityReference.Id}";
}

value = $"/{mUtil.GetEntityMetadata(Xrm.Sdk.Metadata.EntityFilters.Entity, entityReference.LogicalName).EntitySetName}({entRefIdentifier})";

SessionTrackingId is not not added to requests to OrganizationService

Hi,

We are trying to set the CdsServiceClient.SessionTrackingId property to be able to correlate Asp.net core sessions to CDS calls.

When the CdsServiceClient calls a WebAPI endpoint internally, the SessionTrackingId is correctly added as the header x-ms-client-session-id.

However, when the CdsServiceClient calls the OrganizationService internally, it seems that the SessionTrackingId is not added to the request (analyzed using Fiddler).

Regards,
Stefan

Update to create or update records when passing in an Entity Reference using Early Bound

When trying to include an entity reference we get "Operation returned an invalid state code 'BadRequest'"

            var account = new Account
            {
                Name = "Create Test"
            };

            var accountId = svc.Create(account);

            var contact = new Contact
            {
                FirstName = "Create",
                LastName = "Test",
                ParentCustomerId = new EntityReference(Account.EntityLogicalName, accountId)
            };

            var contactId = svc.Create(contact);

Looking at the Last Error we get the following

************ HttpOperationException - POST contacts : Create To CDS via IOrganizationService |=> An error occurred while validating input parameters: Microsoft.OData.ODataException: An undeclared property 'parentcustomerid' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadUndeclaredProperty(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean propertyWithValue)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithoutValue(IODataJsonLightReaderResourceState resourceState, String propertyName)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.b__0(PropertyParsingResult propertyParsingResult, String propertyName)
at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func2 readPropertyAnnotationValue, Action2 handleProperty)
at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState)
at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource()
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties)
at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector)
at Microsoft.OData.ODataReaderCore.ReadImplementation()
at Microsoft.OData.ODataReaderCore.InterceptException[T](Func1 action) at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader) at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext) at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger) Operation returned an invalid status code 'BadRequest'[TerminalFailure] Failed to Execute Command - POST contacts : RequestID=cfc6aec1-339c-4ca7-9f76-f3d4accb6119 : Create To CDS via IOrganizationService duration=00:00:00.0706016 ExceptionMessage = An error occurred while validating input parameters: Microsoft.OData.ODataException: An undeclared property 'parentcustomerid' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values. at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadUndeclaredProperty(IODataJsonLightReaderResourceState resourceState, String propertyName, Boolean propertyWithValue) at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadPropertyWithoutValue(IODataJsonLightReaderResourceState resourceState, String propertyName) at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.<>c__DisplayClass9_0.<ReadResourceContent>b__0(PropertyParsingResult propertyParsingResult, String propertyName) at Microsoft.OData.JsonLight.ODataJsonLightDeserializer.ProcessProperty(PropertyAndAnnotationCollector propertyAndAnnotationCollector, Func2 readPropertyAnnotationValue, Action2 handleProperty) at Microsoft.OData.JsonLight.ODataJsonLightResourceDeserializer.ReadResourceContent(IODataJsonLightReaderResourceState resourceState) at Microsoft.OData.JsonLight.ODataJsonLightReader.StartReadingResource() at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadResourceSetItemStart(PropertyAndAnnotationCollector propertyAndAnnotationCollector, SelectedPropertiesNode selectedProperties) at Microsoft.OData.JsonLight.ODataJsonLightReader.ReadAtStartImplementationSynchronously(PropertyAndAnnotationCollector propertyAndAnnotationCollector) at Microsoft.OData.ODataReaderCore.ReadImplementation() at Microsoft.OData.ODataReaderCore.InterceptException[T](Func1 action)
at System.Web.OData.Formatter.Deserialization.ODataReaderExtensions.ReadResourceOrResourceSet(ODataReader reader)
at System.Web.OData.Formatter.Deserialization.ODataResourceDeserializer.Read(ODataMessageReader messageReader, Type type, ODataDeserializerContext readContext)
at System.Web.OData.Formatter.ODataMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)

We worked out if we do the following it will work

            var account = new Account
            {
                Name = "Create Test"
            };
                
            var accountId = svc.Create(account);

            var contact = new Contact
            {
                FirstName = "Create",
                LastName = "Test",
            };
            contact["parentcustomerid_account"] = new EntityReference(Account.EntityLogicalName, accountId);

            var contactId = svc.Create(contact);

This doesn't seem to work when using custom attributes with entity references.

if we use

registration["htr_address1_stateid"] = new EntityReference(htr_State.EntityLogicalName, request.StateId);

It throws the same error as above
if we use the following

registration["[email protected]"] = new EntityReference(htr_State.EntityLogicalName, request.StateId);

the process no longer throws an error however it doesn't relate the record

Unable to cast object of type 'generatedProxy_2'

I'm getting an odd error occasionally that just started happening in the last couple of weeks. I'm using version 0.2.16-Alpha in an Azure Function (v3.0.9 SDK, runtime version 3.0.14287.0). I have a watchDirectory (Azure Function host.json setting) set, and have a function that updates a file in that directory to restart the Azure Function, the restart works, but after the Azure Function finishes restarting I receive the follow errors whenever attempting to connect to my CDS environment:

"InnerException": {
"ClassName": "System.InvalidCastException",
"Message": "Unable to cast object of type 'generatedProxy_2' to type 'Microsoft.Xrm.Sdk.IOrganizationService'.",
"Data": null,
"InnerException": null,
"HelpURL": null,
"StackTraceString": " at Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.InitCdsService()",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": null,
"HResult": -2147467262,
"Source": "System.Reflection.DispatchProxy",
"WatsonBuckets": null
},

"StackTraceString": " at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)\r\n at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification)\r\n at System.Threading.Tasks.Task1.get_Result()\r\n at Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.GetCachedCDSService(CdsConnectionService& ConnectionObject)\r\n at Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.IntilizeService(CdsConnectionService& ConnectionObject)\r\n at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.CreateCdsServiceConnection(Object externalOrgServiceProxy, AuthenticationType requestedAuthType, String hostName, String port, String orgName, NetworkCredential credential, String userId, SecureString password, String domain, String Geo, String claimsHomeRealm, Boolean useSsl, Boolean useUniqueInstance, OrganizationDetail orgDetail, UserIdentifier user, String clientId, Uri redirectUri, PromptBehavior promptBehavior, String tokenCachePath, OrganizationWebProxyClient externalOrgWebProxyClient, String certificateThumbPrint, StoreName certificateStoreName, X509Certificate2 certificate, Uri instanceUrl, Boolean isCloned, Boolean useDefaultCreds)",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": null,
"HResult": -2146233088,
"Source": "System.Private.CoreLib",

"StackTraceString": " at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.CreateCdsServiceConnection(Object externalOrgServiceProxy, AuthenticationType requestedAuthType, String hostName, String port, String orgName, NetworkCredential credential, String userId, SecureString password, String domain, String Geo, String claimsHomeRealm, Boolean useSsl, Boolean useUniqueInstance, OrganizationDetail orgDetail, UserIdentifier user, String clientId, Uri redirectUri, PromptBehavior promptBehavior, String tokenCachePath, OrganizationWebProxyClient externalOrgWebProxyClient, String certificateThumbPrint, StoreName certificateStoreName, X509Certificate2 certificate, Uri instanceUrl, Boolean isCloned, Boolean useDefaultCreds)\r\n at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.ConnectToCdsService(String cdsConnectionString)\r\n at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient..ctor(String cdsConnectionString)\r\n at ....",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": null,
"HResult": -2146233088,
"Source": "Microsoft.PowerPlatform.Cds.Client",

If I stop the Azure Function, wait a few moments, start the Azure Function, the connection works fine.

Any thoughts on this? Another thing to note is that no code changes have occurred with these Azure Functions in about a month (prior to about 2 weeks ago, they were working wonderfully).

EDITED: Updated to latest versions.

TaskCanceledException on creating CdsServiceClient instance

I'm building poc where an Azure Function is being triggered by a queue and then doing requests towards CDS but I'm getting weird CdsServiceClient error when connecting.
From the behaviour what I'm seeing once you have x amount of items in a queue the CdsServiceClient is unable to connect to your instance since an internal task is being cancelled.

On startup is a key word here. You have to have, for example, 200+ items in queue and then startup your function. If the function was already running and triggered by a single message, the connection can be made and you have no trouble.
Seems like a threading issue to me.

Repo to reproduce: https://github.com/mathiasbl/CdsServiceClient-TaskCanceled

Tracing:
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Verbose: 16 : Initialize CDS connection Started - AuthType: ClientSecret
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Verbose: 16 : Direct Login Process Started
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Information: 8 : Attempting to Connect to Uri https://rkvdev.crm4.dynamics.com/XRMServices/2011/Organization.svc
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Start: 256 : BuildOrgConnectUri CoreClass ()
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Verbose: 16 : DiscoveryServer indicated organization service location = https://xx.crm4.dynamics.com/XRMServices/2011/Organization.svc
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Stop: 512 : BuildOrgConnectUri CoreClass ()
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Information: 8 : Organization Service URI is = https://xx.crm4.dynamics.com/XRMServices/2011/Organization.svc
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Verbose: 16 : ConnectAndInitCdsOrgService - Initializing Organization Service Object
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Information: 8 : ConnectAndInitCdsOrgService - Requesting connection to Organization with CDS Version: No organization data available
[16/06/2020 9:31:20] Host lock lease acquired by instance ID '000000000000000000000000CEAD3CDD'.
[16/06/2020 9:32:54] Message processing error (Action=RenewLock, ClientId=MessageReceiver1dumpqueue, EntityPath=xx, Endpoint=xx.servicebus.windows.net)
[16/06/2020 9:32:54] Microsoft.Azure.ServiceBus: The operation did not complete within the allocated time 00:00:59.9996007 for object request2. System.Private.CoreLib: The operation did not complete within the allocated time 00:00:59.9996007 for object request2.
[16/06/2020 9:32:54] Message processing error (Action=RenewLock, ClientId=MessageReceiver1dumpqueue, EntityPath=xx, Endpoint=xx)
[16/06/2020 9:32:54] Microsoft.Azure.ServiceBus: The operation did not complete within the allocated time 00:00:59.9996007 for object request2. System.Private.CoreLib: The operation did not complete within the allocated time 00:00:59.9996007 for object request2.
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Error: 2 : Source   : System.Private.CoreLib
Method  : ThrowIfExceptional
Date    : 16/06/2020
Time    : 11:33:11
Error   : One or more errors occurred. (A task was canceled.)
Stack Trace     : at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.CreateFromResourceUrlAsync(Uri targetServiceUrl)
   at Microsoft.PowerPlatform.Cds.Client.CdsConnectionService.GetAuthorityFromTargetService(Uri targetServiceUrl, CdsTraceLogger logSink)
======================================================================================================================
Inner Exception Level 1 :
Source  : Not Provided
Method  : Not Provided
Date    : 16/06/2020
Time    : 11:33:11
Error   : A task was canceled.
Stack Trace     : Not Provided
======================================================================================================================

[16/06/2020 9:33:11] Message processing error (Action=RenewLock, ClientId=MessageReceiver1dumpqueue, EntityPath=xx, Endpoint=xx.servicebus.windows.net)
[16/06/2020 9:33:11] Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Error: 2 : ERROR REQUESTING Token FROM THE Authentication context - General ADAL Error

Microsoft.Azure.ServiceBus: The operation did not complete within the allocated time 00:00:59.9996007 for object request2. System.Private.CoreLib: The operation did not complete within the allocated time 00:00:59.9996007 for object request2.
Microsoft.PowerPlatform.Cds.Client.CdsServiceClient Error: 2 : Unable to connect to CDS: A task was canceled.

Message: ExecuteMultiple Request batch size exceeds the maximum batch size allowed!

Hello,

Recently i get error when i send data to dynamics

10/14/2020 3:12:55 PM | UPSERT ERROR, type d'erreur : System.TimeoutException: The request channel timed out attempting to send after 00:02:00. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout.
---> System.TimeoutException: The HTTP request to 'https://****************************.dynamics.com/XRMServices/2011/Organization.svc/web?SDKClientVersion=9.0.45.3122' has exceeded the allotted timeout of 00:02:00. The time allotted to this operation may have been a portion of a longer timeout.
at System.ServiceModel.Channels.HttpChannelFactory1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper) at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout) --- End of inner exception stack trace --- at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.Execute(OrganizationRequest request) at VSMP_Contracts.CTR_Application.CreateMultiple(IOrganizationService _orgService, EntityCollection input) in 10/14/2020 3:14:55 PM | UPSERT ERROR, type d'erreur : System.TimeoutException: The request channel timed out attempting to send after 00:02:00. Increase the timeout value passed to the call to Request or increase the SendTimeout value on the Binding. The time allotted to this operation may have been a portion of a longer timeout. ---> System.TimeoutException: The HTTP request to 'https://*****************************************/XRMServices/2011/Organization.svc/web?SDKClientVersion=9.0.45.3122' has exceeded the allotted timeout of 00:02:00. The time allotted to this operation may have been a portion of a longer timeout. at System.ServiceModel.Channels.HttpChannelFactory1.HttpClientRequestChannel.HttpClientChannelAsyncRequest.SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
at System.ServiceModel.Channels.RequestChannel.RequestAsync(Message message, TimeSpan timeout)
--- End of inner exception stack trace ---
at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.Execute(OrganizationRequest request)
at VSMP_Contracts.CTR_Application.CreateMultiple(IOrganizationService _orgService, EntityCollection input) in

Cordially

Create/Update Records is not working with Lookup (EntityReference) field

I have created console application in .Net Core 3.1 and used โ€œMicrosoft.PowerPlatform.Cds.Clientโ€ (version - 0.2.16-Alpha)

I faced the issue while creating and updating the records with Lookup fields. We fetched the Account and Coupon (custom entity) based on field value and then used those values to set lookup field and we got below error. I already verified all entities and fields name in dynamics and everything is correct in this application.

Bug-2
Bug-1

Unable to commit when uploading the file to the entity file attribute

Hi,

I'm Ziyuan from Dynamics SCM team. We keep receiving exceptions when committing the file upload to the entity file attribute.

Here's the exception message:
"contextUserId=00000000-0000-0000-0000-000000000000 does not map to a high-privileged user. Parameter'user'=xxxxxxxxxxx"

I searched the CDS repo and found the place from where the exception is thrown. CrmSecLib

It's from method CrmSecLib.VerifyUser. From the comments, it looks like a context issue when doing some validations on ExecutionContext and UserIdentityContext.

image

We are using file uploading samples, and our code is much like the method CommitFile in the sample.

We are sending CommitAnnotationBlocksUploadRequest via CDS client.

requestName = "CommitFileBlocksUpload";

commitRequest = new CommitFileBlocksUploadRequest
{
    BlockList = chunkList.ToArray(),
    FileContinuationToken = continuationToken,
    FileName = fileName,
    MimeType = contentType ?? "application/octet-stream",
};

var response = this.CdsServiceClient.Execute(commitRequest);

And our client is initialized using the following constructor:
public CdsServiceClient(Uri instanceUrl, Func<string, Task<string>> tokenProviderFunction, bool useUniqueInstance = true);

It looks like the user id is missing in CDS client or upload commit request. I'm looking forward to your kind suggestions.

Linq query selecting only Id requests all columns from CDS

The following Linq query will return all columns from CDS, I'd only expect the Id column to be returned.

                Guid accountId = (from a in context.AccountSet
                                  where a.Name.Equals("Wonka Chocolate Factory")
                                  select a.Id).FirstOrDefault();

This occurs with latest versions of both clients:

  • Microsoft.PowerPlatform.Cds.Client, Version 0.2.31-Alpha
  • Microsoft.CrmSdk.XrmTooling.CoreAssembly, Version 9.1.0.51

Request:
image

Response:
image

The following query does not return all columns from CDS.

                Guid? accountId = (from a in context.AccountSet
                                   where a.Name.Equals("Wonka Chocolate Factory")
                                   select a.AccountId).FirstOrDefault();

Request:
image

Response:
image

To eliminate the cause being the Early Bound Generator in XrmToolbox I tested again with classes generated by CrmSvcUtil and received the same result.

Test code used for CrmServiceClient, CdsServiceClient and CdsServiceClientWithOOTBCrmSvcUtil are here: https://github.com/filcole/LinqDriverTest

.NET Standard support

Hi,

Is there a practical limitation as why the library cannot support .NET Standard? Most of the services I have are all in .NET Standard and can thus be called from any other .NET Standard project. Using this package would require me to either change all 30+ projects to .NET Core, which is not desired, or 'workaround' the issue by having a web project pull the data and then use the .NET Standard project to store the data in the database. I would prefer to call the service from a business logic, which is a .NET Standard project.

Any plans for .NET Standard?
Thanks!

Using CdsServiceClient with connection string, on prem, IFD

I'm attempting to use the CdsServiceClient. I'm providing a connection string. I get a client but the IsReady is always false. There is no information in the client object telling what is wrong.

Here's my connection string (parameter details are represented with xxxx):
Url = https://xxxxxx.com/xxxxxx; Domain = xxxxxx; AuthType = IFD; UserName = [email protected]; Password = XXXXXX; RequireNewInstance = True

Any help will be greatly appreciated!

services.AddScoped<IServiceContext, ServiceContext>() seems to cache queries

I have a T4 generated ServiceContext with Interface IServiceContext holding limited amount of entities. I use _serviceContext.Set to query data.

If I add those as singleton, everything is extremely fast, but data is 'cached'. That is changing in D365CE is not reflected in the entitity until I restart application. If scoped is used, data is retrieved (not 'cached') but application is much slower.. ..performance is becoming issue. What do I wrong?

` [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.1.0.54")]
public partial class ServiceContext : Microsoft.Xrm.Sdk.Client.OrganizationServiceContext
{

	/// <summary>
	/// Constructor.
	/// </summary>
	public ServiceContext(Microsoft.Xrm.Sdk.IOrganizationService service) : 
			base(service)
	{
	}`

` services.AddCdsServiceClient(
options => Configuration.Bind("CdsServiceClient", options)
);

        services.AddScoped<IServiceContext, ServiceContext>();`

vs

` services.AddCdsServiceClient(
options => Configuration.Bind("CdsServiceClient", options)
);

        services.AddSingleton<IServiceContext, ServiceContext>();`

`public static class CdsServiceCollectionExtensions
{
///


/// Include a CdsServiceClient as a singleton service within the Service Collection
/// Optional include transient services for IOrganizationService
/// and OrganizationServiceContext
///

///
///
public static void AddCdsServiceClient(this IServiceCollection services, Action configureOptions)
{
CdsServiceClientOptions cdsServiceClientOptions = new CdsServiceClientOptions();
configureOptions(cdsServiceClientOptions);

        services.AddSingleton(sp =>
            new CdsServiceClientWrapper(
                cdsServiceClientOptions,
                sp.GetRequiredService<ILogger<CdsServiceClientWrapper>>(),
                cdsServiceClientOptions.TraceLevel)
            );

        services.AddTransient<IOrganizationService, CdsServiceClient>(sp =>
            sp.GetService<CdsServiceClientWrapper>()._cdsServiceClient.Clone());

        if (cdsServiceClientOptions.IncludeOrganizationServiceContext)
        {
            services.AddTransient(sp =>
                new OrganizationServiceContext(sp.GetService<IOrganizationService>()));
        }
    }
}`

Offline sync layer

Does CDS have an offline-capable layer such as SQLite so that I can use my application while offline and sync back to CDS once I have access to internet?

Microsoft.OData.ODataException: Cannot convert a value to target type 'Edm.Decimal'

Hi there,

First of all - Great work on the new SDK - I love using it throughout my non-production .NET Core workloads ๐Ÿ˜„

I am creating an entity record using the CdsServiceClient. The record has a currency field. Upon executing the create request below using the Money type:

_cdsService.Create(new Entity("abc_entity")
    {
        ["abc_amount"] = new Money(650.00m)
    });

I receive the the exception message:

HttpOperationException - POST abc_entities: Create To CDS via IOrganizationService |=> An error occurred while validating input parameters: Microsoft.OData.ODataException: Cannot convert a value to target type 'Edm.Decimal' because of conflict between input format string/number and parameter 'IEEE754Compatible' false/true.

I am using Microsoft.PowerPlatform.Cds.Client version: 0.2.4-Alpha. The same request works when using Microsoft.Xrm.Sdk version 9.x.

I had a quick look at the source for CdsServiceClient and by best guess is the cast exception is being rasied at the below line, seeing as I am providing an object of type Money:
https://github.com/microsoft/PowerPlatform-CdsServiceClient/blob/7ef237ac91d9f47d698d9561c512231d28f7ac72/src/GeneralTools/CDSClient/Client/CdsServiceClient.cs#L4661

I understand that this library is using the OData Web API endpoint primarily to interface with CDS, so the JSON payload needs to mimic the OData requests we carry out normally. In fact, if I use a decimal in the request (below) directly, it works just fine.

_cdsService.Create(new Entity("abc_entity")
    {
        ["abc_amount"] = 650.00m
    });

Error in AzureFunction when creating Entity with Related Entity in Single Request

Hi everyone,

I have a very strange error happening in one of my Azure Functions (v3) when trying to create a parent Entity record with a couple of child records (1:N relationship):

The tv_childentity (Id = 3456ae17-8b9e-ea11-a812-000d3ab6e3d6) in the "tv_parententity_Children." relationship with the tv_parententity (Id = 3356ae17-8b9e-ea11-a812-000d3ab6e3d6) doesn't exist.

   at Microsoft.PowerPlatform.Cds.Client.CdsServiceClient.Create(Entity entity)
   at TeamViewer.D365.Crm.WebApiRepositories.Services.PardonManagementRepository.<CreateAsync>d__3.MoveNext() in D:\Workspace\D365\CRM Web API Repositories\Persistence\Services\PardonManagementRepository.cs:line 51
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at TeamViewer.D365.Crm.Pardoning.Functions.CreatePardonManagement.<CreatePardon>d__4.MoveNext() in D:\Workspace\D365\CRM Pardon Management\Presentation\TeamViewer.D365.Crm.Pardoning.Functions\CreatePardonManagement.cs:line 142
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at TeamViewer.D365.Crm.Pardoning.Functions.CreatePardonManagement.<Run>d__2.MoveNext() in D:\Workspace\D365\CRM Pardon Management\Presentation\TeamViewer.D365.Crm.Pardoning.Functions\CreatePardonManagement.cs:line 80

The weird thing is when I run the exact same code + input data outside of the Azure Function, it is running fine. (As you can see I have a class library with a repository for taking care of creating the entities. Running the repository in an automated test creates the parent + child entities without error.)

I've worked around this for now by first creating the parent record and then bulk creating the child records afterwards, but of course it would be nicer to do everything in one go.

An undeclared property 'customer_entity' which only has property annotations in the payload but no property value was found in the payload

Problem:
An error occurred while validating input parameters: Microsoft.OData.ODataException: An undeclared property 'customer_entity' which only has property annotations in the payload but no property value was found in the payload. In OData, only declared navigation properties and declared named streams can be represented as properties without values.

Cause:
The cdsclient makes lower cases, and sends that to CDS instead of obeying the schema name. of all related custom data types with has upper case. So prefix_MyCustomType becomes prefix_mycustomtype and throws this error.
entity["[email protected]"] = "/prefix_mycustomtypes(6b04618d-5e48-e811-811f-5065f38ada

If the entity is sent with CRM REST builder with caps there is not a problem at all.
Requested fix:

  1. do use different JSON library which does not make lower case;
  2. make the CDS lower/upper case unaware so that it is also easier to code;
  3. patch is to rename all custom entities to lower case so the cds client will work. How to do this?

BUG : EntityReference with keys not working for rest api

using Latest 0.2.24-Alpha.

I cant remember how ToEntityReference works normally, but i had to do a extension method to get a reference with keyValueCollection myself:
image

When using a update request where a keycollection contains a entity reference,
image

the URL generated do not get generated property and it uses the empty id 00000-000...

image

Support for Azure Functions v1?

Does CdsServiceClient support Azure Functions v1?

The Azure functions v1 runtime (Microsoft.NET.Sdk.Functions v1.0.37) provides exactly Newtonsoft.Json = 9.0.1. Yet CdsServiceClient requires Newtonsoft.Json >= 10.0.0.3. When using Visual Studio 2019 to install nuget package Microsoft.CdsServiceClient in a Azure Functions v1 project the following error is given.

Restoring packages for C:\dev\AxisK2\FunctionApp10\FunctionApp10.csproj...
NU1107: Version conflict detected for Newtonsoft.Json. Install/reference Newtonsoft.Json 10.0.3 directly to project FunctionApp10 to resolve this issue. 
 FunctionApp10 -> Microsoft.PowerPlatform.Cds.Client 0.2.17-Alpha -> Newtonsoft.Json (>= 10.0.3) 
 FunctionApp10 -> Microsoft.NET.Sdk.Functions 1.0.37 -> Newtonsoft.Json (= 9.0.1).

If Newtonsoft.Json is upgraded to 10.0.3 (or later) the Azure Function still runs, but anything that requires serialisation will have errors at runtime, examples being:

  1. SwaggerUI/Swagger generation via Aliencube.AzureFunctions.Extensions.OpenApi - see issue #121
  2. Durable functions

There are no problems on Azure Functions v3, which I believe is due to its runtime supporting Newtonsoft.Json >= 11.0.2.

This issue with Azure Functions v1 is present with both this CdsServiceClient and XrmTooling from 9.1.0.26 onwards. XrmTooling 9.1.0.21 and prior required Newtonsoft 6.0.8 and so this issue is not present.

Discussion: Open Source the CDS SDK

Is there any reason that the external, user-facing bits of CDS code remain closed-source?

Instead of complaining and raising issues and expecting the CDS team to fix them, we the people could contribute to the SDK ourselves. I have a TON of improvements and suggestions I'd like to pull request here, and the skills required to write proper code that could potentially be taken seriously.

The HTTP request was forbidden with client authentication scheme 'Anonymous'

Hello,
the CdsServiceClient throws an exception when trying to use the ClientSecret authentication and you have not registered the application in the dynamics instance yet. The stack trace is the following:

Microsoft.Powerplatform.Cds.Client.Utils.CdsConnectionException
  HResult=0x80131500
  Message=Failed to connect to Common Data Service
  Source=Microsoft.Powerplatform.Cds.Client
  StackTrace:
   at Microsoft.Powerplatform.Cds.Client.CdsServiceClient.CreateCdsServiceConnection(Object externalOrgServiceProxy, AuthenticationType requestedAuthType, String hostName, String port, String orgName, NetworkCredential credential, String userId, SecureString password, String domain, String Geo, String claimsHomeRealm, Boolean useSsl, Boolean useUniqueInstance, OrganizationDetail orgDetail, UserIdentifier user, String clientId, Uri redirectUri, PromptBehavior promptBehavior, String tokenCachePath, OrganizationWebProxyClient externalOrgWebProxyClient, String certificateThumbPrint, StoreName certificateStoreName, X509Certificate2 certificate, Uri instanceUrl, Boolean isCloned, Boolean useDefaultCreds)
   at Microsoft.Powerplatform.Cds.Client.CdsServiceClient..ctor(Uri instanceUrl, String clientId, String clientSecret, Boolean useUniqueInstance, String tokenCachePath)
   at CDS.Core_Test.Program.Main(String[] args) in C:\Demo\CDS.Core Test\CDS.Core Test\Program.cs:line 17

  This exception was originally thrown at this call stack:
    Microsoft.Powerplatform.Cds.Client.CdsConnectionService.InitCdsService()
    Microsoft.Powerplatform.Cds.Client.CdsConnectionService.GetCachedCDSService(out Microsoft.Powerplatform.Cds.Client.CdsConnectionService)
    Microsoft.Powerplatform.Cds.Client.CdsConnectionService.IntilizeService(out Microsoft.Powerplatform.Cds.Client.CdsConnectionService)
    Microsoft.Powerplatform.Cds.Client.CdsConnectionService.DoLogin(out Microsoft.Powerplatform.Cds.Client.CdsConnectionService)
    Microsoft.Powerplatform.Cds.Client.CdsServiceClient.CreateCdsServiceConnection(object, Microsoft.Powerplatform.Cds.Client.AuthenticationType, string, string, string, System.Net.NetworkCredential, string, System.Security.SecureString, string, string, string, bool, bool, Microsoft.Xrm.Sdk.Discovery.OrganizationDetail, Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier, string, System.Uri, Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior, string, Microsoft.Xrm.Sdk.WebServiceClient.OrganizationWebProxyClient, string, System.Security.Cryptography.X509Certificates.StoreName, System.Security.Cryptography.X509Certificates.X509Certificate2, System.Uri, bool, bool)

Inner Exception 1:
MessageSecurityException: The HTTP request was forbidden with client authentication scheme 'Anonymous'.

You can use the following code to replicate the problem:

using Microsoft.Extensions.Configuration;
using Microsoft.Powerplatform.Cds.Client;
using System;
using System.IO;

namespace CDS.Core_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                            .AddJsonFile("appsettings.json", true, true)
                                            .Build();
            var cdsClientConfig = config.GetSection("CdsClient");

            var cdsClient = new CdsServiceClient(new Uri(cdsClientConfig["Uri"]), cdsClientConfig["ClientId"], cdsClientConfig["ClientSecret"], true, cdsClientConfig["TokenCache"]);
            if (cdsClient.IsReady)
            {
                Console.WriteLine("Hello, connected to CDS using .NET Core");
            }
            else
            {
                // Never reaches this line of code because the constructor throws an exception
                Console.WriteLine("Failed to connect to CDS using .NET Core :(");
            }

            Console.ReadKey();
        }
    }
}

I replicated the same situation using CrmServiceConnection from Microsoft.Xrm.Tooling.Connector and it does not throw an exception, instead, it handles the exception and stores it in the CrmServiceClient.LastCrmException property. You can use the following code to replicate it using .Net Framewrork

using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Configuration;

namespace CrmServiceClient_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var appSettings = ConfigurationManager.AppSettings;
            var crmClient = new CrmServiceClient(new Uri(appSettings["Uri"]), appSettings["ClientId"], appSettings["ClientSecret"], true, appSettings["TokenCache"]);
            if (crmClient.IsReady)
            {
                Console.WriteLine("Hello, connected to Dynamics using .NET Framework");
            }
            else
            {
                Console.WriteLine("Failed to connect to Dynamics using .NET Framework :(");
                //this works without an exception
            }


            Console.ReadKey();
        }
    }
}

Actually CrmServiceClient.LastCrmException does not have an InnerException and contains no Trace information and the most meaningfull information I got from this (by configuring Visual Studio to break on thrown exceptions) is the following:

Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.HttpRequestWrapperException
  HResult=0x80131500
  Message=
  Source=Microsoft.IdentityModel.Clients.ActiveDirectory
  StackTrace:
   at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Http.HttpClientWrapper.<GetResponseAsync>d__31.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

Inner Exception 1:
HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).

Inner Exception 2:
AdalException: : Unknown error
System.ServiceModel.Security.MessageSecurityException
  HResult=0x80131501
  Message=The HTTP request was forbidden with client authentication scheme 'Anonymous'.
  Source=System.ServiceModel
  StackTrace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory`1 factory)

  This exception was originally thrown at this call stack:
    System.Net.HttpWebRequest.GetResponse()
    System.ServiceModel.Channels.HttpChannelFactory<TChannel>.HttpRequestChannel.HttpChannelRequest.WaitForReply(System.TimeSpan)

Inner Exception 1:
WebException: The remote server returned an error: (403) Forbidden.

System.NullReferenceException in CdsServiceClient constructor

When I'm try to create new CdsServiceClient with single string argument (representing CDS connection string) constructor - I'm getting: "System.NullReferenceException: 'Object reference not set to an instance of an object.'" error every time.

var client = new CdsServiceClient(connectionString);

I'm not sure it is because the connection string is invalid (but even in case it is - I assume that this error should be handled and not throwing NullReferenceException) or because of the some other reason...

I'm using 0.2.14 Nuget package version. Tried it in windows console app (both .NET Framework and .NET Core based).

Simple CRUD application sample

Looking through the linked samples repository, it was tough for me to find any samples that used this new API.

A simple CRUD application would be super useful for understanding how to use this SDK. As a new user, I struggled to understand how to do the following:

  • Get information for my connection string (where do I find this information in the Power Platform portal?) or otherwise authenticate. I would expect inline OAuth flow via an embedded browser window with MSAL.
  • Understand how to query a list of entities, such as querying CDS over LINQ (get a list of all accounts). My expectation was a GetItemsAsync<EntityType>() or similar syntax.
  • Understand how to create a new record. My expectation would syntax such as CreateNewRecord<Account>(account), but it seems like I must manually pass a dictionary rather than using a C# model class.

These reflect my learnings as a completely new user to Common Data Service with previous C# experience as a developer. I'm happy to chat about my experience :)

CdsServiceClient - unspecific error messages are returned

Hi,
It seems after you switched from SOAP to WebAPI backend, the error messages returned by the CdsServiceClient are very generic.

Examples:

  • Create entity with missing mandatory attribute:
    Microsoft.Rest.HttpOperationException: 'Operation returned an invalid status code 'BadRequest''
    Expected: more specific exception indicating missing/invalid attributes of entity

  • Create entity using impersonation - passing invalid CallerId (random Guid)
    JsonReaderException: Bad JSON escape sequence: \x. Path '_error', line 1, position 170.
    Expected: exception indicating that callerId is invalid

There might be more cases like that - please verify.

Regards,
Stefan

Guidance needed.

Dear,

I'm a .NET developer with no power platform or CRM background.
(Luckily I have plenty of expert colleagues at work that can guide me with the specifics of the business logic)

We are currently starting a new greenfield scenario in which we need to be able to use a .NET standard / .NET Core 3.1 compatible packages to talk to Dynamics 365

Example cases are:

  • reading /writing account and contact data
  • reading/ writing invoices, quotes etc.

Would this package be a possible fit? Is it "alpha, please don't use it" or "alpha, please use it, contribute to it."

If not, should I go the ODATA (https://docs.microsoft.com/en-us/dynamics365/customerengagement/on-premises/developer/use-microsoft-dynamics-365-web-api) route, or is the .NET package https://www.nuget.org/packages/Microsoft.CrmSdk.XrmTooling.CoreAssembly/ the only one to use for these sorts of integration scenarios?

It is all a bit confusing to me and I'd love to make an informed decision.

Thanks so much!

Update: the first link should probably be I guess https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/webapi/start-web-api-project-visual-studio-csharp as I'm not on premise.

Unable to create or update records when passing in an Entity Reference using Early Bound

Similar to #39 when utilising early bound to relate records together you get a "RadRequest" response

Seems to be related to the case of the attribute.

I have pushed a sample solution and app to show the issue Repo

I created 2 lookups on the Contact Entity. First using the standard camel case formatting defined in the solution editor and the second I forced lower case.

e.g.
new_Address1StateId
new_address2stateid

New T-SQL endpoint

Just wondering about the new insane amazing t-sql endpoint :)

Will the new t-sql endpoint have a specific api in this repo? But I'm guessing is just "No", if the intent is to just use plain Entity Framework / EF Core to connect to it and run queries?

Are there or there will be any known limits in the endpoint like we have currently with the LINQ provider in the SDK when it translates to QueryExpression (i.e. number of joins, left outer joins and combination of these)?

If there are some bits that translate T-SQL into FetchXml / QueryExpression, would be possible to open source those bits only? :D

Thanks a mill!

BUG: ExecuteCdsWebRequest doesn't re-authenticate after 1 hour (eg. token expiration)

Hi there,

we noticed, that when we have CdsServiceClient in DI as Singleton (eg. lifetime of the application), after 1 hour the calls to CDS start failing with 401 errors. We are using the client_credentials authentication with client ID and client secret (not certificate).

I have been trying to find the exact issue in the code, but didn't really get far enough. One workaround for us is to change the lifetime to scoped, but the will basically lower the efficiency of the token cache and thus request a token with each incoming request.

We are running on .NET Core 3.1 with 0.2.24-Alpha version of this library. Would be happy to dig deeper and submit a PR even, but the README doesn't give much hints on doing it properly.


Probably related to #60

Null exceptions on errors from CDS

I have run into a few null exceptions when using the client and normally just ignore it as its related to when doing something wrong and cds returns an error, as fixing the problem in my code makes the error go away and therefore also the null exception.

But i am guessing its actually a bug still, when CDS returns some error, we properly would like a nice exception at runtime and not just a null exception?

var resp = organizationService.Execute(new RetrieveEntityKeyRequest { EntityLogicalName = "contact" }) as RetrieveEntityKeyResponse;

The above code will throw a null exception.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.