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
|
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;
namespace Tango.BL
{
/// <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 where T : class, IObservableEntity
{
private Regex regExDAL;
private List<KeyValuePair<String, String>> _currentErrors = new List<KeyValuePair<string, string>>(); //Holds the current validation errors.
/// <summary>
/// Occurs after this observable has been saved.
/// </summary>
public event EventHandler Saved;
private Int32 _id;
/// <summary>
/// Gets or sets the entity identifier.
/// </summary>
[Column("ID")]
[JsonIgnore]
[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]
[JsonIgnore]
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]
[JsonIgnore]
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]
[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]
[NotMapped]
public Type ObjectType
{
get { return GetType(); }
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableEntity{T}"/> class.
/// </summary>
public ObservableEntity()
{
Guid = System.Guid.NewGuid().ToString();
LastUpdated = DateTime.UtcNow;
regExDAL = new Regex(@"
(?<=[A-Z])(?=[A-Z][a-z]) |
(?<=[^A-Z])(?=[A-Z]) |
(?<=[A-Za-z])(?=[^A-Za-z])", RegexOptions.IgnorePatternWhitespace);
}
/// <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();
}
OnSaved();
}
/// <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>
/// Deletes this entity from the database
/// </summary>
public virtual void Delete(ObservablesContext context)
{
var delProp = this.GetType().GetProperty("Deleted");
if (delProp != null)
{
delProp.SetValue(this, true);
Save(context);
}
else
{
GetDbSet(context).Remove(this as T);
Save(context);
}
}
/// <summary>
/// Deletes this entity without saving changes to data base.
/// </summary>
public virtual void DefferedDelete(ObservablesContext context)
{
try
{
GetDbSet(context).Remove(this as T);
}
catch (InvalidOperationException)
{
LogManager.Default.Log(
@"An attempt to deffer delete an entity but was not found on context.
Maybe you have deleted an entity that was no yet inserted into database?", LogCategory.Warning);
}
catch (Exception ex)
{
LogManager.Default.Log(ex);
}
}
/// <summary>
/// Deletes this entity from the database
/// </summary>
public Task DeleteAsync(ObservablesContext context)
{
return Task.Factory.StartNew(() =>
{
Delete(context);
});
}
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;
}
protected virtual void OnSaved()
{
Saved?.Invoke(this, new EventArgs());
}
public 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;
}
public virtual T Clone()
{
return (this as T).CloneEntity() as T;
}
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>
/// 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);
}
return !HasErrors;
}
public DbSet<T1> GetDbSet<T1>(ObservablesContext context) where T1 : class, IObservableEntity
{
return GetDbSet(context) as DbSet<T1>;
}
public IEnumerable GetErrors(string propertyName)
{
return _currentErrors.Where(x => x.Key == propertyName).Select(x => x.Value).ToList();
}
protected virtual void OnValidating(ObservablesContext context)
{
}
protected void InsertError(String propName, String error)
{
_currentErrors.Add(new KeyValuePair<string, string>(propName, error));
}
private bool _validateOnPropertyChanged;
[NotMapped]
[ParameterIgnore]
[XmlIgnore]
public bool ValidateOnPropertyChanged
{
get { return _validateOnPropertyChanged; }
set { _validateOnPropertyChanged = value; RaisePropertyChangedAuto(); }
}
/// <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));
}
private bool _hasErrors;
/// <summary>
/// Gets a value that indicates whether the entity has validation errors.
/// </summary>
[NotMapped]
[ParameterIgnore]
[XmlIgnore]
public bool HasErrors
{
get { return _hasErrors; }
set { _hasErrors = value; RaisePropertyChangedAuto(); }
}
private ObservableCollection<String> _validationErrors;
/// <summary>
/// Gets or sets the validation errors.
/// </summary>
[NotMapped]
[ParameterIgnore]
[XmlIgnore]
public ObservableCollection<String> ValidationErrors
{
get { return _validationErrors; }
protected set { _validationErrors = value; RaisePropertyChangedAuto(); }
}
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
protected override void RaisePropertyChanged(string propName)
{
base.RaisePropertyChanged(propName);
if (ValidateOnPropertyChanged)
{
Validate(null);
}
}
#region Operator Overloading
//public static bool operator ==(ObservableEntity<T> observable1, ObservableEntity<T> observable2)
//{
// if (object.ReferenceEquals(observable1, null) || object.ReferenceEquals(observable2, null))
// {
// return object.ReferenceEquals(observable1, observable2);
// }
// return observable1.Guid.ToLower() == observable2.Guid.ToLower();
//}
//public static bool operator !=(ObservableEntity<T> observable1, ObservableEntity<T> observable2)
//{
// if (object.ReferenceEquals(observable1, null) || object.ReferenceEquals(observable2, null))
// {
// return !object.ReferenceEquals(observable1, observable2);
// }
// return observable1.Guid.ToLower() != observable2.Guid.ToLower();
//}
//public override bool Equals(object obj)
//{
// if (object.ReferenceEquals(this, null) || object.ReferenceEquals(obj, null))
// {
// return object.ReferenceEquals(this, obj);
// }
// if (obj is ObservableEntity<T>)
// {
// return Guid.ToLower() == (obj as ObservableEntity<T>).Guid.ToLower();
// }
// else
// {
// return false;
// }
//}
//public override int GetHashCode()
//{
// return base.GetHashCode();
//}
#endregion
}
}
|