public static string GetActionText(AuditEvent evt)
        {
            var action = (MessageAction)evt.Action;
            if (!actions.ContainsKey(action))
            {
                //log.Error(string.Format("There is no action text for \"{0}\" type of event", action));
                return string.Empty;
            }

            try
            {
                var actionText = actions[(MessageAction)evt.Action].GetActionText();

                if (evt.Description == null || !evt.Description.Any()) return actionText;

                var description = evt.Description
                                     .Select(t => t.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries))
                                     .Select(split => string.Join(", ", split.Select(ToLimitedText))).ToList();


                return string.Format(actionText, description.ToArray());
            }
            catch
            {
                //log.Error(string.Format("Error while building action text for \"{0}\" type of event", action));
                return string.Empty;
            }
        }
示例#2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public AuditItem(AuditLevel level, FileSystemTask context, AuditEvent eventId, string message)
 {
   Timestamp = SystemTime.Now();
   Level = level;
   Context = context;
   EventId = eventId;
   Message = message;
 }
示例#3
0
		public Auditable(AuditEvent type, List<Audit> auditTrail, IDateTimeProvider dateTimeProvider)
		{
			this._dateTimeProvider = dateTimeProvider;
			var started = _dateTimeProvider.Now();

			this._audit = new Audit(type, started);
			auditTrail.Add(this._audit);
		}
示例#4
0
        private void ProductDeleted(DateTimeOffset timestamp, IIdentity identity, int id)
        {
            var ae = new AuditEvent();
            ae.User = identity.Name;
            ae.Time = timestamp.UtcDateTime;
            ae.AuditProductsDeleted.Add(new AuditProductDeleted { ProductId = id });

            this.context.AddToAuditEvents(ae);
            this.context.SaveChanges();
        }
示例#5
0
        private void ProductUpdated(DateTimeOffset timestamp, IIdentity identity, int id, string name, Money unitPrice)
        {
            var baseCurrency = this.CreateBaseCurrency();

            var ae = new AuditEvent();
            ae.User = identity.Name;
            ae.Time = timestamp.UtcDateTime;
            ae.AuditProductsUpdated.Add(new AuditProductUpdated { ProductId = id, Name = name, UnitPrice = unitPrice.ConvertTo(baseCurrency).Amount });

            this.context.AddToAuditEvents(ae);
            this.context.SaveChanges();
        }
示例#6
0
        /// <summary>
        /// Returns an enumeration of audit events for the given Azure Document DB SQL expression and the event type given.
        /// </summary>
        /// <typeparam name="T">The AuditEvent type</typeparam>
        /// <param name="sqlExpression">The Azure Document DB SQL expression</param>
        /// <param name="feedOptions">The options for processing the query results feed.</param>
        /// <param name="auditEvent">The AuditEvent to use when calling the builders to get the ConnectionString, Database, Collection and AuthKey.</param>
        public IEnumerable <T> EnumerateEvents <T>(string sqlExpression, FeedOptions feedOptions = null, AuditEvent auditEvent = null) where T : AuditEvent
        {
            var client        = GetClient(auditEvent);
            var collectionUri = GetCollectionUri(auditEvent);

            return(client.CreateDocumentQuery <T>(collectionUri, sqlExpression, feedOptions));
        }
 public static string GetModuleText(AuditEvent evt)
 {
     var action = (MessageAction)evt.Action;
     return !actions.ContainsKey(action)
                ? string.Empty
                : actions[(MessageAction)evt.Action].Module;
 }
示例#8
0
 /// <summary>
 /// Audits a given incident.
 /// </summary>
 /// <param name="level">Indicates the severity of an audited incident.</param>
 /// <param name="context">Defines the context of the audited operation on the file system.</param>
 /// <param name="eventId">An identifier that indicates the incident.</param>
 /// <param name="message">An optional message that provides background information.</param>
 public void Audit(AuditLevel level, FileSystemTask context, AuditEvent eventId, string message)
 {
   Audit(new AuditItem(level, context, eventId, message));
 }
示例#9
0
        /// <summary>
        /// Saves the Dataobject to the Database
        /// </summary>
        /// <param name="IndexColumn"></param>
        /// <param name="db"></param>
        public void SaveObject(Database db)
        {
            this.SetValue(LASTMODIFIED, DateTime.Now);
            this.SetValue(MODIFIEDBY, System.Environment.UserName);
            StringBuilder whereBuilder = new StringBuilder();
            bool first = true;
            foreach (String column in PrimaryKeyColumns)
            {
                if (!first)
                {
                    whereBuilder.Append(" AND ");
                }
                else
                {
                    first = false;
                }
                whereBuilder.Append("`" + column + "` = ");
                if (data.IsColumnNumberDataType(column))
                {
                    whereBuilder.Append(data.getString(column));
                }
                else
                {
                    whereBuilder.Append("'" + data.getString(column) + "'");
                }
            }
            if (newObject)
            {
                try
                {
                    db.Insert(data.GetTableName(), data);
                    newObject = false;
                    updates = new Hashtable();
                    //Parse an array of UniqueID Columns
                    StringBuilder description = new StringBuilder();
                    first = true;
                    foreach (String column in PrimaryKeyColumns)
                    {
                        if (!first)
                        {
                            description.Append(" and ");
                        }
                        else
                        {
                            first = false;
                        }
                        description.Append(column + " is " + data.getString(column));
                    }
                    //Submit an audit event
                    AuditEvent auditEvent = new AuditEvent(db);
                    auditEvent.EventDescription(data.GetTableName(), "New Object added, " + description.ToString());
                    auditEvent.SaveEvent();
                }
                catch (Exception e)
                {
                    Console.Write(e.StackTrace);
                    throw new Exception("Database Error, Audit log failed.", e);
                }
            }
            else
            {
                StringBuilder setStr = new StringBuilder();
                bool firstKey = true;
                foreach (Object key in updates.Keys)
                {
                    if (!firstKey)
                    {
                        setStr.Append(",");
                    }
                    else
                    {
                        firstKey = false;
                    }
                    setStr.Append("`" + key.ToString() + "` = ");
                    if (data.IsColumnNumberDataType(key.ToString()))
                    {
                        setStr.Append(updates[key].ToString());
                    }
                    else if (updates[key].Equals(DBNull.Value))
                    {
                        setStr.Append("NULL");
                    }
                    else
                    {
                        setStr.Append("'" + updates[key].ToString() + "'");
                    }
                }
                DataSet check = db.Select(LASTMODIFIED + "," + MODIFIEDBY, data.GetTableName(), whereBuilder.ToString());
                MessageBoxResult askBox;
                if (!check.getDateTime(LASTMODIFIED).Equals(data.getDateTime(LASTMODIFIED)))
                {
                    askBox = MessageBox.Show(data.GetTableName() + " Object has already been modified by " + check.getString(MODIFIEDBY) + " since you have opened this object. Continue with operation?", "Consistency Error", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                    if (askBox == MessageBoxResult.Yes)
                    {
                        db.Update(data.GetTableName(), setStr.ToString(), whereBuilder.ToString());
                        UpdateAuditEvent(db);
                        data = db.Select("*", data.GetTableName(), whereBuilder.ToString());

                    }
                    else
                    {
                        throw new Exception("Database Error, Object was out of sync. Reload Object.");
                    }
                }
                else
                {
                    db.Update(data.GetTableName(), setStr.ToString(), whereBuilder.ToString());
                    UpdateAuditEvent(db);

                }
                foreach (String column in PrimaryKeyColumns)
                {
                    if (updates.ContainsKey(column))
                    {
                        data.SetCellValue(0, column, updates[column]);
                    }
                }
                updates.Clear();
            }
            ReloadObject();
            //data = db.Select("*", data.GetTableName(), whereBuilder.ToString());
        }
 internal RedisValue GetValue(AuditEvent auditEvent)
 {
     return((RedisValue)Serializer.Invoke(auditEvent));
 }
示例#11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public AuditItem(AuditLevel level,  FileSystemTask context, AuditEvent eventId)
   : this(level, context, eventId, String.Empty)
 {
 }
示例#12
0
		public Audit(AuditEvent type, DateTime occured)
		{
			this.Event = type;
			this.Started = occured;
		}
示例#13
0
 internal override void Replace(string key, object subKey, AuditEvent auditEvent)
 {
     // values cannot be updated on a pubsub. This will send a new message.
     Publish((Guid)subKey, auditEvent);
 }
示例#14
0
 internal override async Task ReplaceAsync(string key, object subKey, AuditEvent auditEvent)
 {
     // values cannot be updated on a pubsub. This will send a new message.
     await PublishAsync((Guid)subKey, auditEvent);
 }
 public void Save(AuditEvent auditEvent)
 {
     _context.AuditEvents.Add(auditEvent);
     _context.SaveChanges();
 }
示例#16
0
 private Auditable Audit(AuditEvent type) => new Auditable(type, this.AuditTrail, this._dateTimeProvider);
示例#17
0
 /// <summary>
 /// Applies the configured behaviours to the specified <see cref="AuditEvent"/>
 /// </summary>
 /// <param name="auditEvent">The audit event.</param>
 public void ApplyTo(AuditEvent auditEvent)
 {
     this.behaviours.ForEach(behaviour => behaviour(auditEvent));
 }
示例#18
0
 private void LazyAuditable(AuditEvent e, Node n)
 {
     using (new Auditable(e, AuditTrail, _dateTimeProvider, n)) { }
 }
示例#19
0
 private Auditable Audit(AuditEvent type, Node node = null) => new Auditable(type, AuditTrail, _dateTimeProvider, node);
 private string GetConnectionString(AuditEvent auditEvent)
 {
     return(ConnectionStringBuilder?.Invoke(auditEvent));
 }
示例#21
0
 // Replaces an existing event given the ID and the event
 public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
 {
     log.Debug(auditEvent.ToJson());
 }
示例#22
0
        public JsonResult SaveRole(RoleInfo Info)
        {
            RequestResultModel _model = new RequestResultModel();

            if (Info.Name == null || Info.Name.Trim().Length == 0)
            {
                _model          = new RequestResultModel();
                _model.Title    = "Warning";
                _model.Message  = "Name is empty. Please, enter role name.";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return(Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)
                }, JsonRequestBehavior.AllowGet));
            }

            if (!AppSession.IsColor(Info.Color))
            {
                _model          = new RequestResultModel();
                _model.Title    = "Warning";
                _model.Message  = "Wrong color value or format, please check.";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return(Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)
                }, JsonRequestBehavior.AllowGet));
            }

            if (Info.RoleID > 0)
            {
                Role role       = Web.Admin.Logic.Collections.Roles.GetBy(Info.RoleID);
                Role roleExists = Web.Admin.Logic.Collections.Roles.GetBy(Info.Name);

                // The role has been deleted.
                if (role.RoleID <= 0)
                {
                    _model.Title   = "Warning";
                    _model.Message = String.Format("Role '{0}' doesn't exist. Please, refresh role list and try again.", roleExists.Name);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return(Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)
                    }, JsonRequestBehavior.AllowGet));
                }

                // The role already esists.
                if (roleExists.RoleID > 0 && Info.RoleID != roleExists.RoleID)
                {
                    _model.Title   = "Warning";
                    _model.Message = String.Format("Role '{0}' already exists. Please, change role name and try again.", roleExists.Name);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return(Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)
                    }, JsonRequestBehavior.AllowGet));
                }

                if (!role.IsBuiltIn)
                {
                    role.Name      = Info.Name;
                    role.IsBuiltIn = false;
                }
                else
                {
                    role.IsBuiltIn = true;
                }

                role.Settings  = Info.Settings;
                role.BackColor = Info.Color != null?Info.Color.Replace("#", "") : "FFFFFF";

                role.ForeColor = Role.ContrastColor(role.BackColor.Replace("#", ""));
                role.Save();

                _model               = new RequestResultModel();
                _model.Message       = String.Format("Role \"{0}\"has been updated.", role.Name);
                _model.HideInSeconds = 4000;
                AuditEvent.AppEventSuccess(Profile.Member.Email, _model.Message);

                return(Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)
                }, JsonRequestBehavior.AllowGet));
            }
            else
            {
                Role roleExists = Web.Admin.Logic.Collections.Roles.GetBy(Info.Name);

                // The role already esists.
                if (roleExists.RoleID > 0)
                {
                    _model.Title   = "Warning";
                    _model.Message = String.Format("Role '{0}' already exists. Please, change role name and try again.", roleExists.Name);

                    return(Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)
                    }, JsonRequestBehavior.AllowGet));
                }

                Role Role = new Role();
                Role.Name      = Info.Name;
                Role.Settings  = Info.Settings;
                Role.BackColor = Info.Color != null?Info.Color.Replace("#", "") : "FFFFFF";

                Role.ForeColor = Role.ContrastColor(Role.BackColor.Replace("#", ""));
                Role.IsBuiltIn = false;
                Role.Save();

                _model.Message = String.Format("New role \"{0}\" has been created.", Role.Name);

                return(Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)
                }, JsonRequestBehavior.AllowGet));
            }
        }
示例#23
0
 public override object InsertEvent(AuditEvent auditEvent)
 {
     log.Debug(auditEvent.ToJson());
     return(string.Empty);
 }
示例#24
0
 /// <summary>
 /// Gets an event stored on cosmos DB from its document id on the collection returned by calling the collection builder with a null AuditEvent.
 /// </summary>
 /// <param name="docId">The document id</param>
 /// <param name="auditEvent">The AuditEvent to use when calling the builders to get the ConnectionString, Database, Collection and AuthKey.</param>
 public async Task <T> GetEventAsync <T>(string docId, AuditEvent auditEvent)
 {
     return(await Task.FromResult(GetEvent <T>(docId, auditEvent)));
 }
示例#25
0
 private BsonDocument ParseBson(AuditEvent auditEvent)
 {
     return(BsonDocument.Parse(JsonConvert.SerializeObject(auditEvent, JsonSerializerSettings)));
 }
示例#26
0
 private void UpdateAuditEvent(Database db)
 {
     StringBuilder eventDesc = new StringBuilder();
     eventDesc.Append("Object was updated, ");
     Boolean first = true;
     foreach (Object key in updates.Keys)
     {
         if (!key.ToString().Equals(LASTMODIFIED) & !key.ToString().Equals(MODIFIEDBY))
         {
             if (first)
             {
                 first = false;
             }
             else
             {
                 eventDesc.Append(", ");
             }
             eventDesc.Append(key.ToString() + " From \"" + data.getString(key.ToString()) + "\" to \"" + updates[key].ToString() + "\"");
         }
     }
     AuditEvent auditEvent = new AuditEvent(db);
     auditEvent.EventDescription(data.GetTableName(), eventDesc.ToString());
     auditEvent.SaveEvent();
 }
示例#27
0
 private IDocumentClient GetClient(AuditEvent auditEvent)
 {
     return(DocumentClient ?? InitializeClient(auditEvent));
 }
 private void cmdRemoveItem_Click(object sender, RoutedEventArgs e)
 {
     if (!isTransactionLocked)
     {
         MessageBoxResult res = MessageBox.Show("Are you sure you want to remove this item from the Transaction?", "Removal of Item", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
         if (res == MessageBoxResult.Yes)
         {
             mTransactionItems.Remove(mTransactionItem.GetItemID());
             InventoryItem item = mTransactionItem.GetInventoryItem();
             if (item.getQuantity() > 0)
             {
                 float newAvg = (item.getAverageCost() * item.getQuantity()) - (mTransactionItem.GetUnitPrice() * mTransactionItem.GetQuantity());
                 newAvg = newAvg / (item.getQuantity() - mTransactionItem.GetQuantity());
                 if (item.getQuantity() - mTransactionItem.GetQuantity() > 0)
                 {
                     item.setAverageCost(newAvg);
                     item.setQuantity(item.getQuantity() - mTransactionItem.GetQuantity());
                 }
                 else
                 {
                     item.setQuantity(0);
                 }
                 item.SaveObject(db);
             }
             db.Delete(InventoryTransactionItem.Table, InventoryTransactionItem.Fields.transactionID.ToString() + " = '" + mTransactionItem.GetTransactionID() + "' AND " + InventoryTransactionItem.Fields.itemID.ToString() + " = '" + mTransactionItem.GetItemID() + "'");
             AuditEvent aEvent = new AuditEvent(db);
             aEvent.EventDescription(InventoryTransactionItem.Table, "Item " + mTransactionItem.GetItemID() + " with a quantity " + mTransactionItem.GetQuantity() + " has been removed from transaction " + mTransaction.GetTransactionID());
             aEvent.SaveEvent();
             isTransactionModified = true;
             LoadDateGrid();
             ClearFields();
             lockItemFields();
             displayOrHideForm();
             this.TabIsGainingFocus();
         }
     }
     else
     {
         MessageBox.Show("Transaction is locked. Please unlock the transaction to modify it.", "Transaction Locked", MessageBoxButton.OK, MessageBoxImage.Warning);
     }
 }
 internal abstract void Replace(object eventId, AuditEvent auditEvent);
        public static string GetActionText(AuditEvent evt)
        {
            var action = (MessageAction)evt.Action;
            if (!actions.ContainsKey(action))
                throw new ArgumentException(string.Format("There is no action text for \"{0}\" type of event", action));

            var text = actions[(MessageAction)evt.Action].ActionText;

            return evt.Ids == null || !evt.Ids.Any()
                       ? text
                       : string.Format(text, evt.Ids.Select(GetLimitedText).ToArray());
        }
示例#31
0
 public override Task <object> InsertEventAsync(AuditEvent auditEvent)
 {
     _inserted.Add(AuditEvent.FromJson(auditEvent.ToJson()));
     return(base.InsertEventAsync(auditEvent));
 }
示例#32
0
		public Audit(AuditEvent type, DateTime started)
		{
			this.Event = type;
			this.Started = started;
		}
示例#33
0
 public override Task ReplaceEventAsync(object eventId, AuditEvent auditEvent)
 {
     _replaced.Add(AuditEvent.FromJson(auditEvent.ToJson()));
     return(base.ReplaceEventAsync(eventId, auditEvent));
 }
示例#34
0
 /// <summary>
 /// Audits a given incident.
 /// </summary>
 /// <param name="level">Indicates the severity of an audited incident.</param>
 /// <param name="context">Defines the context of the audited operation on the file system.</param>
 /// <param name="eventId">An identifier that indicates the incident.</param>
 /// <param name="message">An optional message that provides background information.</param>
 public void Audit(AuditLevel level, FileSystemTask context, AuditEvent eventId, string message)
 {
 }
示例#35
0
 private Uri GetCollectionUri(AuditEvent auditEvent)
 {
     return(UriFactory.CreateDocumentCollectionUri(DatabaseBuilder?.Invoke(auditEvent), CollectionBuilder.Invoke(auditEvent)));
 }
        public async Task Test_EF_Actions_Async()
        {
            var        provider   = new Mock <AuditDataProvider>();
            AuditEvent auditEvent = null;

            provider.Setup(x => x.InsertEventAsync(It.IsAny <AuditEvent>())).ReturnsAsync((AuditEvent ev) =>
            {
                auditEvent = ev;
                return(Guid.NewGuid());
            });
            provider.Setup(p => p.Serialize(It.IsAny <object>())).Returns((object obj) => obj);

            Audit.Core.Configuration.Setup()
            .UseCustomProvider(provider.Object);

            using (var ctx = new MyAuditedVerboseContext())
            {
                ctx.Database.EnsureCreated();
                ctx.Database.ExecuteSqlCommand(@"
--delete from AuditPosts
--delete from AuditBlogs
delete from Posts
delete from Blogs
SET IDENTITY_INSERT Blogs ON 
insert into Blogs (id, title, bloggername) values (1, 'abc', 'def')
insert into Blogs (id, title, bloggername) values (2, 'ghi', 'jkl')
SET IDENTITY_INSERT Blogs OFF
SET IDENTITY_INSERT Posts ON
insert into Posts (id, title, datecreated, content, blogid) values (1, 'my post 1', GETDATE(), 'this is an example 123', 1)
insert into Posts (id, title, datecreated, content, blogid) values (2, 'my post 2', GETDATE(), 'this is an example 456', 1)
insert into Posts (id, title, datecreated, content, blogid) values (3, 'my post 3', GETDATE(), 'this is an example 789', 1)
insert into Posts (id, title, datecreated, content, blogid) values (4, 'my post 4', GETDATE(), 'this is an example 987', 2)
insert into Posts (id, title, datecreated, content, blogid) values (5, 'my post 5', GETDATE(), 'this is an example 000', 2)
SET IDENTITY_INSERT Posts OFF
                    ");

                var postsblog1 = ctx.Blogs.Include(x => x.Posts)
                                 .FirstOrDefault(x => x.Id == 1);
                postsblog1.BloggerName += "-22";

                ctx.Posts.Add(new Post()
                {
                    BlogId = 1, Content = "content", DateCreated = DateTime.Now, Title = "title"
                });

                var ch1 = ctx.Posts.FirstOrDefault(x => x.Id == 1);
                ch1.Content += "-code";

                var pr = ctx.Posts.FirstOrDefault(x => x.Id == 5);
                ctx.Remove(pr);

                int result = await ctx.SaveChangesAsync();

                Assert.IsFalse(auditEvent.CustomFields.ContainsKey("EntityFrameworkEvent"));
                var efEvent = (auditEvent as AuditEventEntityFramework).EntityFrameworkEvent;

                Assert.AreEqual(4, result);
                Assert.AreEqual("Blogs" + "_" + ctx.GetType().Name, auditEvent.EventType);
                Assert.True(efEvent.Entries.Any(e => e.Action == "Insert" && (e.Entity as Post)?.Title == "title"));
                Assert.True(efEvent.Entries.Any(e => e.Action == "Insert" && e.ColumnValues["Title"].Equals("title") && (e.Entity as Post)?.Title == "title"));
                Assert.True(efEvent.Entries.Any(e => e.Action == "Update" && (e.Entity as Blog)?.Id == 1 && e.Changes[0].ColumnName == "BloggerName"));
                Assert.True(efEvent.Entries.Any(e => e.Action == "Delete" && (e.Entity as Post)?.Id == 5));
                Assert.True(efEvent.Entries.Any(e => e.Action == "Delete" && e.ColumnValues["Id"].Equals(5) && (e.Entity as Post)?.Id == 5));
                provider.Verify(p => p.InsertEvent(It.IsAny <AuditEvent>()), Times.Never);
                provider.Verify(p => p.InsertEventAsync(It.IsAny <AuditEvent>()), Times.Once);
            }
        }
 internal abstract object Insert(AuditEvent auditEvent);