-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathServiceClient.cs
2603 lines (2356 loc) · 131 KB
/
ServiceClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Ignore Spelling: Dataverse
#region using
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.PowerPlatform.Dataverse.Client.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.PowerPlatform.Dataverse.Client.Auth;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.PowerPlatform.Dataverse.Client.Model;
using Microsoft.PowerPlatform.Dataverse.Client.Connector;
using Microsoft.PowerPlatform.Dataverse.Client.Connector.OnPremises;
using Microsoft.PowerPlatform.Dataverse.Client.Builder;
#endregion
namespace Microsoft.PowerPlatform.Dataverse.Client
{
/// <summary>
/// Primary implementation of the API interface for Dataverse.
/// </summary>
public class ServiceClient : IOrganizationService, IOrganizationServiceAsync2, IDisposable
{
#region Vars
/// <summary>
/// Cached Object collection, used for pick lists and such.
/// </summary>
internal Dictionary<string, Dictionary<string, object>> _CachObject; //Cache object.
/// <summary>
/// List of Dataverse Language ID's
/// </summary>
internal List<int> _loadedLCIDList;
/// <summary>
/// Name of the cache object.
/// </summary>
internal string _cachObjecName = ".LookupCache";
/// <summary>
/// Logging object for the Dataverse Interface.
/// </summary>
internal DataverseTraceLogger _logEntry;
/// <summary>
/// Dataverse Web Service Connector layer
/// </summary>
internal ConnectionService _connectionSvc;
/// <summary>
/// Dynamic app utility
/// </summary>
internal DynamicEntityUtility _dynamicAppUtility = null;
/// <summary>
/// Configuration
/// </summary>
internal IOptions<ConfigurationOptions> _configuration = ClientServiceProviders.Instance.GetService<IOptions<ConfigurationOptions>>();
/// <summary>
/// Metadata Utility
/// </summary>
internal MetadataUtility _metadataUtlity = null;
/// <summary>
/// This is an internal Lock object, used to sync communication with Dataverse.
/// </summary>
internal object _lockObject = new object();
/// <summary>
/// This is an internal lock object, used to sync clone operations.
/// </summary>
internal object _cloneLockObject = new object();
/// <summary>
/// BatchManager for Execute Multiple.
/// </summary>
internal BatchManager _batchManager = null;
///// <summary>
///// To cache the token
///// </summary>
//private static CdsServiceClientTokenCache _CdsServiceClientTokenCache;
private bool _disableConnectionLocking = false;
/// <summary>
/// SDK Version property backer.
/// </summary>
public string _sdkVersionProperty = null;
/// <summary>
/// Value used by the retry system while the code is running,
/// this value can scale up and down based on throttling limits.
/// </summary>
private TimeSpan _retryPauseTimeRunning;
/// <summary>
/// Internal Organization Service Interface used for Testing
/// </summary>
internal IOrganizationService _testOrgSvcInterface { get; set; }
/// <summary>
/// ConnectionsOptions object used with connection presetup and staging for connect.
/// </summary>
private ConnectionOptions _setupConnectionOptions = null;
/// <summary>
/// Connections Options holder for connection call.
/// </summary>
private ConnectionOptions _connectionOptions = null;
#endregion
#region Properties
/// <summary>
/// Internal OnLineClient
/// </summary>
internal OrganizationWebProxyClientAsync OrganizationWebProxyClient
{
get
{
if (_connectionSvc != null)
{
if (_connectionSvc.WebClient == null)
{
return null;
}
else
return _connectionSvc.WebClient;
}
else
{
return null;
}
}
}
/// <summary>
/// Internal OnLineClient
/// </summary>
internal OrganizationServiceProxyAsync OnPremClient
{
get
{
if (_connectionSvc != null)
{
if (_connectionSvc.OnPremClient == null)
{
return null;
}
else
return _connectionSvc.OnPremClient;
}
else
{
return null;
}
}
}
/// <summary>
/// Enabled Log Capture in memory
/// This capability enables logs that would normally be sent to your configured
/// </summary>
public static bool InMemoryLogCollectionEnabled { get; set; } = Utils.AppSettingsHelper.GetAppSetting<bool>("InMemoryLogCollectionEnabled", false);
/// <summary>
/// This is the number of minuets that logs will be retained before being purged from memory. Default is 5 min.
/// This capability controls how long the log cache is kept in memory.
/// </summary>
public static TimeSpan InMemoryLogCollectionTimeOutMinutes { get; set; } = Utils.AppSettingsHelper.GetAppSettingTimeSpan("InMemoryLogCollectionTimeOutMinutes", Utils.AppSettingsHelper.TimeSpanFromKey.Minutes, TimeSpan.FromMinutes(5));
/// <summary>
/// Gets or sets max retry count.
/// </summary>
public int MaxRetryCount
{
get { return _configuration.Value.MaxRetryCount; }
set { _configuration.Value.MaxRetryCount = value; }
}
/// <summary>
/// Gets or sets retry pause time.
/// </summary>
public TimeSpan RetryPauseTime
{
get { return _configuration.Value.RetryPauseTime; }
set { _configuration.Value.RetryPauseTime = value; }
}
/// <summary>
/// if true the service is ready to accept requests.
/// </summary>
public bool IsReady { get; private set; }
/// <summary>
/// if true then Batch Operations are available.
/// </summary>
public bool IsBatchOperationsAvailable
{
get
{
if (_batchManager != null)
return true;
else
return false;
}
}
/// <summary>
/// OAuth Authority.
/// </summary>
public string Authority
{
get
{ //Restricting to only OAuth login
if (_connectionSvc != null && (
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.OAuth ||
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.Certificate ||
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.ExternalTokenManagement ||
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.ClientSecret))
return _connectionSvc.Authority;
else
return string.Empty;
}
}
/// <summary>
/// Logged in Office365 UserId using OAuth.
/// </summary>
public string OAuthUserId
{
get
{ //Restricting to only OAuth login
if (_connectionSvc != null && _connectionSvc.AuthenticationTypeInUse == AuthenticationType.OAuth)
return _connectionSvc.UserId;
else
return string.Empty;
}
}
/// <summary>
/// Gets or Sets the Max Connection Timeout for the connection.
/// Default setting is 2 min,
/// this property can also be set via app.config/app.settings with the property MaxConnectionTimeOutMinutes
/// </summary>
public static TimeSpan MaxConnectionTimeout
{
get
{
return ConnectionService.MaxConnectionTimeout;
}
set
{
ConnectionService.MaxConnectionTimeout = value;
}
}
/// <summary>
/// Authentication Type to use
/// </summary>
public AuthenticationType ActiveAuthenticationType
{
get
{
if (_connectionSvc != null)
return _connectionSvc.AuthenticationTypeInUse;
else
return AuthenticationType.InvalidConnection;
}
}
/// <summary>
/// Returns the current access token in Use to connect to Dataverse.
/// Note: this is only available when a token based authentication process is in use.
/// </summary>
public string CurrentAccessToken
{
get
{
if (_connectionSvc != null && (
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.OAuth ||
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.Certificate ||
_connectionSvc.AuthenticationTypeInUse == AuthenticationType.ClientSecret))
{
if (_connectionSvc._authenticationResultContainer != null && !string.IsNullOrEmpty(_connectionSvc._resource) && !string.IsNullOrEmpty(_connectionSvc._clientId))
{
if (_connectionSvc._authenticationResultContainer.ExpiresOn.ToUniversalTime() < DateTime.UtcNow.AddMinutes(1))
{
// Force a refresh if the token is about to expire
return _connectionSvc.RefreshClientTokenAsync().ConfigureAwait(false).GetAwaiter().GetResult();
}
return _connectionSvc._authenticationResultContainer.AccessToken;
}
// if not configured, return empty string
return string.Empty;
}
else
return string.Empty;
}
}
/// <summary>
/// Defaults to True.
/// <para>When true, this setting applies the default connection routing strategy to connections to Dataverse.</para>
/// <para>This will 'prefer' a given node when interacting with Dataverse which improves overall connection performance.</para>
/// <para>When set to false, each call to Dataverse will be routed to any given node supporting your organization. </para>
/// <para>See https://docs.microsoft.com/en-us/powerapps/developer/data-platform/api-limits#remove-the-affinity-cookie for proper use.</para>
/// </summary>
public bool EnableAffinityCookie
{
get
{
if (_connectionSvc != null)
return _connectionSvc.EnableCookieRelay;
else
return true;
}
set
{
if (_connectionSvc != null)
_connectionSvc.EnableCookieRelay = value;
}
}
/// <summary>
/// Pointer to Dataverse Service.
/// </summary>
internal IOrganizationService DataverseService
{
get
{
// Added to support testing of ServiceClient direct code.
if (_testOrgSvcInterface != null)
return _testOrgSvcInterface;
if (_connectionSvc != null)
{
if (_connectionSvc.WebClient != null)
return _connectionSvc.WebClient;
else
return _connectionSvc.OnPremClient;
}
else return null;
}
}
/// <summary>
/// Pointer to Dataverse Service.
/// </summary>
internal IOrganizationServiceAsync DataverseServiceAsync
{
get
{
// Added to support testing of ServiceClient direct code.
//if (_testOrgSvcInterface != null)
// return _testOrgSvcInterface;
if (_connectionSvc != null)
{
if (_connectionSvc.WebClient != null)
return _connectionSvc.WebClient;
else
return _connectionSvc.OnPremClient;
}
else return null;
}
}
/// <summary>
/// Current user Record.
/// </summary>
internal WhoAmIResponse SystemUser
{
get
{
if (_connectionSvc != null)
{
if (_connectionSvc.CurrentUser != null)
return _connectionSvc.CurrentUser;
else
{
WhoAmIResponse resp = Task.Run(async () => await _connectionSvc.GetWhoAmIDetails(this).ConfigureAwait(false)).ConfigureAwait(false).GetAwaiter().GetResult();
_connectionSvc.CurrentUser = resp;
return resp;
}
}
else
return null;
}
set
{
_connectionSvc.CurrentUser = value;
}
}
/// <summary>
/// Returns the Last String Error that was created by the Dataverse Connection
/// </summary>
public string LastError { get { if (_logEntry != null) return _logEntry.LastError; else return string.Empty; } }
/// <summary>
/// Returns the Last Exception from Dataverse.
/// </summary>
public Exception LastException { get { if (_logEntry != null) return _logEntry.LastException; else return null; } }
/// <summary>
/// Returns the Actual URI used to connect to Dataverse.
/// this URI could be influenced by user defined variables.
/// </summary>
public Uri ConnectedOrgUriActual { get { if (_connectionSvc != null) return _connectionSvc.ConnectOrgUriActual; else return null; } }
/// <summary>
/// Returns the friendly name of the connected Dataverse instance.
/// </summary>
public string ConnectedOrgFriendlyName { get { if (_connectionSvc != null) return _connectionSvc.ConnectedOrgFriendlyName; else return null; } }
/// <summary>
///
/// Returns the unique name for the org that has been connected.
/// </summary>
public string ConnectedOrgUniqueName { get { if (_connectionSvc != null) return _connectionSvc.CustomerOrganization; else return null; } }
/// <summary>
/// Returns the endpoint collection for the connected org.
/// </summary>
public EndpointCollection ConnectedOrgPublishedEndpoints { get { if (_connectionSvc != null) return _connectionSvc.ConnectedOrgPublishedEndpoints; else return null; } }
/// <summary>
/// OrganizationDetails for the currently connected environment.
/// </summary>
public OrganizationDetail OrganizationDetail { get { if (_connectionSvc != null) return _connectionSvc.ConnectedOrganizationDetail; else return null; } }
/// <summary>
/// This is the connection lock object that is used to control connection access for various threads. This should be used if you are using the Datavers queries via Linq to lock the connection
/// </summary>
internal object ConnectionLockObject { get { return _lockObject; } }
/// <summary>
/// Returns the Version Number of the connected Dataverse organization.
/// If access before the Organization is connected, value returned will be null or 0.0
/// </summary>
public Version ConnectedOrgVersion { get { if (_connectionSvc != null) return _connectionSvc?.OrganizationVersion; else return new Version(0, 0); } }
/// <summary>
/// ID of the connected organization.
/// </summary>
public Guid ConnectedOrgId { get { if (_connectionSvc != null) return _connectionSvc.OrganizationId; else return Guid.Empty; } }
/// <summary>
/// Disabled internal cross thread safeties, this will gain much higher performance, however it places the requirements of thread safety on you, the developer.
/// </summary>
public bool DisableCrossThreadSafeties { get { return _disableConnectionLocking; } set { _disableConnectionLocking = value; } }
/// <summary>
/// Returns the access token from the attached function.
/// This is set via the ServiceContructor that accepts a target url and a function to return an access token.
/// </summary>
internal Func<string, Task<string>> GetAccessToken { get; set; } = null;
/// <summary>
/// Returns any additional or custom headers that need to be added to the request to Dataverse.
/// </summary>
internal Func<Task<Dictionary<string, string>>> GetCustomHeaders { get; set; } = null;
/// <summary>
/// Gets or Sets the current caller ID
/// </summary>
public Guid CallerId
{
get
{
if (OrganizationWebProxyClient != null)
return OrganizationWebProxyClient.CallerId;
return Guid.Empty;
}
set
{
if (OrganizationWebProxyClient != null)
OrganizationWebProxyClient.CallerId = value;
}
}
/// <summary>
/// Gets or Sets the AAD Object ID of the caller.
/// This is supported for Xrm 8.1 + only
/// </summary>
public Guid? CallerAADObjectId
{
get
{
if (_connectionSvc != null)
{
return _connectionSvc.CallerAADObjectId;
}
return null;
}
set
{
if (Utilities.FeatureVersionMinimums.IsFeatureValidForEnviroment(_connectionSvc?.OrganizationVersion, Utilities.FeatureVersionMinimums.AADCallerIDSupported))
_connectionSvc.CallerAADObjectId = value;
else
{
if (_connectionSvc?.OrganizationVersion != null)
{
_connectionSvc.CallerAADObjectId = null; // Null value as this is not supported for this version.
_logEntry.Log($"Setting CallerAADObject ID not supported in version {_connectionSvc?.OrganizationVersion}. Dataverse version {Utilities.FeatureVersionMinimums.AADCallerIDSupported} or higher is required.", TraceEventType.Warning);
}
}
}
}
/// <summary>
/// This ID is used to support Dataverse Telemetry when trouble shooting SDK based errors.
/// When Set by the caller, all Dataverse API Actions executed by this client will be tracked under a single session id for later troubleshooting.
/// For example, you are able to group all actions in a given run of your client ( several creates / reads and such ) under a given tracking id that is shared on all requests.
/// providing this ID when reporting a problem will aid in trouble shooting your issue.
/// </summary>
public Guid? SessionTrackingId
{
get
{
if (_connectionSvc != null)
{
return _connectionSvc.SessionTrackingId;
}
return null;
}
set
{
if (_connectionSvc != null && Utilities.FeatureVersionMinimums.IsFeatureValidForEnviroment(ConnectedOrgVersion, Utilities.FeatureVersionMinimums.SessionTrackingSupported))
_connectionSvc.SessionTrackingId = value;
else
{
if (_connectionSvc?.OrganizationVersion != null)
{
_connectionSvc.SessionTrackingId = null; // Null value as this is not supported for this version.
_logEntry.Log($"Setting SessionTrackingId ID not supported in version {_connectionSvc?.OrganizationVersion}. Dataverse version {Utilities.FeatureVersionMinimums.SessionTrackingSupported} or greater is required.", TraceEventType.Warning);
}
}
}
}
/// <summary>
/// This will force the Dataverse server to refresh the current metadata cache with current DB config.
/// Note, that this is a performance impacting property.
/// Use of this flag will slow down operations server side as the server is required to check for consistency of the platform metadata against disk on each API call executed.
/// It is recommended to use this ONLY in conjunction with solution import or delete operations.
/// </summary>
public bool ForceServerMetadataCacheConsistency
{
get
{
if (_connectionSvc != null)
{
return _connectionSvc.ForceServerCacheConsistency;
}
return false;
}
set
{
if (ConnectedOrgVersion == Version.Parse("9.0.0.0")) // Default setting found as this is a version number that is hard set during setup of connection. it is not possible to actually have an environment with this version number
{
//force update version
_logEntry.Log($"Requested current version from Dataverse, found: {OrganizationDetail.OrganizationVersion}");
}
if (_connectionSvc != null && Utilities.FeatureVersionMinimums.IsFeatureValidForEnviroment(_connectionSvc?.OrganizationVersion, Utilities.FeatureVersionMinimums.ForceConsistencySupported))
_connectionSvc.ForceServerCacheConsistency = value;
else
{
if (_connectionSvc?.OrganizationVersion != null)
{
_connectionSvc.ForceServerCacheConsistency = false; // Null value as this is not supported for this version.
_logEntry.Log($"Setting ForceServerMetadataCacheConsistency not supported in version {_connectionSvc?.OrganizationVersion}. Dataverse version {Utilities.FeatureVersionMinimums.ForceConsistencySupported} or higher is required." , TraceEventType.Warning);
}
}
}
}
/// <summary>
/// Get the Client SDK version property
/// </summary>
public string SdkVersionProperty
{
get
{
if (string.IsNullOrEmpty(_sdkVersionProperty))
{
_sdkVersionProperty = Environs.XrmSdkFileVersion;
}
return _sdkVersionProperty;
}
}
/// <summary>
/// Gets the Tenant Id of the current connection.
/// </summary>
public Guid TenantId
{
get
{
if (_connectionSvc != null)
{
return _connectionSvc.TenantId;
}
else
return Guid.Empty;
}
}
/// <summary>
/// Gets the PowerPlatform Environment Id of the environment that is hosting this instance of Dataverse
/// </summary>
public string EnvironmentId
{
get
{
if (_connectionSvc != null)
{
return _connectionSvc.EnvironmentId;
}
else
return string.Empty;
}
}
/// <summary>
/// Use Dataverse Web API instead of Dataverse Object Model service where possible - Defaults to False.
/// </summary>
public bool UseWebApi
{
get => _configuration.Value.UseWebApi;
set => _configuration.Value.UseWebApi = value;
}
/// <summary>
/// Server Hint for the number of concurrent threads that would provide optimal processing.
/// </summary>
public int RecommendedDegreesOfParallelism => _connectionSvc.RecommendedDegreesOfParallelism;
#endregion
#region Constructor and Setup methods
/// <summary>
/// Default / Non accessible constructor
/// </summary>
private ServiceClient()
{ }
/// <summary>
/// Internal constructor used for testing.
/// </summary>
/// <param name="orgSvc"></param>
/// <param name="httpClient"></param>
/// <param name="targetVersion"></param>
/// <param name="baseConnectUrl"></param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
internal ServiceClient(IOrganizationService orgSvc, HttpClient httpClient, string baseConnectUrl, Version targetVersion = null, ILogger logger = null)
{
_testOrgSvcInterface = orgSvc;
_logEntry = new DataverseTraceLogger(logger)
{
LogRetentionDuration = new TimeSpan(0, 10, 0),
EnabledInMemoryLogCapture = true
};
_connectionSvc = new ConnectionService(orgSvc, baseConnectUrl, httpClient, logger);
if (targetVersion != null)
_connectionSvc.OrganizationVersion = targetVersion;
_batchManager = new BatchManager(_logEntry);
_metadataUtlity = new MetadataUtility(this);
_dynamicAppUtility = new DynamicEntityUtility(this, _metadataUtlity);
IsReady = true;
}
/// <summary>
/// ServiceClient to accept the connectionstring as a parameter
/// </summary>
/// <param name="dataverseConnectionString"></param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(string dataverseConnectionString, ILogger logger = null)
{
if (string.IsNullOrEmpty(dataverseConnectionString))
throw new ArgumentNullException("Dataverse ConnectionString", "Dataverse ConnectionString cannot be null or empty.");
ConnectToService(dataverseConnectionString, logger);
}
/// <summary>
/// Creates an instance of ServiceClient who's authentication is managed by the caller.
/// This requires the caller to implement a function that will accept the InstanceURI as a string will return the access token as a string on demand when the ServiceClient requires it.
/// This approach is recommended when working with WebApplications or applications that are required to implement an on Behalf of flow for user authentication.
/// </summary>
/// <param name="instanceUrl">URL of the Dataverse instance to connect too.</param>
/// <param name="tokenProviderFunction">Function that will be called when the access token is require for interaction with Dataverse. This function must accept a string (InstanceURI) and return a string (accesstoken) </param>
/// <param name="useUniqueInstance">A value of "true" Forces the ServiceClient to create a new connection to the Dataverse instance vs reusing an existing connection, Defaults to true.</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(Uri instanceUrl, Func<string, Task<string>> tokenProviderFunction, bool useUniqueInstance = true, ILogger logger = null)
{
GetAccessToken = tokenProviderFunction ??
throw new DataverseConnectionException("tokenProviderFunction required for this constructor", new ArgumentNullException("tokenProviderFunction")); // Set the function pointer or access.
CreateServiceConnection(
null, AuthenticationType.ExternalTokenManagement, string.Empty, string.Empty, string.Empty, null,
string.Empty, null, string.Empty, string.Empty, string.Empty, true, useUniqueInstance, null,
string.Empty, null, PromptBehavior.Never, null, string.Empty, StoreName.My, null, instanceUrl, externalLogger: logger);
}
/// <summary>
/// Log in with OAuth for online connections,
/// <para>
/// Utilizes the discovery system to resolve the correct endpoint to use given the provided server orgName, user name and password.
/// </para>
/// </summary>
/// <param name="userId">User Id supplied</param>
/// <param name="password">Password for login</param>
/// <param name="regionGeo">Region where server is provisioned in for login</param>
/// <param name="orgName">Name of the organization to connect</param>
/// <param name="useUniqueInstance">if set, will force the system to create a unique connection</param>
/// <param name="orgDetail">Dataverse Org Detail object, this is is returned from a query to the Dataverse Discovery Server service. not required.</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="redirectUri">The redirect URI application will be redirected post OAuth authentication.</param>
/// <param name="promptBehavior">The prompt Behavior.</param>
/// <param name="useDefaultCreds">(optional) If true attempts login using current user ( Online ) </param>
/// <param name="tokenCacheStorePath">(Optional)The token cache path where token cache file is placed. if string.empty, will use default cache file store, if null, will use in memory cache</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(string userId, SecureString password, string regionGeo, string orgName, bool useUniqueInstance, OrganizationDetail orgDetail,
string clientId, Uri redirectUri, PromptBehavior promptBehavior = PromptBehavior.Auto, bool useDefaultCreds = false, string tokenCacheStorePath = null, ILogger logger = null)
{
CreateServiceConnection(
null, AuthenticationType.OAuth, string.Empty, string.Empty, orgName, null,
userId, password, string.Empty, regionGeo, string.Empty, true, useUniqueInstance, orgDetail,
clientId, redirectUri, promptBehavior, null, useDefaultCreds: useDefaultCreds, externalLogger: logger, tokenCacheStorePath: tokenCacheStorePath);
}
/// <summary>
/// Log in with OAuth for online connections,
/// <para>
/// Will attempt to connect directly to the URL provided for the API endpoint.
/// </para>
/// </summary>
/// <param name="userId">User Id supplied</param>
/// <param name="password">Password for login</param>
/// <param name="useUniqueInstance">if set, will force the system to create a unique connection</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="redirectUri">The redirect URI application will be redirected post OAuth authentication.</param>
/// <param name="promptBehavior">The prompt Behavior.</param>
/// <param name="useDefaultCreds">(optional) If true attempts login using current user ( Online ) </param>
/// <param name="hostUri">API or Instance URI to access the Dataverse environment.</param>
/// <param name="tokenCacheStorePath">(Optional)The token cache path where token cache file is placed. if string.empty, will use default cache file store, if null, will use in memory cache</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(string userId, SecureString password, Uri hostUri, bool useUniqueInstance,
string clientId, Uri redirectUri, PromptBehavior promptBehavior = PromptBehavior.Auto, bool useDefaultCreds = false, string tokenCacheStorePath = null, ILogger logger = null)
{
CreateServiceConnection(
null, AuthenticationType.OAuth, string.Empty, string.Empty, null, null,
userId, password, string.Empty, null, string.Empty, true, useUniqueInstance, null,
clientId, redirectUri, promptBehavior, null, useDefaultCreds: useDefaultCreds, instanceUrl: hostUri, externalLogger: logger, tokenCacheStorePath: tokenCacheStorePath);
}
/// <summary>
/// Log in with OAuth for On-Premises connections.
/// </summary>
/// <param name="userId">User Id supplied</param>
/// <param name="password">Password for login</param>
/// <param name="domain">Domain</param>
/// <param name="hostName">Host name of the server that is hosting the Dataverse web service</param>
/// <param name="port">Port number on the Dataverse Host Server ( usually 444 )</param>
/// <param name="orgName">Organization name for the Dataverse Instance.</param>
/// <param name="useSsl">if true, https:// used</param>
/// <param name="useUniqueInstance">if set, will force the system to create a unique connection</param>
/// <param name="orgDetail">Dataverse Org Detail object, this is returned from a query to the Dataverse Discovery Server service. not required.</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="redirectUri">The redirect URI application will be redirected post OAuth authentication.</param>
/// <param name="promptBehavior">The prompt Behavior.</param>
/// <param name="tokenCacheStorePath">(Optional)The token cache path where token cache file is placed. if string.empty, will use default cache file store, if null, will use in memory cache</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(string userId, SecureString password, string domain, string hostName, string port, string orgName, bool useSsl, bool useUniqueInstance,
OrganizationDetail orgDetail, string clientId, Uri redirectUri, PromptBehavior promptBehavior = PromptBehavior.Auto, string tokenCacheStorePath = null, ILogger logger = null)
{
CreateServiceConnection(
null, AuthenticationType.OAuth, hostName, port, orgName, null,
userId, password, domain, string.Empty, string.Empty, useSsl, useUniqueInstance, orgDetail,
clientId, redirectUri, promptBehavior, null, externalLogger: logger, tokenCacheStorePath: tokenCacheStorePath);
}
/// <summary>
/// Log in with Certificate Auth On-Premises connections.
/// </summary>
/// <param name="certificate">Certificate to use during login</param>
/// <param name="certificateStoreName">StoreName to look in for certificate identified by certificateThumbPrint</param>
/// <param name="certificateThumbPrint">ThumbPrint of the Certificate to load</param>
/// <param name="instanceUrl">URL of the Dataverse instance to connect too</param>
/// <param name="orgName">Organization name for the Dataverse Instance.</param>
/// <param name="useSsl">if true, https:// used</param>
/// <param name="useUniqueInstance">if set, will force the system to create a unique connection</param>
/// <param name="orgDetail">Dataverse Org Detail object, this is is returned from a query to the Dataverse Discovery Server service. not required.</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="redirectUri">The redirect URI application will be redirected post OAuth authentication.</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(X509Certificate2 certificate, StoreName certificateStoreName, string certificateThumbPrint, Uri instanceUrl, string orgName, bool useSsl, bool useUniqueInstance,
OrganizationDetail orgDetail, string clientId, Uri redirectUri, ILogger logger = null)
{
if ((string.IsNullOrEmpty(clientId) || redirectUri == null))
{
throw new ArgumentOutOfRangeException("authType",
"When using Certificate Authentication you have to specify clientId and redirectUri.");
}
if (string.IsNullOrEmpty(certificateThumbPrint) && certificate == null)
{
throw new ArgumentOutOfRangeException("authType",
"When using Certificate Authentication you have to specify either a certificate thumbprint or provide a certificate to use.");
}
CreateServiceConnection(
null, AuthenticationType.Certificate, string.Empty, string.Empty, orgName, null,
string.Empty, null, string.Empty, string.Empty, string.Empty, useSsl, useUniqueInstance, orgDetail,
clientId, redirectUri, PromptBehavior.Never, null, certificateThumbPrint, certificateStoreName, certificate, instanceUrl, externalLogger: logger);
}
/// <summary>
/// Log in with Certificate Auth OnLine connections.
/// This requires the org API URI.
/// </summary>
/// <param name="certificate">Certificate to use during login</param>
/// <param name="certificateStoreName">StoreName to look in for certificate identified by certificateThumbPrint</param>
/// <param name="certificateThumbPrint">ThumbPrint of the Certificate to load</param>
/// <param name="instanceUrl">API URL of the Dataverse instance to connect too</param>
/// <param name="useUniqueInstance">if set, will force the system to create a unique connection</param>
/// <param name="orgDetail">Dataverse Org Detail object, this is is returned from a query to the Dataverse Discovery Server service. not required.</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="redirectUri">The redirect URI application will be redirected post OAuth authentication.</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(X509Certificate2 certificate, StoreName certificateStoreName, string certificateThumbPrint, Uri instanceUrl, bool useUniqueInstance, OrganizationDetail orgDetail,
string clientId, Uri redirectUri, ILogger logger = null)
{
if ((string.IsNullOrEmpty(clientId)))
{
throw new ArgumentOutOfRangeException("authType",
"When using Certificate Authentication you have to specify clientId.");
}
if (string.IsNullOrEmpty(certificateThumbPrint) && certificate == null)
{
throw new ArgumentOutOfRangeException("authType",
"When using Certificate Authentication you have to specify either a certificate thumbprint or provide a certificate to use.");
}
CreateServiceConnection(
null, AuthenticationType.Certificate, string.Empty, string.Empty, string.Empty, null,
string.Empty, null, string.Empty, string.Empty, string.Empty, true, useUniqueInstance, orgDetail,
clientId, redirectUri, PromptBehavior.Never, null, certificateThumbPrint, certificateStoreName, certificate, instanceUrl, externalLogger: logger);
}
/// <summary>
/// ClientID \ ClientSecret Based Authentication flow.
/// </summary>
/// <param name="instanceUrl">Direct URL of Dataverse instance to connect too.</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="clientSecret">Client Secret for Client Id.</param>
/// <param name="useUniqueInstance">Use unique instance or reuse current connection.</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(Uri instanceUrl, string clientId, string clientSecret, bool useUniqueInstance, ILogger logger = null)
{
CreateServiceConnection(null,
AuthenticationType.ClientSecret,
string.Empty, string.Empty, string.Empty, null, string.Empty,
MakeSecureString(clientSecret), string.Empty, string.Empty, string.Empty, true, useUniqueInstance,
null, clientId, null, PromptBehavior.Never, null, null, instanceUrl: instanceUrl, externalLogger: logger);
}
/// <summary>
/// ClientID \ ClientSecret Based Authentication flow, allowing for Secure Client ID passing.
/// </summary>
/// <param name="instanceUrl">Direct URL of Dataverse instance to connect too.</param>
/// <param name="clientId">The registered client Id on Azure portal.</param>
/// <param name="clientSecret">Client Secret for Client Id.</param>
/// <param name="useUniqueInstance">Use unique instance or reuse current connection.</param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
public ServiceClient(Uri instanceUrl, string clientId, SecureString clientSecret, bool useUniqueInstance, ILogger logger = null)
{
CreateServiceConnection(null,
AuthenticationType.ClientSecret,
string.Empty, string.Empty, string.Empty, null, string.Empty,
clientSecret, string.Empty, string.Empty, string.Empty, true, useUniqueInstance,
null, clientId, null, PromptBehavior.Never, null, null, instanceUrl: instanceUrl, externalLogger: logger);
}
/// <summary>
/// Creating the ServiceClient Connection with a ConnectionOptions Object and ConfigurationOptions Object. This allows for deferred create of a Dataverse Service Client.
/// </summary>
/// <param name="connectionOptions">Describes how the Connection should be created.</param>
/// <param name="deferConnection">False by Default, if True, stages the properties of the connection and returns. You must call .Connect() to complete the connection. </param>
/// <param name="serviceClientConfiguration">Described Configuration Options for the connection.</param>
public ServiceClient(ConnectionOptions connectionOptions, bool deferConnection = false, ConfigurationOptions serviceClientConfiguration = null)
{
// store the options and ready for connect call.
_setupConnectionOptions = connectionOptions;
//_configuration
if ( serviceClientConfiguration != null )
_configuration.Value.UpdateOptions(serviceClientConfiguration);
// External auth.
if (connectionOptions.AccessTokenProviderFunctionAsync != null)
{
connectionOptions.AuthenticationType = AuthenticationType.ExternalTokenManagement;
GetAccessToken = connectionOptions.AccessTokenProviderFunctionAsync;
}
// Add custom header support.
if ( connectionOptions.RequestAdditionalHeadersAsync != null )
{
GetCustomHeaders = connectionOptions.RequestAdditionalHeadersAsync;
}
if (deferConnection)
{
_connectionOptions = connectionOptions;
if (connectionOptions.Logger != null)
connectionOptions.Logger.LogInformation("Connection creation has been deferred at user request");
return;
}
// Form Connection string.
string connectionString = ConnectionStringConstants.CreateConnectionStringFromConnectionOptions(connectionOptions);
ConnectToService(connectionString, connectionOptions.Logger);
}
/// <summary>
/// Connects the Dataverse Service Client instance when staged with the Deferd Connection constructor.
/// </summary>
/// <returns></returns>
public bool Connect()
{
if (_connectionOptions != null && IsReady == false)
{
if (_connectionOptions.Logger != null)
_connectionOptions.Logger.LogInformation("Initiating connection to Dataverse");
string connectionString = ConnectionStringConstants.CreateConnectionStringFromConnectionOptions(_connectionOptions);
ConnectToService(connectionString, _connectionOptions.Logger);
_connectionOptions = null;
return true;
}
else
return false;
}
/// <summary>
/// Parse the given connection string
/// Connects to Dataverse using CreateWebServiceConnection
/// </summary>
/// <param name="connectionString"></param>
/// <param name="logger">Logging provider <see cref="ILogger"/></param>
internal void ConnectToService(string connectionString, ILogger logger = null)
{
var parsedConnStr = DataverseConnectionStringProcessor.Parse(connectionString, logger);
if (parsedConnStr.AuthenticationType == AuthenticationType.InvalidConnection)
throw new ArgumentException("AuthType is invalid. Please see Microsoft.PowerPlatform.Dataverse.Client.AuthenticationType for supported authentication types.", "AuthType")
{ HelpLink = "https://docs.microsoft.com/powerapps/developer/data-platform/xrm-tooling/use-connection-strings-xrm-tooling-connect" };
var serviceUri = parsedConnStr.ServiceUri;
var networkCredentials = parsedConnStr.ClientCredentials != null && parsedConnStr.ClientCredentials.Windows != null ?
parsedConnStr.ClientCredentials.Windows.ClientCredential : System.Net.CredentialCache.DefaultNetworkCredentials;
string orgName = parsedConnStr.Organization;
if ((parsedConnStr.SkipDiscovery && parsedConnStr.ServiceUri != null) && string.IsNullOrEmpty(orgName))
// Orgname is mandatory if skip discovery is not passed
throw new ArgumentNullException("Dataverse Instance Name or URL name Required",
parsedConnStr.IsOnPremOauth ?
$"Unable to determine instance name to connect to from passed instance Uri. Uri does not match specification for OnPrem instances." :