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
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Tango.Core;
using Tango.DAL.Remote.DB;
using Tango.DAL.Remote;
using Tango.Settings;
using Tango.Core.Helpers;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Runtime.CompilerServices;
using System.Data.Entity.Core.Objects;
using Tango.Serialization;
using System.Xml.Serialization;
using Newtonsoft.Json;
using Tango.Logging;
using System.ComponentModel;
using Tango.Core.Json;
using Newtonsoft.Json.Converters;
using Tango.BL.Serialization;
using Newtonsoft.Json.Linq;
using Tango.BL.ActionLogs;
using Tango.BL.ValueObjects;
using LiteDB;
using System.Linq.Expressions;
namespace Tango.BL
{
internal class ObservableEntitiesContainer
{
static ObservableEntitiesContainer()
{
RegisteredEntities = new List<IObservableEntity>();
}
/// <summary>
/// Gets the list of all registered entities ever created.
/// </summary>
internal static List<IObservableEntity> RegisteredEntities { get; private set; }
}
/// <summary>
/// Represents a generic observable entity base class.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="Tango.Core.ExtendedObject" />
/// <seealso cref="Tango.BL.Entities.IObservableEntity" />
[Serializable]
public abstract class ObservableEntity<T> : ExtendedObject, IObservableEntity, IActionLogComparable where T : class, IObservableEntity
{
#region Events
/// <summary>
/// Occurs after this observable has been modified and saved by this entity context or another.
/// </summary>
public event EventHandler<ObservableModifiedEventArgs> Modified;
#endregion
#region Properties
private Int32 _id;
/// <summary>
/// Gets or sets the entity identifier.
/// </summary>
[Column("ID")]
[JsonIgnore]
[BsonIgnore]
[ParameterIgnore]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 ID
{
get { return _id; }
set { _id = value; RaisePropertyChanged(nameof(ID)); }
}
private String _guid;
/// <summary>
/// Gets or sets the entity unique identifier.
/// </summary>
[Key]
[Column("GUID")]
[ParameterIgnore]
public String Guid
{
get { return _guid; }
set { _guid = value; RaisePropertyChanged(nameof(Guid)); }
}
private DateTime _lastUpdated;
/// <summary>
/// Gets or sets the entity last updated data and time.
/// </summary>
[Column("LAST_UPDATED")]
[ParameterIgnore]
public DateTime LastUpdated
{
get { return _lastUpdated; }
set { _lastUpdated = value; RaisePropertyChanged(nameof(LastUpdated)); }
}
private ReadOnlyObservableCollection<ParameterItem> _parameters;
/// <summary>
/// Gets a bind-able observable collection of the component properties.
/// </summary>
[NotMapped]
[XmlIgnore]
[BsonIgnore]
[JsonIgnore]
[ParameterIgnore]
public ReadOnlyObservableCollection<ParameterItem> Parameters
{
get
{
if (_parameters == null)
{
_parameters = new ReadOnlyObservableCollection<ParameterItem>(this.CreateParametersCollection(ParameterItemMode.Binding));
}
return _parameters;
}
private set { _parameters = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Gets or sets the entity last updated data and time.
/// </summary>
[ParameterIgnore]
[JsonIgnore]
[BsonIgnore]
[NotMapped]
public Type ObjectType
{
get { return GetType(); }
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ObservableEntity{T}"/> class.
/// </summary>
public ObservableEntity()
{
//ObservableEntitiesContainer.RegisteredEntities.Add(this);
Guid = System.Guid.NewGuid().ToString();
LastUpdated = DateTime.UtcNow;
}
#endregion
#region Public Methods
/// <summary>
/// Marks this entity as modified so all properties are saved.
/// </summary>
/// <param name="context">The context.</param>
public virtual void MarkModified(ObservablesContext context)
{
context.Entry(this).State = EntityState.Modified;
}
/// <summary>
/// Saves the changes on this entity to database.
/// </summary>
public virtual void Save(ObservablesContext context)
{
if (context == ObservablesEntitiesAdapter.Instance.Context)
{
var tableName = this.GetType().GetCustomAttribute<TableAttribute>().Name;
String propName = tableName.FromDalNameToTitleCase();
DbSet<T> set = ObservablesEntitiesAdapter.Instance.Context.GetType().GetProperty(propName, BindingFlags.Instance | BindingFlags.Public).GetValue(context) as DbSet<T>;
ObservableCollection<T> obs = ObservablesEntitiesAdapter.Instance.GetType().GetProperty(propName, BindingFlags.Instance | BindingFlags.Public).GetValue(ObservablesEntitiesAdapter.Instance) as ObservableCollection<T>;
if (!obs.Contains(this as T))
{
set.Add(this as T);
}
ObservablesEntitiesAdapter.Instance.SaveChanges();
}
else
{
context.SaveChanges();
}
}
/// <summary>
/// Attaches this entity to the proper DbSet.
/// </summary>
public virtual void Attach(ObservablesContext context)
{
GetDbSet(context).Add(this as T);
}
/// <summary>
/// Detaches this observable from the proper DbSet.
/// </summary>
public virtual void Detach(ObservablesContext context)
{
GetDbSet(context).Remove(this as T);
}
/// <summary>
/// Saves the changes on this entity to database asynchronously.
/// </summary>
/// <returns></returns>
public Task SaveAsync(ObservablesContext context)
{
return Task.Factory.StartNew(() =>
{
Save(context);
});
}
/// <summary>
/// Reloads this observable entity.
/// </summary>
/// <returns></returns>
public Task Reload(ObservablesContext context)
{
return context.Entry(this).ReloadAsync();
}
/// <summary>
/// Gets the database set.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public DbSet<T> GetDbSet(ObservablesContext context)
{
String tabelName = this.GetType().Name.PluralizeMVC();
var p = typeof(ObservablesContext).GetProperty(tabelName);
if (p != null)
{
var set1 = p.GetValue(context) as DbSet<T>;
return set1;
}
else
{
tabelName = this.GetType().BaseType.Name.PluralizeMVC();
p = typeof(ObservablesContext).GetProperty(tabelName);
if (p != null)
{
var set2 = p.GetValue(context) as DbSet<T>;
return set2;
}
}
return null;
}
/// <summary>
/// Gets the database set.
/// </summary>
/// <typeparam name="T1">The type of the 1.</typeparam>
/// <param name="context">The context.</param>
/// <returns></returns>
public DbSet<T1> GetDbSet<T1>(ObservablesContext context) where T1 : class, IObservableEntity
{
return GetDbSet(context) as DbSet<T1>;
}
/// <summary>
/// Clones this entity.
/// </summary>
/// <returns></returns>
public virtual T Clone()
{
return Clone(null);
}
public T Clone(Action<T> action)
{
var cloned = Activator.CreateInstance<T>();
foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.SetMethod != null))
{
if (!prop.PropertyType.IsGenericTypeAndNotNullable())
{
prop.SetValue(cloned, prop.GetValue(this));
}
}
cloned.ID = 0;
cloned.Guid = System.Guid.NewGuid().ToString();
cloned.LastUpdated = DateTime.UtcNow;
action?.Invoke(cloned);
return cloned;
}
/// <summary>
/// Compares another entity using a a JSON string comparison.
/// </summary>
/// <param name="entity">The entity.</param>
/// <returns></returns>
public bool CompareUsingJson(T entity)
{
String me = JsonConvert.SerializeObject(this);
String other = JsonConvert.SerializeObject(entity);
return me == other;
}
/// <summary>
/// Deletes this entity using an SQL statement which will cause the database delete cascade effect.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Task DeleteCascadeAsync(ObservablesContext context)
{
return context.Database.ExecuteSqlCommandAsync(String.Format("DELETE FROM {0} WHERE GUID='{1}'", this.GetType().GetCustomAttribute<TableAttribute>().Name, Guid));
}
/// <summary>
/// Raises the <see cref="Modified" /> event.
/// </summary>
/// <param name="context"></param>
/// <param name="source"></param>
/// <param name="target"></param>
public void RaiseModified(ObservablesContext context, IObservableEntity source, IObservableEntity target)
{
Modified?.Invoke(this, new ObservableModifiedEventArgs(context, source, target));
}
public ObjectContext GetObjectContext()
{
return GetObjectContextFromEntity(this);
}
public DbContext GetDbContext()
{
return GetDbContextFromEntity(this);
}
/// <summary>
/// Removes this entity and all dependent entities from the specified db context.
/// </summary>
/// <param name="context">The context.</param>
public virtual void Delete(ObservablesContext context)
{
}
#endregion
#region Serialization
public virtual EntitySerializationStrategy GetDefaultSerializationStrategy(EntitySerializationFlags flags)
{
EntitySerializationStrategy st = new EntitySerializationStrategy();
st.Ignore(() => this.HasErrors);
st.Ignore(() => this.Parameters);
st.Ignore(() => this.DesignMode);
st.Ignore(() => this.LogManager);
st.Ignore(() => this.ObjectType);
st.Ignore(() => this.TemporaryManager);
st.Ignore(() => this.ValidateOnPropertyChanged);
st.Ignore(() => this.LastUpdated);
st.Ignore(() => this.ValidationErrors);
st.Ignore(() => this.ID);
st.Ignore(this.GetType().GetField("_entityWrapper"));
if (flags.HasFlag(EntitySerializationFlags.IgnoreGuids))
{
st.Ignore(() => this.Guid);
}
if (flags.HasFlag(EntitySerializationFlags.IgnoreReferenceTypes))
{
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !x.PropertyType.IsPrimitive && !x.PropertyType.IsGenericType && !x.PropertyType.IsNullable() && x.PropertyType != typeof(byte[]) && x.PropertyType != typeof(String) && x.PropertyType != typeof(DateTime)).ToList();
foreach (var prop in props)
{
st.Ignore(prop);
}
}
if (flags.HasFlag(EntitySerializationFlags.IgnoreCollections))
{
var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.PropertyType.IsGenericTypeAndNotNullable()).ToList();
foreach (var prop in props)
{
st.Ignore(prop);
}
}
foreach (var prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.SetMethod == null))
{
st.Ignore(prop);
}
return st;
}
public static T FromJson(String json, EntitySerializationStrategy serializationStrategy, EntitySerializationFlags flags)
{
var settings = new JsonSerializerSettings()
{
ContractResolver = new SerializableEntityContractResolver(serializationStrategy, flags),
};
if (flags.HasFlag(EntitySerializationFlags.PreserveReferencesHandling))
{
settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
}
settings.Converters.Add(new StringEnumConverter { CamelCaseText = false });
return JsonConvert.DeserializeObject<T>(json, settings);
}
public String ToJson(EntitySerializationStrategy serializationStrategy, EntitySerializationFlags flags)
{
var settings = new JsonSerializerSettings()
{
ContractResolver = new SerializableEntityContractResolver(serializationStrategy, flags),
};
if (flags.HasFlag(EntitySerializationFlags.PreserveReferencesHandling))
{
settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
}
settings.Converters.Add(new StringEnumConverter { CamelCaseText = false });
String json = JsonConvert.SerializeObject(this, flags.HasFlag(EntitySerializationFlags.Indented) ? Formatting.Indented : Formatting.None, settings);
return json;
}
public static T FromJson(String json)
{
return FromJson(json, new EntitySerializationStrategy(), EntitySerializationFlags.IgnoreReferenceTypes | EntitySerializationFlags.Indented);
}
public String ToJson()
{
return ToJson(new EntitySerializationStrategy(), EntitySerializationFlags.IgnoreReferenceTypes | EntitySerializationFlags.Indented);
}
public void PopulateFromJson(string json, EntitySerializationStrategy serializationStrategy, EntitySerializationFlags flags)
{
var settings = new JsonSerializerSettings()
{
ContractResolver = new SerializableEntityContractResolver(serializationStrategy, flags),
};
if (flags.HasFlag(EntitySerializationFlags.PreserveReferencesHandling))
{
settings.PreserveReferencesHandling = PreserveReferencesHandling.All;
}
settings.Converters.Add(new StringEnumConverter { CamelCaseText = false });
JsonConvert.PopulateObject(json, this, settings);
}
public void PopulateFromJson(string json)
{
PopulateFromJson(json, new EntitySerializationStrategy(), EntitySerializationFlags.PreserveReferencesHandling);
}
#endregion
#region Private Methods
private static DbContext GetDbContextFromEntity(object entity)
{
var object_context = GetObjectContextFromEntity(entity);
if (object_context == null)
return null;
return new DbContext(object_context, dbContextOwnsObjectContext: false);
}
private static ObjectContext GetObjectContextFromEntity(object entity)
{
var field = entity.GetType().GetField("_entityWrapper");
if (field == null)
return null;
var wrapper = field.GetValue(entity);
var property = wrapper.GetType().GetProperty("Context");
var context = (ObjectContext)property.GetValue(wrapper, null);
return context;
}
#endregion
#region Validation
//Holds the current validation errors.
private List<KeyValuePair<String, String>> _currentErrors = new List<KeyValuePair<string, string>>();
/// <summary>
/// Occurs when the validation errors have changed for a property or for the entire entity.
/// </summary>
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
private ObservableCollection<String> _validationErrors;
/// <summary>
/// Gets or sets the validation errors.
/// </summary>
[NotMapped]
[ParameterIgnore]
[XmlIgnore]
[BsonIgnore]
[JsonIgnore]
public ObservableCollection<String> ValidationErrors
{
get { return _validationErrors; }
protected set { _validationErrors = value; RaisePropertyChangedAuto(); }
}
private bool _validateOnPropertyChanged;
[NotMapped]
[ParameterIgnore]
[JsonIgnore]
[BsonIgnore]
[XmlIgnore]
public bool ValidateOnPropertyChanged
{
get { return _validateOnPropertyChanged; }
set { _validateOnPropertyChanged = value; RaisePropertyChangedAuto(); }
}
private bool _hasErrors;
/// <summary>
/// Gets a value that indicates whether the entity has validation errors.
/// </summary>
[NotMapped]
[ParameterIgnore]
[JsonIgnore]
[BsonIgnore]
[XmlIgnore]
public bool HasErrors
{
get { return _hasErrors; }
set { _hasErrors = value; RaisePropertyChangedAuto(); }
}
/// <summary>
/// Performs entity field validation.
/// Will throw an exception with the proper message if one of the fields is invalid.
/// </summary>
/// <param name="context">The context.</param>
public virtual bool Validate(ObservablesContext context)
{
HasErrors = false;
_currentErrors.Clear();
if (ValidationErrors == null)
{
ValidationErrors = new ObservableCollection<string>();
}
ValidationErrors.Clear();
OnValidating(context);
foreach (var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
foreach (var validation in prop.GetCustomAttributes<ValidationAttribute>())
{
if (!validation.IsValid(prop.GetValue(this)))
{
_currentErrors.Add(new KeyValuePair<string, string>(prop.Name, validation.ErrorMessage));
ValidationErrors.Add(validation.ErrorMessage);
}
}
HasErrors = _currentErrors.Count > 0;
RaiseError(prop.Name);
}
foreach (var error in _currentErrors)
{
ValidationErrors.Add(error.Value);
}
return !HasErrors;
}
/// <summary>
/// Gets the validation errors for a specified property or for the entire entity.
/// </summary>
/// <param name="propertyName">The name of the property to retrieve validation errors for; or null or <see cref="F:System.String.Empty" />, to retrieve entity-level errors.</param>
/// <returns>
/// The validation errors for the property or entity.
/// </returns>
public IEnumerable GetErrors(string propertyName)
{
return _currentErrors.Where(x => x.Key == propertyName).Select(x => x.Value).ToList();
}
/// <summary>
/// Called when entity is validating.
/// </summary>
protected virtual void OnValidating(ObservablesContext context)
{
}
/// <summary>
/// Inserts the error.
/// </summary>
/// <param name="propName">Name of the property.</param>
/// <param name="error">The error.</param>
protected void InsertError(String propName, String error)
{
_currentErrors.Add(new KeyValuePair<string, string>(propName, error));
}
/// <summary>
/// Invoked the <see cref="ErrorsChanged"/> event.
/// </summary>
/// <param name="propName">Name of the property.</param>
protected void RaiseError(String propName)
{
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propName));
}
#endregion
#region Virtual Methods
/// <summary>
/// Called when before entity is saved by the context.
/// </summary>
public virtual void OnBeforeSave()
{
}
#endregion
#region INotify Property Changed
/// <summary>
/// Raises the property changed event.
/// </summary>
/// <param name="propName">Name of the property.</param>
protected override void RaisePropertyChanged(string propName)
{
base.RaisePropertyChanged(propName);
if (ValidateOnPropertyChanged)
{
Validate(null);
}
}
public void RaisePropertyChanged<F>(Expression<Func<T, F>> expression)
{
MemberExpression member = expression.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
expression.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
expression.ToString()));
RaisePropertyChanged(propInfo.Name);
}
#endregion
#region Action Log
/// <summary>
/// Returns true if the specified property should be ignored during ActionLog comparison.
/// </summary>
/// <param name="propName">Name of the property.</param>
/// <returns></returns>
bool IActionLogComparable.ShouldActionLogIgnore(string propName)
{
return propName == nameof(LastUpdated) || OnShouldActionLogIgnore(propName);
}
/// <summary>
/// override to specified properties to be ignored when doing ActionLog comparison.
/// </summary>
/// <param name="propName">Name of the property.</param>
/// <returns></returns>
protected virtual bool OnShouldActionLogIgnore(string propName)
{
return false;
}
/// <summary>
/// Returns an optional custom name for this instance in the comparison tree.
/// </summary>
/// <returns></returns>
string IActionLogComparable.GetActionLogName()
{
return OnGetActionLogName();
}
/// <summary>
/// override to specified a custom name for this instance in the ActionLog comparison tree.
/// </summary>
/// <returns></returns>
protected virtual String OnGetActionLogName()
{
return this.GetType().Name;
}
#endregion
}
}
|