aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.DAL.Observables/ObservableEntity.cs
blob: e8a99cea6d8dc8b8255c9d1b13686600489fd72f (plain)
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
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 Force.DeepCloner;

namespace Tango.DAL.Observables
{
    /// <summary>
    /// Represents an observable entity base class.
    /// </summary>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    /// <seealso cref="Tango.DAL.Observables.IObservableEntity" />
    public abstract class ObservableEntity : ExtendedObject, IObservableEntity
    {
        /// <summary>
        /// Gets or sets the entity identifier.
        /// </summary>
        public abstract int ID { get; set; }

        /// <summary>
        /// Gets or sets the entity unique identifier.
        /// </summary>
        public abstract string Guid { get; set; }

        /// <summary>
        /// Gets or sets the entity last updated data and time.
        /// </summary>
        public abstract DateTime LastUpdated { get; set; }

        /// <summary>
        /// Saves the changes on this entity to database.
        /// </summary>
        public abstract void Save();

        /// <summary>
        /// Internal recursive saving method.
        /// </summary>
        /// <param name="savedEntities">The saved entities.</param>
        internal abstract void Save(List<IObservableEntity> savedEntities);

        /// <summary>
        /// Deletes this entity from the database.
        /// </summary>
        public abstract void Delete();

        /// <summary>
        /// Removed this entity from it's DB SET without saving changes.
        /// </summary>
        public abstract void SoftDelete();

        /// <summary>
        /// Deletes this entity from the database
        /// </summary>
        public abstract Task DeleteAsync();

        /// <summary>
        /// Saves the changes on this entity to database asynchronously.
        /// </summary>
        /// <returns></returns>
        public abstract Task SaveAsync();

        /// <summary>
        /// Converts the specified database conventional name to the observables conventional name.
        /// </summary>
        /// <param name="dalName">DAL name.</param>
        /// <returns></returns>
        public static String DalNameToStandardName(String dalName)
        {
            return String.Join("", dalName.Split('_').Select(x => ToTitleCase(x)));
        }

        /// <summary>
        /// Converts the specified text to title case.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public static string ToTitleCase(string text)
        {
            return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
        }

        /// <summary>
        /// Maps the database entity to an observable entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="observable">The observable.</param>
        protected static void MapEntityToObservable(Object entity, IObservableEntity observable)
        {
            String guid = entity.GetType().GetProperty("GUID").GetValue(entity).ToString();
            LoadedEntitiesService.Add(guid, observable);

            foreach (var prop in entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                String name = prop.Name == "ID" ? "ID" : DalNameToStandardName(prop.Name);

                if (prop.PropertyType.IsGenericType)
                {
                    object observableCollection = observable.GetType().GetProperty(name).GetValue(observable);

                    ThreadsHelper.InvokeUINow(() => observableCollection.GetType().GetMethod("Clear").Invoke(observableCollection, new object[] { }));

                    Type genericType = observable.GetType().GetProperty(name).PropertyType.GenericTypeArguments.Single();

                    foreach (var item in prop.GetValue(entity) as IEnumerable)
                    {
                        guid = item.GetType().GetProperty("GUID").GetValue(item).ToString();

                        var loadedEntity = LoadedEntitiesService.Get(guid);

                        if (loadedEntity != null)
                        {
                            ThreadsHelper.InvokeUINow(() => observableCollection.GetType().GetMethod("Add").Invoke(observableCollection, new object[] { loadedEntity }));
                        }
                        else
                        {
                            IObservableEntity newObservable = Activator.CreateInstance(genericType, new object[] { item }) as IObservableEntity;
                            LoadedEntitiesService.Add(guid, newObservable);
                            ThreadsHelper.InvokeUINow(() => observableCollection.GetType().GetMethod("Add").Invoke(observableCollection, new object[] { newObservable }));
                        }
                    }
                }
                else if (prop.PropertyType.IsClass && prop.PropertyType != typeof(String) && prop.PropertyType != typeof(DateTime) && prop.PropertyType != typeof(byte[]))
                {
                    Type propType = observable.GetType().GetProperty(name).PropertyType;

                    var nullableGuid = prop.GetValue(entity).GetType().GetProperty("GUID").GetValue(prop.GetValue(entity));

                    if (nullableGuid == null)
                    {
                        nullableGuid = System.Guid.NewGuid().ToString();
                        prop.GetValue(entity).GetType().GetProperty("GUID").SetValue(prop.GetValue(entity), nullableGuid);
                    }

                    guid = nullableGuid.ToString();

                    var loadedEntity = LoadedEntitiesService.Get(guid);

                    if (loadedEntity != null)
                    {
                        observable.GetType().GetProperty(name).SetValue(observable, loadedEntity);
                    }
                    else
                    {
                        IObservableEntity newObservable = Activator.CreateInstance(propType, new object[] { prop.GetValue(entity) }) as IObservableEntity;
                        LoadedEntitiesService.Add(guid, newObservable);
                        observable.GetType().GetProperty(name).SetValue(observable, newObservable);
                    }
                }
                else
                {
                    observable.GetType().GetProperty(name).SetValue(observable, prop.GetValue(entity));
                }
            }
        }

        /// <summary>
        /// Creates an observable entity from the specified database entity.
        /// </summary>
        /// <typeparam name="TObservable">The type of the observable.</typeparam>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public static TObservable CreateObservableFromEntity<TObservable>(Object entity) where TObservable : IObservableEntity
        {
            String guid = entity.GetType().GetProperty("GUID").GetValue(entity).ToString();
            var observable = LoadedEntitiesService.Get(guid);

            if (observable != null)
            {
                return (TObservable)observable;
            }
            else
            {
                return (TObservable)Activator.CreateInstance(typeof(TObservable), new object[] { entity });
            }
        }

        /// <summary>
        /// Gets a collection of entities which are dependent on this entity.
        /// </summary>
        /// <returns>
        /// Collection of entities names and guids
        /// </returns>
        public List<KeyValuePair<String, String>> GetDependentEntitiesNameAndGuid()
        {
            List<KeyValuePair<String, String>> namesAndIds = new List<KeyValuePair<string, string>>();

            foreach (var prop in this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.PropertyType.IsGenericType))
            {
                IList list = prop.GetValue(this) as IList;

                foreach (var item in list)
                {
                    namesAndIds.Add(new KeyValuePair<string, string>(item.GetType().Name, item.GetType().GetProperty("ID").GetValue(item).ToString()));
                }
            }

            return namesAndIds;
        }
    }

    /// <summary>
    /// Represents a generic observable entity base class.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <seealso cref="Tango.Core.ExtendedObject" />
    /// <seealso cref="Tango.DAL.Observables.IObservableEntity" />
    public abstract class ObservableEntity<T> : ObservableEntity where T : class
    {
        private Regex regExDAL;
        private bool _isNew;

        /// <summary>
        /// Gets or sets the entity.
        /// </summary>
        protected T Entity { get; set; }

        private Int32 _id;
        /// <summary>
        /// Gets or sets the entity identifier.
        /// </summary>
        [EntityFieldName("ID")]
        public override Int32 ID
        {
            get { return _id; }
            set { _id = value; RaisePropertyChanged(nameof(ID)); }
        }

        private String _guid;
        /// <summary>
        /// Gets or sets the entity unique identifier.
        /// </summary>
        [EntityFieldName("GUID")]
        public override 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>
        [EntityFieldName("LAST_UPDATED")]
        public override DateTime LastUpdated
        {
            get { return _lastUpdated; }
            set { _lastUpdated = value; RaisePropertyChanged(nameof(LastUpdated)); }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ObservableEntity{T}"/> class.
        /// </summary>
        public ObservableEntity()
        {
            Entity = Activator.CreateInstance<T>();
            Guid = System.Guid.NewGuid().ToString();
            LastUpdated = DateTime.UtcNow;
            _isNew = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ObservableEntity{T}"/> class.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public ObservableEntity(T entity)
        {
            Entity = entity;

            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 override void Save()
        {
            Save(new List<IObservableEntity>());
            ObservablesEntitiesAdapter.Instance.SaveChanges();
        }

        /// <summary>
        /// Saves the changes on this entity to database asynchronously.
        /// </summary>
        /// <returns></returns>
        public override Task SaveAsync()
        {
            return Task.Factory.StartNew(() =>
            {
                Save();
            });
        }

        /// <summary>
        /// Deletes this entity from the database
        /// </summary>
        public override void Delete()
        {
            var delProp = this.GetType().GetProperty("Deleted");

            if (delProp != null)
            {
                delProp.SetValue(this, true);
                Save();
            }
            else
            {
                String tabelName = this.GetType().GetDALName();
                DbSet<T> dbSet = typeof(RemoteDB).GetProperty(tabelName).GetValue(ObservablesEntitiesAdapter.Instance.Context) as DbSet<T>;
                dbSet.Remove(Entity);
                ObservablesEntitiesAdapter.Instance.SaveChanges();
            }
        }

        /// <summary>
        /// Removed this entity from it's DB SET without saving changes.
        /// </summary>
        public override void SoftDelete()
        {
            var delProp = this.GetType().GetProperty("IsDeleted");

            if (delProp != null)
            {
                delProp.SetValue(this, true);
            }
            else
            {
                String tabelName = this.GetType().GetDALName();
                DbSet<T> dbSet = typeof(RemoteDB).GetProperty(tabelName).GetValue(ObservablesEntitiesAdapter.Instance.Context) as DbSet<T>;
                dbSet.Remove(Entity);
            }
        }

        /// <summary>
        /// Deletes this entity from the database
        /// </summary>
        public override Task DeleteAsync()
        {
            return Task.Factory.StartNew(() => 
            {
                Delete();
            });
        }

        /// <summary>
        /// Internal recursive saving method.
        /// </summary>
        /// <param name="savedEntities">The saved entities.</param>
        internal override void Save(List<IObservableEntity> savedEntities)
        {
            savedEntities.Add(this);

            //Update last updated...
            this.LastUpdated = DateTime.UtcNow;

            //Match guids..

            foreach (var prop in this.GetType().GetProperties().Where(x => !x.PropertyType.IsGenericType && x.PropertyType.IsClass && x.PropertyType != typeof(String) && x.PropertyType != typeof(DateTime) && x.PropertyType != typeof(byte[])))
            {
                IObservableEntity propObservable = prop.GetValue(this) as IObservableEntity;

                if (propObservable != null)
                {
                    var guidProp = this.GetType().GetProperty(prop.Name + "Guid");

                    if (guidProp != null)
                    {
                        guidProp.SetValue(this, propObservable.Guid);
                    }
                    else
                    {
                        guidProp = this.GetType().GetProperty(prop.Name.SingularizeMVC() + "Guid");
                        if (guidProp != null)
                        {
                            guidProp.SetValue(this, propObservable.Guid);
                        }
                    }
                }
            }

            //Match guids..

            using (RemoteDB db = new RemoteDB(SettingsManager.Default.DataBase.SQLServerAddress, false))
            {
                foreach (var prop in this.GetType().GetProperties().OrderBy(x => x.PropertyType.IsPrimitive))
                {

                    String dalName = prop.GetDALName();

                    if (prop.PropertyType.IsGenericType)
                    {
                        foreach (var item in (prop.GetValue(this) as IEnumerable).OfType<ObservableEntity>())
                        {
                            if (!savedEntities.Contains(item))
                            {
                                item.Save(savedEntities);
                            }
                        }
                    }
                    else if (prop.PropertyType.IsClass && prop.PropertyType != typeof(String) && prop.PropertyType != typeof(DateTime) && prop.PropertyType != typeof(byte[]))
                    {
                        var item = (prop.GetValue(this) as ObservableEntity);
                        if (!savedEntities.Contains(item))
                        {
                            item.Save(savedEntities);
                        }
                        var propEntityType = prop.PropertyType.GetProperty("Entity", BindingFlags.NonPublic | BindingFlags.Instance);
                        typeof(T).GetProperty(dalName).SetValue(Entity, propEntityType.GetValue((prop.GetValue(this))));
                    }
                    else
                    {
                        typeof(T).GetProperty(dalName).SetValue(Entity, prop.GetValue(this));
                    }
                }

                if (_isNew)
                {
                    String tabelName = this.GetType().GetDALName();
                    DbSet<T> dbSet = typeof(RemoteDB).GetProperty(tabelName).GetValue(ObservablesEntitiesAdapter.Instance.Context) as DbSet<T>;
                    dbSet.Add(Entity);
                }

                if (LoadedEntitiesService.IsLoaded(this.Guid))
                {
                    MapEntityToObservable(Entity, this);
                }

                _isNew = false;
            }
        }
    }
}