示例#1
0
        public async Task SaveAsync(AuditItem item)
        {
            var queueUrl    = GetUrlQueue();
            var sendRequest = GetAuditMessage(queueUrl, item);

            await _queueProvider.SendMessageAsync(sendRequest);
        }
示例#2
0
        public static void InsertAuditItem(AuditItem item)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();
                    using (SqlCommand command = new SqlCommand("audit_insert", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add("@TableName", SqlDbType.NVarChar).Value = item.TableName;
                        command.Parameters.Add("@Type", SqlDbType.NChar).Value         = item.Type;
                        command.Parameters.Add("@PK", SqlDbType.NVarChar).Value        = item.PK;
                        command.Parameters.Add("@PKValue", SqlDbType.NVarChar).Value   = item.PKValue;
                        command.Parameters.Add("@FieldName", SqlDbType.NVarChar).Value = item.FieldName;
                        command.Parameters.Add("@OldValue", SqlDbType.NVarChar).Value  = item.OldValue;
                        command.Parameters.Add("@NewValue", SqlDbType.NVarChar).Value  = item.NewValue;
                        command.Parameters.Add("@UpdatedBy", SqlDbType.NVarChar).Value = item.UpdatedBy;
                        command.Parameters.Add("@Reason", SqlDbType.NVarChar).Value    = item.Reason;

                        int dbResult = command.ExecuteNonQuery();
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                ErrorHandler.CreateLogFile("AuditHandler", "InsertAuditItem", sqlEx);
            }
        }
示例#3
0
        public string Serialize(AuditItem auditItem)
        {
            EventHubAuditItem eventHubAuditItem = _auditItemMapper.Map(auditItem);
            string            json = JsonConvert.SerializeObject(eventHubAuditItem);

            return(json);
        }
        public async Task AuditPostDispatch(ICommand command, ICommandDispatchContext dispatchContext, long elapsedMilliseconds, CancellationToken cancellationToken)
        {
            if (_registeredPostDispatchAuditors.Count == 0)
            {
                return;
            }

            ICommandAuditSerializer serializer = _auditorSerializerFunc();

            AuditItem auditItem = new AuditItem
            {
                AdditionalProperties = dispatchContext.AdditionalProperties.ToDictionary(x => x.Key, x => x.Value.ToString()),
                CommandId            = null,
                CommandType          = command.GetType().Name,
                CommandTypeFullName  = command.GetType().AssemblyQualifiedName,
                CorrelationId        = dispatchContext.CorrelationId,
                Depth             = dispatchContext.Depth,
                DispatchedUtc     = DateTime.UtcNow,
                SerializedCommand = serializer.Serialize(command),
                Type           = AuditItem.PostDispatchType,
                DispatchTimeMs = elapsedMilliseconds
            };

            // ReSharper disable once SuspiciousTypeConversion.Global - used by consumers of the package
            if (command is IIdentifiableCommand identifiableCommand)
            {
                auditItem.CommandId = identifiableCommand.CommandId;
            }
            _auditItemEnricherPipeline.Enrich(auditItem.AdditionalProperties, command, dispatchContext);
            await AuditPostDispatch(auditItem, cancellationToken);
        }
        /// <summary>
        /// Insert the audit item into the database.
        /// </summary>
        /// <param name="auditItem">The audit item to insert.</param>
        public void Write(AuditItem auditItem)
        {
            var valueToSerialize = auditItem.Details;
            var type             = auditItem.Details.GetType().Name;

            var serializedMessage = JsonConvert.SerializeObject(
                valueToSerialize,
                Formatting.None,
                _jsonSerializerSettings);

            using (var cn = this._databaseConnectionFactory.Open())
                using (var transaction = cn.BeginTransaction())
                {
                    cn.Execute(
                        $@"INSERT INTO {this._configuration.Value.QualifiedTableName} (CorrelationId,  WasSuccessful,  ResultMessage,  Username,  Timestamp,  MessageType,  MessageData)
                           VALUES (@CorrelationId, @WasSuccessful, @ResultMessage, @Username, @Timestamp, @MessageType, @MessageData)",
                        new
                    {
                        auditItem.CorrelationId,
                        auditItem.ResultMessage,
                        auditItem.Username,
                        auditItem.WasSuccessful,
                        Timestamp   = SystemTime.UtcNow,
                        MessageType = type,
                        MessageData = serializedMessage,
                    },
                        transaction);

                    transaction.Commit();
                }
        }
示例#6
0
        public async Task <List <AuditItem> > GetAuditLogsAsync(LogsFilter filter)
        {
            var guild = Client.GetGuild(filter.GuildId);

            if (guild == null)
            {
                return(new List <AuditItem>());
            }

            var queryFilter = await CreateQueryFilterAsync(filter, guild);

            var data = await GrillBotRepository.AuditLogs.GetAuditLogsQuery(queryFilter)
                       .Skip(queryFilter.Skip).Take(queryFilter.Take).ToListAsync();

            var items = new List <AuditItem>();

            foreach (var item in data)
            {
                var user = item.User == null ? null : await UserHelper.MapUserAsync(Client, BotState, item.User);

                var auditItem = await AuditItem.CreateAsync(guild, item, user, MessageCache);

                items.Add(auditItem);
            }

            return(items);
        }
示例#7
0
        private async Task <bool> HandleRecievedItemAsync(CloudQueue deadLetterQueue, QueueItem <AuditItem> item, int maxDequeueCount, CancellationToken cancellationToken)
        {
            AuditItem auditQueueItem = item.Item;

            try
            {
                await _commandAuditPipeline.Audit(auditQueueItem, cancellationToken);

                return(true);
            }
            catch (Exception)
            {
                if (item.DequeueCount > maxDequeueCount && deadLetterQueue != null)
                {
                    try
                    {
                        string json = _serializer.Serialize(auditQueueItem);
                        await deadLetterQueue.AddMessageAsync(new CloudQueueMessage(json));

                        return(true);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
                return(false);
            }
        }
        private void TransformAudit(AuditItem audit)
        {
            Entity entity = audit.AuditDetail.OldValue;

            switch (audit.Metadata.ObjectTypeCode)
            {
            case 1:
                if (entity.Contains("primarycontactid"))
                {
                    FindContacts(((EntityReference)entity.Attributes["primarycontactid"]).Id);
                }
                Service.Create(entity);
                break;

            case 2:
                if (entity.Contains("parentcustomerid"))
                {
                    entity.Attributes.Remove("parentcustomerid");
                }
                Service.Create(entity);
                break;

            case 3:
                TransformEntity(entity);
                break;

            default:
                break;
            }
            ;
        }
 private void CheckAndAddToAuditItems(string fieldName, string oldValue, string newValue)
 {
     if (oldValue.Trim() != newValue.Trim())
     {
         AuditItem item = CreateAuditItem(fieldName, oldValue, newValue);
         this.auditItems.Add(item);
     }
 }
示例#10
0
        SendMessageRequest GetAuditMessage(string queueUrl, AuditItem item)
        {
            var sendRequest = new SendMessageRequest();

            sendRequest.QueueUrl    = queueUrl;
            sendRequest.MessageBody = JsonConvert.SerializeObject(item);
            return(sendRequest);
        }
        public Task Audit(AuditItem auditItem, CancellationToken cancellationToken)
        {
            LogLevel level = _normalLogLevel;

            if (auditItem.Type == AuditItem.ExecutionType && !(auditItem.ExecutedSuccessfully ?? true))
            {
                level = _executionFailureLogLevel;
            }
            _logger.Log(level, (EventId)0, (object)new FormattedLogValues("command:{0}\nid:{1}\nstage:{2}\ncorrelation ID {3}", auditItem.CommandType, auditItem.CommandId, auditItem.Type, auditItem.CorrelationId), null, (state, ex) => state.ToString());
            return(Task.FromResult(0));
        }
        private async Task AuditPreDispatch(AuditItem auditItem, CancellationToken cancellationToken)
        {
            auditItem.Type = AuditItem.PreDispatchType;
            IReadOnlyCollection <ICommandAuditor> auditors = GetPreDispatchAuditors(auditItem.Depth == 0);
            List <Task> auditTasks = new List <Task>();

            foreach (ICommandAuditor auditor in auditors)
            {
                auditTasks.Add(auditor.Audit(auditItem, cancellationToken));
            }
            await Task.WhenAll(auditTasks);
        }
示例#13
0
        public Message GetEntityById(WebOperationContext ctx, string entityName, string entityKPID)
        {
            Message responseMsg = null;

            try
            {
                // get the specified entities for the specified teams
                switch (entityName)
                {
                case "KPAccomplishmentMisses":
                    Accomplishment accomplishments = this.GetEntityById <Accomplishment>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <Accomplishment>(ctx, accomplishments, this.timer);
                    break;

                case "KPAuditItems":
                    AuditItem auditItems = this.GetEntityById <AuditItem>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <AuditItem>(ctx, auditItems, this.timer);
                    break;

                case "KPEffortInstances":
                    EffortInstance effortInstances = this.GetEntityById <EffortInstance>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <EffortInstance>(ctx, effortInstances, this.timer);
                    break;

                case "KPGoals":
                    Goal goals = this.GetEntityById <Goal>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <Goal>(ctx, goals, this.timer);
                    break;

                case "KPKeyInsightsInnovations":
                    KeyInsightInnovation keyInsightsInnovations = this.GetEntityById <KeyInsightInnovation>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <KeyInsightInnovation>(ctx, keyInsightsInnovations, this.timer);
                    break;

                case "KPMilestones":
                    Milestone milestones = this.GetEntityById <Milestone>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <Milestone>(ctx, milestones, this.timer);
                    break;

                case "KPProjects":
                    Project projects = this.GetEntityById <Project>(entityName, entityKPID);
                    responseMsg = HttpUtilities.GenerateResponse <Project>(ctx, projects, this.timer);
                    break;
                }
            }
            catch (Exception ex)
            {
                responseMsg = HttpUtilities.GenerateExceptionResponse(ctx, ex, "GET", HttpStatusCode.InternalServerError);
            }

            this.timer.Stop();
            return(responseMsg);
        }
        public void Get_Single_From_Cache()
        {
            var cache = new Mock <IAppPolicyCache>();

            cache.Setup(x => x.Get(It.IsAny <string>())).Returns(new AuditItem(1, AuditType.Copy, 123, "test", "blah"));

            var defaultPolicy = new DefaultRepositoryCachePolicy <AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());

            AuditItem found = defaultPolicy.Get(1, id => null, ids => null);

            Assert.IsNotNull(found);
        }
        private void Audit(AuditType type, int userId, int objectId, string message = null, string parameters = null)
        {
            var entry = new AuditItem(
                objectId,
                type,
                userId,
                UmbracoObjectTypes.Document.GetName(),
                message,
                parameters);

            _auditRepository.Save(entry);
        }
示例#16
0
 public EventHubAuditItem Map(AuditItem auditItem)
 {
     return(new EventHubAuditItem
     {
         AdditionalProperties = auditItem.AdditionalProperties,
         Command = new JRaw(auditItem.SerializedCommand),
         CommandId = auditItem.CommandId,
         CommandType = auditItem.CommandTypeFullName,
         CorrelationId = auditItem.CorrelationId,
         Depth = auditItem.Depth,
         DispatchedUtc = auditItem.DispatchedUtc
     });
 }
示例#17
0
        public async Task Audit(AuditItem auditItem, CancellationToken cancellationToken)
        {
            string messageText  = _serializer.Serialize(auditItem);
            string partitionKey = _partitionKeyProvider.GetPartitionKey(auditItem);

            if (string.IsNullOrWhiteSpace(partitionKey))
            {
                await _client.SendAsync(messageText);
            }
            else
            {
                await _client.SendAsync(messageText, partitionKey);
            }
        }
示例#18
0
        public void Caches_Single()
        {
            var isCached = false;
            var cache    = new Mock <IAppPolicyCache>();

            cache.Setup(x => x.Insert(It.IsAny <string>(), It.IsAny <Func <object> >(), It.IsAny <TimeSpan?>(), It.IsAny <bool>(), It.IsAny <string[]>()))
            .Callback(() => isCached = true);

            var defaultPolicy = new SingleItemsOnlyRepositoryCachePolicy <AuditItem, object>(cache.Object, DefaultAccessor, new RepositoryCachePolicyOptions());

            AuditItem unused = defaultPolicy.Get(1, id => new AuditItem(1, AuditType.Copy, 123, "test", "blah"), ids => null);

            Assert.IsTrue(isCached);
        }
        public override bool Filter(object element)
        {
            AuditItem ai = element as AuditItem;

            if (ai == null)
            {
                return(true);
            }

            return((string.IsNullOrEmpty(Verb) || ai.Verb == null ||
                    ai.Verb.Equals(Verb, System.StringComparison.InvariantCultureIgnoreCase)) &&
                   (string.IsNullOrEmpty(User) || ai.User == null ||
                    ai.User.Equals(User, System.StringComparison.InvariantCultureIgnoreCase)));
        }
        public Task Audit(AuditItem item, CancellationToken cancellationToken)
        {
            ConsoleColor previousColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine($"Type: {item.CommandTypeFullName}");
            Console.WriteLine($"Correlation ID: {item.CorrelationId}");
            Console.WriteLine($"Depth: {item.Depth}");
            foreach (KeyValuePair <string, string> enrichedProperty in item.AdditionalProperties)
            {
                Console.WriteLine($"{enrichedProperty.Key}: {enrichedProperty.Value}");
            }
            Console.ForegroundColor = previousColor;
            return(Task.FromResult(0));
        }
示例#21
0
        public async Task Audit(AuditItem auditItem, CancellationToken cancellationToken)
        {
            CloudBlobContainer blobContainer = _blobContainerProvider.BlobContainer;

            if (blobContainer != null && !string.IsNullOrWhiteSpace(auditItem.SerializedCommand))
            {
                CloudBlockBlob blob = blobContainer.GetBlockBlobReference($"{auditItem.CommandId}.json");
                await blob.UploadTextAsync(auditItem.SerializedCommand);

                auditItem.SerializedCommand = null;
            }
            CloudQueue queue         = _cloudAuditQueueProvider.Queue;
            string     queueItemJson = _serializer.Serialize(auditItem);
            await queue.AddMessageAsync(new CloudQueueMessage(queueItemJson), null, null, null, null, cancellationToken);
        }
 public Task Audit(AuditItem auditItem, CancellationToken cancellationToken)
 {
     if (auditItem.AdditionalProperties.ContainsKey("UserId"))
     {
         _logger.LogInformation("Executing command {commandType} for user {userId}",
                                auditItem.CommandType,
                                auditItem.AdditionalProperties["UserId"]);
     }
     else
     {
         _logger.LogInformation("Executing command {commandType}",
                                auditItem.CommandType);
     }
     return(Task.FromResult(0));
 }
        private AuditItem CreateAuditItem(string fieldName, string oldValue, string newValue)
        {
            AuditItem item = new AuditItem();

            item.TableName = "ProtocolNumbers";
            item.Type      = "U";
            item.PK        = "RequestID,TemplateID";
            item.PKValue   = this.protocolNumber.RequestID.ToString() + "," + this.protocolNumber.TemplateID.ToString();
            item.FieldName = fieldName;
            item.OldValue  = oldValue.Trim() == String.Empty ? "N/A" : oldValue;
            item.NewValue  = newValue;
            item.UpdatedBy = loginInfo.UserName;
            item.Reason    = "Admin Protocol Number Update.";

            return(item);
        }
        private AuditItem CreateAuditItem(string fieldName, string oldValue, string newValue)
        {
            AuditItem item = new AuditItem();

            item.TableName = "TemplateGroups";
            item.Type      = "U";
            item.PK        = "ID";
            item.PKValue   = this.selectedItem.ID.ToString();
            item.FieldName = fieldName;
            item.OldValue  = oldValue.Trim() == String.Empty ? "N/A" : oldValue;
            item.NewValue  = newValue;
            item.UpdatedBy = loginInfo.UserName;
            item.Reason    = "Admin Template Group Update.";

            return(item);
        }
示例#25
0
        public void Log(AuditLogItem log)
        {
            var dbItem = new AuditItem();

            dbItem.Title = log.Title;
            dbItem.Content = log.FriendlyContent;
            dbItem.PrivateContent = log.PrivateContent;
            dbItem.User = log.User;
            dbItem.MachineName = log.MachineName;
            dbItem.ModuleName = log.ModuleName;
            dbItem.Type = log.Type;
            dbItem.LogTime = log.LogTime;
            dbItem.EntityId = log.EntityId;

            RF.Save(dbItem);
        }
示例#26
0
        public static AuditItem CreateEntity(this AuditItemDto dto)
        {
            var entity = new AuditItem
            {
                Order = dto.Order,
                Title = dto.Title,
                IsCheckedAvailable  = dto.IsCheckedAvailable,
                IsChecked           = dto.IsChecked,
                IsCommentsAvailable = dto.IsCommentsAvailable,
                Comments            = dto.Comments,
                IsPhotoAvailable    = dto.IsPhotoAvailable,
                Photos = dto.Photos.Where(x => !x.Removed).Select(x => x.CreateEntity()).ToList()
            };

            return(entity);
        }
        private AuditItem CreateAuditItem(string fieldName, string oldValue, string newValue)
        {
            AuditItem item = new AuditItem();

            item.TableName = "ProtocolRequests";
            item.Type      = "U";
            item.PK        = "ID";
            item.PKValue   = this.selectedRequest.ID.ToString();
            item.FieldName = fieldName;
            item.OldValue  = oldValue.Trim() == String.Empty ? "N/A" : oldValue;
            item.NewValue  = newValue;
            item.UpdatedBy = loginInfo.UserName;
            item.Reason    = "Reset request in History page.";

            return(item);
        }
示例#28
0
        public static void Insert_ProtocolNumber_AuditItem(ProtocolNumber protocolNumber, string userName)
        {
            AuditItem item = new AuditItem();

            item.TableName = "ProtocolNumbers";
            item.Type      = "I";
            item.PK        = "RequestID,TemplateID";
            item.PKValue   = protocolNumber.RequestID + "," + protocolNumber.TemplateID;
            item.FieldName = "ProtocolNumber";
            item.OldValue  = "N/A";
            item.NewValue  = protocolNumber.FullCode;
            item.UpdatedBy = userName;
            item.Reason    = "Protocol Number button clicked.";

            InsertAuditItem(item);
        }
示例#29
0
        public static void Insert_RemoveTitle_AuditItem(int requestID, int templateID, string userName)
        {
            AuditItem item = new AuditItem();

            item.TableName = "ProtocolRequestTemplates";
            item.Type      = "U";
            item.PK        = "RequestID,TemplateID";
            item.PKValue   = requestID + "," + templateID;
            item.FieldName = "IsActive";
            item.OldValue  = "true";
            item.NewValue  = "false";
            item.UpdatedBy = userName;
            item.Reason    = "Remove Title button clicked.";

            InsertAuditItem(item);
        }
        private AuditItem CreateAuditItem(string fieldName, string oldValue, string newValue)
        {
            AuditItem item = new AuditItem();

            item.TableName = "ProtocolRequests";
            item.Type      = "U";
            item.PK        = "ID";
            item.PKValue   = this.request.ID.ToString();
            item.FieldName = fieldName;
            item.OldValue  = oldValue.Trim() == String.Empty ? "N/A" : oldValue;
            item.NewValue  = newValue;
            item.UpdatedBy = loginInfo.UserName;
            item.Reason    = "Update using Save Changes button.";

            return(item);
        }
        private AuditItem CreateAuditItem(string fieldName, string oldValue, string newValue)
        {
            LoginInfo loginInfo = LoginInfo.GetInstance();
            AuditItem item      = new AuditItem();

            item.TableName = "ListItems";
            item.Type      = "U";
            item.PK        = "ListName,ItemName";
            item.PKValue   = this.selectedListName + "," + this.selectedItem.Text;
            item.FieldName = fieldName;
            item.OldValue  = oldValue.Trim() == String.Empty ? "N/A" : oldValue;
            item.NewValue  = newValue;
            item.UpdatedBy = loginInfo.UserName;
            item.Reason    = "Admin List Item Update.";

            return(item);
        }
 /// <summary>
 /// There are no comments for AuditItem in the schema.
 /// </summary>
 public void AddToAuditItem(AuditItem auditItem)
 {
     base.AddObject("AuditItem", auditItem);
 }
 /// <summary>
 /// Create a new AuditItem object.
 /// </summary>
 /// <param name="auditItemID">Initial value of AuditItemID.</param>
 /// <param name="name">Initial value of Name.</param>
 /// <param name="description">Initial value of Description.</param>
 /// <param name="isActive">Initial value of IsActive.</param>
 /// <param name="createdBy">Initial value of CreatedBy.</param>
 /// <param name="createdDate">Initial value of CreatedDate.</param>
 /// <param name="lastModifiedBy">Initial value of LastModifiedBy.</param>
 /// <param name="lastModifiedDate">Initial value of LastModifiedDate.</param>
 public static AuditItem CreateAuditItem(int auditItemID, string name, string description, bool isActive, string createdBy, global::System.DateTime createdDate, string lastModifiedBy, global::System.DateTime lastModifiedDate)
 {
     AuditItem auditItem = new AuditItem();
     auditItem.AuditItemID = auditItemID;
     auditItem.Name = name;
     auditItem.Description = description;
     auditItem.IsActive = isActive;
     auditItem.CreatedBy = createdBy;
     auditItem.CreatedDate = createdDate;
     auditItem.LastModifiedBy = lastModifiedBy;
     auditItem.LastModifiedDate = lastModifiedDate;
     return auditItem;
 }
示例#34
0
 public void Insert(int index, AuditItem entity)
 {
     base.Insert(index, entity);
 }
示例#35
0
 public bool Remove(AuditItem entity)
 {
     return base.Remove(entity);
 }
示例#36
0
 public void Add(AuditItem entity)
 {
     base.Add(entity);
 }
示例#37
0
 public bool Contains(AuditItem entity)
 {
     return base.Contains(entity);
 }
示例#38
0
 public int IndexOf(AuditItem entity)
 {
     return base.IndexOf(entity);
 }