public static void Bind (this ModuleAuditControl auditControl, IAuditable 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 ());
 }
Example #2
0
        //-------------------------------------------------------------------------------------------
        public static void UpdateAuditFields(IAuditable auditEntity, bool InsertMode = true)
        {
            var appUserID = GetUserId();
               if (InsertMode)
               {
                    if (auditEntity.Id == Guid.Empty)
                         auditEntity.Id = Guid.NewGuid(); // alternative method: http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/
                    //  or [DatabaseGenerated(DatabaseGeneratedOption.Identity)] // http://stackoverflow.com/questions/5270721/using-guid-as-pk-with-ef4-code-first
                    // auditEntity.OrganizationId = Session["OrganizationId"] = HttpContext.Current.Session["SelectedOrganizationId"];

                    // we do this to enforce security so data can't be inserted into an organization that we are not associated with
                    // -- warning this is currently buggy and disabled it's changing system_user row's organizationid to organizations that they do not belong to
                    //auditEntity.OrganizationId = GetOrganizationId();
                    auditEntity.CreatedAt = DateTime.Now.ToUniversalTime();

                    if (auditEntity.CreatedBy == Guid.Empty)
                    {
                         auditEntity.CreatedBy = appUserID;
                    }
               }
               auditEntity.UpdatedAt = DateTime.Now.ToUniversalTime();
               if (auditEntity.UpdatedBy == Guid.Empty)
               {
                    auditEntity.UpdatedBy = appUserID;
               }
        }
        public void Update(IAuditable auditable, object[] oldState, object[] state, IEntityPersister persister)
        {
            if (auditable == null)
                return;

            this.SetChange(auditable, state);
        }
        private void SetCreate(IAuditable auditable, object[] state)
        {
            auditable.CreatedBy = this.GetUserId();
            auditable.CreatedTime = DateTime.Now;

            this.SetState(state, this.createdBy, auditable.CreatedBy);
            this.SetState(state, this.createdTime, auditable.CreatedTime);
        }
        public void Insert(IAuditable auditable, object[] state, IEntityPersister persister)
        {
            if (auditable == null)
                return;

            this.SetCreate(auditable, state);
            this.SetChange(auditable, state);
        }
Example #6
0
        /// <summary>
        /// Adds an inner auditable object, including a message prefix
        /// for the messages.
        /// </summary>
        public void AddAuditable(IAuditable auditable, string message)
        {
            if (auditable == null)
                return;

            if (message != null && message != "")
                prefixes[auditable] = message;

            AddAuditable(auditable);
        }
Example #7
0
        public string AuditIcon(IAuditable auditable)
        {
            DateFormatHelper dateHelper = new DateFormatHelper();
            StringBuilder auditInfo = new StringBuilder();
            auditInfo.AppendFormat("Created at: {0}\n", dateHelper.ToShortDateTime(auditable.CreatedAt));
            auditInfo.AppendFormat("Created by: {0}\n", HtmlEncode(auditable.CreatedBy));
            auditInfo.AppendFormat("Updated at: {0}\n", dateHelper.ToShortDateTime(auditable.UpdatedAt));
            auditInfo.AppendFormat("Updated by: {0}\n", HtmlEncode(auditable.UpdatedBy));

            return string.Format("<img src='/Content/images/audit.png' alt='{0}' />", auditInfo.ToString().Replace("'", "\\'"));
        }
        private void CommonAudit(IAuditable auditable, Action<object> setter)
        {
            if (auditable.ChangeAuditInfo.Created == null) //create
            {
                auditable.ChangeAuditInfo.Created = _clock.Now();
                auditable.ChangeAuditInfo.CreatedBy = _userSession.GetCurrentUser().Username;
            }
            auditable.ChangeAuditInfo.Updated = _clock.Now();
            auditable.ChangeAuditInfo.UpdatedBy = _userSession.GetCurrentUser().Username;

            setter(auditable.ChangeAuditInfo);
        }
Example #9
0
        /// <summary>
        /// Adds an auditable into this nested one, including
        /// registering for new messages.
        /// </summary>
        public void AddAuditable(IAuditable auditable)
        {
            // Add the listener
            auditable.AuditMessageChanged += OnAuditMessageChanged;

            // Add the audit messages
            string pmsg = "";
            Hashtable a = auditable.AuditMessages;

            if (prefixes.Contains(auditable))
                pmsg = prefixes[auditable].ToString();

            foreach (string msg in a.Keys)
                SetAuditMessage((Severity) a[msg], pmsg + msg);
        }
        /// <summary>
        /// Creates the audit update records.
        /// </summary>
        private void CreateAuditUpdateRecords()
        {
            var entities = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Modified).Where(ose => !ose.IsRelationship);

            //var entities = ChangeTracker.Entries().Where(e => e.State == EntityState.Modified);
            foreach (var item in entities)
            {
                IAuditable <TKey> entity = item.Entity as IAuditable <TKey>;
                if (entity != null)
                {
                    try
                    {
                        string oldValue;
                        string newValue;

                        var props = GetEntityType(entity).GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        foreach (var prop in props)
                        {
                            AuditProperty auditProperty = GetAuditProperty(entity, prop);

                            if (auditProperty != null)
                            {
                                var oldObj = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity).OriginalValues[prop.Name];
                                var newObj = prop.GetValue(entity);

                                oldValue = oldObj == null || oldObj == DBNull.Value ? null : oldObj.ToString();
                                newValue = newObj == null || newObj == DBNull.Value ? null : newObj.ToString();

                                if (newValue != oldValue)
                                {
                                    TAuditItem auditItem = new TAuditItem()
                                    {
                                        Audit = this.currentAudit, AuditProperty = auditProperty, Entity1 = entity, Entity2 = null, OperationType = "U", OldValue = oldValue, NewValue = newValue
                                    };

                                    this.currentAuditItems.Add(auditItem);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // TODO: log the error?
                        System.Diagnostics.Debug.WriteLine("Error auditing an update: " + ex.Message);
                    }
                }
            }
        }
Example #11
0
 protected override void DeleteEntity(IEventSource session, object entity, NHibernate.Engine.EntityEntry entityEntry, bool isCascadeDeleteEnabled, IEntityPersister persister, Iesi.Collections.ISet transientEntities)
 {
     if (entity is IAuditable)
     {
         IAuditable audit = entity as IAuditable;
         audit.AuditInfo.IsDeleted        = true;
         audit.AuditInfo.ModificationDate = DateTime.UtcNow;
         audit.AuditInfo.ModificationUser = Thread.CurrentPrincipal.Identity.Name;
         CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities);
         CascadeAfterDelete(session, persister, entity, transientEntities);
     }
     else
     {
         base.DeleteEntity(session, entity, entityEntry, isCascadeDeleteEnabled, persister, transientEntities);
     }
 }
Example #12
0
        protected void ExplicitUpdateCall(IAuditable trackable)
        {
            if (trackable == null)
            {
                return;
            }

            trackable.UpdatedAt = this.CurrentDateTimeProvider();
            trackable.UpdatedBy = this.CurrentIdentityProvider();

            if (trackable.CreatedAt == DateTime.MinValue)
            {
                trackable.CreatedAt = trackable.UpdatedAt;
                trackable.CreatedBy = trackable.UpdatedBy;
            }
        }
Example #13
0
        public static void Audit(this IAuditable auditable, string by, bool create = false)
        {
            if (auditable == null)
            {
                return;
            }

            if (create)
            {
                auditable.CreatedOn = DateTime.UtcNow;
                auditable.CreatedBy = by;
            }

            auditable.UpdatedOn = DateTime.UtcNow;
            auditable.UpdatedBy = by;
        }
Example #14
0
        //Create 'Delete' audit records
        private List <Audit> AuditDeleteRecords(List <ObjectStateEntry> deletedChanges)
        {
            Audit        auditItem = null;
            List <Audit> audits    = new List <Audit>();

            //Check if Auditing is enabled
            if (bool.Parse(ConfigurationManager.AppSettings.Get("EnableLogging")))
            {
                // Process Deletes
                foreach (ObjectStateEntry stateEntry in deletedChanges)
                {
                    if (!stateEntry.IsRelationship && stateEntry.Entity != null)
                    {
                        Type t;
                        //if object is a dynamic proxy, then get its basetype
                        t = stateEntry.Entity.GetType().Namespace == "System.Data.Entity.DynamicProxies" ? stateEntry.Entity.GetType().BaseType : stateEntry.Entity.GetType();

                        //Create an instance of t. This is then used in the GetOriginalEntity method to infer the Type.
                        dynamic Empty_t = Activator.CreateInstance(t);

                        //Get the original entitity so we can check the old values
                        IAuditable oldEntity = GetOriginalEntity(stateEntry, Empty_t);

                        StringBuilder sb = new StringBuilder();
                        //Check if Detailed Logging is Enabled
                        if (bool.Parse(ConfigurationManager.AppSettings.Get("EnableDetailedLogging")))
                        {
                            foreach (EdmMember member in ((stateEntry.EntitySet.ElementType.Members).Where(x => x.TypeUsage.EdmType is PrimitiveType && x.Name != "RowIdentifier")))
                            {
                                string propertyName = member.Name;
                                var    oldValue     = oldEntity.GetType().GetProperty(propertyName).GetValue(oldEntity, null);
                                sb.AppendLine(string.Format("PropertyName:{0}, Value:{1};", propertyName, oldValue));
                            }
                        }
                        else
                        {
                            sb.AppendLine("Record Deleted");
                        }

                        auditItem = CreateAudit(stateEntry.Entity, "Delete", sb.ToString(), Empty_t.GetType());
                        audits.Add(auditItem);
                    }
                }
            }

            return(audits);
        }
Example #15
0
        /// <summary>
        /// Creates the audit add relation records.
        /// </summary>
        private void CreateAuditAddRelationRecords()
        {
            var relations = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntries(System.Data.Entity.EntityState.Added).Where(ose => ose.IsRelationship);

            foreach (var item in relations)
            {
                try
                {
                    ObjectStateEntry  parentEntry = GetEntityEntryFromRelation(item, 0);
                    ObjectStateEntry  childEntry;
                    IAuditable <TKey> parent = parentEntry.Entity as IAuditable <TKey>;
                    if (parent != null)
                    {
                        IAuditable <TKey> child;

                        // Find representation of the relation
                        System.Data.Entity.Core.Objects.DataClasses.IRelatedEnd relatedEnd = parentEntry.RelationshipManager.GetAllRelatedEnds().First(r => r.RelationshipSet == item.EntitySet);

                        childEntry = GetEntityEntryFromRelation(item, 1);
                        child      = childEntry.Entity as IAuditable <TKey>;

                        if (child != null)
                        {
                            try
                            {
                                TAuditProperty auditProperty = GetAuditProperty(relatedEnd);
                                TAuditItem     auditItem     = new TAuditItem()
                                {
                                    Audit = this.currentAudit, AuditProperty = auditProperty, Entity1 = parent, Entity2 = child, OperationType = "+", OldValue = string.Empty, NewValue = string.Empty
                                };

                                this.currentAuditItems.Add(auditItem);
                            }
                            catch (Exception ex)
                            {
                                // TODO: log the error?
                                System.Diagnostics.Debug.WriteLine("Error auditing an add relation: " + ex.Message);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Error auditing added relation: " + ex.Message);
                }
            }
        }
Example #16
0
        /// <summary>
        /// Gets the entity edit points.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns></returns>
        public HyperEntityEditPoint <TKey>[] GetEntityEditPoints(IAuditable <TKey> entity)
        {
            var auditIds = this.AuditItems
                           .Where(i => i.Entity1Id.Equals(entity.Id))
                           .Select(i => i.AuditId)
                           .Distinct()
                           .ToArray();

            return(this.Audits
                   .Where(a => auditIds.Contains(a.Id))
                   .Select(a => new HyperEntityEditPoint <TKey>()
            {
                EntityId = entity.Id, EditDate = a.AuditDate, UserName = a.UserName, UserId = a.UserId
            })
                   .OrderByDescending(ep => ep.EditDate)
                   .ToArray());
        }
Example #17
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;
                        }
                    }
                }
            }
        }
        public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
        {
            IAuditable auditableObject = entity as IAuditable;

            if (auditableObject != null)
            {
                for (int i = 0; i < propertyNames.Length; i++)
                {
                    if (propertyNames[i] == auditableObject.UpdatedPropertyName)
                    {
                        currentState[i] = DateTime.Now;
                    }
                }
                return(true);
            }

            return(false);
        }
Example #19
0
        public void UpdateAuditable(EntityEntry entityEntry, IAuditable auditableEntry)
        {
            switch (entityEntry.State)
            {
            case EntityState.Added:
                auditableEntry.CreatedAt = DateTime.UtcNow;
                break;

            case EntityState.Modified:
                auditableEntry.UpdatedAt = DateTime.UtcNow;
                break;

            case EntityState.Deleted:
                entityEntry.State        = EntityState.Modified;
                auditableEntry.DeletedAt = DateTime.UtcNow;
                break;
            }
        }
Example #20
0
        protected BaseServerPersistenceObject(Func <IFrozenContext> lazyCtx)
            : base(lazyCtx)
        {
            _auditable        = this as IAuditable;
            ClientObjectState = DataObjectState.NotDeserialized;
#if TRACE_OBJECT_CREATION
            var trace = new System.Diagnostics.StackTrace(true);
            _constructTrace = String.Join("\n",
                                          trace
                                          .GetFrames()
                                          .Select(frm => String.Format(
                                                      "  at {0}.{1} ({2}:{3})",
                                                      frm.GetMethod().ReflectedType != null ? frm.GetMethod().ReflectedType.FullName : "<not a type>",
                                                      frm.GetMethod().Name,
                                                      frm.GetFileName(),
                                                      frm.GetFileLineNumber()))
                                          .ToArray());
#endif
        }
Example #21
0
        public void OnFlushEntity(FlushEntityEvent @event)
        {
            if ((@event.EntityEntry.Status == Status.Deleted) || (@event.EntityEntry.Status == Status.ReadOnly))
            {
                return;
            }

            IAuditable trackable = @event.Entity as IAuditable;

            if (trackable == null)
            {
                return;
            }

            if (this.HasDirtyProperties(@event) == true)
            {
                this.ExplicitUpdateCall(trackable);
            }
        }
Example #22
0
        public bool OnPreInsert(PreInsertEvent @event)
        {
            if (@event.Entity is IAuditable)
            {
                DateTime   now   = DateTime.UtcNow;
                IAuditable audit = @event.Entity as IAuditable;
                audit.AuditInfo.IsDeleted        = false;
                audit.AuditInfo.CreationDate     = now;
                audit.AuditInfo.ModificationDate = now;
                audit.AuditInfo.CreationUser     = Thread.CurrentPrincipal.Identity.Name;
                audit.AuditInfo.ModificationUser = Thread.CurrentPrincipal.Identity.Name;

                Auditable auditable = audit.AuditInfo;
                Set(@event.Persister, @event.State, "AuditInfo", auditable);

                return(false);
            }
            return(false);
        }
Example #23
0
        private void HandleAuditableEntities()
        {
            string currentUser = Thread.CurrentPrincipal?.Identity?.Name;

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

            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;

                            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;
                        auditable.UpdatedBy = currentUser;
                    }
                }
            }
        }
Example #24
0
        private void TrackChanges()
        {
            foreach (var entry in this.ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))
            {
                if (entry.Entity is IAuditable)
                {
                    IAuditable auditable = entry.Entity as IAuditable;
                    if (entry.State == EntityState.Added)
                    {
                        auditable.CreatedDate = TimestampProvider();

                        auditable.UpdateDate = TimestampProvider();
                    }
                    else
                    {
                        auditable.UpdateDate = TimestampProvider();
                    }
                }
            }
        }
Example #25
0
        public virtual T Save(T obj)
        {
            bool shouldInsert = CheckForInsert(obj);

            TV  dto;
            var conn = GetCurrentConnection();

            if (shouldInsert)
            {
                if (_implementedInterfaces.Contains(nameof(IAuditable)))
                {
                    IAuditable auditableObj = obj as IAuditable;
                    auditableObj.CreatedUtc = DateTime.UtcNow;
                    auditableObj.CreatedBy  = auditableObj.ModifiedBy;
                }
                else if (_implementedInterfaces.Contains(nameof(IAuditableDates)))
                {
                    IAuditableDates auditableObj = obj as IAuditableDates;
                    auditableObj.CreatedUtc = DateTime.UtcNow;
                }
                dto = ToDto(obj);
                conn.Insert(dto, s => s.AttachToTransaction(GetCurrentTransaction()));
            }
            else
            {
                if (_implementedInterfaces.Contains(nameof(IAuditable)))
                {
                    IAuditable auditableObj = obj as IAuditable;
                    auditableObj.UpdatedUtc = DateTime.UtcNow;
                    auditableObj.UpdatedBy  = auditableObj.ModifiedBy;
                }
                else if (_implementedInterfaces.Contains(nameof(IAuditableDates)))
                {
                    IAuditableDates auditableObj = obj as IAuditableDates;
                    auditableObj.UpdatedUtc = DateTime.UtcNow;
                }
                dto = ToDto(obj);
                conn.Update(dto, s => s.AttachToTransaction(GetCurrentTransaction()));
            }
            return(FromDto(dto));
        }
Example #26
0
        public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
        {
            IAuditable auditableEntity = entity as IAuditable;

            if (auditableEntity != null)
            {
                DateTime currentDate = DateTime.UtcNow;
                for (int i = 0; i < propertyNames.Length; i++)
                {
                    if (propertyNames[i] == "Created" || propertyNames[i] == "Updated")
                    {
                        state[i] = currentDate;
                    }
                }
                auditableEntity.SetCreatedDate(currentDate);
                auditableEntity.SetUpdatedDate(currentDate);

                return(true);
            }
            return(false);
        }
Example #27
0
//-------------------------------------------------------------------------------------------
        void DetailsDataSource_Inserted(object sender, EntityDataSourceChangedEventArgs e)
        {
            if (!String.IsNullOrEmpty(Request["ParentId"]))
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "refreshParent", "<script type='text/javascript'>parent.refreshParent('" + Request["ParentId"] + "');</script>", false);
            }

            IAuditable auditData = e.Entity as IAuditable;
            string     url       = "Details.aspx?Id={0}&WindowId={1}&ParentId={2}&IFrame={3}";

            url = String.Format(url, auditData.Id, Request["WindowId"], Request["ParentId"], Request["IFrame"]);

            if (Request["IFrame"] == "true")
            {
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "refreshParent2", "<script type='text/javascript'>document.location.href = '" + url + "';</script>", false);
            }
            else
            {
                Response.Redirect(url);
            }
        }
Example #28
0
        public void Save(object instance)
        {
            IAuditable auditable = instance as IAuditable;

            if (auditable != null)
            {
                DateTime dateTimeNow = DateTime.Now;
                User     user        = SecurityContextHolder.Get();
                if (auditable.CreateUserName == null)
                {
                    auditable.CreateUserId   = user.Id;
                    auditable.CreateUserName = user.FullName;
                    auditable.CreateDate     = dateTimeNow;
                }

                auditable.LastModifyUserId   = user.Id;
                auditable.LastModifyUserName = user.FullName;
                auditable.LastModifyDate     = dateTimeNow;
            }
            dao.Save(instance);
        }
Example #29
0
        internal void CopyAuditInformationTo(IAuditable auditable)
        {
            NullGuard.NotNull(auditable, nameof(auditable));

            DateTime createdUtcDateTime  = CreatedUtcDateTime;
            string   createdByIdentifier = CreatedByIdentifier;

            if (createdUtcDateTime > BasicAccount.CreatedUtcDateTime)
            {
                createdUtcDateTime  = BasicAccount.CreatedUtcDateTime;
                createdByIdentifier = BasicAccount.CreatedByIdentifier;
            }

            DateTime modifiedUtcDateTime  = ModifiedUtcDateTime;
            string   modifiedByIdentifier = ModifiedByIdentifier;

            if (modifiedUtcDateTime < BasicAccount.ModifiedUtcDateTime)
            {
                modifiedUtcDateTime  = BasicAccount.ModifiedUtcDateTime;
                modifiedByIdentifier = BasicAccount.ModifiedByIdentifier;
            }

            AuditModelBase lastModifiedInfoModel = GetLastModifiedInfoModel();

            if (lastModifiedInfoModel != null && modifiedUtcDateTime < lastModifiedInfoModel.ModifiedUtcDateTime)
            {
                modifiedUtcDateTime  = lastModifiedInfoModel.ModifiedUtcDateTime;
                modifiedByIdentifier = lastModifiedInfoModel.ModifiedByIdentifier;
            }

            AuditModelBase lastModifiedPostingLineModel = GetLastModifiedPostingLineModel();

            if (lastModifiedPostingLineModel != null && modifiedUtcDateTime < lastModifiedPostingLineModel.ModifiedUtcDateTime)
            {
                modifiedUtcDateTime  = lastModifiedPostingLineModel.ModifiedUtcDateTime;
                modifiedByIdentifier = lastModifiedPostingLineModel.ModifiedByIdentifier;
            }

            auditable.AddAuditInformation(createdUtcDateTime, createdByIdentifier, modifiedUtcDateTime, modifiedByIdentifier);
        }
Example #30
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());
        }
Example #31
0
        private void SaveLogEntry(IAuditable auditable, List <AudytLogItem> items, AudytLogType audytLogType)
        {
            using (var session = NHibernateSession.GetDefaultSessionFactory().OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    var log = new AudytLog
                    {
                        AudytLogTypeEnum = audytLogType,
                        LogDateTime      = DateTime.Now,
                        UserLogin        = GetCurentUserId(),
                        ObjectId         = auditable.IdString,
                        ObjectIdType     = auditable.IdType,
                        ObjectType       = auditable.ObjectType,
                        ObjectValue      = JsonConvert.SerializeObject(items)
                    };

                    session.Save(log);

                    tx.Commit();
                }
            }
        }
        //public override int SaveChanges()
        //{
        //    Auditar(new DTOSessionUsuario());
        //    return base.SaveChanges();
        //}

        private void Auditar(DTOSessionUsuario _sess)
        {
            var modifiedEntries = ChangeTracker.Entries().Where(x => x.Entity is IAuditable && (x.State == System.Data.Entity.EntityState.Added ||
                                                                                                x.State == System.Data.Entity.EntityState.Modified || x.State == System.Data.Entity.EntityState.Deleted));

            foreach (var entry in modifiedEntries)
            {
                IAuditable entity = entry.Entity as IAuditable;
                if (entity != null)
                {
                    Log log = new Log()
                    {
                        USU_ID        = (int)_sess.Usuario.USU_ID,
                        LOG_FECHA     = DateTime.Now,
                        LOG_LLAMADA   = _sess.llamada,
                        LOG_OPERACION = (entry.State == EntityState.Added) ? "insercion" : ((entry.State == EntityState.Modified) ? "modificacion" : "eliminacion"),
                        LOG_DATOS     = JsonConvert.SerializeObject(entry.Entity, Formatting.Indented)
                    };

                    this.Set <Log>().Add(log);
                }
            }
        }
Example #33
0
        private void InitSaveChanges(int?userId)
        {
            var modifiedEntries = ChangeTracker.Entries()
                                  .Where(x => x.Entity is IAuditable &&
                                         (x.State == System.Data.Entity.EntityState.Added || x.State == System.Data.Entity.EntityState.Modified));


            //int? userId = null;

            //if (!string.IsNullOrWhiteSpace(Thread.CurrentPrincipal.Identity.Name))
            //if (HttpContext.Current != null)
            //{
            //    userId = (int?)HttpContext.Current.Session["UserId"];

            //}

            foreach (var entry in modifiedEntries)
            {
                IAuditable entity = entry.Entity as IAuditable;
                if (entity != null)
                {
                    if (entry.State == System.Data.Entity.EntityState.Added)
                    {
                        entity.CreatedBy  = userId;
                        entity.CreateDate = DateTime.Now;
                    }
                    else
                    {
                        base.Entry(entity).Property(x => x.CreatedBy).IsModified  = false;
                        base.Entry(entity).Property(x => x.CreateDate).IsModified = false;
                        entity.UpdatedBy  = userId;
                        entity.UpdateDate = DateTime.Now;
                    }
                }
            }
        }
        /// <summary>
        /// Sets the entity property.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="auditItem">The audit item.</param>
        private void SetEntityProperty(IAuditable <TKey> entity, AuditItem <TKey> auditItem)
        {
            Contract.Requires <ArgumentNullException>(entity != null, "entity");
            Contract.Requires <ArgumentNullException>(auditItem != null, "auditItem");

            var auditProperty = this.AuditProperties.Single(p => p.Id == auditItem.AuditPropertyId);

            PropertyInfo prop = GetEntityType(entity).GetProperty(auditProperty.PropertyName);

            if (auditItem.NewValue == null)
            {
                prop.SetValue(entity, null);
            }
            else
            {
                var type = prop.PropertyType;
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type = Nullable.GetUnderlyingType(type);
                }

                prop.SetValue(entity, Convert.ChangeType(auditItem.NewValue, type));
            }
        }
Example #35
0
        /// <summary>
        /// Gets the audit property.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        private TAuditProperty GetAuditProperty(IAuditable <TKey> entity, string propertyName)
        {
            Helpers.ThrowIfNull(entity != null, "entity");
            Helpers.ThrowIfNull(!propertyName.IsNullOrWhiteSpace(), "propertyName");

            string entityName = GetEntityTypeName(entity); // ObjectContext.GetObjectType(entity.GetType()).Name;

            // check our list
            TAuditProperty auditProperty = this.currentAuditProperties.FirstOrDefault(ap => ap.EntityName == entityName && ap.PropertyName == propertyName);

            if (auditProperty == null)
            {
                // check the database
                auditProperty = this.AuditProperties.FirstOrDefault(ap => ap.EntityName == entityName && ap.PropertyName == propertyName);

                if (auditProperty != null)
                {
                    this.currentAuditProperties.Add(auditProperty);
                }
            }

            // might return null
            return(auditProperty);
        }
Example #36
0
        /// <summary>
        /// Sets the entity property.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="auditItem">The audit item.</param>
        private void SetEntityProperty(IAuditable <TKey> entity, HyperAuditItem <TKey, TAudit, TAuditItem, TAuditProperty> auditItem)
        {
            Helpers.ThrowIfNull(entity != null, "entity");
            Helpers.ThrowIfNull(auditItem != null, "auditItem");

            var auditProperty = this.AuditProperties.Single(p => p.Id.Equals(auditItem.AuditPropertyId));

            PropertyInfo prop = GetEntityType(entity).GetProperty(auditProperty.PropertyName);

            if (auditItem.NewValue == null)
            {
                prop.SetValue(entity, null);
            }
            else
            {
                var type = prop.PropertyType;
                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
                {
                    type = Nullable.GetUnderlyingType(type);
                }

                prop.SetValue(entity, Convert.ChangeType(auditItem.NewValue, type));
            }
        }
        internal void CopyAuditInformationTo(IAuditable auditable)
        {
            NullGuard.NotNull(auditable, nameof(auditable));

            DateTime createdUtcDateTime  = CreatedUtcDateTime;
            string   createdByIdentifier = CreatedByIdentifier;

            if (createdUtcDateTime > YearMonth.CreatedUtcDateTime)
            {
                createdUtcDateTime  = YearMonth.CreatedUtcDateTime;
                createdByIdentifier = YearMonth.CreatedByIdentifier;
            }

            DateTime modifiedUtcDateTime  = ModifiedUtcDateTime;
            string   modifiedByIdentifier = ModifiedByIdentifier;

            if (modifiedUtcDateTime < YearMonth.ModifiedUtcDateTime)
            {
                modifiedUtcDateTime  = YearMonth.ModifiedUtcDateTime;
                modifiedByIdentifier = YearMonth.ModifiedByIdentifier;
            }

            auditable.AddAuditInformation(createdUtcDateTime, createdByIdentifier, modifiedUtcDateTime, modifiedByIdentifier);
        }
Example #38
0
 public DbContextBase(string connectionString, IAuditable auditLogger)
     : this(connectionString)
 {
     this.AuditLogger = auditLogger;
 }
Example #39
0
 /// <summary>
 /// Removes an auditable object from this one. This
 /// automatically removes the auditable's messages from this
 /// one.
 /// </summary>
 public void RemoveAuditable(IAuditable auditable)
 {
     RemoveAuditable(auditable, true);
 }
 private void SetModified(IAuditable entity)
 {
     entity.SetAuditModified(_now.Moment, _currentUserAccessor.User.Login);
 }
 protected PersistenceObjectBaseImpl(Func<IFrozenContext> lazyCtx)
     : base(lazyCtx)
 {
     _auditable = this as IAuditable;
 }
Example #42
0
        /// <summary>
        /// Removes an auditable from this object, optionally removing
        /// the messages.
        /// </summary>
        public void RemoveAuditable(IAuditable auditable, bool remove)
        {
            // Remove our messages
            if (remove)
            {
                string pmsg = "";

                if (prefixes.Contains(auditable))
                    pmsg = prefixes[auditable].ToString();

                foreach (string msg in auditable.AuditMessages.Keys)
                    ClearAuditMessage(pmsg + msg);
            }

            // Remove the prefix
            if (prefixes.Contains(auditable))
                prefixes.Remove(auditable);

            // Remove the message
            auditable.AuditMessageChanged -= OnAuditMessageChanged;
        }
 public static void DefaultAuditableToNow(IAuditable obj)
 {
     obj.Created = DateTime.Now;
     obj.Updated = obj.Created;
 }
Example #44
0
 protected BaseServerPersistenceObject(Func<IFrozenContext> lazyCtx)
     : base(lazyCtx)
 {
     _auditable = this as IAuditable;
     ClientObjectState = DataObjectState.NotDeserialized;
     #if TRACE_OBJECT_CREATION
     var trace = new System.Diagnostics.StackTrace(true);
     _constructTrace = String.Join("\n",
         trace
         .GetFrames()
         .Select(frm => String.Format(
             "  at {0}.{1} ({2}:{3})",
             frm.GetMethod().ReflectedType != null ? frm.GetMethod().ReflectedType.FullName : "<not a type>",
             frm.GetMethod().Name,
             frm.GetFileName(),
             frm.GetFileLineNumber()))
         .ToArray());
     #endif
 }
Example #45
0
 protected void UpdateDateUpdated(IAuditable itemToChange)
 {
     itemToChange.DateUpdated = DateTime.Now;
 }
Example #46
0
 protected void UpdateIsDeletedToFalse(IAuditable itemToChange)
 {
     itemToChange.IsDeleted = false;
 }
Example #47
0
 protected void UpdateIsDeletedToTrue(IAuditable itemToChange)
 {
     itemToChange.IsDeleted = true;
 }