Ejemplo n.º 1
0
        private void OnEntityAdded(EntityChangeData changeData)
        {
            bool include = false;

            foreach (var includeitem in IncludeDBTypeIndexFilter)
            {
                //debug
                var someentity = changeData.Entity.Manager.GetFirstEntityWithDataBlob(includeitem);
                var db         = someentity.GetDataBlob <BaseDataBlob>(includeitem);
                //end debug

                if (changeData.Entity.HasDataBlob(includeitem))
                {
                    include = true;
                }
                else
                {
                    include = false;
                    break;
                }
            }
            if (include && _ownerDB.OwnedEntities.ContainsKey(changeData.Entity.Guid)) //note: this will miss a lot of new entittes, since this code gets called before ownership is set on a new entity. it will get caught when a datablob is set though.
            {
                ListningToEntites.Add(changeData.Entity);
                EntityChanges.Enqueue(changeData);
            }
        }
Ejemplo n.º 2
0
        public void LogTrackedChanges <TEntity>(EntityChanges <TEntity> change) where TEntity : class, IPersistable
        {
            if (change?.FieldChanges == null)
            {
                return;
            }

            var config = GetTypeConfiguration(typeof(TEntity).Name);

            var changes = change.FieldChanges.Where(f => config.Properties.Any(x => x.Name == f.FieldName)).ToList();

            foreach (var field in changes)
            {
                var property = config.Properties.FirstOrDefault(x => x.Name == field.FieldName);

                object newValue = field.NewValue;
                if (newValue != null && (property?.PropertyType == typeof(Guid) || property?.PropertyType == typeof(Guid?)))
                {
                    newValue = LoadReferenceName(field, property) ?? newValue;
                }

                _historyService.Save(change.Entity.Id, "fieldChanged",
                                     field.FieldName.ToLowerFirstLetter(),
                                     field.OldValue, newValue);
            }
        }
        /// <summary>
        /// Find changed, related entities before the entities are saved or deleted.
        /// </summary>
        /// <param name="entities">
        /// The entities supplied to OnBeforeSave or OnBeforeDelete.
        /// </param>
        /// <param name="cause">
        /// Whether the operation is a save or delete.
        /// </param>
        /// <returns>
        /// Any entities, along with modified fields and related entities.
        /// </returns>
        protected internal static IDictionary <long, EntityChanges> GetEntityChanges(IList <IEntity> entities, InvalidationCause cause)
        {
            IDictionary <long, EntityChanges> result;
            EntityChanges      entityChanges;
            IEntityFieldValues fields;
            IDictionary <long, IChangeTracker <IMutableIdKey> > forwardRelationships;
            IDictionary <long, IChangeTracker <IMutableIdKey> > reverseRelationships;

            result = new Dictionary <long, EntityChanges>();
            foreach (IEntity entity in entities)
            {
                entityChanges = new EntityChanges();
                entity.GetChanges(out fields, out forwardRelationships, out reverseRelationships);
                if (forwardRelationships != null)
                {
                    entityChanges.RelationshipTypesToEntities.UnionWith(
                        GetModifiedEntitiesForRelationships(forwardRelationships));
                }
                if (reverseRelationships != null)
                {
                    entityChanges.RelationshipTypesToEntities.UnionWith(
                        GetModifiedEntitiesForRelationships(reverseRelationships));
                }
                if (fields != null)
                {
                    entityChanges.FieldTypes.UnionWith(fields.FieldIds);
                }

                result.Add(entity.Id, entityChanges);
            }

            return(result);
        }
Ejemplo n.º 4
0
        internal bool TryDequeue(out EntityChangeData changeData)
        {
            /*
             * if (EntityChanges.TryDequeue(out changeData))
             * {
             *  if (changeData.ChangeType == EntityChangeData.EntityChangeType.EntityRemoved)
             *      ListningToEntites.Remove(changeData.Entity);
             *  if (changeData.ChangeType == EntityChangeData.EntityChangeType.EntityAdded)
             *  {
             *
             *      if (changeData.Entity.HasDataBlob<OwnedDB>() && changeData.Entity.GetDataBlob<OwnedDB>().OwnedByFaction != ListenForFaction)
             *      {
             *          if(
             *      }
             *
             *  }
             *  return true;
             * }
             *
             *
             *
             * return
             * false; */

            return(EntityChanges.TryDequeue(out changeData));
        }
Ejemplo n.º 5
0
 private void OnEntityRemoved(EntityChangeData changeData)
 {
     if (ListningToEntites.Contains(changeData.Entity))
     {
         ListningToEntites.Add(changeData.Entity);
         EntityChanges.Enqueue(changeData);
     }
 }
Ejemplo n.º 6
0
        public void Test_DefaultCtor()
        {
            EntityChanges fieldsAndRelationshipTypes;

            fieldsAndRelationshipTypes = new EntityChanges();

            Assert.That(fieldsAndRelationshipTypes, Has.Property("RelationshipTypesToEntities").Empty);
            Assert.That(fieldsAndRelationshipTypes, Has.Property("FieldTypes").Empty);
        }
Ejemplo n.º 7
0
        public bool IsTriggered(EntityChanges <Order> changes)
        {
            var watchProperties = new[]
            {
                nameof(Order.DeliveryDate),
            };

            return(changes?.FieldChanges?.Count(x => watchProperties.Contains(x.FieldName)) > 0);
        }
        public bool IsTriggered(EntityChanges <Shipping> changes)
        {
            var watchProperties = new[]
            {
                nameof(Shipping.TarifficationType),
            };

            return(changes?.FieldChanges?.Count(x => watchProperties.Contains(x.FieldName)) > 0);
        }
        public bool IsTriggered(EntityChanges <Warehouse> changes)
        {
            var watchProperties = new[]
            {
                nameof(Warehouse.City),
                nameof(Warehouse.Address)
            };

            return(changes?.FieldChanges?.Count(x => watchProperties.Contains(x.FieldName)) > 0);
        }
Ejemplo n.º 10
0
 private void OnDBRemoved(EntityChangeData changeData)
 {
     if (ListningToEntites.Contains(changeData.Entity))
     {
         if (IncludeDBTypeIndexFilter.Contains(EntityManager.DataBlobTypes[changeData.Datablob.GetType()]))
         {
             ListningToEntites.Remove(changeData.Entity);
         }
         EntityChanges.Enqueue(changeData);
     }
 }
Ejemplo n.º 11
0
        public void Test_Ctor()
        {
            EntityChanges fieldsAndRelationshipTypes;
            HashSet <RelationshipTypeToEntity> relationshipTypesToEntities;
            HashSet <long> fieldTypes;

            relationshipTypesToEntities = new HashSet <RelationshipTypeToEntity>();
            fieldTypes = new HashSet <long>();

            fieldsAndRelationshipTypes = new EntityChanges(relationshipTypesToEntities, fieldTypes);

            Assert.That(fieldsAndRelationshipTypes, Has.Property("RelationshipTypesToEntities").EquivalentTo(relationshipTypesToEntities));
            Assert.That(fieldsAndRelationshipTypes, Has.Property("FieldTypes").EquivalentTo(fieldTypes));
        }
Ejemplo n.º 12
0
        public void Appy(EntityChanges <TEntity> changes)
        {
            if (changes?.FieldChanges == null)
            {
                return;
            }

            foreach (var change in changes.FieldChanges)
            {
                if (this._afterActions.ContainsKey(change.FieldName))
                {
                    this._afterActions[change.FieldName](changes.Entity, change);
                }
            }
        }
Ejemplo n.º 13
0
 public virtual void AddEntityChange(object entity)
 {
     try
     {
         var change = CreateEntityChange(entity);
         if (change != null)
         {
             EntityChanges.Add(change);
         }
     }
     catch (Exception e)
     {
         Logger.Error(e.Message, e);
     }
 }
        public bool IsTriggered(EntityChanges <Order> changes)
        {
            var watchProperties = new[]
            {
                nameof(Order.ShippingId),
                nameof(Order.DeliveryType),
                nameof(Order.PalletsCount),
                nameof(Order.ClientId),
                nameof(Order.ShippingDate),
                nameof(Order.DeliveryDate),
                nameof(Order.ShippingCity),
                nameof(Order.DeliveryCity)
            };

            return(changes?.FieldChanges?.Count(x => watchProperties.Contains(x.FieldName)) > 0);
        }
Ejemplo n.º 15
0
        public virtual EntityChangeSet CreateEntityChangeSet()
        {
            if (!IsEntityHistoryEnabled)
            {
                return(null);
            }

            var changeSet = new EntityChangeSet()
            {
                Reason = EntityChangeSetReasonProvider.Reason.TruncateWithPostfix(EntityChangeSet.MaxReasonLength),

                // Fill "who did this change"
                BrowserInfo          = ClientInfoProvider.BrowserInfo.TruncateWithPostfix(EntityChangeSet.MaxBrowserInfoLength),
                ClientIpAddress      = ClientInfoProvider.ClientIpAddress.TruncateWithPostfix(EntityChangeSet.MaxClientIpAddressLength),
                ClientName           = ClientInfoProvider.ComputerName.TruncateWithPostfix(EntityChangeSet.MaxClientNameLength),
                ImpersonatorTenantId = AbpSession.ImpersonatorTenantId,
                ImpersonatorUserId   = AbpSession.ImpersonatorUserId,
                TenantId             = AbpSession.TenantId,
                UserId = AbpSession.UserId
            };

            // Add description for property change
            foreach (var entityHistoryEvent in EntityHistoryEvents.Where(x =>
                                                                         !string.IsNullOrEmpty(x.PropertyName) &&
                                                                         x.EntityChange != null &&
                                                                         x.EventType != EntityHistoryCommonEventTypes.PROPERTY_CHANGE_AS_EVENT))
            {
                var prop = EntityChanges
                           .FirstOrDefault(x =>
                                           x.EntityId == entityHistoryEvent.EntityChange.EntityId &&
                                           x.EntityTypeFullName == entityHistoryEvent.EntityChange.EntityTypeFullName &&
                                           x.PropertyChanges != null)
                           ?.PropertyChanges.FirstOrDefault(x => x.PropertyName == entityHistoryEvent.PropertyName);

                if (prop != null)
                {
                    entityHistoryEvent.EntityPropertyChange = prop;

                    EntityChanges.Remove(entityHistoryEvent.EntityChange);
                    entityHistoryEvent.EntityChange = null;
                }
            }

            changeSet.EntityChanges = EntityChanges;

            return(changeSet);
        }
Ejemplo n.º 16
0
        public override string ToString()
        {
            var sb = new StringBuilder();

            sb.AppendLine($"AUDIT LOG: [{HttpStatusCode?.ToString() ?? "---"}: {(HttpMethod ?? "-------").PadRight(7)}] {Url}");
            sb.AppendLine($"- UserName - UserId                 : {UserName} - {UserId}");
            sb.AppendLine($"- ClientIpAddress        : {ClientIpAddress}");
            sb.AppendLine($"- ExecutionDuration      : {ExecutionDuration}");

            if (Actions.Any())
            {
                sb.AppendLine("- Actions:");
                foreach (var action in Actions)
                {
                    sb.AppendLine($"  - {action.ServiceName}.{action.MethodName} ({action.ExecutionDuration} ms.)");
                    sb.AppendLine($"    {action.Parameters}");
                }
            }

            if (Exceptions.Any())
            {
                sb.AppendLine("- Exceptions:");
                foreach (var exception in Exceptions)
                {
                    sb.AppendLine($"  - {exception.Message}");
                    sb.AppendLine($"    {exception}");
                }
            }

            if (EntityChanges.Any())
            {
                sb.AppendLine("- Entity Changes:");
                foreach (var entityChange in EntityChanges)
                {
                    sb.AppendLine($"  - [{entityChange.ChangeType}] {entityChange.EntityTypeFullName}, Id = {entityChange.EntityId}");
                    foreach (var propertyChange in entityChange.PropertyChanges)
                    {
                        //sb.AppendLine($"    {propertyChange.PropertyName}: {propertyChange.OriginalValue} -> {propertyChange.NewValue}");
                    }
                }
            }

            return(sb.ToString());
        }
Ejemplo n.º 17
0
        internal virtual void AddChange(EntityChangeData changeData)
        {
            if (changeData.ChangeType != EntityChangeData.EntityChangeType.EntityAdded)
            {
                if (ListningToEntites.Contains(changeData.Entity))
                {
                    EntityChanges.Enqueue(changeData);
                }
            }
            else
            {
                bool isvalid = changeData.Entity.IsValid;

                ListningToEntites.Add(changeData.Entity);
                EntityChanges.Enqueue(changeData);
            }
            if (changeData.ChangeType == EntityChangeData.EntityChangeType.EntityRemoved)
            {
                ListningToEntites.Remove(changeData.Entity);
            }
        }
Ejemplo n.º 18
0
        private void LogEntityChanges(IEnumerable <EntityEntry> entities)
        {
            var modificationDate = DateTime.UtcNow;

            foreach (var entity in entities)
            {
                // todo: currently can't log values without Id property. (like book editions)
                if (!entity.IsKeySet || entity.Properties.All(x => x.Metadata.Name != "Id"))
                {
                    continue;
                }

                var entityId   = entity.OriginalValues["Id"].ToString();
                var properties = entity.OriginalValues.Properties.Where(p => p.Name != "ModificationDate").ToList();

                foreach (var property in properties)
                {
                    var originalValue = entity.OriginalValues[property]?.ToString();
                    var currentValue  = entity.CurrentValues[property]?.ToString();

                    if (originalValue == currentValue)
                    {
                        continue;
                    }

                    var ec = new EntityChange
                    {
                        EntityId         = new Guid(entityId),
                        PropertyName     = property.Name,
                        OldValue         = originalValue,
                        NewValue         = currentValue,
                        ModificationDate = modificationDate
                                           // TODO (v0.5): create relations with user model.
                                           // ModifierId =
                    };
                    EntityChanges.Add(ec);
                }
            }
        }
Ejemplo n.º 19
0
 private void OnDBAdded(EntityChangeData changeData)
 {
     if (ListningToEntites.Contains(changeData.Entity))
     {
         ListningToEntites.Add(changeData.Entity);
         EntityChanges.Enqueue(changeData);
     }
     else
     {
         if (IncludeDBTypeIndexFilter.Contains(EntityManager.DataBlobTypes[changeData.Datablob.GetType()]))
         {
             bool include = false;
             foreach (var includeitem in IncludeDBTypeIndexFilter)
             {
                 if (!changeData.Entity.HasDataBlob(includeitem))
                 {
                     include = false;
                     break;
                 }
                 else
                 {
                     include = true;
                 }
             }
             if (include && _ownerDB.OwnedEntities.ContainsKey(changeData.Entity.Guid))
             {
                 ListningToEntites.Add(changeData.Entity);
                 EntityChangeData addedChange = new EntityChangeData()
                 {
                     ChangeType = EntityChangeData.EntityChangeType.EntityAdded,
                     Entity     = changeData.Entity
                 };
                 EntityChanges.Enqueue(addedChange);
                 //EntityChanges.Enqueue(changeData);
             }
         }
     }
 }
Ejemplo n.º 20
0
        public virtual void SaveAndClear()
        {
            try
            {
                if (!IsEntityHistoryEnabled)
                {
                    return;
                }

                var changeSet = CreateEntityChangeSet();
                if (changeSet == null)
                {
                    return;
                }
                Save(changeSet);
                EntityChanges.Clear();
                EntityHistoryEvents.Clear();
            }
            catch (Exception e)
            {
                Logger.Error(e.Message, e);
            }
        }
Ejemplo n.º 21
0
 public async Task UpdateSharedEntity(string key1, string key2, EntityChanges entityChanges)
 {
     var jsonString = await cache.Do(key1, key2, entity =>
     {
         foreach (var item in entityChanges.Operations)
         {
             if (item.Name == nameof(AddOrSetOperation))
             {
                 var addOrSet = JsonConvert.DeserializeObject <AddOrSetOperation>(item.JSON);
                 var at       = OrType.Make <JObject, JArray>(entity);
                 foreach (var pathPart in addOrSet.Path.SkipLast(1))
                 {
                     at = at.SwitchReturns(x => Navigate(x, pathPart), x => Navigate(x, pathPart));
                 }
                 at.Switch(x => x[addOrSet.Path.Last()] = ToValue(addOrSet.Value), x => x[int.Parse(addOrSet.Path.Last())] = ToValue(addOrSet.Value));
             }
             if (item.Name == nameof(DeleteOperation))
             {
                 var deleteOperation = JsonConvert.DeserializeObject <DeleteOperation>(item.JSON);
                 var at = OrType.Make <JObject, JArray>(entity);
                 foreach (var pathPart in deleteOperation.Path.SkipLast(1))
                 {
                     at = at.SwitchReturns(x => Navigate(x, pathPart), x => Navigate(x, pathPart));
                 }
                 at.Switch(x => x.Remove(deleteOperation.Path.Last()), x => throw new Exception("cannot delete from list"));
             }
             else if (item.Name == nameof(AppendToListOperation))
             {
                 var append = JsonConvert.DeserializeObject <AppendToListOperation>(item.JSON);
                 var at     = OrType.Make <JObject, JArray>(entity);;
                 foreach (var pathPart in append.Path)
                 {
                     at = at.SwitchReturns(x => Navigate(x, pathPart), x => Navigate(x, pathPart));
                 }
                 at.Switch(x => throw new Exception("cannot append to object"), x => x.Append(ToValue(append.Value)));
             }
 public bool IsTriggered(EntityChanges <Tariff> changes)
 {
     return(changes?.FieldChanges?.Count > 0);
 }
Ejemplo n.º 23
0
 internal void Enqueue(EntityChangeData changeData)
 {
     EntityChanges.Enqueue(changeData);
 }