Exemple #1
0
 public GetAuditApplicationQueryHandler(IAuditContextFactory dbContextFactory, IMapper mapper, IUriService uriService, ILogger <GetAuditApplicationQueryHandler> logger)
 {
     _dbContext  = dbContextFactory.AuditContext;
     _mapper     = mapper;
     _uriService = uriService;
     _logger     = logger;
 }
Exemple #2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="date"></param>
 /// <returns></returns>
 public IEnumerable <Event> FindEventsFrom(DateTime date)
 {
     using (var context = new AuditContext(_options))
     {
         return(context.Events.Where(e => e.Date >= date).ToList());
     }
 }
Exemple #3
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public IEnumerable <Event> GetAllEvents()
 {
     using (var context = new AuditContext(_options))
     {
         return(context.Events.ToList());
     }
 }
Exemple #4
0
        public static AuditContext GetAuditContext(this HttpContext httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return(null);
            }
            var result    = new AuditContext();
            var routeData = httpContext.GetRouteData();

            if (routeData.Values.ContainsKey("action"))
            {
                result.ActionName     = routeData.Values["action"]?.ToString();
                result.ControllerName = routeData.Values["controller"]?.ToString();
            }

            var claims = httpContext.User.Claims;

            result.ClientId     = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.ClientId)?.Value;
            result.Name         = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value;
            result.Email        = claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
            result.SenderName   = SenderAppName;
            result.Organisation = httpContext.GetOrganisation();

            return(result);
        }
Exemple #5
0
 public AuditUnitOfWork(
     AuditContext context,
     IAuditLogRepository auditLogRepository
     ) : base(context)
 {
     AuditLogRepository = auditLogRepository;
 }
Exemple #6
0
 public SearchAuditsQueryHandler(IAuditContextFactory dbContextFactory, IMapper mapper, IUriService uriService, ILogger <SearchAuditsQueryHandler> logger)
 {
     _dbContext  = dbContextFactory.AuditContext;
     _mapper     = mapper;
     _uriService = uriService;
     _logger     = logger;
 }
Exemple #7
0
        public void Test_DatabaseAuditor_HeaderAuditMessageBuilder()
        {
            string            configPath = GetSettingsPath("TestSmtpAgentAuditConfig.xml");
            SmtpAgentSettings settings   = SmtpAgentSettings.LoadSettings(configPath);

            SimpleComponentSettings[] components = new SimpleComponentSettings[1];


            SimpleComponentSettings localAuditComponent = new SimpleComponentSettings();

            localAuditComponent.Scope   = InstanceScope.Singleton;
            localAuditComponent.Service = "Health.Direct.SmtpAgent.Diagnostics.IAuditor`1[[Health.Direct.SmtpAgent.Diagnostics.IBuildAuditLogMessage, Health.Direct.SmtpAgent]], Health.Direct.SmtpAgent";
            localAuditComponent.Type    = "Health.Direct.DatabaseAuditor.Auditor`1[[Health.Direct.DatabaseAuditor.HeaderAuditMessageBuilder, Health.Direct.DatabaseAuditor]], Health.Direct.DatabaseAuditor";
            components[0] = localAuditComponent;

            settings.Container.Components = components;
            m_agent = SmtpAgentFactory.Create(settings);
            Assert.True(IoC.Resolve <IAuditor <IBuildAuditLogMessage> >() is DatabaseAuditor.Auditor <HeaderAuditMessageBuilder>);

            Assert.Equal(0, AuditEventCount);
            m_agent.Settings.InternalMessage.EnableRelay = true;
            Assert.Null(Record.Exception(() => RunEndToEndTest(this.LoadMessage(string.Format(TestMessage, Guid.NewGuid())))));
            Assert.Null(Record.Exception(() => RunEndToEndTest(this.LoadMessage(CrossDomainMessage))));
            m_agent.Settings.InternalMessage.EnableRelay = false;
            Assert.Equal(4, AuditEventCount);

            using (var db = new AuditContext().CreateContext(m_settings))
            {
                foreach (AuditEvent auditEvent in db.AuditEvents)
                {
                    Console.WriteLine(auditEvent.Message);
                }
            }
        }
        public override async Task <T> GetEventAsync <T>(object eventId)
        {
            if (JsonColumnNameBuilder == null)
            {
                return(null);
            }
            using (var ctx = new AuditContext(ConnectionStringBuilder?.Invoke(null)))
            {
                var cmdText = GetSelectCommandText(null);
#if NET45
                var result = ctx.Database.SqlQuery <string>(cmdText, new SqlParameter("@eventId", eventId));
                var json   = await result.FirstOrDefaultAsync();
#elif NETSTANDARD1_3 || NETSTANDARD2_0
                var result = ctx.FakeIdSet.FromSql(cmdText, new SqlParameter("@eventId", eventId));
                var json   = (await result.FirstOrDefaultAsync())?.Id;
#elif NETSTANDARD2_1
                var result = ctx.FakeIdSet.FromSqlRaw(cmdText, new SqlParameter("@eventId", eventId));
                var json   = (await result.FirstOrDefaultAsync())?.Id;
#endif
                if (json != null)
                {
                    return(AuditEvent.FromJson <T>(json));
                }
            }
            return(null);
        }
 public NotificationService(DataContext context, IMapper mapper,
                            AuditContext auditContext)
 {
     _contextNotification = context;
     _contextAudit        = auditContext;
     _mapper = mapper;
 }
Exemple #10
0
        public void SetUserDataUsingToFlowedUserSetsUserData()
        {
            var userId       = Guid.NewGuid().ToString();
            var userName     = $"JohnSmith_{userId}";
            var userEmail    = $"{userName}@email.com";
            var userIdentity = $"Fake|{userName}";

            var auditEvent = new AuditEvent();

            auditEvent.UserId.Should().BeNull();
            auditEvent.UserName.Should().BeNull();
            auditEvent.UserEmail.Should().BeNull();
            auditEvent.UserIdentity.Should().BeNull();

            lock (Padlock)
            {
                AuditContext.AddOrUpdatePersistentData("UserId", userId);
                AuditContext.AddOrUpdatePersistentData("UserName", userName);
                AuditContext.AddOrUpdatePersistentData("UserEmail", userEmail);
                AuditContext.AddOrUpdatePersistentData("UserIdentity", userIdentity);

                AuditBehaviours.SetUserDataToFlowedUser(auditEvent);

                auditEvent.UserId.Should().Be(userId);
                auditEvent.UserName.Should().Be(userName);
                auditEvent.UserEmail.Should().Be(userEmail);
            }
        }
        public static void Initialise(TestContext context)
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json", true, true)
                         .Build();
            var startUp = new Startup(config);


            var odataClientSettings = startUp.GetODataClientSettings(() => AuditContext,
                                                                     new ODataMessageAuthenticatorFunction(
                                                                         new AuthorityDetails
            {
                ClientId     = startUp.Configuration.GetValue <string>("ClientId"),
                ClientSecret = startUp.Configuration.GetValue <string>("ClientSecret"),
                ClientUrl    = startUp.Configuration.GetValue <string>("AuthorityUrl"),
                ResourceUrl  = startUp.Configuration.GetValue <string>("ClientResource")
            }, null)
                                                                     );

            ManagingMoneyOrganisationId = config.GetValue <Guid>("ManagingMoneyOrganisationId");
            Client          = new ODataClient(odataClientSettings);
            DynamicsOptions = new DynamicsGatewayOptions();
            config.Bind("DynamicsGateway", DynamicsOptions);
            AuditContext = new AuditContext {
                ClientId = "tests-integration-dynamics", Name = "Dynamics integration test"
            };
            Fixture = new Fixture();
            Fixture.Customize(new AllCustomAddresses());
            Fixture.Customize(new AllNominatedContactModel());
            AuditService = new Mock <IAuditService>().Object;
        }
Exemple #12
0
        public void CreateCompanyAudit()
        {
            using (var transactionScope = new TransactionScope())
            {
                using (var dataContext = new DataContext())
                {
                    using (var dataTransaction = dataContext.Database.BeginTransaction())
                    {
                        dataContext.Set <Company>().Add(new Company {
                            Name = "Sookin & Son"
                        });

                        dataContext.SaveChanges();
                        dataTransaction.Commit();
                    }
                }

                using (var auditContext = new AuditContext())
                {
                    using (var auditTransaction = auditContext.Database.BeginTransaction())
                    {
                        auditContext.Set <AuditRecord>().Add(new AuditRecord
                        {
                            ActionName = "Test", UserLoginName = "JDoe"
                        });

                        auditContext.SaveChanges();
                        auditTransaction.Commit();
                    }
                }

                transactionScope.Complete();
            }
        }
Exemple #13
0
        public static int Add(AuditContext db, AuditModel model)
        {
            SAIS.Data.Audit audit = CreateAudit(model);

            // Понякога броят на детайлите е много голям и, за да се добавят бързо, трябва да се изключи AutoDetectChanges.
            //bool originalAutoDetectSetting = db.Configuration.AutoDetectChangesEnabled;
            //db.Configuration.AutoDetectChangesEnabled = false;
            try
            {
                db.Audits.Add(audit);
                foreach (AuditDetail detail in audit.AuditDetails)
                {
                    detail.Audit = audit;
                    db.AuditDetails.Add(detail);
                }
            }
            finally
            {
                //db.Configuration.AutoDetectChangesEnabled = originalAutoDetectSetting;
            }

            db.SaveChangesWithValidationExplained();
            int id = audit.Id;

            model.Id = id;
            return(id);
        }
Exemple #14
0
 public static void PurgeTable <T>(this AuditContext auditContext, DbSet <T> table) where T : class
 {
     foreach (var row in table)
     {
         auditContext.Set <T>().Remove(row);
     }
     auditContext.SaveChanges();
 }
Exemple #15
0
 private void CleanAuditEventTable()
 {
     using (var db = new AuditContext().CreateContext(m_settings))
     {
         db.ObjectContext.ExecuteStoreCommand("Delete From AuditEvents");
         db.SaveChanges();
     }
 }
 public NotificationAuditService(
     AuditContext auditContext,
     IMapper mapper
     )
 {
     _auditContext = auditContext;
     _mapper       = mapper;
 }
Exemple #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="eventWrapper"></param>
 public void SaveEvent(Event eventWrapper)
 {
     using (var context = new AuditContext(_options))
     {
         context.Events.Add(eventWrapper);
         context.SaveChanges();
     }
 }
Exemple #18
0
 public void Log(string category, string message)
 {
     using (var db = new AuditContext().CreateContext(m_settings))
     {
         AuditEvent auditEvent = new AuditEvent(category, message);
         db.AuditEvents.Add(auditEvent);
         db.SaveChanges();
     }
 }
Exemple #19
0
 public HeaderAuditRepository(IOptions <AppSettings> options, IHttpContextAccessor httpContextAccessor)
 {
     if (_context == null)
     {
         _context = new AuditContextFactory().CreateDbContext(options);
     }
     _httpContextAccessor = httpContextAccessor;
     _entities            = _context.Instance.Set <HeaderAudit>();
 }
Exemple #20
0
        private static void UpdateValues(AuditContext db)
        {
            Random r = new Random();
            int    i = r.Next(1, 3);

            UpdateUser(db, i);
            UpdateProduct(db, i);
            db.SaveChanges();
        }
        public AuditLogRepository(AuditContext dbContext)
        {
            _dbContext = dbContext;
            var pendingMigrations = _dbContext.Database.GetPendingMigrations();

            if (pendingMigrations.Count() > 0)
            {
                _dbContext.Database.Migrate();
            }
        }
        public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
        {
            var json = auditEvent.ToJson();

            using (var ctx = new AuditContext(ConnectionStringBuilder?.Invoke(auditEvent)))
            {
                var cmdText = GetReplaceCommandText(auditEvent);
                ctx.Database.ExecuteSqlCommand(cmdText, new SqlParameter("@json", json), new SqlParameter("@eventId", eventId));
            }
        }
Exemple #23
0
        public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
        {
            var parameters = GetParametersForReplace(eventId, auditEvent);

            using (var ctx = new AuditContext(ConnectionStringBuilder?.Invoke(auditEvent)))
            {
                var cmdText = GetReplaceCommandText(auditEvent);
                ctx.Database.ExecuteSqlCommand(cmdText, parameters);
            }
        }
 public CreditorServiceDynamicsGateway(
     IODataClient client,
     ILogger <CreditorServiceDynamicsGateway> logger,
     AuditContext auditContext,
     IAuditService auditService)
 {
     _logger       = logger;
     _client       = client;
     _auditContext = auditContext;
     _auditService = auditService;
 }
Exemple #25
0
    public void SaveChangesFailed(DbContextErrorEventData eventData)
    {
        using (var auditContext = new AuditContext(_connectionString))
        {
            auditContext.Attach(_audit);
            _audit.Succeeded    = false;
            _audit.EndTime      = DateTime.UtcNow;
            _audit.ErrorMessage = eventData.Exception.Message;

            auditContext.SaveChanges();
        }
    }
        public override void ReplaceEvent(object eventId, AuditEvent auditEvent)
        {
            var json = auditEvent.ToJson();

            using (var ctx = new AuditContext(_connectionString))
            {
                var ludScript = _lastUpdatedDateColumnName != null?string.Format(", [{0}] = GETUTCDATE()", _lastUpdatedDateColumnName) : string.Empty;

                var cmdText = string.Format("UPDATE {0} SET [{1}] = @json{2} WHERE [{3}] = @eventId",
                                            FullTableName, _jsonColumnName, ludScript, _idColumnName);
                ctx.Database.ExecuteSqlCommand(cmdText, new SqlParameter("@json", json), new SqlParameter("@eventId", eventId));
            }
        }
 public MoneyAdviserServiceDynamicsGateway(
     IODataClient client,
     DynamicsGatewayOptions options,
     ILogger <MoneyAdviserServiceDynamicsGateway> logger,
     AuditContext auditContext,
     IAuditService auditService)
 {
     _logger       = logger;
     _client       = client;
     _options      = options;
     _auditContext = auditContext;
     _auditService = auditService;
 }
Exemple #28
0
    public int SavedChanges(SaveChangesCompletedEventData eventData, int result)
    {
        using (var auditContext = new AuditContext(_connectionString))
        {
            auditContext.Attach(_audit);
            _audit.Succeeded = true;
            _audit.EndTime   = DateTime.UtcNow;

            auditContext.SaveChanges();
        }

        return(result);
    }
Exemple #29
0
 public override bool ProcessRequest(AuditContext request)
 {
     if (request.LeaveTime < 14)
     {
         System.Console.WriteLine("{0}-{1} approved the request of Leave {2}", this, Name, request.Name);
     }
     else if (NextApprover != null)
     {
         System.Console.WriteLine("Manager Said:Sorry,I will commit it to Manager,I only handle limit 14");
         return(NextApprover.ProcessRequest(request));
     }
     return(true);
 }
Exemple #30
0
 public override bool ProcessRequest(AuditContext request)
 {
     if (request.LeaveTime < 28)
     {
         System.Console.WriteLine("{0}-{1} approved the request of Leave {2}", this, Name, request.Name);
     }
     else
     {
         System.Console.WriteLine("Present Said:Sorry,you can not leave so long!");
         return(false);
     }
     return(true);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ObjectContextAuditor"/> class.
 /// </summary>
 /// <param name="auditContext">The audit context.</param>
 /// <param name="auditEventPublisher">The audit event publisher.</param>
 /// <param name="auditConfiguration">The audit configuration.</param>
 public ObjectContextAuditor(AuditContext auditContext, IAuditEventPublisher auditEventPublisher, IAuditConfiguration auditConfiguration)
 {
     _auditEvent = new TrackingAuditEvent(auditContext);
     _auditEventPublisher = auditEventPublisher;
     _auditConfiguration = auditConfiguration;
 }