aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Embedded_SW/Embedded/Communication/PMR/FirmwareUpgrade/ValidateVersionResponse.pb-c.c
blob: 9be2cce207a6faeb271f46b4d8954f7ad0e31134 (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
/* Generated by the protocol buffer compiler.  DO NOT EDIT! */
/* Generated from: ValidateVersionResponse.proto */

/* Do not generate deprecated warnings for self */
#ifndef PROTOBUF_C__NO_DEPRECATED
#define PROTOBUF_C__NO_DEPRECATED
#endif

#include "ValidateVersionResponse.pb-c.h"
void   validate_version_response__init
                     (ValidateVersionResponse         *message)
{
  static const ValidateVersionResponse init_value = VALIDATE_VERSION_RESPONSE__INIT;
  *message = init_value;
}
size_t validate_version_response__get_packed_size
                     (const ValidateVersionResponse *message)
{
  assert(message->base.descriptor == &validate_version_response__descriptor);
  return protobuf_c_message_get_packed_size ((const ProtobufCMessage*)(message));
}
size_t validate_version_response__pack
                     (const ValidateVersionResponse *message,
                      uint8_t       *out)
{
  assert(message->base.descriptor == &validate_version_response__descriptor);
  return protobuf_c_message_pack ((const ProtobufCMessage*)message, out);
}
size_t validate_version_response__pack_to_buffer
                     (const ValidateVersionResponse *message,
                      ProtobufCBuffer *buffer)
{
  assert(message->base.descriptor == &validate_version_response__descriptor);
  return protobuf_c_message_pack_to_buffer ((const ProtobufCMessage*)message, buffer);
}
ValidateVersionResponse *
       validate_version_response__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data)
{
  return (ValidateVersionResponse *)
     protobuf_c_message_unpack (&validate_version_response__descriptor,
                                allocator, len, data);
}
void   validate_version_response__free_unpacked
                     (ValidateVersionResponse *message,
                      ProtobufCAllocator *allocator)
{
  if(!message)
    return;
  assert(message->base.descriptor == &validate_version_response__descriptor);
  protobuf_c_message_free_unpacked ((ProtobufCMessage*)message, allocator);
}
#define validate_version_response__field_descriptors NULL
#define validate_version_response__field_indices_by_name NULL
#define validate_version_response__number_ranges NULL
const ProtobufCMessageDescriptor validate_version_response__descriptor =
{
  PROTOBUF_C__MESSAGE_DESCRIPTOR_MAGIC,
  "ValidateVersionResponse",
  "ValidateVersionResponse",
  "ValidateVersionResponse",
  "",
  sizeof(ValidateVersionResponse),
  0,
  validate_version_response__field_descriptors,
  validate_version_response__field_indices_by_name,
  0,  validate_version_response__number_ranges,
  (ProtobufCMessageInit) validate_version_response__init,
  NULL,NULL,NULL    /* reserved[123] */
};
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;

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

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