-
Notifications
You must be signed in to change notification settings - Fork 52
/
Utils.cs
1284 lines (1162 loc) · 56.8 KB
/
Utils.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
#region using
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.PowerPlatform.Dataverse.Client.Model;
using Microsoft.PowerPlatform.Dataverse.Client.Utils;
using Microsoft.Rest;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Metadata;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
#endregion
namespace Microsoft.PowerPlatform.Dataverse.Client
{
/// <summary>
/// Utility functions the ServiceClient assembly.
/// </summary>
internal class Utilities
{
internal static DiscoveryServer GetDiscoveryServerByUri(Uri orgUri)
{
if (orgUri != null)
{
string OnlineRegon = string.Empty;
string OrgName = string.Empty;
bool IsOnPrem = false;
Utilities.GetOrgnameAndOnlineRegionFromServiceUri(orgUri, out OnlineRegon, out OrgName, out IsOnPrem);
if (!string.IsNullOrEmpty(OnlineRegon))
{
using (DiscoveryServers discoSvcs = new DiscoveryServers())
{
return discoSvcs.GetServerByShortName(OnlineRegon);
};
}
}
return null;
}
/// <summary>
/// Get the organization name and on-line region from the Uri
/// </summary>
/// <param name="serviceUri">Service Uri to parse</param>
/// <param name="isOnPrem">if OnPrem, will be set to true, else false.</param>
/// <param name="onlineRegion">Name of the Dataverse Online Region serving this request</param>
/// <param name="organizationName">Name of the Organization extracted from the Service URI</param>
public static void GetOrgnameAndOnlineRegionFromServiceUri(Uri serviceUri, out string onlineRegion, out string organizationName, out bool isOnPrem)
{
isOnPrem = false;
onlineRegion = string.Empty;
organizationName = string.Empty;
//support for detecting a Online URI in the path and rerouting to use that..
if (IsValidOnlineHost(serviceUri))
{
try
{
// Determine deployment region from Uri
List<string> elements = new List<string>(serviceUri.Host.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries));
organizationName = elements[0];
elements.RemoveAt(0); // remove the first ( org name ) from the Uri.
// construct Prospective Dataverse Online path.
System.Text.StringBuilder buildPath = new System.Text.StringBuilder();
foreach (var item in elements)
{
if (item.Equals("api"))
continue; // Skip the .api. when running via this path.
buildPath.AppendFormat("{0}.", item);
}
string dvKey = buildPath.ToString().TrimEnd('.').TrimEnd('/');
buildPath.Clear();
if (!string.IsNullOrEmpty(dvKey))
{
using (DiscoveryServers discoSvcs = new DiscoveryServers())
{
// drop in the discovery region if it can be determined. if not, default to scanning.
var locatedDiscoServer = discoSvcs.OSDPServers.Where(w => w.DiscoveryServerUri != null && w.DiscoveryServerUri.Host.Contains(dvKey)).FirstOrDefault();
if (locatedDiscoServer != null && !string.IsNullOrEmpty(locatedDiscoServer.ShortName))
onlineRegion = locatedDiscoServer.ShortName;
}
}
isOnPrem = false;
}
finally
{ }
}
else
{
isOnPrem = true;
//Setting organization for the AD/Onpremise Oauth/IFD
if (serviceUri.Segments.Count() >= 2)
{
organizationName = serviceUri.Segments[1].TrimEnd('/'); // Fix for bug 294040 http://vstfmbs:8080/tfs/web/wi.aspx?pcguid=12e6d33f-1461-4da4-b3d9-5517a4567489&id=294040
}else
{
// IFD style.
var segementsList = serviceUri.DnsSafeHost.Split('.');
if ( segementsList.Length > 1)
{
organizationName = segementsList[0];
}
}
}
}
/// <summary>
/// returns ( if possible ) the org detail for a given organization name from the list of orgs in discovery
/// </summary>
/// <param name="orgList">OrgList to Parse though</param>
/// <param name="organizationName">Name to find</param>
/// <returns>Found Organization Instance or Null</returns>
public static OrgByServer DeterminOrgDataFromOrgInfo(OrgList orgList, string organizationName)
{
OrgByServer orgDetail = orgList.OrgsList.Where(o => o.OrgDetail.UniqueName.Equals(organizationName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
if (orgDetail == null)
orgDetail = orgList.OrgsList.Where(o => o.OrgDetail.FriendlyName.Equals(organizationName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
// still not found... try by URI name.
if (orgDetail == null)
{
string formatedOrgName = string.Format("://{0}.", organizationName).ToLowerInvariant();
orgDetail = orgList.OrgsList.Where(o => o.OrgDetail.Endpoints[EndpointType.WebApplication].Contains(formatedOrgName)).FirstOrDefault();
}
return orgDetail;
}
/// <summary>
/// returns ( if possible ) the org detail for a given organization name from the list of orgs in discovery
/// </summary>
/// <param name="orgList">OrgList to Parse though</param>
/// <param name="organizationName">Name to find</param>
/// <returns>Found Organization Instance or Null</returns>
public static OrganizationDetail DeterminOrgDataFromOrgInfo(OrganizationDetailCollection orgList, string organizationName)
{
OrganizationDetail orgDetail = orgList.Where(o => o.UniqueName.Equals(organizationName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
if (orgDetail == null)
orgDetail = orgList.Where(o => o.FriendlyName.Equals(organizationName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
// still not found... try by URI name.
if (orgDetail == null)
{
string formatedOrgName = string.Format("://{0}.", organizationName).ToLowerInvariant();
orgDetail = orgList.Where(o => o.Endpoints[EndpointType.WebApplication].Contains(formatedOrgName)).FirstOrDefault();
}
return orgDetail;
}
/// <summary>
/// Parses an OrgURI to determine what the supporting discovery server is.
/// </summary>
/// <param name="serviceUri">Service Uri to parse</param>
/// <param name="Geo">Geo Code for region (Optional)</param>
/// <param name="isOnPrem">if OnPrem, will be set to true, else false.</param>
public static DiscoveryServer DeterminDiscoveryDataFromOrgDetail(Uri serviceUri, out bool isOnPrem, string Geo = null)
{
isOnPrem = false;
//support for detecting a Live/Online URI in the path and rerouting to use that..
if (IsValidOnlineHost(serviceUri))
{
// Check for Geo code and to make sure that the region is not on our internal list.
if (!string.IsNullOrEmpty(Geo)
&& !(serviceUri.Host.ToUpperInvariant().Contains("CRMLIVETIE.COM")
|| serviceUri.Host.ToUpperInvariant().Contains("CRMLIVETODAY.COM"))
)
{
using (DiscoveryServers discoSvcs = new DiscoveryServers())
{
// Find by Geo, if null fall though to next check
var locatedDiscoServer = discoSvcs.OSDPServers.Where(w => !string.IsNullOrEmpty(w.GeoCode) && w.GeoCode == Geo).FirstOrDefault();
if (locatedDiscoServer != null && !string.IsNullOrEmpty(locatedDiscoServer.ShortName))
return locatedDiscoServer;
}
}
try
{
isOnPrem = false;
// Determine deployment region from Uri
List<string> elements = new List<string>(serviceUri.Host.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries));
elements.RemoveAt(0); // remove the first ( org name ) from the Uri.
// construct Prospective Dataverse Online path.
System.Text.StringBuilder buildPath = new System.Text.StringBuilder();
foreach (var item in elements)
{
if (item.Equals("api"))
continue; // Skip the .api. when running via this path.
buildPath.AppendFormat("{0}.", item);
}
string dvKey = buildPath.ToString().TrimEnd('.').TrimEnd('/');
buildPath.Clear();
if (!string.IsNullOrEmpty(dvKey))
{
using (DiscoveryServers discoSvcs = new DiscoveryServers())
{
// drop in the discovery region if it can be determined. if not, default to scanning.
var locatedDiscoServer = discoSvcs.OSDPServers.Where(w => w.DiscoveryServerUri != null && w.DiscoveryServerUri.Host.Contains(dvKey)).FirstOrDefault();
if (locatedDiscoServer != null && !string.IsNullOrEmpty(locatedDiscoServer.ShortName))
return locatedDiscoServer;
}
}
}
finally
{ }
}
else
{
isOnPrem = true;
return null;
}
return null;
}
/// <summary>
/// Looks at the URL provided and determines if the URL is a valid online URI
/// </summary>
/// <param name="hostUri">URI to examine</param>
/// <returns>Returns True if the URI is recognized as online, or false if not.</returns>
public static bool IsValidOnlineHost(Uri hostUri)
{
#if DEBUG
if (hostUri.DnsSafeHost.ToUpperInvariant().Contains("DYNAMICS.COM")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("DYNAMICS-INT.COM")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("MICROSOFTDYNAMICS.DE")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("MICROSOFTDYNAMICS.US")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("APPSPLATFORM.US")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("CRM.DYNAMICS.CN")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("CRMLIVETIE.COM")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("CRMLIVETODAY.COM"))
#else
if (hostUri.DnsSafeHost.ToUpperInvariant().Contains("DYNAMICS.COM")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("MICROSOFTDYNAMICS.DE")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("MICROSOFTDYNAMICS.US")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("APPSPLATFORM.US")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("CRM.DYNAMICS.CN")
|| hostUri.DnsSafeHost.ToUpperInvariant().Contains("DYNAMICS-INT.COM")) // Allows integration Test as well as PRD
#endif
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Determines if the request type can be translated to WebAPI
/// This is a temp method to support the staged transition to the webAPI and will be removed or reintegrated with the overall pipeline at some point in the future.
/// </summary>
/// <param name="req"></param>
/// <param name="inLoginFlow"></param>
/// <returns></returns>
internal static bool IsRequestValidForTranslationToWebAPI(OrganizationRequest req, bool inLoginFlow = false)
{
bool useWebApi = ClientServiceProviders.Instance.GetService<IOptions<ConfigurationOptions>>().Value.UseWebApi;
bool useWebApiForLogin = false;
if (inLoginFlow)
useWebApiForLogin = ClientServiceProviders.Instance.GetService<IOptions<ConfigurationOptions>>().Value.UseWebApiLoginFlow;
switch (req.RequestName.ToLowerInvariant())
{
case "create":
case "update":
case "delete":
case "importsolution":
case "exportsolution":
case "stagesolution":
return useWebApi; // Only supported with useWebApi flag
case "retrievecurrentorganization":
case "retrieveorganizationinfo":
case "retrieveversion":
case "whoami":
return useWebApiForLogin; // Separate webAPI login methods from general WebAPI use.
case "upsert":
// Disabling WebAPI support for upsert right now due to issues with generating the response.
// avoid bug in WebAPI around Support for key's as EntityRefeances //TODO: TEMP
//Xrm.Sdk.Messages.UpsertRequest upsert = (Xrm.Sdk.Messages.UpsertRequest)req;
//if (upsert.Target.KeyAttributes?.Any(a => a.Value is string) != true)
// return false;
//else
//return true;
default:
return false;
}
}
/// <summary>
/// Returns Http request method based on request message name
/// </summary>
/// <param name="requestName">request name</param>
/// <returns>Http method</returns>
internal static HttpMethod RequestNameToHttpVerb(string requestName)
{
if (string.IsNullOrWhiteSpace(requestName))
throw new ArgumentNullException(nameof(requestName));
switch (requestName.ToLowerInvariant())
{
case "retrievecurrentorganization":
case "retrieveorganizationinfo":
case "retrieveversion":
case "retrieveuserlicenseinfo":
case "whoami":
return HttpMethod.Get;
case "create":
case "importsolution":
case "exportsolution":
case "stagesolution":
return HttpMethod.Post;
case "update":
case "upsert":
return new HttpMethod("Patch");
case "delete":
return HttpMethod.Delete;
default:
return null;
}
}
/// <summary>
/// Constructs Web API request url and adds public request properties to the url as key/value pairs
/// </summary>
internal static string ConstructWebApiRequestUrl(OrganizationRequest request, HttpMethod httpMethod, Entity entity, EntityMetadata entityMetadata)
{
var result = new StringBuilder();
if (httpMethod != HttpMethod.Post)
{
if (entity != null)
{
if (entity.KeyAttributes?.Any() == true)
{
result.Append($"{entityMetadata.EntitySetName}({Utilities.ParseAltKeyCollection(entity.KeyAttributes)})");
}
else
{
result.Append($"{entityMetadata.EntitySetName}({entity.Id})");
}
}
else // Add public properties to Url
{
result.Append(request.RequestName);
bool hasProperties = false;
object propertyValue;
foreach (var property in request.GetType().GetProperties())
{
if (property.DeclaringType == typeof(OrganizationRequest))
continue;
propertyValue = property.GetValue(request);
if (propertyValue == null)
continue;
if (!hasProperties)
{
result.Append("(");
hasProperties = true;
}
else
{
result.Append(",");
}
result.Append(property.Name);
result.Append("='");
result.Append(propertyValue.ToString());
result.Append("'");
}
if (hasProperties)
{
result.Append(")");
}
}
}
else
{
if (entityMetadata != null)
{
result.Append(entityMetadata.EntitySetName);
}
else
{
result.Append(request.RequestName);
}
}
return result.ToString();
}
/// <summary>
/// retry request
/// </summary>
/// <param name="req">request</param>
/// <param name="requestTrackingId">requestTrackingId</param>
/// <param name="LockWait">LockWait</param>
/// <param name="logDt">logDt</param>
/// <param name="logEntry">Dataverse TraceLogger</param>
/// <param name="sessionTrackingId">sessionTrackingId</param>
/// <param name="disableConnectionLocking">disableConnectionLocking</param>
/// <param name="retryPauseTimeRunning">retryPauseTimeRunning</param>
/// <param name="ex">ex</param>
/// <param name="errorStringCheck">errorStringCheck</param>
/// <param name="retryCount">retryCount</param>
/// <param name="isThrottled">when set indicated this was caused by a Throttle</param>
/// <param name="webUriReq"></param>
internal static void RetryRequest(OrganizationRequest req, Guid requestTrackingId, TimeSpan LockWait, Stopwatch logDt,
DataverseTraceLogger logEntry, Guid? sessionTrackingId, bool disableConnectionLocking, TimeSpan retryPauseTimeRunning,
Exception ex, string errorStringCheck, ref int retryCount, bool isThrottled, string webUriReq = "")
{
retryCount++;
logEntry.LogFailure(req, requestTrackingId, sessionTrackingId, disableConnectionLocking, LockWait, logDt, ex, errorStringCheck, webUriMessageReq: webUriReq);
logEntry.LogRetry(retryCount, req, retryPauseTimeRunning, isThrottled: isThrottled);
System.Threading.Thread.Sleep(retryPauseTimeRunning);
}
/// <summary>
/// Parses an attribute array into a object that can be used to create a JSON request.
/// </summary>
/// <param name="sourceEntity">Entity to process</param>
/// <param name="mUtil">Metadata interface utility</param>
/// <param name="requestedMethod">Operation being executed</param>
/// <param name="logger">Log sink</param>
/// <returns>ExpandoObject</returns>
internal static ExpandoObject ToExpandoObject(Entity sourceEntity, MetadataUtility mUtil, HttpMethod requestedMethod, DataverseTraceLogger logger )
{
dynamic expando = new ExpandoObject();
// Check for primary Id info:
if (sourceEntity.Id != Guid.Empty)
sourceEntity = UpdateEntityAttributesForPrimaryId(sourceEntity, mUtil);
AttributeCollection entityAttributes = sourceEntity.Attributes;
if (!(entityAttributes != null) && (entityAttributes.Count > 0))
{
return expando;
}
var expandoObject = (IDictionary<string, object>)expando;
var attributes = entityAttributes.ToArray();
// this is used to support ActivityParties collections
List<ExpandoObject> partiesCollection = null;
foreach (var attrib in entityAttributes)
{
var keyValuePair = attrib;
var value = keyValuePair.Value;
var key = keyValuePair.Key;
if (value is EntityReference entityReference)
{
var attributeInfo = mUtil.GetAttributeMetadata(sourceEntity.LogicalName, key.ToLower());
if (!IsAttributeValidForOperation(attributeInfo, requestedMethod))
continue;
// Get Lookup attribute meta data for the ER to check for polymorphic relationship.
if (attributeInfo is LookupAttributeMetadata attribData)
{
// Now get relationship to make sure we use the correct name.
EntityMetadata eData = mUtil.GetEntityMetadata(EntityFilters.Relationships, sourceEntity.LogicalName);
string ERNavName = eData.ManyToOneRelationships.FirstOrDefault(w => w.ReferencingAttribute.Equals(attribData.LogicalName) &&
w.ReferencedEntity.Equals(entityReference.LogicalName))
?.ReferencingEntityNavigationPropertyName;
if (string.IsNullOrEmpty(ERNavName ))
{
ERNavName = eData.ManyToOneRelationships.FirstOrDefault(w => w.ReferencingAttribute.Equals(attribData.LogicalName))?.ReferencingEntityNavigationPropertyName;
}
if (!string.IsNullOrEmpty(ERNavName))
{
key = ERNavName;
}
else
{
logger.Log($"{key} describes an entity reference but does not have a corresponding relationship. Skipping adding it in the {requestedMethod} operation");
continue;
}
// Populate Key property
key = $"{key}@odata.bind";
}
else if (attributeInfo == null)
{
// Fault here.
throw new DataverseOperationException($"Entity Reference {key.ToLower()} was not found for entity {sourceEntity.LogicalName}.", null);
}
string entityReferanceValue = string.Empty;
// process ER Value
if (entityReference.KeyAttributes?.Any() == true)
{
entityReferanceValue = ParseAltKeyCollection(entityReference.KeyAttributes);
}
else
{
entityReferanceValue = entityReference.Id.ToString();
}
value = $"/{mUtil.GetEntityMetadata(EntityFilters.Entity, entityReference.LogicalName).EntitySetName}({entityReferanceValue})";
}
else
{
if (value is EntityCollection || value is Entity[])
{
if (value is Entity[] v1s)
{
EntityCollection ec = new EntityCollection(((Entity[])value).ToList<Entity>());
value = ec;
}
// try to get the participation type id from the key.
int PartyTypeId = PartyListHelper.GetParticipationtypeMasks(key);
bool isActivityParty = PartyTypeId != -1; // if the partytypeID is -1 this is not a activity party collection.
if (isActivityParty && partiesCollection == null)
partiesCollection = new List<ExpandoObject>(); // Only build it when needed.
// build linked collection here.
foreach (var ent in (value as EntityCollection).Entities)
{
ExpandoObject rslt = ToExpandoObject(ent, mUtil, requestedMethod , logger);
if (isActivityParty)
{
var tempDict = ((IDictionary<string, object>)rslt);
if (!tempDict.ContainsKey("participationtypemask"))
tempDict.Add("participationtypemask", PartyTypeId);
partiesCollection.Add((ExpandoObject)tempDict);
}
}
if (isActivityParty)
continue;
// Note.. if this is not an activity party but instead an embedded entity.. this will fall though and fail with trying to embed an entity.
}
else
{
key = key.ToLower();
if (value is OptionSetValueCollection optionSetValues)
{
string mselectValueString = string.Empty;
foreach (var opt in optionSetValues)
{
mselectValueString += $"{opt.Value},";
}
if (!string.IsNullOrEmpty(mselectValueString) && mselectValueString.Last().Equals(','))
value = mselectValueString.Remove(mselectValueString.Length - 1);
else
value = null;
}
else if (value is OptionSetValue optionSetValue)
{
value = optionSetValue.Value.ToString();
}
else if (value is DateTime dateTimeValue)
{
var attributeInfo = mUtil.GetAttributeMetadata(sourceEntity.LogicalName, key.ToLower());
if (attributeInfo is DateTimeAttributeMetadata attribDateTimeData)
{
if (attribDateTimeData.DateTimeBehavior == DateTimeBehavior.DateOnly)
{
value = dateTimeValue.ToUniversalTime().ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
else
{
if (attribDateTimeData.DateTimeBehavior == DateTimeBehavior.TimeZoneIndependent)
{
value = dateTimeValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
}
else
{
if (attribDateTimeData.DateTimeBehavior == DateTimeBehavior.UserLocal)
{
value = dateTimeValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
}
}
}
}
}
else if (value is Money moneyValue)
{
value = moneyValue.Value;
}
else if (value is bool boolValue)
{
value = boolValue.ToString();
}
else if (value is Guid guidValue)
{
value = guidValue.ToString();
}
else if (value is null)
{
var attributeInfo = mUtil.GetAttributeMetadata(sourceEntity.LogicalName, key.ToLower());
if (!IsAttributeValidForOperation((AttributeMetadata)attributeInfo, requestedMethod))
continue;
if (attributeInfo is Xrm.Sdk.Metadata.LookupAttributeMetadata attribData)
{
// This will not work for Polymorphic currently.
var eData = mUtil.GetEntityMetadata(EntityFilters.Relationships, sourceEntity.LogicalName);
var ERNavName = eData.ManyToOneRelationships.FirstOrDefault(w => w.ReferencingAttribute.Equals(attribData.LogicalName) &&
w.ReferencedEntity.Equals(attribData.Targets.FirstOrDefault()))
?.ReferencingEntityNavigationPropertyName;
if (!string.IsNullOrEmpty(ERNavName))
key = ERNavName;
// Populate Key property
key = $"{key}@odata.bind";
}
value = null;
}
}
}
expandoObject.Add(key, value);
}
// Check to see if this contained an activity party
if (partiesCollection?.Count > 0)
{
var sourceMdata = mUtil.GetEntityMetadata(sourceEntity.LogicalName);
if (sourceMdata != null )
expandoObject.Add($"{sourceMdata.LogicalName}_activity_parties", partiesCollection);
}
return (ExpandoObject)expandoObject;
}
/// <summary>
/// Checks if the operation being preformed is permitted for the attribute.
/// </summary>
/// <param name="attrib"></param>
/// <param name="requestedMethod"></param>
/// <returns></returns>
private static bool IsAttributeValidForOperation(AttributeMetadata attrib, HttpMethod requestedMethod)
{
switch (requestedMethod.ToString().ToLowerInvariant())
{
case "post":
case "put":
if (attrib.IsValidForCreate.HasValue && !attrib.IsValidForCreate.Value)
return false;
break;
case "patch":
if (attrib.IsValidForUpdate.HasValue && !attrib.IsValidForUpdate.Value)
return false;
break;
default:
break;
}
return true;
}
/// <summary>
/// checks to see if an attribute has been added to the collection containing the ID of the entity .
/// this is required for the WebAPI to properly function.
/// </summary>
/// <param name="sourceEntity"></param>
/// <param name="mUtil"></param>
/// <returns></returns>
private static Entity UpdateEntityAttributesForPrimaryId(Entity sourceEntity, MetadataUtility mUtil)
{
if (sourceEntity.Id != Guid.Empty)
{
var entMeta = mUtil.GetEntityMetadata(sourceEntity.LogicalName);
sourceEntity.Attributes[entMeta.PrimaryIdAttribute] = sourceEntity.Id;
}
return sourceEntity;
}
/// <summary>
/// Handle general related entity collection construction
/// </summary>
/// <param name="rootExpando">Object being added too</param>
/// <param name="entityName">parent entity</param>
/// <param name="entityCollection">collection of relationships</param>
/// <param name="mUtil">meta-data utility</param>
/// <param name="requestedMethod">Operation being executed</param>
/// <param name="logger">Logger</param>
/// <returns></returns>
internal static ExpandoObject ReleatedEntitiesToExpandoObject(ExpandoObject rootExpando, string entityName, RelatedEntityCollection entityCollection, MetadataUtility mUtil, HttpMethod requestedMethod, DataverseTraceLogger logger)
{
if (rootExpando == null)
return rootExpando;
if (entityCollection != null && entityCollection.Count == 0)
{
// nothing to do, just return.
return rootExpando;
}
foreach (var entItem in entityCollection)
{
string key = "";
bool isArrayRequired = false;
dynamic expando = new ExpandoObject();
var expandoObject = (IDictionary<string, object>)expando;
ExpandoObject childEntities = new ExpandoObject();
List<ExpandoObject> childCollection = new List<ExpandoObject>();
// Get the Entity relationship key and entity and reverse it back to the entity key name
var eData = mUtil.GetEntityMetadata(EntityFilters.Relationships, entItem.Value.Entities[0].LogicalName);
key = ExtractKeyNameFromRelationship(entItem.Key.SchemaName.ToLower(), entityName, ref isArrayRequired, eData);
if (string.IsNullOrEmpty(key)) // Failed to find key
{
throw new DataverseOperationException($"Relationship key {entItem.Key.SchemaName} cannot be found for related entities of {entityName}.");
}
foreach (var ent in entItem.Value.Entities)
{
// Check to see if the entity itself has related entities
if (ent.RelatedEntities != null && ent.RelatedEntities.Count > 0)
{
childEntities = ReleatedEntitiesToExpandoObject(childEntities, entityName, ent.RelatedEntities, mUtil, requestedMethod, logger);
}
// generate object.
ExpandoObject ent1 = ToExpandoObject(ent, mUtil, requestedMethod, logger);
if (((IDictionary<string, object>)childEntities).Count() > 0)
{
foreach (var item in childEntities)
{
((IDictionary<string, object>)ent1).Add(item.Key, item.Value);
}
}
childCollection?.Add(ent1);
}
if (childCollection.Count == 1 && isArrayRequired == false)
((IDictionary<string, object>)rootExpando).Add(key, childCollection[0]);
else
((IDictionary<string, object>)rootExpando).Add(key, childCollection);
}
return rootExpando;
}
/// <summary>
/// Helper to extract key name from one of the relationships.
/// </summary>
/// <param name="schemaName"></param>
/// <param name="entityName"></param>
/// <param name="isArrayRequired"></param>
/// <param name="eData"></param>
/// <returns></returns>
private static string ExtractKeyNameFromRelationship(string schemaName, string entityName, ref bool isArrayRequired, EntityMetadata eData)
{
string key = "";
// Find the relationship that is referenced.
OneToManyRelationshipMetadata ERM21 = eData.ManyToOneRelationships.FirstOrDefault(w1 => w1.SchemaName.ToLower().Equals(schemaName.ToLower()));
ManyToManyRelationshipMetadata ERM2M = eData.ManyToManyRelationships.FirstOrDefault(w2 => w2.SchemaName.ToLower().Equals(schemaName.ToLower()));
OneToManyRelationshipMetadata ER12M = eData.OneToManyRelationships.FirstOrDefault(w3 => w3.SchemaName.ToLower().Equals(schemaName.ToLower()));
// Determine which one hit
if (ERM21 != null)
{
isArrayRequired = true;
key = ERM21.ReferencedEntityNavigationPropertyName;
}
else if (ERM2M != null)
{
isArrayRequired = true;
if (ERM2M.Entity1LogicalName.ToLower().Equals(entityName))
{
key = ERM2M.Entity1NavigationPropertyName;
}
else
{
key = ERM2M.Entity2NavigationPropertyName;
}
}
else if (ER12M != null)
{
key = ER12M.ReferencingAttribute;
}
return key;
}
/// <summary>
/// Parses Key attribute collection for alt key support.
/// </summary>
/// <param name="keyValues">alt key's for object</param>
/// <returns>webAPI compliant key string</returns>
internal static string ParseAltKeyCollection(KeyAttributeCollection keyValues)
{
string keycollection = string.Empty;
foreach (var itm in keyValues)
{
if (itm.Value is EntityReference er)
{
keycollection += $"_{itm.Key}_value={er.Id.ToString("P")},";
}
else
{
if (itm.Value is int iValue)
{
keycollection += $"{itm.Key}={iValue.ToString(CultureInfo.InvariantCulture)},";
}
else if (itm.Value is float fValue)
{
keycollection += $"{itm.Key}={fValue.ToString(CultureInfo.InvariantCulture)},";
}
else if (itm.Value is OptionSetValue oValue)
{
keycollection += $"{itm.Key}={oValue.Value},";
}
else if (itm.Value is DateTime dtValue) // Note : Should work for 'datetime types' may not work for date only types.
{
keycollection += $"{itm.Key}={dtValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture)},";
}
else
keycollection += $"{itm.Key}='{itm.Value?.ToString().Replace("'", "''")}',";
}
}
return keycollection.Remove(keycollection.Length - 1); // remove trailing ,
}
/// <summary>
/// List of entities to retry retrieves on.
/// </summary>
private static List<string> _autoRetryRetrieveEntityList = null;
/// <summary>
/// if the Incoming query has an entity on the retry list, returns true. else returns false.
/// </summary>
/// <param name="queryStringToParse">string containing entity name to check against</param>
/// <returns>true if found, false if not</returns>
internal static bool ShouldAutoRetryRetrieveByEntityName(string queryStringToParse)
{
if (_autoRetryRetrieveEntityList == null)
{
_autoRetryRetrieveEntityList = new List<string>
{
"asyncoperation", // to support failures when looking for async Jobs.
"importjob" // to support failures when looking for importjob.
};
}
foreach (var itm in _autoRetryRetrieveEntityList)
{
if (queryStringToParse.Contains(itm)) return true;
}
return false;
}
/// <summary>
/// Creates or Adds scopes and returns the current scope
/// </summary>
/// <param name="scopeToAdd"></param>
/// <param name="currentScopes"></param>
/// <returns></returns>
internal static List<string> AddScope(string scopeToAdd, List<string> currentScopes = null)
{
if (currentScopes == null)
currentScopes = new List<string>();
if (!currentScopes.Contains(scopeToAdd))
{
currentScopes.Add(scopeToAdd);
}
return currentScopes;
}
/// <summary>
/// Request Headers used by comms to Dataverse
/// </summary>
internal static class RequestHeaders
{
/// <summary>
/// Populated with the host process
/// </summary>
public const string USER_AGENT_HTTP_HEADER = "User-Agent";
/// <summary>
/// Session ID used to track all operations associated with a given group of calls.
/// </summary>
public const string X_MS_CLIENT_SESSION_ID = "x-ms-client-session-id";
/// <summary>
/// PerRequest ID used to track a specific request.
/// </summary>
public const string X_MS_CLIENT_REQUEST_ID = "x-ms-client-request-id";
/// <summary>
/// Content type of WebAPI request.
/// </summary>
public const string CONTENT_TYPE = "Content-Type";
/// <summary>
/// Header loaded with the AADObjectID of the user to impersonate
/// </summary>
public const string AAD_CALLER_OBJECT_ID_HTTP_HEADER = "CallerObjectId";
/// <summary>
/// Header loaded with the Dataverse user ID of the user to impersonate
/// </summary>
public const string CALLER_OBJECT_ID_HTTP_HEADER = "MSCRMCallerID";
/// <summary>
/// Header used to pass the token for the user
/// </summary>
public const string AUTHORIZATION_HEADER = "Authorization";
/// <summary>
/// Header requesting the connection be kept alive.
/// </summary>
public const string CONNECTION_KEEP_ALIVE = "Keep-Alive";
/// <summary>
/// Header requiring Cache Consistency Server side.
/// </summary>
public const string FORCE_CONSISTENCY = "Consistency";
/// <summary>
/// This key used to indicate if the custom plugins need to be bypassed during the execution of the request.
/// </summary>
public const string BYPASSCUSTOMPLUGINEXECUTION = "BypassCustomPluginExecution";
/// <summary>
/// key used to apply the operation to a given solution.
/// See: https://docs.microsoft.com/powerapps/developer/common-data-service/org-service/use-messages#passing-optional-parameters-with-a-request
/// </summary>
public const string SOLUTIONUNIQUENAME = "SolutionUniqueName";
/// <summary>
/// used to apply duplicate detection behavior to a given request.
/// See: https://docs.microsoft.com/powerapps/developer/common-data-service/org-service/use-messages#passing-optional-parameters-with-a-request
/// </summary>
public const string SUPPRESSDUPLICATEDETECTION = "SuppressDuplicateDetection";
/// <summary>
/// used to pass data though Dataverse to a plugin or downstream system on a request.
/// See: https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/org-service/use-messages#add-a-shared-variable-from-the-organization-service
/// </summary>
public const string TAG = "tag";
/// <summary>
/// used to identify concurrencybehavior property in an organization request.
/// </summary>
public const string CONCURRENCYBEHAVIOR = "ConcurrencyBehavior";
/// <summary>
/// Dataverse Platform Property Prefix
/// </summary>
public const string DATAVERSEHEADERPROPERTYPREFIX = "MSCRM.";
}
internal static class ResponseHeaders
{
/// <summary>
/// Recomended number of client connection threads Hint
/// </summary>
public const string RECOMMENDEDDEGREESOFPARALLELISM = "x-ms-dop-hint";
/// <summary>
/// header for Cookie's
/// </summary>
public const string SETCOOKIE = "Set-Cookie";
}
/// <summary>
/// Minim Version numbers for various features of Dataverse API's.
/// </summary>
internal static class FeatureVersionMinimums
{
/// <summary>
/// returns true of the feature version is valid for this environment.
/// </summary>
/// <param name="instanceVersion">Instance version of the Dataverse Instance</param>
/// <param name="featureVersion">MinFeatureVersion</param>
/// <returns></returns>
internal static bool IsFeatureValidForEnviroment(Version instanceVersion, Version featureVersion)
{
if (instanceVersion != null && (instanceVersion >= featureVersion))
return true;
else
return false;
}