This repository has been archived by the owner on Jun 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 183
/
XrmFakedContext.Queries.cs
2223 lines (1882 loc) · 103 KB
/
XrmFakedContext.Queries.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.ServiceModel;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using FakeXrmEasy.Extensions;
using FakeXrmEasy.Extensions.FetchXml;
using FakeXrmEasy.Models;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
namespace FakeXrmEasy
{
public partial class XrmFakedContext : IXrmContext
{
protected internal Type FindReflectedType(string logicalName)
{
var types =
ProxyTypesAssemblies.Select(a => FindReflectedType(logicalName, a))
.Where(t => t != null);
if (types.Count() > 1)
{
var errorMsg = $"Type { logicalName } is defined in multiple assemblies: ";
foreach (var type in types)
{
errorMsg += type.Assembly
.GetName()
.Name + "; ";
}
var lastIndex = errorMsg.LastIndexOf("; ");
errorMsg = errorMsg.Substring(0, lastIndex) + ".";
throw new InvalidOperationException(errorMsg);
}
return types.SingleOrDefault();
}
/// <summary>
/// Finds reflected type for given entity from given assembly.
/// </summary>
/// <param name="logicalName">
/// Entity logical name which type is searched from given
/// <paramref name="assembly"/>.
/// </param>
/// <param name="assembly">
/// Assembly where early-bound type is searched for given
/// <paramref name="logicalName"/>.
/// </param>
/// <returns>
/// Early-bound type of <paramref name="logicalName"/> if it's found
/// from <paramref name="assembly"/>. Otherwise null is returned.
/// </returns>
private static Type FindReflectedType(string logicalName,
Assembly assembly)
{
try
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
/* This wasn't building within the CI FAKE build script...
var subClassType = assembly.GetTypes()
.Where(t => typeof(Entity).IsAssignableFrom(t))
.Where(t => t.GetCustomAttributes<EntityLogicalNameAttribute>(true).Any())
.FirstOrDefault(t => t.GetCustomAttributes<EntityLogicalNameAttribute>(true).First().LogicalName.Equals(logicalName, StringComparison.OrdinalIgnoreCase));
*/
var subClassType = assembly.GetTypes()
.Where(t => typeof(Entity).IsAssignableFrom(t))
.Where(t => t.GetCustomAttributes(typeof(EntityLogicalNameAttribute), true).Length > 0)
.Where(t => ((EntityLogicalNameAttribute)t.GetCustomAttributes(typeof(EntityLogicalNameAttribute), true)[0]).LogicalName.Equals(logicalName.ToLower()))
.FirstOrDefault();
return subClassType;
}
catch (ReflectionTypeLoadException exception)
{
// now look at ex.LoaderExceptions - this is an Exception[], so:
var s = "";
foreach (var innerException in exception.LoaderExceptions)
{
// write details of "inner", in particular inner.Message
s += innerException.Message + " ";
}
throw new Exception("XrmFakedContext.FindReflectedType: " + s);
}
}
protected internal Type FindAttributeTypeInInjectedMetadata(string sEntityName, string sAttributeName)
{
if (!EntityMetadata.ContainsKey(sEntityName))
return null;
if (EntityMetadata[sEntityName].Attributes == null)
return null;
var attribute = EntityMetadata[sEntityName].Attributes
.Where(a => a.LogicalName == sAttributeName)
.FirstOrDefault();
if (attribute == null)
return null;
if (attribute.AttributeType == null)
return null;
switch (attribute.AttributeType.Value)
{
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.BigInt:
return typeof(long);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Integer:
return typeof(int);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Boolean:
return typeof(bool);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.CalendarRules:
throw new Exception("CalendarRules: Type not yet supported");
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Lookup:
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Customer:
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Owner:
return typeof(EntityReference);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.DateTime:
return typeof(DateTime);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Decimal:
return typeof(decimal);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Double:
return typeof(double);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.EntityName:
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Memo:
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.String:
return typeof(string);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Money:
return typeof(Money);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.PartyList:
return typeof(EntityReferenceCollection);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Picklist:
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.State:
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Status:
return typeof(OptionSetValue);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Uniqueidentifier:
return typeof(Guid);
case Microsoft.Xrm.Sdk.Metadata.AttributeTypeCode.Virtual:
#if FAKE_XRM_EASY_9
if (attribute.AttributeTypeName.Value == "MultiSelectPicklistType")
{
return typeof(OptionSetValueCollection);
}
#endif
throw new Exception("Virtual: Type not yet supported");
default:
return typeof(string);
}
}
protected internal Type FindReflectedAttributeType(Type earlyBoundType, string sEntityName, string attributeName)
{
//Get that type properties
var attributeInfo = GetEarlyBoundTypeAttribute(earlyBoundType, attributeName);
if (attributeInfo == null && attributeName.EndsWith("name"))
{
// Special case for referencing the name of a EntityReference
attributeName = attributeName.Substring(0, attributeName.Length - 4);
attributeInfo = GetEarlyBoundTypeAttribute(earlyBoundType, attributeName);
if (attributeInfo.PropertyType != typeof(EntityReference))
{
// Don't mess up if other attributes follow this naming pattern
attributeInfo = null;
}
}
if (attributeInfo == null || attributeInfo.PropertyType.FullName == null)
{
//Try with metadata
var injectedType = FindAttributeTypeInInjectedMetadata(sEntityName, attributeName);
if (injectedType == null)
{
throw new Exception($"XrmFakedContext.FindReflectedAttributeType: Attribute {attributeName} not found for type {earlyBoundType}");
}
return injectedType;
}
if (attributeInfo.PropertyType.FullName.EndsWith("Enum") || attributeInfo.PropertyType.BaseType.FullName.EndsWith("Enum"))
{
return typeof(int);
}
if (!attributeInfo.PropertyType.FullName.StartsWith("System."))
{
try
{
var instance = Activator.CreateInstance(attributeInfo.PropertyType);
if (instance is Entity)
{
return typeof(EntityReference);
}
}
catch
{
// ignored
}
}
#if FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 || FAKE_XRM_EASY_9
else if (attributeInfo.PropertyType.FullName.StartsWith("System.Nullable"))
{
return attributeInfo.PropertyType.GenericTypeArguments[0];
}
#endif
return attributeInfo.PropertyType;
}
private static PropertyInfo GetEarlyBoundTypeAttribute(Type earlyBoundType, string attributeName)
{
var attributeInfo = earlyBoundType.GetProperties()
.Where(pi => pi.GetCustomAttributes(typeof(AttributeLogicalNameAttribute), true).Length > 0)
.Where(pi => (pi.GetCustomAttributes(typeof(AttributeLogicalNameAttribute), true)[0] as AttributeLogicalNameAttribute).LogicalName.Equals(attributeName))
.FirstOrDefault();
return attributeInfo;
}
public IQueryable<Entity> CreateQuery(string entityLogicalName)
{
return this.CreateQuery<Entity>(entityLogicalName);
}
public IQueryable<T> CreateQuery<T>()
where T : Entity
{
var typeParameter = typeof(T);
if (ProxyTypesAssembly == null)
{
//Try to guess proxy types assembly
var assembly = Assembly.GetAssembly(typeof(T));
if (assembly != null)
{
ProxyTypesAssembly = assembly;
}
}
var logicalName = "";
if (typeParameter.GetCustomAttributes(typeof(EntityLogicalNameAttribute), true).Length > 0)
{
logicalName = (typeParameter.GetCustomAttributes(typeof(EntityLogicalNameAttribute), true)[0] as EntityLogicalNameAttribute).LogicalName;
}
return this.CreateQuery<T>(logicalName);
}
protected IQueryable<T> CreateQuery<T>(string entityLogicalName)
where T : Entity
{
var subClassType = FindReflectedType(entityLogicalName);
if (subClassType == null && !(typeof(T) == typeof(Entity)) || (typeof(T) == typeof(Entity) && string.IsNullOrWhiteSpace(entityLogicalName)))
{
throw new Exception($"The type {entityLogicalName} was not found");
}
var lst = new List<T>();
if (!Data.ContainsKey(entityLogicalName))
{
return lst.AsQueryable(); //Empty list
}
foreach (var e in Data[entityLogicalName].Values)
{
if (subClassType != null)
{
var cloned = e.Clone(subClassType);
lst.Add((T)cloned);
}
else
lst.Add((T)e.Clone());
}
return lst.AsQueryable();
}
public IQueryable<Entity> CreateQueryFromEntityName(string entityName)
{
return Data[entityName].Values.AsQueryable();
}
public static IQueryable<Entity> TranslateLinkedEntityToLinq(XrmFakedContext context, LinkEntity le, IQueryable<Entity> query, ColumnSet previousColumnSet, Dictionary<string, int> linkedEntities, string linkFromAlias = "", string linkFromEntity = "")
{
if (!string.IsNullOrEmpty(le.EntityAlias))
{
if (!Regex.IsMatch(le.EntityAlias, "^[A-Za-z_](\\w|\\.)*$", RegexOptions.ECMAScript))
{
FakeOrganizationServiceFault.Throw(ErrorCodes.QueryBuilderInvalid_Alias, $"Invalid character specified for alias: {le.EntityAlias}. Only characters within the ranges [A-Z], [a-z] or [0-9] or _ are allowed. The first character may only be in the ranges [A-Z], [a-z] or _.");
}
}
var leAlias = string.IsNullOrWhiteSpace(le.EntityAlias) ? le.LinkToEntityName : le.EntityAlias;
context.EnsureEntityNameExistsInMetadata(le.LinkFromEntityName != linkFromAlias ? le.LinkFromEntityName : linkFromEntity);
context.EnsureEntityNameExistsInMetadata(le.LinkToEntityName);
if (!context.AttributeExistsInMetadata(le.LinkToEntityName, le.LinkToAttributeName))
{
FakeOrganizationServiceFault.Throw(ErrorCodes.QueryBuilderNoAttribute, string.Format("The attribute {0} does not exist on this entity.", le.LinkToAttributeName));
}
IQueryable<Entity> inner = null;
if (le.JoinOperator == JoinOperator.LeftOuter)
{
//inner = context.CreateQuery<Entity>(le.LinkToEntityName);
//filters are applied in the inner query and then ignored during filter evaluation
var outerQueryExpression = new QueryExpression()
{
EntityName = le.LinkToEntityName,
Criteria = le.LinkCriteria,
ColumnSet = new ColumnSet(true)
};
var outerQuery = TranslateQueryExpressionToLinq(context, outerQueryExpression);
inner = outerQuery;
}
else
{
//Filters are applied after joins
inner = context.CreateQuery<Entity>(le.LinkToEntityName);
}
//if (!le.Columns.AllColumns && le.Columns.Columns.Count == 0)
//{
// le.Columns.AllColumns = true; //Add all columns in the joined entity, otherwise we can't filter by related attributes, then the Select will actually choose which ones we need
//}
if (string.IsNullOrWhiteSpace(linkFromAlias))
{
linkFromAlias = le.LinkFromAttributeName;
}
else
{
linkFromAlias += "." + le.LinkFromAttributeName;
}
switch (le.JoinOperator)
{
case JoinOperator.Inner:
case JoinOperator.Natural:
query = query.Join(inner,
outerKey => outerKey.KeySelector(linkFromAlias, context),
innerKey => innerKey.KeySelector(le.LinkToAttributeName, context),
(outerEl, innerEl) => outerEl.Clone(outerEl.GetType(), context).JoinAttributes(innerEl, new ColumnSet(true), leAlias, context));
break;
case JoinOperator.LeftOuter:
query = query.GroupJoin(inner,
outerKey => outerKey.KeySelector(linkFromAlias, context),
innerKey => innerKey.KeySelector(le.LinkToAttributeName, context),
(outerEl, innerElemsCol) => new { outerEl, innerElemsCol })
.SelectMany(x => x.innerElemsCol.DefaultIfEmpty()
, (x, y) => x.outerEl
.JoinAttributes(y, new ColumnSet(true), leAlias, context));
break;
default: //This shouldn't be reached as there are only 3 types of Join...
throw new PullRequestException(string.Format("The join operator {0} is currently not supported. Feel free to implement and send a PR.", le.JoinOperator));
}
// Process nested linked entities recursively
foreach (var nestedLinkedEntity in le.LinkEntities)
{
if (string.IsNullOrWhiteSpace(le.EntityAlias))
{
le.EntityAlias = le.LinkToEntityName;
}
if (string.IsNullOrWhiteSpace(nestedLinkedEntity.EntityAlias))
{
nestedLinkedEntity.EntityAlias = EnsureUniqueLinkedEntityAlias(linkedEntities, nestedLinkedEntity.LinkToEntityName);
}
query = TranslateLinkedEntityToLinq(context, nestedLinkedEntity, query, le.Columns, linkedEntities, le.EntityAlias, le.LinkToEntityName);
}
return query;
}
private static string EnsureUniqueLinkedEntityAlias(IDictionary<string, int> linkedEntities, string entityName)
{
if (linkedEntities.ContainsKey(entityName))
{
linkedEntities[entityName]++;
}
else
{
linkedEntities[entityName] = 1;
}
return $"{entityName}{linkedEntities[entityName]}";
}
protected static XElement RetrieveFetchXmlNode(XDocument xlDoc, string sName)
{
return xlDoc.Descendants().Where(e => e.Name.LocalName.Equals(sName)).FirstOrDefault();
}
public static XDocument ParseFetchXml(string fetchXml)
{
try
{
return XDocument.Parse(fetchXml);
}
catch (Exception ex)
{
throw new Exception(string.Format("FetchXml must be a valid XML document: {0}", ex.ToString()));
}
}
public static QueryExpression TranslateFetchXmlToQueryExpression(XrmFakedContext context, string fetchXml)
{
return TranslateFetchXmlDocumentToQueryExpression(context, ParseFetchXml(fetchXml));
}
public static QueryExpression TranslateFetchXmlDocumentToQueryExpression(XrmFakedContext context, XDocument xlDoc)
{
//Validate nodes
if (!xlDoc.Descendants().All(el => el.IsFetchXmlNodeValid()))
throw new Exception("At least some node is not valid");
//Root node
if (!xlDoc.Root.Name.LocalName.Equals("fetch"))
{
throw new Exception("Root node must be fetch");
}
var entityNode = RetrieveFetchXmlNode(xlDoc, "entity");
var query = new QueryExpression(entityNode.GetAttribute("name").Value);
query.ColumnSet = xlDoc.ToColumnSet();
// Ordering is done after grouping/aggregation
if (!xlDoc.IsAggregateFetchXml())
{
var orders = xlDoc.ToOrderExpressionList();
foreach (var order in orders)
{
query.AddOrder(order.AttributeName, order.OrderType);
}
}
query.Distinct = xlDoc.IsDistincFetchXml();
query.Criteria = xlDoc.ToCriteria(context);
query.TopCount = xlDoc.ToTopCount();
query.PageInfo.Count = xlDoc.ToCount() ?? 0;
query.PageInfo.PageNumber = xlDoc.ToPageNumber() ?? 1;
query.PageInfo.ReturnTotalRecordCount = xlDoc.ToReturnTotalRecordCount();
var linkedEntities = xlDoc.ToLinkEntities(context);
foreach (var le in linkedEntities)
{
query.LinkEntities.Add(le);
}
return query;
}
public static IQueryable<Entity> TranslateQueryExpressionToLinq(XrmFakedContext context, QueryExpression qe)
{
if (qe == null) return null;
//Start form the root entity and build a LINQ query to execute the query against the In-Memory context:
context.EnsureEntityNameExistsInMetadata(qe.EntityName);
IQueryable<Entity> query = null;
query = context.CreateQuery<Entity>(qe.EntityName);
var linkedEntities = new Dictionary<string, int>();
#if !FAKE_XRM_EASY
ValidateAliases(qe, context);
#endif
// Add as many Joins as linked entities
foreach (var le in qe.LinkEntities)
{
if (string.IsNullOrWhiteSpace(le.EntityAlias))
{
le.EntityAlias = EnsureUniqueLinkedEntityAlias(linkedEntities, le.LinkToEntityName);
}
query = TranslateLinkedEntityToLinq(context, le, query, qe.ColumnSet, linkedEntities);
}
// Compose the expression tree that represents the parameter to the predicate.
ParameterExpression entity = Expression.Parameter(typeof(Entity));
var expTreeBody = TranslateQueryExpressionFiltersToExpression(context, qe, entity);
Expression<Func<Entity, bool>> lambda = Expression.Lambda<Func<Entity, bool>>(expTreeBody, entity);
query = query.Where(lambda);
//Sort results
if (qe.Orders != null)
{
if (qe.Orders.Count > 0)
{
IOrderedQueryable<Entity> orderedQuery = null;
var order = qe.Orders[0];
if (order.OrderType == OrderType.Ascending)
orderedQuery = query.OrderBy(e => e.Attributes.ContainsKey(order.AttributeName) ? e[order.AttributeName] : null, new XrmOrderByAttributeComparer());
else
orderedQuery = query.OrderByDescending(e => e.Attributes.ContainsKey(order.AttributeName) ? e[order.AttributeName] : null, new XrmOrderByAttributeComparer());
//Subsequent orders should use ThenBy and ThenByDescending
for (var i = 1; i < qe.Orders.Count; i++)
{
var thenOrder = qe.Orders[i];
if (thenOrder.OrderType == OrderType.Ascending)
orderedQuery = orderedQuery.ThenBy(e => e.Attributes.ContainsKey(thenOrder.AttributeName) ? e[thenOrder.AttributeName] : null, new XrmOrderByAttributeComparer());
else
orderedQuery = orderedQuery.ThenByDescending(e => e[thenOrder.AttributeName], new XrmOrderByAttributeComparer());
}
query = orderedQuery;
}
}
//Project the attributes in the root column set (must be applied after the where and order clauses, not before!!)
query = query.Select(x => x.Clone(x.GetType(), context).ProjectAttributes(qe, context));
return query;
}
#if !FAKE_XRM_EASY
protected static void ValidateAliases(QueryExpression qe, XrmFakedContext context)
{
if (qe.Criteria != null)
ValidateAliases(qe, context, qe.Criteria);
if (qe.LinkEntities != null)
foreach (var link in qe.LinkEntities)
{
ValidateAliases(qe, context, link);
}
}
protected static void ValidateAliases(QueryExpression qe, XrmFakedContext context, LinkEntity link)
{
if (link.LinkCriteria != null)
ValidateAliases(qe, context, link.LinkCriteria);
if (link.LinkEntities != null)
foreach (var innerLink in link.LinkEntities)
{
ValidateAliases(qe, context, innerLink);
}
}
protected static void ValidateAliases(QueryExpression qe, XrmFakedContext context, FilterExpression filter)
{
if (filter.Filters != null)
foreach (var innerFilter in filter.Filters)
{
ValidateAliases(qe, context, innerFilter);
}
if (filter.Conditions != null)
foreach (var condition in filter.Conditions)
{
if (!string.IsNullOrEmpty(condition.EntityName))
{
ValidateAliases(qe, context, condition);
}
}
}
protected static void ValidateAliases(QueryExpression qe, XrmFakedContext context, ConditionExpression condition)
{
var matches = qe.LinkEntities != null ? MatchByAlias(qe, context, condition, qe.LinkEntities) : 0;
if (matches > 1)
{
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"Table {condition.EntityName} is not unique amongst all top-level table and join aliases");
}
else if (matches == 0)
{
if (qe.LinkEntities != null) matches = MatchByEntity(qe, context, condition, qe.LinkEntities);
if (matches > 1)
{
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"There's more than one LinkEntity expressions with name={condition.EntityName}");
}
else if (matches == 0)
{
if (condition.EntityName == qe.EntityName) return;
throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(), $"LinkEntity with name or alias {condition.EntityName} is not found");
}
condition.EntityName += "1";
}
}
protected static int MatchByEntity(QueryExpression qe, XrmFakedContext context, ConditionExpression condition, DataCollection<LinkEntity> linkEntities)
{
var matches = 0;
foreach (var link in linkEntities)
{
if (string.IsNullOrEmpty(link.EntityAlias) && condition.EntityName == link.LinkToEntityName)
{
matches += 1;
}
if (link.LinkEntities != null) matches += MatchByEntity(qe, context, condition, link.LinkEntities);
}
return matches;
}
protected static int MatchByAlias(QueryExpression qe, XrmFakedContext context, ConditionExpression condition, DataCollection<LinkEntity> linkEntities)
{
var matches = 0;
foreach (var link in linkEntities)
{
if (link.EntityAlias == condition.EntityName)
{
matches += 1;
}
if (link.LinkEntities != null) matches += MatchByAlias(qe, context, condition, link.LinkEntities);
}
return matches;
}
#endif
protected static Expression TranslateConditionExpression(QueryExpression qe, XrmFakedContext context, TypedConditionExpression c, ParameterExpression entity)
{
Expression attributesProperty = Expression.Property(
entity,
"Attributes"
);
//If the attribute comes from a joined entity, then we need to access the attribute from the join
//But the entity name attribute only exists >= 2013
#if FAKE_XRM_EASY_2013 || FAKE_XRM_EASY_2015 || FAKE_XRM_EASY_2016 || FAKE_XRM_EASY_365 || FAKE_XRM_EASY_9
string attributeName = "";
//Do not prepend the entity name if the EntityLogicalName is the same as the QueryExpression main logical name
if (!string.IsNullOrWhiteSpace(c.CondExpression.EntityName) && !c.CondExpression.EntityName.Equals(qe.EntityName))
{
attributeName = c.CondExpression.EntityName + "." + c.CondExpression.AttributeName;
}
else
attributeName = c.CondExpression.AttributeName;
Expression containsAttributeExpression = Expression.Call(
attributesProperty,
typeof(AttributeCollection).GetMethod("ContainsKey", new Type[] { typeof(string) }),
Expression.Constant(attributeName)
);
Expression getAttributeValueExpr = Expression.Property(
attributesProperty, "Item",
Expression.Constant(attributeName, typeof(string))
);
#else
Expression containsAttributeExpression = Expression.Call(
attributesProperty,
typeof(AttributeCollection).GetMethod("ContainsKey", new Type[] { typeof(string) }),
Expression.Constant(c.CondExpression.AttributeName)
);
Expression getAttributeValueExpr = Expression.Property(
attributesProperty, "Item",
Expression.Constant(c.CondExpression.AttributeName, typeof(string))
);
#endif
Expression getNonBasicValueExpr = getAttributeValueExpr;
Expression operatorExpression = null;
switch (c.CondExpression.Operator)
{
case ConditionOperator.Equal:
case ConditionOperator.Today:
case ConditionOperator.Yesterday:
case ConditionOperator.Tomorrow:
case ConditionOperator.EqualUserId:
operatorExpression = TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotEqualUserId:
operatorExpression = Expression.Not(TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.EqualBusinessId:
operatorExpression = TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotEqualBusinessId:
operatorExpression = Expression.Not(TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.BeginsWith:
case ConditionOperator.Like:
operatorExpression = TranslateConditionExpressionLike(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.EndsWith:
operatorExpression = TranslateConditionExpressionEndsWith(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.Contains:
operatorExpression = TranslateConditionExpressionContains(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotEqual:
operatorExpression = Expression.Not(TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.DoesNotBeginWith:
case ConditionOperator.DoesNotEndWith:
case ConditionOperator.NotLike:
case ConditionOperator.DoesNotContain:
operatorExpression = Expression.Not(TranslateConditionExpressionLike(c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.Null:
operatorExpression = TranslateConditionExpressionNull(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotNull:
operatorExpression = Expression.Not(TranslateConditionExpressionNull(c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.GreaterThan:
operatorExpression = TranslateConditionExpressionGreaterThan(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.GreaterEqual:
operatorExpression = TranslateConditionExpressionGreaterThanOrEqual(context, c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.LessThan:
operatorExpression = TranslateConditionExpressionLessThan(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.LessEqual:
operatorExpression = TranslateConditionExpressionLessThanOrEqual(context, c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.In:
operatorExpression = TranslateConditionExpressionIn(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotIn:
operatorExpression = Expression.Not(TranslateConditionExpressionIn(c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.On:
operatorExpression = TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotOn:
operatorExpression = Expression.Not(TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.OnOrAfter:
operatorExpression = Expression.Or(
TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression),
TranslateConditionExpressionGreaterThan(c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.LastXHours:
case ConditionOperator.LastXDays:
case ConditionOperator.Last7Days:
case ConditionOperator.LastXWeeks:
case ConditionOperator.LastXMonths:
case ConditionOperator.LastXYears:
operatorExpression = TranslateConditionExpressionLast(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.OnOrBefore:
operatorExpression = Expression.Or(
TranslateConditionExpressionEqual(context, c, getNonBasicValueExpr, containsAttributeExpression),
TranslateConditionExpressionLessThan(c, getNonBasicValueExpr, containsAttributeExpression));
break;
case ConditionOperator.Between:
if (c.CondExpression.Values.Count != 2)
{
throw new Exception("Between operator requires exactly 2 values.");
}
operatorExpression = TranslateConditionExpressionBetween(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NotBetween:
if (c.CondExpression.Values.Count != 2)
{
throw new Exception("Not-Between operator requires exactly 2 values.");
}
operatorExpression = Expression.Not(TranslateConditionExpressionBetween(c, getNonBasicValueExpr, containsAttributeExpression));
break;
#if !FAKE_XRM_EASY && !FAKE_XRM_EASY_2013
case ConditionOperator.OlderThanXMinutes:
case ConditionOperator.OlderThanXHours:
case ConditionOperator.OlderThanXDays:
case ConditionOperator.OlderThanXWeeks:
case ConditionOperator.OlderThanXYears:
#endif
case ConditionOperator.OlderThanXMonths:
operatorExpression = TranslateConditionExpressionOlderThan(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.NextXHours:
case ConditionOperator.NextXDays:
case ConditionOperator.Next7Days:
case ConditionOperator.NextXWeeks:
case ConditionOperator.NextXMonths:
case ConditionOperator.NextXYears:
operatorExpression = TranslateConditionExpressionNext(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.ThisYear:
case ConditionOperator.LastYear:
case ConditionOperator.NextYear:
case ConditionOperator.ThisMonth:
case ConditionOperator.LastMonth:
case ConditionOperator.NextMonth:
case ConditionOperator.LastWeek:
case ConditionOperator.ThisWeek:
case ConditionOperator.NextWeek:
case ConditionOperator.InFiscalYear:
operatorExpression = TranslateConditionExpressionBetweenDates(c, getNonBasicValueExpr, containsAttributeExpression, context);
break;
#if FAKE_XRM_EASY_9
case ConditionOperator.ContainValues:
operatorExpression = TranslateConditionExpressionContainValues(c, getNonBasicValueExpr, containsAttributeExpression);
break;
case ConditionOperator.DoesNotContainValues:
operatorExpression = Expression.Not(TranslateConditionExpressionContainValues(c, getNonBasicValueExpr, containsAttributeExpression));
break;
#endif
default:
throw new PullRequestException(string.Format("Operator {0} not yet implemented for condition expression", c.CondExpression.Operator.ToString()));
}
if (c.IsOuter)
{
//If outer join, filter is optional, only if there was a value
return Expression.Constant(true);
}
else
return operatorExpression;
}
private static void ValidateSupportedTypedExpression(TypedConditionExpression typedExpression)
{
Expression validateOperatorTypeExpression = Expression.Empty();
ConditionOperator[] supportedOperators = (ConditionOperator[])Enum.GetValues(typeof(ConditionOperator));
#if FAKE_XRM_EASY_9
if (typedExpression.AttributeType == typeof(OptionSetValueCollection))
{
supportedOperators = new[]
{
ConditionOperator.ContainValues,
ConditionOperator.DoesNotContainValues,
ConditionOperator.Equal,
ConditionOperator.NotEqual,
ConditionOperator.NotNull,
ConditionOperator.Null,
ConditionOperator.In,
ConditionOperator.NotIn,
};
}
#endif
if (!supportedOperators.Contains(typedExpression.CondExpression.Operator))
{
FakeOrganizationServiceFault.Throw(ErrorCodes.InvalidOperatorCode, "The operator is not valid or it is not supported.");
}
}
protected static Expression GetAppropiateTypedValue(object value)
{
//Basic types conversions
//Special case => datetime is sent as a string
if (value is string)
{
DateTime dtDateTimeConversion;
if (DateTime.TryParse(value.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out dtDateTimeConversion))
{
return Expression.Constant(dtDateTimeConversion, typeof(DateTime));
}
else
{
return GetCaseInsensitiveExpression(Expression.Constant(value, typeof(string)));
}
}
else if (value is EntityReference)
{
var cast = (value as EntityReference).Id;
return Expression.Constant(cast);
}
else if (value is OptionSetValue)
{
var cast = (value as OptionSetValue).Value;
return Expression.Constant(cast);
}
else if (value is Money)
{
var cast = (value as Money).Value;
return Expression.Constant(cast);
}
return Expression.Constant(value);
}
protected static Type GetAppropiateTypeForValue(object value)
{
//Basic types conversions
//Special case => datetime is sent as a string
if (value is string)
{
DateTime dtDateTimeConversion;
if (DateTime.TryParse(value.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out dtDateTimeConversion))
{
return typeof(DateTime);
}
else
{
return typeof(string);
}
}
else
return value.GetType();
}
protected static Expression GetAppropiateTypedValueAndType(object value, Type attributeType)
{
if (attributeType == null)
return GetAppropiateTypedValue(value);
if (Nullable.GetUnderlyingType(attributeType) != null)
{
attributeType = Nullable.GetUnderlyingType(attributeType);
}
//Basic types conversions
//Special case => datetime is sent as a string
if (value is string)
{
int iValue;
DateTime dtDateTimeConversion;
Guid id;
if (attributeType.IsDateTime() //Only convert to DateTime if the attribute's type was DateTime
&& DateTime.TryParse(value.ToString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out dtDateTimeConversion))
{
return Expression.Constant(dtDateTimeConversion, typeof(DateTime));
}
else if (attributeType.IsOptionSet() && int.TryParse(value.ToString(), out iValue))
{
return Expression.Constant(iValue, typeof(int));
}
else if ((attributeType == typeof(EntityReference) || attributeType == typeof(Guid)) && Guid.TryParse((string)value, out id))
{
return Expression.Constant(id);
}
else