Exemplo n.º 1
0
        public override int SaveChanges()
        {
            var modifiedEntries = ChangeTracker.Entries()
                                  .Where(x => (x.Entity is ITrackableEntity)
                                         &&
                                         (x.State == EntityState.Added ||
                                          x.State == EntityState.Modified));

            foreach (var entry in modifiedEntries)
            {
                ITrackableEntity entity = entry.Entity as ITrackableEntity;
                if (entity != null)
                {
                    string   identityName = GetUser();
                    DateTime now          = DateTime.UtcNow;

                    if (entry.State == EntityState.Added)
                    {
                        entity.CreatedBy   = identityName;
                        entity.CreatedDate = now;
                    }
                    else
                    {
                        Entry(entity).Property(x => x.CreatedBy).IsModified   = false;
                        Entry(entity).Property(x => x.CreatedDate).IsModified = false;
                    }

                    entity.UpdatedBy   = identityName;
                    entity.UpdatedDate = now;
                }
            }
            return(base.SaveChanges());
        }
Exemplo n.º 2
0
        private void FillTracableData(EntityEntry entry)
        {
            if (!(entry.Entity is ITrackableEntity))
            {
                return;
            }

            ITrackableEntity trackableEntity = entry.Entity as ITrackableEntity;
            SystemUser       currentUser     = GlobalConstants.GetCurrentUser();

            if (entry.State == EntityState.Added)
            {
                trackableEntity.CreateById   = currentUser.RecordId;
                trackableEntity.CreateByCode = currentUser.UserCode;
                trackableEntity.CreateByName = currentUser.UserName;
                trackableEntity.CreateTime   = DateTime.Now;
            }
            else if (entry.State == EntityState.Modified)
            {
                trackableEntity.UpdateById   = currentUser.RecordId;
                trackableEntity.UpdateByCode = currentUser.UserCode;
                trackableEntity.UpdateByName = currentUser.UserName;
                trackableEntity.UpdateTime   = DateTime.Now;
            }
        }
 public static void Bind(this ModuleAuditControl auditControl, ITrackableEntity item, int portalId, string unknownUserName)
 {
     auditControl.CreatedDate        = item.CreatedOnDate.ToLongDateString();
     auditControl.CreatedByUser      = UserHelper.GetUserDisplayName(portalId, item.CreatedByUserId) ?? unknownUserName;
     auditControl.LastModifiedDate   = item.LastModifiedOnDate.ToLongDateString();
     auditControl.LastModifiedByUser = UserHelper.GetUserDisplayName(portalId, item.LastModifiedByUserId) ?? unknownUserName;
 }
 public static TrackedItem CreateInsertTrackedItem(ITrackableEntity trackedEntity)
 {
     return(new TrackedItem
     {
         TrackedEntity = trackedEntity,
         Operation = ChangeTrackingOperation.Insert
     });
 }
 public static void Bind(this ModuleAuditControl auditControl, ITrackableEntity item)
 {
     auditControl.CreatedDate        = item.CreatedOnDate.ToLongDateString();
     auditControl.CreatedByUser      = Utils.GetUserDisplayName(item.CreatedByUserId, Null.NullInteger.ToString());
     auditControl.LastModifiedDate   = item.LastModifiedOnDate.ToLongDateString();
     auditControl.LastModifiedByUser = Utils.GetUserDisplayName(
         item.LastModifiedByUserId,
         Null.NullInteger.ToString());
 }
 public static TrackedItem CreateUpdateTrackedItem(ITrackableEntity trackedEntity, Dictionary <string, object> initialState)
 {
     return(new TrackedItem
     {
         TrackedEntity = trackedEntity,
         InitialState = initialState,
         Operation = ChangeTrackingOperation.Update
     });
 }
Exemplo n.º 7
0
        private static NativeLuaTable GenerateEntryForEntity(ITrackableEntity entity)
        {
            var entry = new NativeLuaTable();

            entry["text"]         = entity.Name;
            entry["icon"]         = entity.IconPath;
            entry["func"]         = entity.OnSelect.ToLuaFunction();
            entry["notCheckable"] = true;

            return(entry);
        }
Exemplo n.º 8
0
        private static void CopyTrackableFields(ITrackableDto target, ITrackableEntity source)
        {
            CheckHelper.ArgumentNotNull(target, "target");
            CheckHelper.ArgumentNotNull(source, "source");

            target.CreateDate = source.CreateDate;
            target.CreateUser = source.CreatedBy.GetFullName();

            target.ChangeDate = source.ChangeDate;
            target.ChangeUser = source.ChangedBy.GetFullName();
        }
Exemplo n.º 9
0
        /// <summary>
        /// Создать мета-информацию по сущности
        /// </summary>
        /// <param name="trackedEntity">Сущность, для которой требуется создать мета-информацию</param>
        /// <param name="user">Пользователь</param>
        /// <param name="userId">User id.</param>
        public static void CreateEntityInfo(this ITrackableEntity trackedEntity, ClaimsPrincipal user, long userId)
        {
            if (user is null)
            {
                throw new ArgumentNullException(nameof(user), $"{nameof(user)} is null.");
            }

            trackedEntity.EntityInfo = new TrackedEntity
            {
                CreatedBy     = userId,
                CreatedByName = userId != SystemUserId ? user.Identity?.Name : SystemUserName
            };
        }
Exemplo n.º 10
0
        public static void UpdateTrackingProperties(this ITrackableEntity trackable)
        {
            if (trackable == null)
            {
                return;
            }

            var now = DateTime.UtcNow;

            trackable.LastUpdatedOn = now;

            if (trackable.CreatedOn == default)
            {
                trackable.CreatedOn = now;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Обновить мета-информацию по сущности
        /// </summary>
        /// <param name="trackedEntity">Сущность, для которой требуется обновить мета-информацию</param>
        /// <param name="user">Пользователь</param>
        /// <param name="userId">User id.</param>
        public static void UpdateEntityInfo(this ITrackableEntity trackedEntity, ClaimsPrincipal user, long userId)
        {
            if (user is null)
            {
                throw new ArgumentNullException(nameof(user), $"{nameof(user)} is null.");
            }

            if (trackedEntity.EntityInfo is null)
            {
                throw new ArgumentNullException(nameof(trackedEntity.EntityInfo), $"{nameof(trackedEntity.EntityInfo)} is null.");
            }

            trackedEntity.EntityInfo.UpdatedAt     = DateTimeOffset.Now;
            trackedEntity.EntityInfo.UpdatedBy     = userId;
            trackedEntity.EntityInfo.UpdatedByName = userId != SystemUserId ? user.Identity?.Name : SystemUserName;
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Asynchronously adds an object to the table
        /// </summary>
        /// <param name="obj">The object to be added</param>
        /// <returns>Returns the <paramref name="obj"/> after being inserted</returns>
        public async Task <TEntity> AddAsync(TEntity obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj), "The given object must not be null");
            }
            if (obj is ITrackableEntity)
            {
                ITrackableEntity entity = obj as ITrackableEntity;
                entity.CreatedAt  = DateTime.UtcNow;
                entity.ModifiedAt = DateTime.UtcNow;
            }
            await this.Entities.AddAsync(obj);

            return(obj);
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Asynchronously begins tracking the given param
        /// <remarks>
        ///     All the properties will be marked
        ///     as modified. To mark only some properties use the
        ///     <see cref="M:Microsoft.EntityFrameworkCore.DbSet`1.Attach(`0)"/>
        /// </remarks>
        /// </summary>
        /// <param name="obj">The object to be marked</param>
        /// <returns>The given <paramref name="obj"/> after being inserted</returns>
        public async Task <TEntity> UpdateAsync(TEntity obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj), "The given object must not be null");
            }

            if (!ExistsAsync(obj.Id).Result)
            {
                throw new ArgumentException("The given object does not exist in DB", nameof(obj));
            }
            if (obj is ITrackableEntity)
            {
                ITrackableEntity entity = obj as ITrackableEntity;
                entity.ModifiedAt = DateTime.UtcNow;
            }

            await Task.Factory.StartNew(() =>
            {
                this.Entities.Update(obj);
            });

            return(obj);
        }
Exemplo n.º 14
0
        public static void UpdateTrackFields(this ITrackableEntity trackableEntity, IReadOnlyContainer container)
        {
            CheckHelper.ArgumentNotNull(trackableEntity, "trackableEntity");
            CheckHelper.ArgumentNotNull(container, "container");

            var utcNow = container.Get <ITimeService>().UtcNow;

            var currentUserDto = container.Get <ISecurityService>().CurrentUser;

            CheckHelper.NotNull(currentUserDto, "currentUserDto");

            var currentUser = container.Get <IPersistentService>().GetEntityById <User>(currentUserDto.Id);

            if (trackableEntity.IsNew())
            {
                trackableEntity.CreateDate   = utcNow;
                trackableEntity.CreatedBy    = currentUser;
                trackableEntity.CreateUserId = currentUser.Id;
            }

            trackableEntity.ChangeDate   = utcNow;
            trackableEntity.ChangedBy    = currentUser;
            trackableEntity.ChangeUserId = currentUser.Id;
        }
        public void TrackDelete(ITrackableEntity trackedObject)
        {
            var initialState = _stateService.GetState(trackedObject);

            _trackedItems.Add(TrackedItem.CreateDeleteTrackedItem(trackedObject, initialState));
        }
 public void TrackInsert(ITrackableEntity trackedObject)
 {
     _trackedItems.Add(TrackedItem.CreateInsertTrackedItem(trackedObject));
 }
Exemplo n.º 17
0
        public override int SaveChanges()
        {
            List <RecordAuditLog> auditLogs = new List <RecordAuditLog>();

            foreach (DbEntityEntry entry in this.ChangeTracker.Entries())
            {
                ITrackableEntity trackableEntity = entry.Entity as ITrackableEntity;
                IEntity          entity          = entry.Entity as IEntity;

                if (entry.State == EntityState.Deleted && !(entry.Entity is ISafeToDeleteEntity))
                {
                    RecordAuditLog log = new RecordAuditLog();
                    log.EntityName = entry.Entity.GetType().Name;
                    log.Operation  = entry.State.ToString();
                    log.Content    = this._xmlSerializer.SerializeToXML(entry.Entity);
                    log.CreatedBy  = this._contextProvider.UserName;
                    log.CreatedOn  = DateTime.UtcNow;

                    auditLogs.Add(log);
                }
                else if (entry.State == EntityState.Modified && trackableEntity != null)
                {
                    trackableEntity.ModifiedOn = DateTime.UtcNow;
                    trackableEntity.ModifiedBy = this._contextProvider.UserName;
                }
                else if (entry.State == EntityState.Added && entity != null)
                {
                    if (string.IsNullOrEmpty(entity.CreatedBy))
                    {
                        entity.CreatedBy = this._contextProvider.UserName;
                    }
                    if (entity.CreatedOn == default(DateTime))
                    {
                        entity.CreatedOn = DateTime.UtcNow;
                    }
                }
            }
            if (auditLogs.Count > 0 && AuditLoggingEnabled)
            {
                this.Set <RecordAuditLog>().AddRange(auditLogs);
            }
            try
            {
                return(base.SaveChanges());
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                                    .SelectMany(x => x.ValidationErrors)
                                    .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }