示例#1
0
        /// <summary>
        /// Loads the item recorded in this event.
        /// </summary>
        public static async Task <IEntity> LoadItem(IAuditEvent applicationEvent)
        {
            var type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(applicationEvent.ItemType)).ExceptNull().FirstOrDefault();

            if (type == null)
            {
                throw new("Could not load the type " + applicationEvent.ItemType);
            }

            if (applicationEvent.Event.IsAnyOf("Update", "Insert"))
            {
                return(await Database.Get(applicationEvent.ItemId.To <Guid>(), type));
            }

            if (applicationEvent.Event == "Delete")
            {
                var result = Activator.CreateInstance(type) as GuidEntity;
                result.ID = applicationEvent.ItemId.To <Guid>();

                foreach (var p in XElement.Parse(applicationEvent.ItemData).Elements())
                {
                    var old      = p.Value;
                    var property = type.GetProperty(p.Name.LocalName);
                    property.SetValue(result, old.To(property.PropertyType));
                }

                return(result);
            }

            throw new NotSupportedException();
        }
示例#2
0
        /// <summary>
        /// Loads the item recorded in this event.
        /// </summary>
        public static async Task <IEntity> LoadItem(IAuditEvent applicationEvent, bool newItem = false)
        {
            var type = AppDomain.CurrentDomain.GetAssemblies()
                       .Select(a => a.GetType(applicationEvent.ItemType))
                       .ExceptNull().FirstOrDefault();

            if (type == null)
            {
                throw new("Could not load the type " + applicationEvent.ItemType);
            }

            if (applicationEvent.Event.IsAnyOf("Update", "Insert"))
            {
                var item = await Context.Current.Database().GetOrDefault(applicationEvent.ItemId.To <Guid>(), type);

                if (item == null)
                {
                    return(MapAuditToInstance(applicationEvent, type, newItem));
                }

                return(item);
            }

            if (applicationEvent.Event == "Delete")
            {
                return(MapAuditToInstance(applicationEvent, type, newItem));
            }

            throw new NotSupportedException();
        }
示例#3
0
 /// <summary>
 /// Writes an audit message to the log. Event level will be Verbose; it is
 /// the responsibility of the logger to channel this event to the appropriate
 /// log storage based on the provided category.
 /// </summary>
 /// <param name="auditEvent">An object that represents an audit event.</param>
 /// <param name="properties">Event properties.</param>
 public static void WriteAudit(
     IAuditEvent auditEvent,
     IDictionary <string, object> properties = null)
 {
     Write(TraceEventType.Verbose, auditEvent.Message, AuditCategory,
           eventId: auditEvent.EventId, title: auditEvent.Title, properties: properties);
 }
示例#4
0
        public static async Task <string> OldChangesToHtml(this IAuditEvent applicationEvent)
        {
            if (applicationEvent.Event.IsAnyOf("Update", "Delete"))
            {
                return(await applicationEvent.ToHtml("old"));
            }

            return(string.Empty);
        }
示例#5
0
        static async Task <string> ToHtml(this IAuditEvent applicationEvent, string parentNode = null)
        {
            var item = await EntityProcessor.LoadItem(applicationEvent, parentNode == "new");

            if (item == null)
            {
                throw new("Could not load the type " + applicationEvent.ItemType);
            }

            var properties   = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var ouputBuilder = new StringBuilder();

            if (parentNode == "old")
            {
                ouputBuilder.AppendLine("<div class =\"audit-log audit-log-old\">");
            }
            else
            {
                ouputBuilder.AppendLine("<div class =\"audit-log audit-log-new\">");
            }

            var elements = XElement.Parse(applicationEvent.ItemData).Elements();

            elements = parentNode.HasValue() ? elements.FirstOrDefault(x => x.Name.LocalName == parentNode)?.Elements() : elements;

            var linker = parentNode == "new" ? "\u2192" : ":";

            foreach (var element in elements.ToArray())
            {
                var propertyClass = "audit-log-property";
                var property      = properties.FirstOrDefault(x => x.Name == element.Name.LocalName);

                if (property == null)
                {
                    continue;
                }

                if (property.IsEntity(item))
                {
                    propertyClass = $"{propertyClass} audit-log-property-entity";
                }
                else if (property.PropertyType == typeof(bool))
                {
                    propertyClass = $"{propertyClass} audit-log-property-bool";
                }

                ouputBuilder.AppendLine($"<span class=\"audit-log-label\">{element.Name.LocalName?.ToLiteralFromPascalCase()}</span> {linker} <span class=\"{propertyClass}\">{element.Value}</span><br>");
            }

            ouputBuilder.AppendLine("</div>");
            return(ouputBuilder.ToString());
        }
示例#6
0
        public static async Task <string> NewChangesToHtml(this IAuditEvent applicationEvent)
        {
            if (applicationEvent.Event == "Update")
            {
                return(await applicationEvent.ToHtml("new"));
            }

            if (applicationEvent.Event == "Insert")
            {
                return(await applicationEvent.ToHtml());
            }

            return(string.Empty);
        }
        public async Task <SaveResponse <IAuditEvent> > SaveAsync(IAuditEvent auditEvent)
        {
            var saveResponse = new SaveResponse <IAuditEvent>();

            try
            {
                saveResponse = await _auditEventRepository.SaveAsync(auditEvent);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                saveResponse.AddError(ex);
                _logManager.LogError(ex, "Error saving auditEvent");
            }

            return(saveResponse);
        }
示例#8
0
        static GuidEntity MapAuditToInstance(IAuditEvent applicationEvent, Type type, bool newItem)
        {
            var item = Activator.CreateInstance(type) as GuidEntity;

            item.ID = applicationEvent.ItemId.To <Guid>();

            string parentNode;

            if (applicationEvent.Event == "Insert")
            {
                parentNode = null;
            }
            else if (applicationEvent.Event == "Update" && newItem)
            {
                parentNode = "new";
            }
            else
            {
                parentNode = "old";
            }

            var elements = XElement.Parse(applicationEvent.ItemData).Elements();

            elements = parentNode.HasValue() ? elements.FirstOrDefault(x => x.Name.LocalName == parentNode)?.Elements() : elements;

            foreach (var element in elements.ToArray())
            {
                var eValue   = element.Value;
                var property = type.GetProperty(element.Name.LocalName);

                if (property.IsEntity(item))
                {
                    continue;
                }
                else if (property.PropertyType == typeof(Blob))
                {
                    property.SetValue(item, (new Blob()).Attach(item, property.Name));
                }
                else
                {
                    property.SetValue(item, eValue.To(property.PropertyType));
                }
            }

            return(item);
        }
 public void Write(IAuditEvent auditEvent, IDictionary <string, object> properties)
 {
 }
 public Task <ValidationResult> ValidateAsync(IAuditEvent auditEvent)
 {
     throw new NotImplementedException();
 }
示例#11
0
文件: Audit.cs 项目: pharzath/Olive
 public static Task Log(IAuditEvent auditEvent)
 => Context.Current.ServiceProvider.GetServices <ILogger>().AwaitAll(x => x.Log(auditEvent));
示例#12
0
 public void Write(IAuditEvent auditEvent, IDictionary <string, object> properties)
 {
     DataStore.WriteAuditEventAsync(new AuditEventInfo(auditEvent, properties), CancellationToken.None)
     .GetAwaiter().GetResult();
 }
示例#13
0
 public Task Log(IAuditEvent auditEvent) => Context.Current.Database().Save(auditEvent);
示例#14
0
        public AuditEventInfo(IAuditEvent auditEvent, IDictionary <string, object> properties)
        {
            var formatValue = new Func <object, string>(obj =>
            {
                if (obj == null)
                {
                    return(string.Empty);
                }
                if (obj is DateTime time)
                {
                    return(XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc));
                }

                var s          = obj as string ?? obj.ToString();
                var mustEscape = s.Any(c => c == '<' || c == '>' || c == '&' || c == '"' || c == '\'');

                return(mustEscape ? WebUtility.HtmlEncode(s) : s);
            });

            var process = Process.GetCurrentProcess();
            var thread  = Thread.CurrentThread;

            _auditEvent   = auditEvent;
            Timestamp     = DateTime.UtcNow;
            Severity      = "Verbose";
            Priority      = -1;
            MachineName   = Environment.MachineName;
            AppDomainName = Environment.UserDomainName;
            ProcessId     = process.Id;
            ProcessName   = process.ProcessName;
            ThreadId      = thread.ManagedThreadId;
            ThreadName    = thread.Name;

            // format message
            var sb = new StringBuilder();

            sb.AppendFormat("<LogEntry>").AppendLine();
            sb.AppendFormat("  <Timestamp>{0}</Timestamp>", Timestamp).AppendLine();
            sb.AppendFormat("  <Message>{0}</Message>", auditEvent.Message).AppendLine();
            sb.AppendFormat("  <Category>{0}</Category>", "Audit").AppendLine();
            sb.AppendFormat("  <Priority>{0}</Priority>", Priority).AppendLine();
            sb.AppendFormat("  <EventId>{0}</EventId>", auditEvent.EventId).AppendLine();
            sb.AppendFormat("  <Severity>{0}</Severity>", Severity).AppendLine();
            sb.AppendFormat("  <Title>{0}</Title>", auditEvent.Title).AppendLine();
            sb.AppendFormat("  <Machine>{0}</Machine>", MachineName).AppendLine();
            sb.AppendFormat("  <ApplicationDomain>{0}</ApplicationDomain>", AppDomainName).AppendLine();
            sb.AppendFormat("  <ProcessId>{0}</ProcessId>", ProcessId).AppendLine();
            sb.AppendFormat("  <ProcessName>{0}</ProcessName>", ProcessName).AppendLine();
            sb.AppendFormat("  <Win32ThreadId>{0}</Win32ThreadId>", ThreadId).AppendLine();
            sb.AppendFormat("  <ThreadName>{0}</ThreadName>", ThreadName).AppendLine();
            sb.AppendFormat("  <ExtendedProperties>").AppendLine();
            foreach (var prop in properties)
            {
                sb.AppendFormat("    <{0}>{1}</{0}>", prop.Key, formatValue(prop.Value)).AppendLine();
            }
            sb.AppendFormat("  </ExtendedProperties>").AppendLine();
            sb.AppendFormat("</LogEntry>").AppendLine();

            FormattedMessage = sb.ToString();

            properties.TryGetValue("Category", out var category);
            Category = (string)category;

            properties.TryGetValue("Id", out var id);
            ContentId = (int?)id ?? 0;

            properties.TryGetValue("Path", out var path);
            ContentPath = (string)path;

            properties.TryGetValue("UserName", out var userName);
            UserName = (string)userName;
        }
示例#15
0
 public Task Log(IAuditEvent auditEvent) => Entity.Database.Save(auditEvent);
 public void Write(IAuditEvent auditEvent, IDictionary <string, object> properties)
 {
     DataProvider.Current.WriteAuditEvent(new AuditEventInfo(auditEvent, properties));
 }