public void RefreshSystemLog() { SystemLogs.Clear(); foreach (LogModel.SystemLog log in LogDb.Table <LogModel.SystemLog>()) { log.Time = log.Time.ToLocalTime(); SystemLogs.Add(log); } SystemLogsSelectedIndex = SystemLogs.Count - 1; }
/// <summary> /// Creates a system log for any database changes that occur for auditing purposes. /// </summary> private void CreateSystemLog() { // get all DbSet Properties that have a class that has the AuditLog attribute // only log tables with "AuditLog" attribute var objectLogType = this.GetType().GetProperties().Where(w => w.PropertyType.IsGenericType && w.PropertyType.GenericTypeArguments[0].GetCustomAttributes(typeof(RocketLaunchJournal.Model.Attributes.AuditLogAttribute), false).Any()) .ToDictionary(k => k.PropertyType.GenericTypeArguments[0], v => v.PropertyType.GenericTypeArguments[0].GetCustomAttributes(typeof(RocketLaunchJournal.Model.Attributes.AuditLogAttribute), false).OfType <RocketLaunchJournal.Model.Attributes.AuditLogAttribute>().First()); //Populate the IP Address for system logs foreach (var item in ChangeTracker.Entries().Where(obj => obj.Entity.GetType() == typeof(SystemLog))) { ((SystemLog)item.Entity).IpAddress = _userPermissionService.UserClaimModel.IpAddress; } // only log tables with "AuditLog" attribute foreach (var item in ChangeTracker.Entries().Where(w => w.Entity.GetType() != typeof(SystemLog) && objectLogType.ContainsKey(w.Entity.GetType())).ToList()) { // don't log unchanged if (item.State == EntityState.Unchanged) { continue; } DateTimeOffset sysEventDate; int? sysUserId = null; int? itemId = null; //Check if object has audit fields var auditFieldsProperty = item.Entity.GetType().GetProperty("AuditFields"); if (auditFieldsProperty != null) { Model.OwnedTypes.AuditFields auditFields = (Model.OwnedTypes.AuditFields)auditFieldsProperty.GetValue(item.Entity) !; sysUserId = auditFields.UpdatedById; sysEventDate = auditFields.UpdatedDateTime; } else { sysEventDate = DateTime.UtcNow; } //Check if object has an id var idProperty = item.Entity.GetType().GetProperty($"{item.Entity.GetType().Name}Id"); if (idProperty != null) { itemId = (int?)idProperty.GetValue(item.Entity); if (item.Entity.GetType().BaseType == typeof(User)) { sysUserId = itemId; //Set the userId == object id if the } } var itemIdAddedOrUnknown = item.State == EntityState.Added ? "check matching timestamp in corresponding table to obtain added id" : "unknown"; SystemLog sysLog = new SystemLog() { UserId = sysUserId <= 0 ? null : sysUserId, IpAddress = _userPermissionService.UserClaimModel.IpAddress, EventDateTime = sysEventDate, LogTypeId = objectLogType.ContainsKey(item.Entity.GetType()) ? objectLogType[item.Entity.GetType()].LogType : RocketLaunchJournal.Model.Enums.LogTypeEnum.Unknown, EventDescription = String.Format("{0} with an id of ({1}) was {2}.", item.Entity.GetType().Name.ToString(), itemId.HasValue && itemId > 0 ? itemId.ToString() : itemIdAddedOrUnknown, item.State.ToString()) }; SystemLogs.Add(sysLog); } }