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 182
/
EntityExtensions.cs
489 lines (435 loc) · 18.7 KB
/
EntityExtensions.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
using FakeXrmEasy.Metadata;
using FakeXrmEasy.OrganizationFaults;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq;
namespace FakeXrmEasy.Extensions
{
public static class EntityExtensions
{
/// <summary>
/// Extension method to add an attribute and return the entity itself
/// </summary>
/// <param name="e"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static Entity AddAttribute(this Entity e, string key, object value)
{
e.Attributes.Add(key, value);
return e;
}
/// <summary>
/// Projects the attributes of entity e so that only the attributes specified in the columnSet are returned
/// </summary>
/// <param name="e"></param>
/// <param name="columnSet"></param>
/// <param name="alias"></param>
/// <returns></returns>
public static Entity ProjectAttributes(this Entity e, ColumnSet columnSet, XrmFakedContext context)
{
return ProjectAttributes(e, new QueryExpression() { ColumnSet = columnSet }, context);
}
public static void ApplyDateBehaviour(this Entity e, XrmFakedContext context)
{
#if FAKE_XRM_EASY || FAKE_XRM_EASY_2013
return; //Do nothing... DateBehavior wasn't available for versions <= 2013
#else
if (context.DateBehaviour.Count == 0 || e.LogicalName == null || !context.DateBehaviour.ContainsKey(e.LogicalName))
{
return;
}
var entityDateBehaviours = context.DateBehaviour[e.LogicalName];
foreach (var attribute in entityDateBehaviours.Keys)
{
if (!e.Attributes.ContainsKey(attribute))
{
continue;
}
switch (entityDateBehaviours[attribute])
{
case DateTimeAttributeBehavior.DateOnly:
var currentValue = (DateTime)e[attribute];
e[attribute] = new DateTime(currentValue.Year, currentValue.Month, currentValue.Day, 0, 0, 0, DateTimeKind.Utc);
break;
default:
break;
}
}
#endif
}
public static void ProjectAttributes(Entity e, Entity projected, LinkEntity le, XrmFakedContext context)
{
var sAlias = string.IsNullOrWhiteSpace(le.EntityAlias) ? le.LinkToEntityName : le.EntityAlias;
if (le.Columns.AllColumns)
{
foreach (var attKey in e.Attributes.Keys)
{
if (attKey.StartsWith(sAlias + "."))
{
projected[attKey] = e[attKey];
}
}
foreach (var attKey in e.FormattedValues.Keys)
{
if (attKey.StartsWith(sAlias + "."))
{
projected.FormattedValues[attKey] = e.FormattedValues[attKey];
}
}
}
else
{
foreach (var attKey in le.Columns.Columns)
{
var linkedAttKey = sAlias + "." + attKey;
if (e.Attributes.ContainsKey(linkedAttKey))
projected[linkedAttKey] = e[linkedAttKey];
if (e.FormattedValues.ContainsKey(linkedAttKey))
projected.FormattedValues[linkedAttKey] = e.FormattedValues[linkedAttKey];
}
}
foreach (var nestedLinkedEntity in le.LinkEntities)
{
ProjectAttributes(e, projected, nestedLinkedEntity, context);
}
}
public static Entity ProjectAttributes(this Entity e, QueryExpression qe, XrmFakedContext context)
{
if (qe.ColumnSet == null) return e;
if (qe.ColumnSet.AllColumns)
{
return e; //return all the original attributes
}
else
{
//Return selected list of attributes in a projected entity
Entity projected = null;
//However, if we are using proxy types, we must create a instance of the appropiate class
if (context.ProxyTypesAssembly != null)
{
var subClassType = context.FindReflectedType(e.LogicalName);
if (subClassType != null)
{
var instance = Activator.CreateInstance(subClassType);
projected = (Entity)instance;
projected.Id = e.Id;
}
else
projected = new Entity(e.LogicalName) { Id = e.Id }; //fallback to generic type if type not found
}
else
projected = new Entity(e.LogicalName) { Id = e.Id };
//Remove primary attribute unless explicitly specified
if (projected.Attributes.ContainsKey($"{e.LogicalName}id"))
{
projected.Attributes.Remove($"{e.LogicalName}id");
}
foreach (var attKey in qe.ColumnSet.Columns)
{
//Check if attribute really exists in metadata
if (!context.AttributeExistsInMetadata(e.LogicalName, attKey))
{
OrganizationServiceFaultQueryBuilderNoAttributeException.Throw(attKey);
}
if (e.Attributes.ContainsKey(attKey) && e.Attributes[attKey] != null)
{
projected[attKey] = CloneAttribute(e[attKey]);
string formattedValue = "";
if (e.FormattedValues.TryGetValue(attKey, out formattedValue))
{
projected.FormattedValues[attKey] = formattedValue;
}
}
}
//Plus attributes from joins
foreach (var le in qe.LinkEntities)
{
ProjectAttributes(e, projected, le, context);
}
//foreach (var attKey in e.Attributes.Keys)
//{
// if(e[attKey] is AliasedValue && !projected.Attributes.ContainsKey(attKey))
// projected[attKey] = e[attKey];
//}
return projected;
}
}
public static object CloneAttribute(object attributeValue)
{
if (attributeValue == null)
return null;
var type = attributeValue.GetType();
if (type == typeof(string))
return new string((attributeValue as string).ToCharArray());
else if (type == typeof(EntityReference)
#if FAKE_XRM_EASY
|| type == typeof(Microsoft.Xrm.Client.CrmEntityReference)
#endif
)
{
var original = (attributeValue as EntityReference);
var clone = new EntityReference(original.LogicalName, original.Id);
clone.Name = CloneAttribute(original.Name) as string;
return clone;
}
else if (type == typeof(BooleanManagedProperty))
{
var original = (attributeValue as BooleanManagedProperty);
return new BooleanManagedProperty(original.Value);
}
else if (type == typeof(OptionSetValue))
{
var original = (attributeValue as OptionSetValue);
return new OptionSetValue(original.Value);
}
else if (type == typeof(AliasedValue))
{
var original = (attributeValue as AliasedValue);
return new AliasedValue(original.EntityLogicalName, original.AttributeLogicalName, CloneAttribute(original.Value));
}
else if (type == typeof(Money))
{
var original = (attributeValue as Money);
return new Money(original.Value);
}
else if (attributeValue.GetType() == typeof(EntityCollection))
{
var collection = attributeValue as EntityCollection;
return new EntityCollection(collection.Entities.Select(e => e.Clone(e.GetType())).ToList());
}
else if(attributeValue is IEnumerable<Entity>)
{
var enumerable = attributeValue as IEnumerable<Entity>;
return enumerable.Select(e => e.Clone(e.GetType())).ToArray();
}
#if !FAKE_XRM_EASY
else if(type == typeof(byte[]))
{
var original = (attributeValue as byte[]);
var copy = new byte[original.Length];
original.CopyTo(copy, 0);
return copy;
}
#endif
else if (type == typeof(int) || type == typeof(Int64))
return attributeValue; //Not a reference type
else if (type == typeof(decimal))
return attributeValue; //Not a reference type
else if (type == typeof(double))
return attributeValue; //Not a reference type
else if (type == typeof(float))
return attributeValue; //Not a reference type
else if (type == typeof(byte))
return attributeValue; //Not a reference type
else if (type == typeof(float))
return attributeValue; //Not a reference type
else if (type == typeof(bool))
return attributeValue; //Not a reference type
else if (type == typeof(Guid))
return attributeValue; //Not a reference type
else if (type == typeof(DateTime))
return attributeValue; //Not a reference type
else if (attributeValue is Enum)
return attributeValue; //Not a reference type
throw new Exception(string.Format("Attribute type not supported when trying to clone attribute '{0}'", type.ToString()));
}
public static Entity Clone(this Entity e)
{
var cloned = new Entity(e.LogicalName);
cloned.Id = e.Id;
cloned.LogicalName = e.LogicalName;
if (e.FormattedValues != null)
{
var formattedValues = new FormattedValueCollection();
foreach (var key in e.FormattedValues.Keys)
formattedValues.Add(key, e.FormattedValues[key]);
cloned.Inject("FormattedValues", formattedValues);
}
foreach (var attKey in e.Attributes.Keys)
{
cloned[attKey] = e[attKey] != null ? CloneAttribute(e[attKey]) : null;
}
return cloned;
}
public static T Clone<T>(this Entity e) where T : Entity
{
return (T)e.Clone(typeof(T));
}
public static Entity Clone(this Entity e, Type t)
{
if (t == null)
return e.Clone();
var cloned = Activator.CreateInstance(t) as Entity;
cloned.Id = e.Id;
cloned.LogicalName = e.LogicalName;
if (e.FormattedValues != null)
{
var formattedValues = new FormattedValueCollection();
foreach (var key in e.FormattedValues.Keys)
formattedValues.Add(key, e.FormattedValues[key]);
cloned.Inject("FormattedValues", formattedValues);
}
foreach (var attKey in e.Attributes.Keys)
{
if (e[attKey] != null)
{
cloned[attKey] = CloneAttribute(e[attKey]);
}
}
return cloned;
}
/// <summary>
/// Extension method to join the attributes of entity e and otherEntity
/// </summary>
/// <param name="e"></param>
/// <param name="otherEntity"></param>
/// <param name="attributes"></param>
/// <returns></returns>
public static Entity JoinAttributes(this Entity e, Entity otherEntity, ColumnSet columnSet, string alias, XrmFakedContext context)
{
if (otherEntity == null) return e; //Left Join where otherEntity was not matched
otherEntity = otherEntity.Clone(); //To avoid joining entities from/to the same entities, which would cause collection modified exceptions
if (columnSet.AllColumns)
{
foreach (var attKey in otherEntity.Attributes.Keys)
{
e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, otherEntity[attKey]);
}
foreach (var attKey in otherEntity.FormattedValues.Keys)
{
e.FormattedValues[alias + "." + attKey] = otherEntity.FormattedValues[attKey];
}
}
else
{
//Return selected list of attributes
foreach (var attKey in columnSet.Columns)
{
if (!context.AttributeExistsInMetadata(otherEntity.LogicalName, attKey))
{
OrganizationServiceFaultQueryBuilderNoAttributeException.Throw(attKey);
}
if (otherEntity.Attributes.ContainsKey(attKey))
{
e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, otherEntity[attKey]);
}
else
{
e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, null);
}
if (otherEntity.FormattedValues.ContainsKey(attKey))
{
e.FormattedValues[alias + "." + attKey] = otherEntity.FormattedValues[attKey];
}
}
}
return e;
}
public static Entity JoinAttributes(this Entity e, IEnumerable<Entity> otherEntities, ColumnSet columnSet, string alias, XrmFakedContext context)
{
foreach (var otherEntity in otherEntities)
{
var otherClonedEntity = otherEntity.Clone(); //To avoid joining entities from/to the same entities, which would cause collection modified exceptions
if (columnSet.AllColumns)
{
foreach (var attKey in otherClonedEntity.Attributes.Keys)
{
e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, otherClonedEntity[attKey]);
}
foreach (var attKey in otherEntity.FormattedValues.Keys)
{
e.FormattedValues[alias + "." + attKey] = otherEntity.FormattedValues[attKey];
}
}
else
{
//Return selected list of attributes
foreach (var attKey in columnSet.Columns)
{
if (!context.AttributeExistsInMetadata(otherEntity.LogicalName, attKey))
{
OrganizationServiceFaultQueryBuilderNoAttributeException.Throw(attKey);
}
if (otherClonedEntity.Attributes.ContainsKey(attKey))
{
e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, otherClonedEntity[attKey]);
}
else
{
e[alias + "." + attKey] = new AliasedValue(otherEntity.LogicalName, attKey, null);
}
if (otherEntity.FormattedValues.ContainsKey(attKey))
{
e.FormattedValues[alias + "." + attKey] = otherEntity.FormattedValues[attKey];
}
}
}
}
return e;
}
/// <summary>
/// Returns the key for the attribute name selected (could an entity reference or a primary key or a guid)
/// </summary>
/// <param name="e"></param>
/// <param name="sAttributeName"></param>
/// <returns></returns>
public static Guid KeySelector(this Entity e, string sAttributeName, XrmFakedContext context)
{
if (sAttributeName.Contains("."))
{
//Do not lowercase the alias prefix
var splitted = sAttributeName.Split('.');
sAttributeName = string.Format("{0}.{1}", splitted[0], splitted[1].ToLower());
}
else
{
sAttributeName = sAttributeName.ToLower();
}
if (!e.Attributes.ContainsKey(sAttributeName))
{
//Check if it is the primary key
if (sAttributeName.Contains("id") &&
e.LogicalName.ToLower().Equals(sAttributeName.Substring(0, sAttributeName.Length - 2)))
{
return e.Id;
}
return Guid.Empty; //Atrribute is null or doesn´t exists so it can´t be joined
}
object keyValue = null;
if (e[sAttributeName] is AliasedValue)
{
keyValue = (e[sAttributeName] as AliasedValue).Value;
}
else
{
keyValue = e[sAttributeName];
}
if (keyValue is EntityReference)
return (keyValue as EntityReference).Id;
if (keyValue is Guid)
return ((Guid)keyValue);
return Guid.Empty;
}
/// <summary>
/// Extension method to "hack" internal set properties on sealed classes via reflection
/// </summary>
/// <param name="e"></param>
/// <param name="property"></param>
/// <param name="value"></param>
public static void Inject(this Entity e, string property, object value)
{
e.GetType().GetProperty(property).SetValue(e, value, null);
}
public static void SetValueIfEmpty(this Entity e, string property, object value)
{
var containsKey = e.Attributes.ContainsKey(property);
if (!containsKey || containsKey && e[property] == null)
{
e[property] = value;
}
}
}
}