예제 #1
0
        /// <summary>
        ///     Trim for string properties
        /// </summary>
        private void OnBeforeSaving()
        {
            var entries = ChangeTracker?.Entries();

            if (entries == null)
            {
                return;
            }

            foreach (var entry in entries)
            {
                var propertyValues =
                    entry.CurrentValues.Properties.Where(p =>
                                                         p.ClrType == typeof(string));

                foreach (var property in propertyValues)
                {
                    if (entry.CurrentValues[property.Name] != null)
                    {
                        entry.CurrentValues[property.Name] =
                            entry.CurrentValues[property.Name].ToString().Trim();
                    }
                }
            }
        }
예제 #2
0
        private void HandleSoftDeletableEntities()
        {
            IEnumerable <EntityEntry> entries = ChangeTracker?.Entries()?.Where(x => x.Entity is ISoftDeletable && x.State == EntityState.Deleted);

            if (entries.HasElements())
            {
                foreach (var entry in entries)
                {
                    entry.State = EntityState.Modified;
                    ISoftDeletable entity = (ISoftDeletable)entry.Entity;
                    entity.IsDeleted = true;
                }
            }
        }
예제 #3
0
        private void HandleAuditableEntities()
        {
            string currentUser = _httpContextAccessor?.HttpContext?.User?.Identity?.Name;

            IEnumerable <EntityEntry> entities = ChangeTracker?.Entries()?.Where(x => x.Entity is IAuditable && (x.State == EntityState.Added || x.State == EntityState.Modified));

            if (entities.HasElements())
            {
                foreach (EntityEntry entry in entities)
                {
                    if (entry.Entity is IAuditable)
                    {
                        IAuditable auditable = ((IAuditable)entry.Entity);

                        if (entry.State == EntityState.Added)
                        {
                            if (auditable.CreatedOn == DateTime.MinValue)
                            {
                                auditable.CreatedOn = SillycoreApp.Instance?.DateTimeProvider?.Now ?? DateTime.UtcNow;

                                if (SetUpdatedOnSameAsCreatedOnForNewObjects)
                                {
                                    auditable.UpdatedOn = auditable.CreatedOn;
                                }
                            }

                            if (String.IsNullOrEmpty(auditable.CreatedBy))
                            {
                                auditable.CreatedBy = currentUser;

                                if (SetUpdatedOnSameAsCreatedOnForNewObjects)
                                {
                                    auditable.UpdatedBy = auditable.CreatedBy;
                                }
                            }
                        }
                        else
                        {
                            auditable.UpdatedOn = SillycoreApp.Instance?.DateTimeProvider?.Now ?? DateTime.UtcNow;
                            auditable.UpdatedBy = currentUser;
                        }
                    }
                }
            }
        }
예제 #4
0
        public void Save(User loggedUser)
        {
            if (loggedUser == null)
            {
                loggedUser = GetDaemonUser();
            }

            if (ChangeTracker != null)
            {
                foreach (var entry in ChangeTracker?.Entries())
                {
                    if (loggedUser != null && entry.Entity?.GetType() != typeof(Log))
                    {
                        GerarLog(entry, loggedUser);
                    }
                }
            }
            SaveChanges();
        }
예제 #5
0
        /// <summary> Updates timestamps values on changed entities. </summary>
        void ApplyUpdate()
        {
            var entries = ChangeTracker?.Entries()
                          .Where(e => e.Entity is BaseEntity && (e.State == EntityState.Added || e.State == EntityState.Modified));

            if (entries == null)
            {
                return;
            }

            foreach (var entry in entries)
            {
                var entity = (BaseEntity)entry.Entity;
                if (entry.State == EntityState.Added)
                {
                    entity.CreatedAt = DateTimeOffset.UtcNow;
                }
                entity.LastUpdatedAt = DateTimeOffset.UtcNow;
            }
        }
예제 #6
0
        public override async Task <int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            // Get the entries that are auditable
            var auditableEntitySet = ChangeTracker.Entries <IAuditableModel>().ToList();

            if (auditableEntitySet.Any())
            {
                Guid userId = _httpContextAccessor.HttpContext.GetLoggedUserId();
                //Guid userId = new Guid("9F917B76-5B52-4DF2-9A9E-D99875777AC4");
                DateTime currentDate = DateTime.Now;

                // Set the audit information for each record
                foreach (var auditableEntity in auditableEntitySet.Where(x =>
                                                                         x.State == EntityState.Added || x.State == EntityState.Modified))
                {
                    if (auditableEntity.State == EntityState.Added)
                    {
                        auditableEntity.Entity.CreatedDate = currentDate;
                        auditableEntity.Entity.CreatedBy   = userId;
                    }

                    auditableEntity.Entity.UpdatedDate = currentDate;
                    auditableEntity.Entity.UpdatedBy   = userId;
                }
            }

            // Try-catch for ConcurrencyException
            try
            {
                return(await base.SaveChangesAsync(cancellationToken));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                await ex.Entries.Single().ReloadAsync(cancellationToken);

                return(await base.SaveChangesAsync(cancellationToken));
            }
        }
예제 #7
0
        public override async Task <int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
        {
            foreach (var entry in ChangeTracker.Entries <AuditableEntity>())
            {
                switch (entry.State)
                {
                case EntityState.Added:
                    entry.Entity.UserId = _identityService.UserId;
                    if (entry.Entity.Created == default)
                    {
                        entry.Entity.Created = _dateTime.Now;
                    }
                    break;

                case EntityState.Modified:
                    entry.Entity.LastModified = _dateTime.Now;
                    break;

                case EntityState.Detached:
                    break;

                case EntityState.Unchanged:
                    break;

                case EntityState.Deleted:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            var result = await base.SaveChangesAsync(cancellationToken);

            await DispatchEvents();

            return(result);
        }
예제 #8
0
        //Değişiklikleri har kaydetme metodunu çağırdığımda otomatik loglama işlemleri gerçekleşsin
        //https://www.tutorialsteacher.com/ioc
        public override int SaveChanges()
        {
            //Yeni eklenen veya yeni güncellenen kayıtları yakalıyoruz. IEntityChangeTracker isimli interface sayesinde kendisi yapılan değişimleri izler. Bu özellik sayesinde kendi tuttuğu EntityState(Status Enum Gibi) üzerinden yakalama şansına sahip oluruz.

            var modifiedEntries = ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);

            string   identity     = WindowsIdentity.GetCurrent().Name;
            string   computerName = Environment.MachineName;
            DateTime date         = DateTime.UtcNow;
            //IP Yakalama Utility içerisine atılacak.
            string ip = RemoteIP.IpAddress;

            foreach (var item in modifiedEntries)
            {
                //Tüm yeni eklenen/güncellenen kayıtları sırayla alıyorum. Hepsinin ortak tipi CoreEntity'dir.
                CoreEntity entity = item.Entity as CoreEntity;
                if (item != null)
                {
                    if (item.State == EntityState.Added)
                    {
                        entity.Status              = Core.Core.Entity.Enum.Status.Active;
                        entity.CreatedADUserName   = identity;
                        entity.CreatedComputerName = computerName;
                        entity.CreatedDate         = date;
                        entity.CreatedIp           = ip;
                    }
                    else if (item.State == EntityState.Modified)
                    {
                        entity.ModifiedADUserName   = identity;
                        entity.ModifiedComputerName = computerName;
                        entity.ModifiedDate         = date;
                        entity.ModifiedIp           = ip;
                    }
                }
            }

            return(base.SaveChanges());
        }
예제 #9
0
        protected virtual void ChangeDefaultValue()
        {
            int cntAdded    = 0;
            int cntDeleted  = 0;
            int cntModified = 0;

            foreach (var entry in ChangeTracker.Entries().Where(p => (p.State == EntityState.Added || p.State == EntityState.Deleted || p.State == EntityState.Modified)))
            {
                logger.Debug(string.Format("ChangeEntity : {0} {1}", entry.Entity.ToString(), entry.State.ToString()));
                if (entry.State == EntityState.Modified)
                {
                    cntModified++;
                }
                else if (entry.State == EntityState.Deleted)
                {
                    cntDeleted++;
                }
                else
                {
                    cntAdded++;
                }

                if (typeof(ICUModel).IsAssignableFrom(entry.Entity.GetType()))
                {
                    DateTime dtCur = DateTime.UtcNow;
                    if (entry.State == EntityState.Added)
                    {
                        ((ICUModel)entry.Entity).CreateDT = dtCur;
                    }
                    if (entry.State != EntityState.Deleted)
                    {
                        ((ICUModel)entry.Entity).UpdateDT = dtCur;
                    }
                }
            }

            logger.Debug(string.Format("ChangeEntity Count : Added={0}, Deleted={1}, Modified={2}", cntAdded, cntDeleted, cntModified));
        }
예제 #10
0
        async Task <IEnumerable <Tuple <EntityEntry, Audit> > > AuditNonTemporaryProperties()
        {
            ChangeTracker.DetectChanges();

            var entitiesToTrack = ChangeTracker.Entries().Where(e => !(e.Entity is Audit) && e.State != EntityState.Detached && e.State != EntityState.Unchanged);

            if (!entitiesToTrack.Any())
            {
                return(null);
            }

            var userId = CurrentUserId;

            await Audits.AddRangeAsync(
                entitiesToTrack.Where(e => !e.Properties.Any(p => p.IsTemporary)).Select(e => new Audit()
            {
                TableName = e.Metadata.GetTableName(),
                Action = Enum.GetName(typeof(EntityState), e.State),
                CreateDate = DateTime.UtcNow,
                UserId = userId,
                KeyValues = JsonConvert.SerializeObject(e.Properties.Where(p => p.Metadata.IsPrimaryKey()).ToDictionary(p => p.Metadata.Name, p => p.CurrentValue).NullIfEmpty()),
                NewValues = JsonConvert.SerializeObject(e.Properties.Where(p => e.State == EntityState.Added || e.State == EntityState.Modified).ToDictionary(p => p.Metadata.Name, p => p.CurrentValue).NullIfEmpty()),
                OldValues = JsonConvert.SerializeObject(e.Properties.Where(p => e.State == EntityState.Deleted || e.State == EntityState.Modified).ToDictionary(p => p.Metadata.Name, p => p.OriginalValue).NullIfEmpty())
            }).ToList()
                );

            return(entitiesToTrack.Where(e => e.Properties.Any(p => p.IsTemporary))
                   .Select(e => new Tuple <EntityEntry, Audit>(e,
                                                               new Audit()
            {
                TableName = e.Metadata.GetTableName(),
                Action = Enum.GetName(typeof(EntityState), e.State),
                CreateDate = DateTime.UtcNow,
                UserId = userId,
                NewValues = JsonConvert.SerializeObject(e.Properties.Where(p => !p.Metadata.IsPrimaryKey()).ToDictionary(p => p.Metadata.Name, p => p.CurrentValue).NullIfEmpty())
            }
                                                               )).ToList());
        }
예제 #11
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            var now    = DateTime.Now;
            var userId = _currentApplicationUserService.GetCurrentUser();

            //Generate new guids for new entities if not populated by EF
            var newEntities = ChangeTracker.Entries <IEntity>().Where(x => x.State == EntityState.Added && x.Entity.Id == Guid.Empty);

            newEntities.ForEach(x => x.Entity.Id = Guid.NewGuid());

            var modifiedEntities = ChangeTracker.Entries <IMutableEntity>().Where(x => x.State == EntityState.Modified);

            foreach (var modifiedEntity in modifiedEntities)
            {
                modifiedEntity.Entity.ModifiedAt   = now;
                modifiedEntity.Entity.ModifiedById = userId;
            }

            var createdMutableEntities = ChangeTracker.Entries <IMutableEntity>().Where(x => x.State == EntityState.Added);

            foreach (var createdEntity in createdMutableEntities)
            {
                createdEntity.Entity.CreatedAt    = now;
                createdEntity.Entity.CreatedById  = userId;
                createdEntity.Entity.ModifiedAt   = now;
                createdEntity.Entity.ModifiedById = userId;
            }

            var createdImmutableEntities = ChangeTracker.Entries <IImmutableEntity>().Where(x => x.State == EntityState.Added);

            foreach (var createdEntity in createdImmutableEntities)
            {
                createdEntity.Entity.CreatedAt   = now;
                createdEntity.Entity.CreatedById = userId;
            }

            return(base.SaveChanges());
        }
예제 #12
0
        private void SetAuditEntities()
        {
            foreach (var entry in ChangeTracker.Entries <IBaseEntity>())
            {
                switch (entry.State)
                {
                case EntityState.Added:

                    if (entry.Entity.Id > 0)
                    {
                        entry.State = EntityState.Modified;
                        goto case EntityState.Modified;
                    }

                    entry.Entity.Deleted = false;
                    if (!entry.Entity.CreatedAt.HasValue)
                    {
                        entry.Entity.CreatedAt = DateTimeOffset.Now;
                    }
                    break;

                case EntityState.Modified:
                    entry.Property(x => x.CreatedAt).IsModified = false;
                    entry.Property(x => x.CreatedBy).IsModified = false;
                    entry.Entity.UpdatedAt = DateTimeOffset.Now;

                    break;

                case EntityState.Deleted:
                    entry.State          = EntityState.Modified;
                    entry.Entity.Deleted = true;
                    goto case EntityState.Modified;

                default:
                    goto case EntityState.Modified;
                }
            }
        }
예제 #13
0
파일: AbpDbContext.cs 프로젝트: kali802/abp
        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            //TODO: Reduce duplications with SaveChangesAsync
            //TODO: Instead of adding entity changes to audit log, write them to uow and add to audit log only if uow succeed

            try
            {
                var auditLog = AuditingManager?.Current?.Log;

                List <EntityChangeInfo> entityChangeList = null;
                if (auditLog != null)
                {
                    entityChangeList = EntityHistoryHelper.CreateChangeList(ChangeTracker.Entries().ToList());
                }

                var changeReport = ApplyAbpConcepts();

                var result = base.SaveChanges(acceptAllChangesOnSuccess);

                AsyncHelper.RunSync(() => EntityChangeEventHelper.TriggerEventsAsync(changeReport));

                if (auditLog != null)
                {
                    EntityHistoryHelper.UpdateChangeList(entityChangeList);
                    auditLog.EntityChanges.AddRange(entityChangeList);
                }

                return(result);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                throw new AbpDbConcurrencyException(ex.Message, ex);
            }
            finally
            {
                ChangeTracker.AutoDetectChangesEnabled = true;
            }
        }
예제 #14
0
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();

            string username = "";

            if (accessor.HttpContext.User.Identity.Name != null)
            {
                username = accessor.HttpContext.User.Identity.Name;
            }
            DateTime date = DateTime.UtcNow;

            var created = ChangeTracker.Entries()
                          .Where(x => x.State == EntityState.Added);

            foreach (var item in created)
            {
                if (item.Entity is IAuditable entity)
                {
                    item.CurrentValues[nameof(IAuditable.CreatedBy)] = username;
                    item.CurrentValues[nameof(IAuditable.CreatedOn)] = date;
                }
            }

            var modified = ChangeTracker.Entries()
                           .Where(x => x.State == EntityState.Modified || x.State == EntityState.Added);

            foreach (var item in modified)
            {
                if (item.Entity is IAuditable entity)
                {
                    item.CurrentValues[nameof(IAuditable.ModifiedBy)] = username;
                    item.CurrentValues[nameof(IAuditable.ModifiedOn)] = date;
                }
            }

            return(base.SaveChanges());
        }
예제 #15
0
        private void AuditEntities()
        {
            var now = DateTime.UtcNow;

            foreach (var entity in ChangeTracker.Entries <IHasCreationTime>().Where(p => p.State == EntityState.Added).Select(p => p.Entity))
            {
                entity.CreationTime = now;
            }

            foreach (var entity in ChangeTracker.Entries <IHasCreatorId>().Where(p => p.State == EntityState.Added).Select(p => p.Entity))
            {
                entity.CreatorId = UserId;
            }

            foreach (var entity in ChangeTracker.Entries <IHasTenant>().Where(p => p.State == EntityState.Added).Select(p => p.Entity))
            {
                entity.TenantId = TenantId.Value;
            }

            foreach (var entity in ChangeTracker.Entries <IHasModificationTime>().Where(p => p.State == EntityState.Modified).Select(p => p.Entity))
            {
                entity.ModificationTime = now;
            }

            foreach (var entity in ChangeTracker.Entries <IHasModifierId>().Where(p => p.State == EntityState.Modified).Select(p => p.Entity))
            {
                entity.ModifierId = UserId;
            }

            foreach (var entity in ChangeTracker.Entries <IFullAudited>().Where(p => p.State == EntityState.Deleted).Select(p => p.Entity))
            {
                Entry(entity).State = EntityState.Modified;
                Entry(entity).CurrentValues.SetValues(Entry(entity).GetDatabaseValues());
                entity.IsDeleted    = true;
                entity.DeletionTime = now;
                entity.DeleterId    = UserId;
            }
        }
예제 #16
0
        /// <summary>
        /// Last SaveChange operation result
        /// </summary>

        public override int SaveChanges()
        {
            try {
                _lastOPerationResult = new SaveChangesResult();
                var createdSourceInfo  = ChangeTracker.Entries().Where(e => e.State == EntityState.Added);
                var modifiedSourceInfo = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified);

                foreach (var entry in createdSourceInfo)
                {
                    if (entry.Entity.GetType().GetInterfaces().Contains(typeof(IAuditable)))
                    {
                        var creationDate = DateTime.Now;
                        entry.Property("CreatedAt").CurrentValue = creationDate;
                        entry.Property("UpdatedAt").CurrentValue = creationDate;

                        string userName = Thread.CurrentPrincipal.Identity?.Name ?? "Anonymous";
                        //entry.Property("CreatedBy").CurrentValue = userName;
                        entry.Property("UpdatedBy").CurrentValue = userName;


                        _lastOPerationResult.AddMessage($"ChangeTracker has new entities: {entry.Entity.GetType()}");
                    }
                }
                foreach (var entry in modifiedSourceInfo)
                {
                    if (entry.Entity.GetType().GetInterfaces().Contains(typeof(IAuditable)))
                    {
                        entry.Property("UpdatedAt").CurrentValue = DateTime.Now;
                    }
                    _lastOPerationResult.AddMessage($"ChangeTracker has modified entities: {entry.Entity.GetType()}");
                }
                return(base.SaveChanges());
            }
            catch (DbUpdateException exception) {
                _lastOPerationResult.Exception = exception;
                return(0);
            }
        }
예제 #17
0
        public override int SaveChanges()
        {
            //get user audit value if not supplied
            string auditUser = "******";

            try //need to try because HttpContext may not exist
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    auditUser = HttpContext.Current.User.Identity.Name;
                }
            }
            catch (Exception)
            { }

            DateTime auditDate = DateTime.UtcNow;

            foreach (DbEntityEntry <IAuditable> entry in ChangeTracker.Entries <IAuditable>())
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Entity.CreatedOn = auditDate;
                    entry.Entity.CreatedBy = auditUser;
                    entry.Entity.UpdatedOn = auditDate;
                    entry.Entity.UpdatedBy = auditUser;
                }
                else if (entry.State == EntityState.Modified)
                {
                    //if (!entry.Entity.CreatedOn.HasValue)
                    //{
                    //    entry.Entity.CreatedOn = auditDate;
                    //}
                    entry.Entity.UpdatedOn = auditDate;
                    entry.Entity.UpdatedBy = auditUser;
                }
            }
            return(base.SaveChanges());
        }
예제 #18
0
        private void OnBeforeSaving()
        {
            IEnumerable <EntityEntry> entries = ChangeTracker.Entries();

            foreach (EntityEntry entry in entries)
            {
                if (entry.Entity is ITrackable trackable)
                {
                    DateTime now  = DateTime.UtcNow;
                    string   user = GetCurrentUser();
                    switch (entry.State)
                    {
                    case EntityState.Modified:
                        entry.Properties.First(x => x.Metadata.Name == "CreatedAt").IsModified = false;
                        entry.Properties.First(x => x.Metadata.Name == "CreatedBy").IsModified = false;
                        trackable.LastUpdatedAt = now;
                        if (string.IsNullOrEmpty(trackable.LastUpdatedBy))
                        {
                            trackable.LastUpdatedBy = user;
                        }
                        break;

                    case EntityState.Added:
                        trackable.CreatedAt = now;
                        if (string.IsNullOrEmpty(trackable.CreatedBy))
                        {
                            trackable.CreatedBy = user;
                        }
                        trackable.LastUpdatedAt = now;
                        if (string.IsNullOrEmpty(trackable.LastUpdatedBy))
                        {
                            trackable.LastUpdatedBy = user;
                        }
                        break;
                    }
                }
            }
        }
예제 #19
0
        public override async Task <int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            int result = default(int);

            var domainEventEntities = ChangeTracker.Entries <AggregateRoot>()
                                      .Select(entityEntry => entityEntry.Entity)
                                      .Where(entity => entity.DomainEvents.Any())
                                      .ToArray();

            foreach (var entity in ChangeTracker.Entries <AggregateRoot>()
                     .Where(e => (e.State == EntityState.Added || (e.State == EntityState.Modified)))
                     .Select(x => x.Entity))
            {
                var isNew = entity.CreatedOn == default(DateTime);
                entity.CreatedOn      = isNew ? DateTime.UtcNow : entity.CreatedOn;
                entity.LastModifiedOn = DateTime.UtcNow;
            }

            foreach (var item in ChangeTracker.Entries <AggregateRoot>().Where(e => e.State == EntityState.Deleted))
            {
                item.State            = EntityState.Modified;
                item.Entity.IsDeleted = true;
            }

            result = await base.SaveChangesAsync(cancellationToken);

            foreach (var entity in domainEventEntities)
            {
                var events = entity.DomainEvents.ToArray();
                entity.ClearEvents();
                foreach (var domainEvent in events)
                {
                    await _mediator.Publish(domainEvent);
                }
            }

            return(result);
        }
예제 #20
0
        public override int SaveChanges()
        {
            var addedEntities = this.ChangeTracker.Entries <BaseEntity>()
                                .Where(e => e.State == EntityState.Added)
                                .Select(e => e.Entity);

            foreach (var entity in addedEntities)
            {
                entity.CreateOn = DateTime.Now;
            }

            var modifiedEntities = this.ChangeTracker.Entries <BaseEntity>()
                                   .Where(e => e.State == EntityState.Modified)
                                   .Select(e => e.Entity);

            var customers = ChangeTracker.Entries <Customer>()
                            .Where(e => e.State == EntityState.Modified)
                            .Select(e => e.Entity);


            foreach (var entity in modifiedEntities)
            {
                // https://docs.microsoft.com/pl-pl/ef/ef6/saving/change-tracking/property-values#reading-current-original-and-database-values-for-all-properties-of-an-entity

                Console.WriteLine("Current values:");
                PrintValues(this.Entry(entity).CurrentValues);

                Console.WriteLine("Original values:");
                PrintValues(this.Entry(entity).OriginalValues);

                Console.WriteLine("Database values:");
                PrintValues(this.Entry(entity).GetDatabaseValues());

                entity.ModifyOn = DateTime.Now;
            }

            return(base.SaveChanges());
        }
        private void MakeAudit()
        {
            var modifiedEntries = ChangeTracker.Entries().Where(
                x => x.Entity is AuditEntity &&
                (
                    x.State == EntityState.Added ||
                    x.State == EntityState.Modified ||
                    x.State == EntityState.Deleted
                )
                );

            foreach (var entry in modifiedEntries)
            {
                var entity = entry.Entity as AuditEntity;
                if (entity != null)
                {
                    var date   = DateTime.Now;
                    var userId = CurrentUserHelper.Get != null ? CurrentUserHelper.Get.UserId : null;

                    if (entry.State == EntityState.Added)
                    {
                        entity.CreatedAt = date;
                        entity.CreatedBy = userId;
                    }
                    else if (entity is ISoftDeleted && ((ISoftDeleted)entity).Deleted)
                    {
                        entity.DeletedAt = date;
                        entity.DeletedBy = userId;
                    }

                    Entry(entity).Property(x => x.CreatedAt).IsModified = false;
                    Entry(entity).Property(x => x.CreatedBy).IsModified = false;

                    entity.UpdatedAt = date;
                    entity.UpdatedBy = userId;
                }
            }
        }
예제 #22
0
파일: Db.cs 프로젝트: MadeInMama/BankSystem
        public override int SaveChanges()
        {
            var entities       = new List <EntityEntry>();
            var entitiesStates = new List <EntityState>();

            if (ChangeTracker.Entries().Last().Entity.GetType() != typeof(DbChange))
            {
                entities.AddRange(ChangeTracker.Entries().Where(f =>
                                                                f.State == EntityState.Added ||
                                                                f.State == EntityState.Modified ||
                                                                f.State == EntityState.Deleted).ToArray());

                foreach (var el in entities)
                {
                    entitiesStates.Add(el.State);
                }
            }

            var res = base.SaveChanges();

            if (entities.Any())
            {
                var list = new List <DbChange>();

                for (var i = 0; i < entities.Count; i++)
                {
                    list.Add(new DbChange(entities[i].Entity.GetType().Name,
                                          int.Parse(entities[i].Entity.GetType().GetProperty("Id").GetValue(entities[i].Entity).ToString()),
                                          entitiesStates[i],
                                          DateTime.Now));
                }

                using (var repo = new DbChangeRepository())
                    repo.AddRange(list.ToArray());
            }

            return(res);
        }
        public override int SaveChanges()
        {
            ChangeTracker.DetectChanges();
            if (ChangeTracker.HasChanges())
            {
                foreach (var item in ChangeTracker.Entries())
                {
                    var temp = (BaseEntity)item.Entity;
                    switch (item.State)
                    {
                    case EntityState.Detached:
                        break;

                    case EntityState.Unchanged:
                        break;

                    case EntityState.Added:
                        temp.RecordStatus = RecordStatus.Active;
                        temp.CreateDate   = DateTime.UtcNow;
                        temp.UpdateDate   = DateTime.UtcNow;
                        break;

                    case EntityState.Deleted:
                        temp.RecordStatus = RecordStatus.Deleted;
                        temp.UpdateDate   = DateTime.UtcNow;
                        break;

                    case EntityState.Modified:
                        temp.UpdateDate = DateTime.UtcNow;
                        break;

                    default:
                        break;
                    }
                }
            }
            return(base.SaveChanges());
        }
예제 #24
0
        /// <summary>
        ///     Asynchronously saves all changes made in this context to the underlying database.
        /// </summary>
        /// <exception cref="System.Data.Entity.Infrastructure.DbUpdateException">
        ///     An error occurred sending updates to the database.</exception>
        /// <exception cref="System.Data.Entity.Infrastructure.DbUpdateConcurrencyException">
        ///     A database command did not affect the expected number of rows. This usually
        ///     indicates an optimistic concurrency violation; that is, a row has been changed
        ///     in the database since it was queried.</exception>
        /// <exception cref="System.Data.Entity.Validation.DbEntityValidationException">
        ///     The save was aborted because validation of entity property values failed.</exception>
        /// <exception cref="System.NotSupportedException">
        ///     An attempt was made to use unsupported behavior such as executing multiple
        ///     asynchronous commands concurrently on the same context instance.</exception>
        /// <exception cref="System.ObjectDisposedException">
        ///     The context or connection have been disposed.</exception>
        /// <exception cref="System.InvalidOperationException">
        ///     Some error occurred attempting to process entities in the context either
        ///     before or after sending commands to the database.</exception>
        /// <seealso cref="DbContext.SaveChangesAsync"/>
        /// <returns>A task that represents the asynchronous save operation.  The
        ///     <see cref="Task.Result">Task.Result</see> contains the number of
        ///     objects written to the underlying database.</returns>
        public override async Task <int> SaveChangesAsync(CancellationToken cancellationToken)
        {
            SyncObjectsStatePreCommit();

            var currentDateTime = DateTime.Now;

            foreach (var auditableEntity in ChangeTracker.Entries <IAuditable>())
            {
                if (auditableEntity.State == EntityState.Added || auditableEntity.State == EntityState.Modified)
                {
                    //auditableEntity.Entity.LastModifiedDate = currentDateTime;
                    switch (auditableEntity.State)
                    {
                    case EntityState.Added:
                        auditableEntity.Entity.CreatedDate = currentDateTime;
                        //auditableEntity.Entity.CreatedBy = AppDomain.CurrentDomain.ApplicationIdentity.FullName;
                        break;

                    case EntityState.Modified:

                        auditableEntity.Property("CreatedDate").IsModified = false;
                        auditableEntity.Property("CreatedBy").IsModified   = false;
                        auditableEntity.Entity.LastModifiedDate            = currentDateTime;
                        //auditableEntity.Entity.LastModifiedBy = AppDomain.CurrentDomain.ApplicationIdentity.FullName;
                        //if (auditableEntity.Property(p => p.Created).IsModified || auditableEntity.Property(p => p.CreatedBy).IsModified)
                        //{
                        //    throw new DbEntityValidationException(string.Format("Attempt to change created audit trails on a modified {0}", auditableEntity.Entity.GetType().FullName));
                        //}
                        break;
                    }
                }
            }

            var changesAsync = await base.SaveChangesAsync(cancellationToken);

            SyncObjectsStatePostCommit();
            return(changesAsync);
        }
예제 #25
0
        public async override Task <int> SaveChangesAsync(CancellationToken cancellationToken = default)
        {
            foreach (var item in ChangeTracker.Entries())
            {
                if (item.Entity is UserRecord)
                {
                    var userRecord = (UserRecord)item.Entity;

                    switch (item.State)
                    {
                    case EntityState.Detached:
                        break;

                    case EntityState.Unchanged:
                        break;

                    case EntityState.Deleted:
                        break;

                    case EntityState.Modified:
                        userRecord.ModificationDate  = DateTime.UtcNow;
                        userRecord.ModifiedByVoterId = _userId;
                        break;

                    case EntityState.Added:
                        userRecord.ModificationDate  = DateTime.UtcNow;
                        userRecord.ModifiedByVoterId = _userId;
                        userRecord.CreatationDate    = DateTime.UtcNow;
                        userRecord.CreatedByVoterId  = _userId;
                        break;

                    default:
                        break;
                    }
                }
            }
            return(await base.SaveChangesAsync(cancellationToken));
        }
예제 #26
0
        public override int SaveChanges()
        {
            foreach (var auditableEntity in ChangeTracker.Entries <IAuditable>())
            {
                if (auditableEntity.State == EntityState.Added ||
                    auditableEntity.State == EntityState.Modified)
                {
                    // implementation may change based on the useage scenario, this
                    // sample is for forma authentication.
                    var currentUser = !string.IsNullOrEmpty(System.Web.HttpContext.Current?.User?.Identity?.Name)
                ? HttpContext.Current.User.Identity.Name
                : "Anonymous";
                    // modify updated date and updated by column for
                    // adds of updates.
                    auditableEntity.Entity.DateModified = DateTime.Now;
                    auditableEntity.Entity.UserModified = currentUser;

                    // pupulate created date and created by columns for
                    // newly added record.
                    if (auditableEntity.State == EntityState.Added)
                    {
                        auditableEntity.Entity.DateCreated = DateTime.Now;
                        auditableEntity.Entity.UserCreated = currentUser;
                    }
                    else
                    {
                        // we also want to make sure that code is not inadvertly
                        // modifying created date and created by columns
                        auditableEntity.Entity.DateCreated = DateTime.Now;
                        auditableEntity.Entity.UserCreated = currentUser;
                        auditableEntity.Property(p => p.DateCreated).IsModified = false;
                        auditableEntity.Property(p => p.UserCreated).IsModified = false;
                    }
                }
            }

            return(base.SaveChanges());
        }
예제 #27
0
        public override int SaveChanges()
        {
            string currentUser = Thread.CurrentPrincipal.Identity.Name;

            IEnumerable <DbEntityEntry> entities = ChangeTracker.Entries().Where(x => x.Entity is IAuditable && (x.State == EntityState.Added || x.State == EntityState.Modified));

            foreach (DbEntityEntry entry in entities)
            {
                if (entry.Entity is IAuditable)
                {
                    IAuditable auditable = ((IAuditable)entry.Entity);

                    if (entry.State == EntityState.Added)
                    {
                        if (auditable.CreatedOn == DateTime.MinValue)
                        {
                            auditable.CreatedOn = TrendyolApp.Instance.DateTimeProvider.Now;
                            if (SetUpdatedOnSameAsCreatedOnForNewObjects)
                            {
                                auditable.UpdatedOn = auditable.CreatedOn;
                            }
                        }

                        if (String.IsNullOrEmpty(auditable.CreatedBy))
                        {
                            auditable.CreatedBy = currentUser;
                        }
                    }
                    else
                    {
                        auditable.UpdatedOn = TrendyolApp.Instance.DateTimeProvider.Now;
                        auditable.UpdatedBy = currentUser;
                    }
                }
            }

            return(base.SaveChanges());
        }
예제 #28
0
        public override int SaveChanges()
        {
            // Set changed/updated info
            var entities = ChangeTracker.Entries().Where(x => x.Entity is EntityBase && (x.State == EntityState.Added || x.State == EntityState.Modified)).ToList();

            foreach (var entity in entities)
            {
                var timeStamp = DateTime.UtcNow;

                if (entity.State == EntityState.Added)
                {
                    ((EntityBase)entity.Entity).Id        = Guid.NewGuid();
                    ((EntityBase)entity.Entity).CreatedOn = timeStamp;
                    ((EntityBase)entity.Entity).CreatedBy = CurrentUserName();
                }

                ((EntityBase)entity.Entity).UpdatedOn = timeStamp;
                ((EntityBase)entity.Entity).UpdatedBy = CurrentUserName();
            }

            // Should invalidate cache?
            bool shouldInvalidateCache = ChangeTracker.Entries().Any(
                x => x.Entity is EntityBase && (x.State == EntityState.Added || x.State == EntityState.Modified || x.State == EntityState.Deleted)
                );

            var saveChangesResult = base.SaveChanges();

            shouldInvalidateCache = shouldInvalidateCache && saveChangesResult > 0;

            if (shouldInvalidateCache)
            {
                log.Debug("Changes in data saved to database. Trigger full cache update.");
                // TODO: ZZZ This is too wide. Since it is affecting both saving of data and changing registered sips and everything else
                _cache.FullReload();
            }

            return(saveChangesResult);
        }
        private void SaveChangesMetadataUpdate()
        {
            // update the state of ef tracked objects
            ChangeTracker.DetectChanges();

            var markedAsAdded = ChangeTracker.Entries().Where(x => x.State == EntityState.Added);

            foreach (var entityEntry in markedAsAdded)
            {
                if (!(entityEntry.Entity is IDomainEntityMetadata entityWithMetaData))
                {
                    continue;
                }

                entityWithMetaData.CreatedAt = DateTime.Now;
                entityWithMetaData.CreatedBy = _userNameProvider?.CurrentUserName;
                entityWithMetaData.ChangedAt = entityWithMetaData.CreatedAt;
                entityWithMetaData.ChangedBy = entityWithMetaData.CreatedBy;
            }

            var markedAsModified = ChangeTracker.Entries().Where(x => x.State == EntityState.Modified);

            foreach (var entityEntry in markedAsModified)
            {
                // check for IDomainEntityMetadata
                if (!(entityEntry.Entity is IDomainEntityMetadata entityWithMetaData))
                {
                    continue;
                }

                entityWithMetaData.ChangedAt = DateTime.Now;
                entityWithMetaData.ChangedBy = _userNameProvider?.CurrentUserName;

                // do not let changes on these properties get into generated db sentences - db keeps old values
                entityEntry.Property(nameof(entityWithMetaData.CreatedAt)).IsModified = false;
                entityEntry.Property(nameof(entityWithMetaData.CreatedBy)).IsModified = false;
            }
        }
예제 #30
0
        private void ModifyDetectChange()
        {
            var entries = ChangeTracker.Entries();
            var Now     = DateTime.Now;

            foreach (var entry in entries)
            {
                if (entry.Entity is BaseEntity trackable)
                {
                    switch (entry.State)
                    {
                    case EntityState.Modified:

                        trackable.UpdateDate = Now;

                        entry.Property("CreateDate").IsModified = false;
                        trackable.CreateDate = DateTime.Parse(entry.GetDatabaseValues().GetValue <object>("CreateDate").ToString());

                        /*foreach (var property in entry.Properties)
                         * {
                         *  if (property.IsModified)
                         *  {
                         *      var original = entry.GetDatabaseValues().GetValue<object>(property.Metadata.Name);
                         *      var current = property.CurrentValue;
                         *  }
                         *
                         * }*/
                        break;

                    case EntityState.Added:

                        trackable.CreateDate = Now;
                        trackable.UpdateDate = Now;
                        break;
                    }
                }
            }
        }