aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Integration/Observables/ObservableEntity.cs
blob: d5b218453a869b7a5b8ebd6f44c5ca05db11bfbd (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
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;

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

        /// <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")]
        [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")]
        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")]
        [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]
        public ReadOnlyObservableCollection<ParameterItem> Parameters
        {
            get { return _parameters; }
            set { _parameters = value; RaisePropertyChangedAuto(); }
        }

        /// <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);

            if (!DesignMode)
            {
                ThreadsHelper.InvokeWhenAvailable(() =>
                {
                    Parameters = new ReadOnlyObservableCollection<ParameterItem>(this.CreateParametersCollection(ParameterItemMode.Binding));
                });
            }
        }

        /// <summary>
        /// Saves the changes on this entity to database.
        /// </summary>
        public virtual void Save()
        {
            ObservablesEntitiesAdapter.Instance.SaveChanges();
            OnSaved();
        }

        /// <summary>
        /// Attaches this entity to the proper DbSet.
        /// </summary>
        public virtual void Attach()
        {
            GetDbSet().Add(this as T);
        }

        /// <summary>
        /// Detaches this observable from the proper DbSet.
        /// </summary>
        public virtual void Detach()
        {
            GetDbSet().Remove(this as T);
        }

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

        /// <summary>
        /// Reloads this observable entity.
        /// </summary>
        /// <returns></returns>
        public Task Reload()
        {
            return ObservablesEntitiesAdapter.Instance.Context.Entry(this).ReloadAsync();
        }

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

            if (delProp != null)
            {
                delProp.SetValue(this, true);
                Save();
            }
            else
            {
                GetDbSet().Remove(this as T);
                Save();
            }
        }

        /// <summary>
        /// Deletes this entity without saving changes to data base.
        /// </summary>
        public virtual void DefferedDelete()
        {
            GetDbSet().Remove(this as T);
        }

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

        /// <summary>
        /// Gets the observable database set.
        /// </summary>
        /// <returns></returns>
        public DbSet<T> GetDbSet()
        {
            String tabelName = this.GetType().Name.PluralizeMVC();
            var p = typeof(ObservablesContext).GetProperty(tabelName);
            if (p != null)
            {
                var set1 = p.GetValue(ObservablesEntitiesAdapter.Instance.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(ObservablesEntitiesAdapter.Instance.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 void Save(DbContext context)
        {
            context.SaveChanges();
            OnSaved();
        }

        public Task SaveAsync(DbContext context)
        {
            return Task.Factory.StartNew(() => Save(context));
        }

        public bool CompareUsingJson(T entity)
        {
            String me = JsonConvert.SerializeObject(this);
            String other = JsonConvert.SerializeObject(entity);
            return me == other;
        }

        #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
    }
}