private long CreateAuditEvent (DbManagerProxy manager, AuditEventType auditEventType, EIDSSAuditObject eidssAuditObject, AuditTable auditTable, long?objectId) { try { DataAuditEvent = manager.SetSpCommand("dbo.spAudit_CreateNewEvent", auditEventType, eidssAuditObject, auditTable, objectId, DBNull.Value, DBNull.Value ).ExecuteScalar <long>(ScalarSourceType.OutputParameter, "idfDataAuditEvent"); return(DataAuditEvent); } catch (Exception e) { if (e is DataException) { throw DbModelException.Create(null, e as DataException); } throw; } }
public static void Log(User user, AuditEventType eventType, string eventDescription, string comment) { try { OCM.Core.Data.OCMEntities dataModel = new OCM.Core.Data.OCMEntities(); var auditEntry = new Core.Data.AuditLog(); if (user == null) { auditEntry.User = dataModel.Users.First(u => u.ID == (int)StandardUsers.System); } else { auditEntry.UserID = user.ID; } auditEntry.EventDescription = "[" + eventType.ToString() + "]:" + (eventDescription != null ? eventDescription : ""); auditEntry.Comment = comment; auditEntry.EventDate = DateTime.UtcNow; dataModel.AuditLogs.Add(auditEntry); dataModel.SaveChanges(); System.Diagnostics.Debug.WriteLine("Log:" + auditEntry.EventDescription); } catch (Exception) { //TODO: fallback to alternative logging } }
public async Task HandleAsync( AuditEventType action, EntityDomainEvent <IAudit> args, Func <PropertyEntry, bool> predicate) { var now = DateTime.Now; var audit = new Audit { Module = args.EntityType.Name, Action = action, Date = now.Date, Time = now.TimeOfDay }; foreach (var property in args.Properties.Where(predicate).Where(w => !Attribute.IsDefined(w.Info, typeof(IsNotAudit)))) { if (property.CurrentValue is IList) { continue; } var originalValue = GetValue(property.OriginalValue); var currentValue = GetValue(property.CurrentValue); audit.Data.Add(new AuditData(audit, property.Info.Name, originalValue, currentValue)); } await _session.SaveAsync(audit); }
public static void Log(User user, AuditEventType eventType, string eventDescription, string comment) { try { OCM.Core.Data.OCMEntities dataModel = new OCM.Core.Data.OCMEntities(); var auditEntry = new Core.Data.AuditLog(); if (user == null) { auditEntry.User = dataModel.Users.First(u => u.ID == (int)StandardUsers.System); } else { auditEntry.UserID = user.ID; } auditEntry.EventDescription = "[" + eventType.ToString() + "]:" + (eventDescription != null ? eventDescription : ""); auditEntry.Comment = comment; auditEntry.EventDate = DateTime.UtcNow; dataModel.AuditLogs.Add(auditEntry); dataModel.SaveChanges(); System.Diagnostics.Debug.WriteLine("Log:"+auditEntry.EventDescription); } catch (Exception) { //TODO: fallback to alternative logging } }
/// <summary> /// constructor that accepts the most common required values for audit command /// </summary> /// <param name="sessionModel">ensure ._IdentityModel.Identity_ID and ._ActivityLog.SESSION_ID are present, as these values are use to populate the corresponding fields</param> /// <param name="applicationId"></param> /// <param name="eventType"></param> /// <param name="description"></param> public AuditDB(SessionObjects sessionModel, long applicationId, AuditEventType eventType, string description) { this.IDENTITY_ID = sessionModel._IdentityModel.identities_id; this.SESSION_ID = sessionModel._ActivityLog.SESSION_ID; this.EVENT_TYPE = eventType; this.APPLICATION_ID = applicationId; this.DESCRIPTION = description; }
/// <summary> /// Checks whether the given event type was used /// </summary> private bool IsEventTypeOn(AuditEventType lookedForType, AuditEventType[] userSelectedTypes) { if (userSelectedTypes.Contains(lookedForType)) { return(true); } return(false); }
public async Task HandleAsync( AuditEventType type, EntityDomainEvent <IAudit> args) { Console.WriteLine($"{DateTime.Now:s} - {type}: {args.EntityType}"); await Task.CompletedTask; }
/// <summary> /// Creates an instance of an AuditEvent /// </summary> /// <param name="type">The type of the audit event</param> /// <param name="time">The time in whic the audit event was generated</param> /// <param name="id">The ID of the audit event</param> /// <param name="messageData">The data the audit event contains</param> /// <param name="eventText">The ausearch line containing the event</param> private AuditEvent(AuditEventType type, DateTime time, string id, Dictionary <AuditMessageProperty, string> messageData, string eventText) { Type = type; TimeUTC = time; Id = id; MessageData = messageData; EventText = eventText; }
/// <summary> /// Parse a line from ausearch output into an AuditEvent /// </summary> /// <param name="eventText">Line from ausearch</param> /// <returns>An AuditEvent</returns> public static AuditEvent ParseFromAusearchLine(string eventText) { var messageData = new Dictionary <AuditMessageProperty, string>(); foreach (AuditMessageProperty prop in Enum.GetValues(typeof(AuditMessageProperty))) { if (TryGetPropertyValue(eventText, prop, out string match)) { string expectedValue; if (prop == AuditMessageProperty.SocketAddress) { expectedValue = match; // In case of 'saddr', hex-encoded bytes are expected } else { expectedValue = EncodedAuditFieldsUtils.DecodeHexStringIfNeeded(match, Encoding.UTF8); } messageData[prop] = expectedValue; if (prop == AuditMessageProperty.ProcessArgCount && UInt32.TryParse(match, out uint argCount)) { string[] processCommandArgs = new string[argCount]; for (int i = 0; i < argCount; i++) { string parameter = Regex.Match(eventText, string.Format(QuotedPropertyRegexTemplate, $"a{i}")).Value; if (string.IsNullOrEmpty(parameter)) { var encodedString = Regex.Match(eventText, string.Format(PropertyRegexTemplate, $"a{i}")).Value; parameter = EncodedAuditFieldsUtils.DecodeHexStringIfNeeded(encodedString, Encoding.UTF8); } processCommandArgs[i] = parameter; } messageData[AuditMessageProperty.CommandLine] = String.Join(' ', processCommandArgs); } } } if (messageData.ContainsKey(AuditMessageProperty.FilePath)) { messageData[AuditMessageProperty.Executable] = messageData[AuditMessageProperty.FilePath]; } AuditEventType type = (AuditEventType)TypeRegex.Match(eventText).Value.ParseFromDisplayName <AuditEventType>(); string eventId = IdRegex.Match(eventText).Value; DateTime eventTimeUTC = TimeUtils.FromUnixTime(eventId.Split(':').First()); var ev = new AuditEvent ( type, eventTimeUTC, eventId, messageData, eventText ); return(ev); }
/// <summary> /// Creates a new AuditEventPropertyNotFoundException exception /// </summary> /// <param name="eventType">The type of the audit event</param> /// <param name="eventId">The id of the event</param> /// <param name="eventData">The content of the event</param> /// <param name="missingProperty">The property that caused the exception</param> /// <param name="eventText">The ausearch line containing the event</param> public AuditEventPropertyNotFoundException(AuditEventType eventType, string eventId, IDictionary <AuditEvent.AuditMessageProperty, string> eventData, AuditEvent.AuditMessageProperty missingProperty, string eventText) { _eventType = eventType; _eventId = eventId; _eventData = eventData; _missingProperty = missingProperty; _eventText = eventText; }
private void WriteLogEntries(AuditEventType eventType, ErrorEntry logEntry) { string message = string.Format("{0} - {1} - {2} - {3}", new object[] { eventType.ToString(), logEntry.ResultCode, logEntry.Source, logEntry.ErrorReason }); Debug.WriteLine(message); }
/// <summary> /// Initializes a new instance of the <see cref="Audit"/> class /// </summary> /// <param name="action">The action that causes the audit</param> /// <param name="eventType">The type of event</param> /// <param name="objectType">The type of Object (use o.GetType().Name)</param> /// <param name="fieldName">The name of the field the object identifier can be found</param> /// <param name="objectId">The Id of the object.</param> /// <param name="success">Indicates whether the action was a success or not</param> /// <param name="message">The optional message to add</param> public Audit(Actions action, AuditEventType eventType, Type objectType, string fieldName, string objectId, bool success = true, string message = null) { this.Action = action; this.AuditEventType = eventType; this.ObjectType = objectType.Name; this.FieldName = fieldName; this.ObjectId = objectId; this.Success = success; this.Message = message; }
public async Task AuditAsync( string source, AuditEventType eventType, string userId, long jobId = -1, string filename = null, string ukPrn = null, string extraInfo = null) { await _queuePublishService.PublishAsync(new AuditingDto(source, (int)eventType, userId, jobId, filename, ukPrn, extraInfo)); }
/// <summary> /// Writes an event to the audit log using the specified parameters. /// </summary> /// <param name="eventType">The type of the audit event</param> /// <param name="successful">Indicates whether the event was successful</param> /// <param name="comment">A brief explanation of the event</param> /// <param name="userId">The user causing the audit event</param> /// <param name="relatedId">A related ID to the event, if applicable</param> /// <param name="remoteIP">IP of the remote system causing the event</param> public static void Audit(AuditEventType eventType, bool successful, string comment, int userId, int relatedId, string remoteIP) { AuditEvent logEntry = new AuditEvent(); logEntry.EventDate = DateTime.UtcNow; logEntry.EventType = eventType; logEntry.Successful = successful; logEntry.UserId = userId; logEntry.RelatedId = relatedId; logEntry.RemoteIP = StringHelper.Truncate(remoteIP, 39); logEntry.Comment = comment; logEntry.Save(); }
public async Task AuditAsync( IJobContextMessage jobContextMessage, AuditEventType eventType, string extraInfo = null) { await AuditAsync( jobContextMessage.Topics[jobContextMessage.TopicPointer].SubscriptionName, eventType, (string)jobContextMessage.KeyValuePairs[JobContextMessageKey.Username], jobContextMessage.JobId, (string)jobContextMessage.KeyValuePairs[JobContextMessageKey.Filename], (string)jobContextMessage.KeyValuePairs[JobContextMessageKey.UkPrn], extraInfo); }
/// <summary> /// Writes an event to the audit log using the specified parameters. /// </summary> /// <param name="eventType">The type of the audit event</param> /// <param name="successful">Indicates whether the event was successful</param> /// <param name="comment">A brief explanation of the event</param> /// <param name="userId">The user causing the audit event</param> /// <param name="relatedId">A related ID to the event, if applicable</param> public static void Audit(AuditEventType eventType, bool successful, string comment, int userId, int relatedId) { string remoteIP; HttpContext context = HttpContext.Current; if (context != null) { remoteIP = context.Request.UserHostAddress; } else { remoteIP = string.Empty; } Audit(eventType, successful, comment, userId, relatedId, remoteIP); }
/// <summary> /// Creates the Audit scope. /// </summary> private AuditScope CreateAuditScope(EntityFrameworkEvent efEvent) { var typeName = GetType().Name; var eventType = AuditEventType?.Replace("{context}", typeName).Replace("{database}", efEvent.Database) ?? typeName; var scope = AuditScope.Create(eventType, null, EventCreationPolicy.Manual, AuditDataProvider); if (_extraFields != null) { foreach (var field in _extraFields) { scope.SetCustomField(field.Key, field.Value); } } return(scope); }
public static void AppEvent(AuditEventType AuditEventType, String MemberEmail, String Description, String Details = null, bool NoMatterIfAuditEnabled = false) { if (!IsAduitEnabled()) { return; } AUDITEVENT Item = new AUDITEVENT { EventType = AuditEventType, IPAddress = GetIPAddress(), MemberEmail = MemberEmail, Description = Description, Details = Details }; AddEvent(Item); }
/// <summary> /// Initializes a new instance of the <see cref="Audit"/> class /// </summary> /// <param name="action">The action that causes the audit</param> /// <param name="eventType">The type of event</param> /// <param name="o">The Object. The object type and Id are retrieved from the object instance</param> /// <param name="success">Indicates whether the action was a success or not</param> /// <param name="message">The optional message to add</param> public Audit(Actions action, AuditEventType eventType, object o, bool success = true, string message = null) { this.Action = action; this.AuditEventType = eventType; this.ObjectType = o.GetType().Name; if (o != null) { // Get primary key value (If you have more than one key column, this will need to be adjusted) var keyNames = o.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0 || p.Name == "Id").ToList(); bool first = true; foreach (PropertyInfo kn in keyNames) { object v = o.GetType().GetProperty(kn.Name).GetValue(o); this.FieldName += (first ? string.Empty : " , ") + kn.Name; this.ObjectId += (first ? string.Empty : " , ") + (v != null ? v.ToString() : string.Empty); first = false; } } this.Success = success; this.Message = message; }
public void AddEventProcessor(XmlNode node) { var attr = node.Attributes; if (attr != null) { string[] parts = attr["type"].Value.Split(','); var assembly = Assembly.Load(parts[1].Trim()); var type = assembly.GetType(parts[0]); AuditEventType o = Activator.CreateInstance(type) as AuditEventType; if (o != null) { o.Color = attr["color"].Value; o.Id = attr["id"].Value; o.Label = attr["label"].Value; AuditLogger.Current.RegisterEventType(o); EventHandler e = (sender, args) => { o.Process(sender, args); }; Event.Subscribe(attr["event"].Value, e); } } }
/// <summary> /// Checks whether the given event type was used /// </summary> private bool IsEventTypeOn(AuditEventType lookedForType, AuditEventType[] userSelectedTypes) { if (userSelectedTypes.Contains(lookedForType)) { return true; } return false; }
public static void ReportWebException(bool enableNotifications, string contextUrl, AuditEventType eventType, string msg = null, Exception exp = null) { bool ignoreException = false; string body = "An error has occurred while a user was browsing OCM:<br><br>"; if (msg != null) { body = msg; } if (exp != null) { object exceptionObject = exp; if (exp.InnerException != null) { exceptionObject = exp.InnerException; } body += ((Exception)exceptionObject).ToString(); if (contextUrl != null) { body += "<br><br>Request Url:" + contextUrl.ToString(); //special case to avoid reporting /trackback url exceptions if (contextUrl.ToString().EndsWith("/trackback/")) { ignoreException = true; } } /*if (con.Request.UserAgent != null) * { * body += "<br>User Agent: " + con.Request.UserAgent; * }*/ } body += "<br><br>" + DateTime.UtcNow.ToString(); //if (exp is System.Web.HttpRequestValidationException || exceptionObject is System.Web.UI.ViewStateException) ignoreException = true; if (!ignoreException) { if (enableNotifications) { NotificationManager notification = new NotificationManager(); var msgParams = new Hashtable() { { "Description", "System Error" }, { "Name", "OCM Website" }, { "Email", "*****@*****.**" }, { "Comment", body } }; notification.PrepareNotification(NotificationType.ContactUsMessage, msgParams); notification.SendNotification(NotificationType.ContactUsMessage); } AuditLogManager.Log(null, eventType, body, null); } }
public void Update(AuditEventType item) => UpdateOrInsertItem <AuditEventType>(_folder, _type, item, item.ID.ToString());
public static void ReportWebException(HttpServerUtility Server, AuditEventType eventType) { bool ignoreException = false; string body = "An error has occurred while a user was browsing OCM:<br><br>"; object exceptionObject = null; if (Server.GetLastError() != null) { Exception exp = Server.GetLastError(); exceptionObject = exp; if (exp.InnerException != null) { exceptionObject = exp.InnerException; } body += ((Exception)exceptionObject).ToString(); HttpContext con = HttpContext.Current; if (con.Request.Url != null) { body += "<br><br>Request Url:" + con.Request.Url.ToString(); //special case to avoid reporting /trackback url exceptions if (con.Request.Url.ToString().EndsWith("/trackback/")) { ignoreException = true; } } if (con.Request.UserAgent != null) { body += "<br>User Agent: " + con.Request.UserAgent; } body += "<br><br>" + DateTime.UtcNow.ToString(); } if (exceptionObject is System.Web.HttpRequestValidationException || exceptionObject is System.Web.UI.ViewStateException) { ignoreException = true; } if (!ignoreException) { if (ConfigurationManager.AppSettings["EnableErrorNotifications"] == "true") { NotificationManager notification = new NotificationManager(); var msgParams = new Hashtable() { { "Description", "System Error" }, { "Name", "OCM Website" }, { "Email", "*****@*****.**" }, { "Comment", body } }; notification.PrepareNotification(NotificationType.ContactUsMessage, msgParams); notification.SendNotification(NotificationType.ContactUsMessage); } AuditLogManager.Log(null, eventType, body, null); } }
public int GetEventCount(string transformId, string recordId, AuditEventType eventType) { return(0); }
public static void ReportWebException(HttpServerUtility Server, AuditEventType eventType, string msg=null) { bool ignoreException = false; string body = "An error has occurred while a user was browsing OCM:<br><br>"; if (msg!=null) { body = msg; } object exceptionObject = null; if (Server.GetLastError() != null) { Exception exp = Server.GetLastError(); exceptionObject = exp; if (exp.InnerException != null) { exceptionObject = exp.InnerException; } body += ((Exception)exceptionObject).ToString(); if (HttpContext.Current != null) { HttpContext con = HttpContext.Current; if (con.Request.Url != null) { body += "<br><br>Request Url:" + con.Request.Url.ToString(); //special case to avoid reporting /trackback url exceptions if (con.Request.Url.ToString().EndsWith("/trackback/")) ignoreException = true; } if (con.Request.UserAgent != null) { body += "<br>User Agent: " + con.Request.UserAgent; } } body += "<br><br>" + DateTime.UtcNow.ToString(); } if (exceptionObject is System.Web.HttpRequestValidationException || exceptionObject is System.Web.UI.ViewStateException) ignoreException = true; if (!ignoreException) { if (ConfigurationManager.AppSettings["EnableErrorNotifications"] == "true") { NotificationManager notification = new NotificationManager(); var msgParams = new Hashtable(){ {"Description", "System Error"}, {"Name", "OCM Website"}, {"Email", "*****@*****.**"}, {"Comment", body} }; notification.PrepareNotification(NotificationType.ContactUsMessage, msgParams); notification.SendNotification(NotificationType.ContactUsMessage); } AuditLogManager.Log(null, eventType, body, null); } }