Exemplo n.º 1
0
            protected TestModelBuilder(TestHelpers testHelpers, Action <ModelConfigurationBuilder>?configure)
            {
                var options = new LoggingOptions();

                options.Initialize(new DbContextOptionsBuilder().EnableSensitiveDataLogging(false).Options);
                ValidationLoggerFactory = new ListLoggerFactory(l => l == DbLoggerCategory.Model.Validation.Name);
                ValidationLogger        = new DiagnosticsLogger <DbLoggerCategory.Model.Validation>(
                    ValidationLoggerFactory,
                    options,
                    new DiagnosticListener("Fake"),
                    testHelpers.LoggingDefinitions,
                    new NullDbContextLogger());

                ModelLoggerFactory = new ListLoggerFactory(l => l == DbLoggerCategory.Model.Name);
                var modelLogger = new DiagnosticsLogger <DbLoggerCategory.Model>(
                    ModelLoggerFactory,
                    options,
                    new DiagnosticListener("Fake"),
                    testHelpers.LoggingDefinitions,
                    new NullDbContextLogger());

                ModelBuilder = testHelpers.CreateConventionBuilder(
                    modelLogger,
                    ValidationLogger,
                    configure == null ? null : c => configure(c));
            }
Exemplo n.º 2
0
        // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
        private void FilterTest(Func <string, bool> filter, params string[] expected)
        {
            var loggerFactory = new ListLoggerFactory(filter);

            var dbLogger = new DiagnosticsLogger <DbLoggerCategory.Database>(
                loggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"), new TestLoggingDefinitions(),
                new NullDbContextLogger());
            var sqlLogger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                loggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"), new TestLoggingDefinitions(),
                new NullDbContextLogger());
            var queryLogger = new DiagnosticsLogger <DbLoggerCategory.Query>(
                loggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"), new TestLoggingDefinitions(),
                new NullDbContextLogger());
            var randomLogger = loggerFactory.CreateLogger("Random");

            dbLogger.Logger.LogInformation(1, "DB1");
            sqlLogger.Logger.LogInformation(2, "SQL1");
            queryLogger.Logger.LogInformation(3, "Query1");
            randomLogger.LogInformation(4, "Random1");

            dbLogger.Logger.LogInformation(1, "DB2");
            sqlLogger.Logger.LogInformation(2, "SQL2");
            queryLogger.Logger.LogInformation(3, "Query2");
            randomLogger.LogInformation(4, "Random2");

            Assert.Equal(expected, loggerFactory.Log.Select(l => l.Message));
        }
            protected TestModelBuilder(TestHelpers testHelpers)
            {
                Log = new List <(LogLevel, EventId, string)>();
                var options = new LoggingOptions();

                options.Initialize(new DbContextOptionsBuilder().EnableSensitiveDataLogging(false).Options);
                var validationLogger = new DiagnosticsLogger <DbLoggerCategory.Model.Validation>(
                    new ListLoggerFactory(Log, l => l == DbLoggerCategory.Model.Validation.Name),
                    options,
                    new DiagnosticListener("Fake"));
                var modelLogger = new DiagnosticsLogger <DbLoggerCategory.Model>(
                    new ListLoggerFactory(Log, l => l == DbLoggerCategory.Model.Name),
                    options,
                    new DiagnosticListener("Fake"));

                var contextServices = testHelpers.CreateContextServices();

                ModelBuilder = new ModelBuilder(
                    new CompositeConventionSetBuilder(contextServices.GetRequiredService <IEnumerable <IConventionSetBuilder> >().ToList())
                    .AddConventions(
                        new CoreConventionSetBuilder(
                            contextServices.GetRequiredService <CoreConventionSetBuilderDependencies>().With(modelLogger))
                        .CreateConventionSet()));

                ModelValidator = new ModelValidator(new ModelValidatorDependencies(validationLogger, modelLogger));
            }
        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected virtual KeyBuilder VisitPrimaryKey([NotNull] EntityTypeBuilder builder, [NotNull] DatabaseTable table)
        {
            Check.NotNull(builder, nameof(builder));
            Check.NotNull(table, nameof(table));

            var primaryKey = table.PrimaryKey;

            if (primaryKey == null)
            {
                _reporter.WriteWarning(DesignStrings.MissingPrimaryKey(table.DisplayName()));
                return(null);
            }

            var unmappedColumns = primaryKey.Columns
                                  .Where(c => _unmappedColumns.Contains(c))
                                  .Select(c => c.Name)
                                  .ToList();

            if (unmappedColumns.Count > 0)
            {
                _reporter.WriteWarning(
                    DesignStrings.PrimaryKeyErrorPropertyNotFound(
                        table.DisplayName(),
                        string.Join(CultureInfo.CurrentCulture.TextInfo.ListSeparator, unmappedColumns)));
                return(null);
            }

            var keyBuilder = builder.HasKey(primaryKey.Columns.Select(GetPropertyName).ToArray());


            if (primaryKey.Columns.Count == 1 &&
                primaryKey.Columns[0].ValueGenerated == null &&
                primaryKey.Columns[0].DefaultValueSql == null)
            {
                var property = builder.Metadata.FindProperty(GetPropertyName(primaryKey.Columns[0]))?.AsProperty();
                if (property != null)
                {
                    var dummyLogger = new DiagnosticsLogger <DbLoggerCategory.Model>(
                        new ScopedLoggerFactory(new LoggerFactory(), dispose: true),
                        new LoggingOptions(),
                        new DiagnosticListener(""));

                    var conventionalValueGenerated = new RelationalValueGeneratorConvention(dummyLogger).GetValueGenerated(property);
                    if (conventionalValueGenerated == ValueGenerated.OnAdd)
                    {
                        property.ValueGenerated = ValueGenerated.Never;
                    }
                }
            }

            if (!string.IsNullOrEmpty(primaryKey.Name) &&
                primaryKey.Name != ConstraintNamer.GetDefaultName(keyBuilder.Metadata))
            {
                keyBuilder.HasName(primaryKey.Name);
            }

            keyBuilder.Metadata.AddAnnotations(primaryKey.GetAnnotations());

            return(keyBuilder);
        }
        public async Task Logs_commands_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var optionsExtension = new FakeRelationalOptionsExtension().WithConnectionString(ConnectionString);

            var options = CreateOptions(optionsExtension);

            var logFactory = new ListLoggerFactory();

            var fakeConnection = new FakeRelationalConnection(options);

            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                logFactory,
                new FakeLoggingOptions(true),
                new DiagnosticListener("Fake"),
                new TestRelationalLoggingDefinitions());

            var relationalCommand = CreateRelationalCommand(
                commandText: "Logged Command",
                parameters: new[]
            {
                new TypeMappedRelationalParameter(
                    "FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object> {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }

            Assert.Equal(5, logFactory.Log.Count);
            Assert.Equal(LogLevel.Debug, logFactory.Log[0].Level);
            Assert.Equal(LogLevel.Debug, logFactory.Log[1].Level);
            Assert.Equal(LogLevel.Warning, logFactory.Log[2].Level);
            Assert.Equal(
                CoreResources.LogSensitiveDataLoggingEnabled(new TestLogger <TestRelationalLoggingDefinitions>()).GenerateMessage(),
                logFactory.Log[2].Message);

            Assert.Equal(LogLevel.Information, logFactory.Log[3].Level);
            Assert.Equal(LogLevel.Debug, logFactory.Log[4].Level);

            foreach (var(_, _, message, _, _) in logFactory.Log.Skip(3))
            {
                Assert.EndsWith(
                    "[Parameters=[FirstParameter='17'], CommandType='0', CommandTimeout='30']" + _eol +
                    "Logged Command",
                    message);
            }
        }
 protected ModelValidatorTest()
 {
     Log    = new List <(LogLevel, EventId, string)>();
     Logger = new DiagnosticsLogger <DbLoggerCategory.Model.Validation>(
         new ListLoggerFactory(Log, l => l == DbLoggerCategory.Model.Validation.Name),
         new LoggingOptions(),
         new DiagnosticListener("Fake"));
 }
 public override IModelValidator CreateModelValidator(
     DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
     DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
 => new SqlServerModelValidator(
     new ModelValidatorDependencies(validationLogger, modelLogger),
     new RelationalModelValidatorDependencies(
         new SqlServerTypeMappingSource(
             TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(),
             TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>())));
Exemplo n.º 8
0
        public async Task Reports_command_diagnostic(
            Delegate commandDelegate,
            DbCommandMethod diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var fakeConnection = new FakeRelationalConnection(options);

            var diagnostic = new List <Tuple <string, object> >();

            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                new ListLoggerFactory(),
                new FakeLoggingOptions(false),
                new ListDiagnosticSource(diagnostic),
                new TestRelationalLoggingDefinitions());

            var relationalCommand = CreateRelationalCommand(
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }

            Assert.Equal(4, diagnostic.Count);
            Assert.Equal(RelationalEventId.CommandCreating.Name, diagnostic[0].Item1);
            Assert.Equal(RelationalEventId.CommandCreated.Name, diagnostic[1].Item1);
            Assert.Equal(RelationalEventId.CommandExecuting.Name, diagnostic[2].Item1);
            Assert.Equal(RelationalEventId.CommandExecuted.Name, diagnostic[3].Item1);

            var beforeData = (CommandEventData)diagnostic[2].Item2;
            var afterData  = (CommandExecutedEventData)diagnostic[3].Item2;

            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], beforeData.Command);
            Assert.Equal(fakeConnection.DbConnections[0].DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);
        }
Exemplo n.º 9
0
        public ConventionSet CreateConventionalConventionSet(
            DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
            DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
        {
            var contextServices = CreateContextServices(
                new ServiceCollection()
                .AddScoped <IDiagnosticsLogger <DbLoggerCategory.Model> >(_ => modelLogger)
                .AddScoped <IDiagnosticsLogger <DbLoggerCategory.Model.Validation> >(_ => validationLogger));

            return(contextServices.GetRequiredService <IConventionSetBuilder>().CreateConventionSet());
        }
Exemplo n.º 10
0
        private DiagnosticsLogger <DbLoggerCategory.Database.Transaction> CreateLogger()
        {
            var options = new LoggingOptions();

            options.Initialize(new DbContextOptionsBuilder().ConfigureWarnings(w => w.Default(WarningBehavior.Throw)).Options);
            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Transaction>(
                new ListLoggerFactory(l => false),
                options,
                new DiagnosticListener("Fake"));

            return(logger);
        }
Exemplo n.º 11
0
        public override IModelValidator CreateModelValidator(
            DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
            DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
        => new SqliteModelValidator(
            new ModelValidatorDependencies(validationLogger, modelLogger),
            new RelationalModelValidatorDependencies(
#pragma warning disable 618
                TestServiceFactory.Instance.Create <ObsoleteRelationalTypeMapper>(),
#pragma warning restore 618
                new SqliteTypeMappingSource(
                    TestServiceFactory.Instance.Create <TypeMappingSourceDependencies>(),
                    TestServiceFactory.Instance.Create <RelationalTypeMappingSourceDependencies>())));
        public DiagnosticsLoggerTest()
        {
            this.mockHttpClient = new Mock <IHttpClient>();
            this.mockLogger     = new Mock <ILogger>();

            this.target = new DiagnosticsLogger(
                this.mockHttpClient.Object,
                new ServicesConfig
            {
                DiagnosticsEndpointUrl = DIAGNOSTICS_SERVICE_URL
            },
                this.mockLogger.Object);
        }
        private DiagnosticsLogger <DbLoggerCategory.Model> CreateLogger()
        {
            ListLoggerFactory.Clear();
            var options = new LoggingOptions();

            options.Initialize(new DbContextOptionsBuilder().EnableSensitiveDataLogging(false).Options);
            var modelLogger = new DiagnosticsLogger <DbLoggerCategory.Model>(
                ListLoggerFactory,
                options,
                new DiagnosticListener("Fake"));

            return(modelLogger);
        }
Exemplo n.º 14
0
		public void SimpleUsage()
		{
			DiagnosticsLogger logger = new DiagnosticsLogger("castle_testlog", "test_source");

			logger.Warn("my message");
			logger.Error("my other message", new Exception("Bad, bad exception"));

			EventLog log = new EventLog();
			log.Log = "castle_testlog";
			log.MachineName = ".";

			Assert.AreEqual(2, log.Entries.Count);
		}
Exemplo n.º 15
0
        public ModelBuilder CreateConventionBuilder(
            DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
            DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
        {
            var contextServices = CreateContextServices(
                new ServiceCollection()
                .AddScoped <IDiagnosticsLogger <DbLoggerCategory.Model> >(_ => modelLogger)
                .AddScoped <IDiagnosticsLogger <DbLoggerCategory.Model.Validation> >(_ => validationLogger));

            return(new ModelBuilder(
                       contextServices.GetRequiredService <IConventionSetBuilder>().CreateConventionSet(),
                       contextServices.GetRequiredService <ModelDependencies>().With(modelLogger)));
        }
Exemplo n.º 16
0
        public async Task Logs_commands_without_parameter_values(
            Delegate commandDelegate,
            string diagnosticName,
            bool async)
        {
            var options = CreateOptions();

            var logFactory = new ListLoggerFactory();

            var fakeConnection = new FakeRelationalConnection(options);

            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                logFactory,
                new FakeLoggingOptions(false),
                new DiagnosticListener("Fake"),
                new TestRelationalLoggingDefinitions());

            var relationalCommand = CreateRelationalCommand(
                commandText: "Logged Command",
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }
            else
            {
                ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger);
            }

            Assert.Equal(2, logFactory.Log.Count);

            Assert.Equal(LogLevel.Debug, logFactory.Log[0].Level);
            Assert.Equal(LogLevel.Debug, logFactory.Log[1].Level);

            foreach (var(_, _, message, _, _) in logFactory.Log)
            {
                Assert.EndsWith(
                    "[Parameters=[FirstParameter='?' (DbType = Int32)], CommandType='0', CommandTimeout='30']" + _eol +
                    "Logged Command",
                    message);
            }
        }
        public void SimpleUsage()
        {
            DiagnosticsLogger logger = new DiagnosticsLogger("castle_testlog", "test_source");

            logger.Warn("my message");
            logger.Error("my other message", new Exception("Bad, bad exception"));

            EventLog log = new EventLog();

            log.Log         = "castle_testlog";
            log.MachineName = ".";

            Assert.AreEqual(2, log.Entries.Count);
        }
Exemplo n.º 18
0
        public ModelBuilder CreateConventionBuilder(
            DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
            DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
        {
            var contextServices = CreateContextServices();

            var conventionSet = new CoreConventionSetBuilder(
                contextServices.GetRequiredService <CoreConventionSetBuilderDependencies>().With(modelLogger))
                                .CreateConventionSet();

            conventionSet = new CompositeConventionSetBuilder(
                contextServices.GetRequiredService <IEnumerable <IConventionSetBuilder> >().ToList())
                            .AddConventions(conventionSet);

            conventionSet.ModelBuiltConventions.Add(new ValidatingConvention(CreateModelValidator(modelLogger, validationLogger)));

            return(new ModelBuilder(conventionSet));
        }
Exemplo n.º 19
0
        public ModelBuilder CreateConventionBuilder(
            DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
            DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
        {
            var contextServices = CreateContextServices(
                new ServiceCollection()
                .AddScoped <IDiagnosticsLogger <DbLoggerCategory.Model> >(_ => modelLogger)
                .AddScoped <IDiagnosticsLogger <DbLoggerCategory.Model.Validation> >(_ => validationLogger));

            var conventionSet = contextServices.GetRequiredService <IConventionSetBuilder>().CreateConventionSet();

            conventionSet.ModelBuiltConventions.Add(
                new ValidatingConvention(
                    CreateModelValidator(),
                    validationLogger));

            return(new ModelBuilder(conventionSet));
        }
Exemplo n.º 20
0
        public async Task LogOperationAsyncTestAsync()
        {
            var serviceProvider = BuildServiceProvider();
            var db        = serviceProvider.GetRequiredService <IDiagnosticsDbContext>();
            var http      = serviceProvider.GetRequiredService <IHttpContextAccessor>();
            var principal = PrincipalUser.Personate(1, "Someone", serviceProvider);

            var logger = new DiagnosticsLogger(db, http, principal);

            //log an operation
            await logger.LogOperationAsync(LogLevel.Trace, "UnitTest");

            Assert.AreEqual(1, db.OperationLogs.Count());

            var findRow = db.OperationLogs.FirstOrDefault(x => x.Message == "UnitTest");
            var rowId   = findRow.Id;

            Assert.IsNotNull(findRow);
            Assert.AreEqual(1, findRow.Repeated);
            Assert.AreEqual(LogLevel.Trace, findRow.LogLevel);
            Assert.AreEqual(principal.Id, findRow.UserId);
            Assert.AreEqual(principal.AnonymousId, findRow.AnonymousId);
            Assert.AreEqual(principal.DisplayName, findRow.UserName);

            //log the same message one more time, should be still only 1 row
            await logger.LogOperationAsync(LogLevel.Trace, "UnitTest");

            Assert.AreEqual(1, db.OperationLogs.Count());

            //find back the row, the Repeated value should be 2 now
            findRow = db.OperationLogs.Find(rowId);
            Assert.AreEqual(2, findRow.Repeated);

            //log some different operations
            await logger.LogOperationAsync(LogLevel.Warning, "Make a difference");

            await logger.LogOperationAsync(LogLevel.Warning, "Again");

            await logger.LogOperationAsync(LogLevel.Warning, "One more time");

            Assert.AreEqual(4, db.OperationLogs.Count());

            db.Normalize().Database.EnsureDeleted();
        }
            protected TestModelBuilder(TestHelpers testHelpers)
            {
                var options = new LoggingOptions();

                options.Initialize(new DbContextOptionsBuilder().EnableSensitiveDataLogging(false).Options);
                ValidationLoggerFactory = new ListLoggerFactory(l => l == DbLoggerCategory.Model.Validation.Name);
                var validationLogger = new DiagnosticsLogger <DbLoggerCategory.Model.Validation>(
                    ValidationLoggerFactory,
                    options,
                    new DiagnosticListener("Fake"));

                ModelLoggerFactory = new ListLoggerFactory(l => l == DbLoggerCategory.Model.Name);
                var modelLogger = new DiagnosticsLogger <DbLoggerCategory.Model>(
                    ModelLoggerFactory,
                    options,
                    new DiagnosticListener("Fake"));

                ModelBuilder = testHelpers.CreateConventionBuilder(modelLogger, validationLogger);
            }
        public DatabaseModel CreateModel(string dbName, string sql, IEnumerable <string> tables, IEnumerable <string> schemas, bool executeScript = false)
        {
            if (executeScript)
            {
                MySQLTestStore.ExecuteScript(sql);
            }
            else
            {
                MySQLTestStore.Execute(sql);
            }

            _logger = new DiagnosticsLogger <DbLoggerCategory.Scaffolding>(
                ListLoggerFactory,
                new LoggingOptions(),
                new DiagnosticListener("Fake"),
                new MySQLLoggingDefinitions());

            return(new MySQLDatabaseModelFactory(_logger, options).
                   Create(MySQLTestStore.rootConnectionString + ";database=" + dbName + ";",
                          new DatabaseModelFactoryOptions(tables, schemas)));
        }
        internal static (string, IEnumerable <SqlParameter>) ToParametrizedSql <TEntity>(this IQueryable <TEntity> query) where TEntity : class
        {
            var queryCompiler           = (QueryCompiler)QueryCompilerField.GetValue(query.Provider);
            var modelGenerator          = (QueryModelGenerator)QueryModelGeneratorField.GetValue(queryCompiler);
            var parameterValues         = new SimpleParameterValues();
            var diagnosticsLogger       = new DiagnosticsLogger <DbLoggerCategory.Query>(new LoggerFactory(), null, new DiagnosticListener("Temp"));
            var parameterExpression     = modelGenerator.ExtractParameters(diagnosticsLogger, query.Expression, parameterValues);
            var queryModel              = modelGenerator.ParseQuery(parameterExpression);
            var database                = (IDatabase)DataBaseField.GetValue(queryCompiler);
            var databaseDependencies    = (DatabaseDependencies)DatabaseDependenciesField.GetValue(database);
            var queryCompilationContext = databaseDependencies.QueryCompilationContextFactory.Create(false);
            var modelVisitor            = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();

            modelVisitor.CreateQueryExecutor <TEntity>(queryModel);
            //modelVisitor.CreateAsyncQueryExecutor<TEntity>(queryModel);
            // CreateAsync not used, throws: Message: System.ArgumentException : Expression of type 'System.Collections.Generic.IEnumerable`1[EFCore.BulkExtensions.Tests.Item]'
            // cannot be used for return type 'System.Collections.Generic.IAsyncEnumerable`1[EFCore.BulkExtensions.Tests.Item]'

            string sql = modelVisitor.Queries.First().ToString();

            return(sql, parameterValues.ParameterValues.Select(x => new SqlParameter(x.Key, x.Value)));
        }
        private void FilterTest(Func <string, bool> filter, params string[] expected)
        {
            var loggerFactory  = new LoggerFactory();
            var loggerProvider = new TestLoggerProvider(filter);

            loggerFactory.AddProvider(loggerProvider);

            var dbLogger     = new DiagnosticsLogger <DbLoggerCategory.Database>(loggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"));
            var sqlLogger    = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(loggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"));
            var queryLogger  = new DiagnosticsLogger <DbLoggerCategory.Query>(loggerFactory, new LoggingOptions(), new DiagnosticListener("Fake"));
            var randomLogger = loggerFactory.CreateLogger("Random");

            dbLogger.Logger.LogInformation(1, "DB1");
            sqlLogger.Logger.LogInformation(2, "SQL1");
            queryLogger.Logger.LogInformation(3, "Query1");
            randomLogger.LogInformation(4, "Random1");

            dbLogger.Logger.LogInformation(1, "DB2");
            sqlLogger.Logger.LogInformation(2, "SQL2");
            queryLogger.Logger.LogInformation(3, "Query2");
            randomLogger.LogInformation(4, "Random2");

            Assert.Equal(loggerProvider.Messages, expected);
        }
Exemplo n.º 25
0
        public async Task LogExceptionAsyncTestAsync()
        {
            var serviceProvider = BuildServiceProvider();
            var db   = serviceProvider.GetRequiredService <IDiagnosticsDbContext>();
            var http = serviceProvider.GetRequiredService <IHttpContextAccessor>();

            var anonymous = PrincipalUser.Personate(0, "Anonymous", serviceProvider);
            var logger    = new DiagnosticsLogger(db, http, anonymous);

            var exception = new Exception("Oops");

            //insert exception log should be successful, the PrincipalUser is anonymous
            await logger.LogExceptionAsync(exception);

            Assert.AreEqual(1, db.ExceptionLogs.Count());

            //exception data should be written to the fields
            var findRow = db.ExceptionLogs.SingleOrDefault(x => x.Message == exception.Message);
            var rowId   = findRow.Id;

            Assert.IsNotNull(findRow);
            Assert.AreEqual(1, findRow.Repeated);
            Assert.AreEqual(exception.GetType().Name, findRow.ExceptionType);
            Assert.AreEqual(exception.StackTrace, findRow.StackTrace);
            Assert.AreEqual(exception.Source, findRow.Source);
            Assert.AreEqual(anonymous.Id, findRow.UserId);
            Assert.AreEqual(anonymous.AnonymousId, findRow.AnonymousId);
            Assert.AreEqual(anonymous.DisplayName, findRow.UserName);

            //log the same exception again, should be still only 1 exception log record
            await logger.LogExceptionAsync(exception);

            Assert.AreEqual(1, db.ExceptionLogs.Count());

            //find back the row, the Repeated value should be 2 now
            findRow = db.ExceptionLogs.Find(rowId);
            Assert.AreEqual(2, findRow.Repeated);

            //log the same exception with a known user this time
            var someone = PrincipalUser.Personate(1, "Someone", serviceProvider);

            logger = new DiagnosticsLogger(db, http, someone);

            //a new row should be inserted and there should be 2 rows in total
            await logger.LogExceptionAsync(exception);

            findRow = db.ExceptionLogs.SingleOrDefault(x => x.Message == exception.Message && x.UserId == someone.Id);
            Assert.AreEqual(2, db.ExceptionLogs.Count());
            Assert.IsNotNull(findRow);
            Assert.AreEqual(1, findRow.Repeated);
            Assert.AreEqual(someone.Id, findRow.UserId);
            Assert.AreEqual(someone.AnonymousId, findRow.AnonymousId);
            Assert.AreEqual(someone.DisplayName, findRow.UserName);

            //log a different exception
            exception = new InvalidOperationException("Boom");
            await logger.LogExceptionAsync(exception);

            //another new row should be inserted and there should be 3 rows in total
            findRow = db.ExceptionLogs.SingleOrDefault(x => x.Message == exception.Message);
            Assert.AreEqual(3, db.ExceptionLogs.Count());
            Assert.IsNotNull(findRow);
            Assert.AreEqual(1, findRow.Repeated);
            Assert.AreEqual(exception.Source, findRow.Source);
            Assert.AreEqual(exception.GetType().Name, findRow.ExceptionType);
            Assert.AreEqual(exception.StackTrace, findRow.StackTrace);
            Assert.AreEqual(exception.Source, findRow.Source);
            Assert.AreEqual(someone.Id, findRow.UserId);
            Assert.AreEqual(someone.AnonymousId, findRow.AnonymousId);
            Assert.AreEqual(someone.DisplayName, findRow.UserName);

            db.Normalize().Database.EnsureDeleted();
        }
Exemplo n.º 26
0
 public ModelBuilder CreateConventionBuilder(
     DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
     DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
 => new ModelBuilder(CreateConventionalConventionSet(modelLogger, validationLogger));
Exemplo n.º 27
0
 public virtual IModelValidator CreateModelValidator(
     DiagnosticsLogger <DbLoggerCategory.Model> modelLogger,
     DiagnosticsLogger <DbLoggerCategory.Model.Validation> validationLogger)
 => new ModelValidator(new ModelValidatorDependencies(validationLogger, modelLogger));
Exemplo n.º 28
0
        private void GenerateProperty(IProperty property, bool useDataAnnotations)
        {
            var lines = new List <string>
            {
                $".{nameof(EntityTypeBuilder.Property)}(e => e.{property.Name})"
            };

            var annotations = property.GetAnnotations().ToList();

            RemoveAnnotation(ref annotations, RelationalAnnotationNames.ColumnName);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.ColumnType);
            RemoveAnnotation(ref annotations, CoreAnnotationNames.MaxLength);
            RemoveAnnotation(ref annotations, CoreAnnotationNames.TypeMapping);
            RemoveAnnotation(ref annotations, CoreAnnotationNames.Unicode);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.DefaultValue);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.DefaultValueSql);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.ComputedColumnSql);
            RemoveAnnotation(ref annotations, RelationalAnnotationNames.IsFixedLength);
            RemoveAnnotation(ref annotations, ScaffoldingAnnotationNames.ColumnOrdinal);

            if (!useDataAnnotations)
            {
                if (!property.IsNullable &&
                    property.ClrType.IsNullableType() &&
                    !property.IsPrimaryKey())
                {
                    lines.Add($".{nameof(PropertyBuilder.IsRequired)}()");
                }

                var columnName = property.Relational().ColumnName;

                if (columnName != null &&
                    columnName != property.Name)
                {
                    lines.Add(
                        $".{nameof(RelationalPropertyBuilderExtensions.HasColumnName)}" +
                        $"({_code.Literal(columnName)})");
                }

                var columnType = property.GetConfiguredColumnType();

                if (columnType != null)
                {
                    lines.Add(
                        $".{nameof(RelationalPropertyBuilderExtensions.HasColumnType)}" +
                        $"({_code.Literal(columnType)})");
                }

                var maxLength = property.GetMaxLength();

                if (maxLength.HasValue)
                {
                    lines.Add(
                        $".{nameof(PropertyBuilder.HasMaxLength)}" +
                        $"({_code.Literal(maxLength.Value)})");
                }
            }

            if (property.IsUnicode() != null)
            {
                lines.Add(
                    $".{nameof(PropertyBuilder.IsUnicode)}" +
                    $"({(property.IsUnicode() == false ? "false" : "")})");
            }

            if (property.Relational().IsFixedLength)
            {
                lines.Add(
                    $".{nameof(RelationalPropertyBuilderExtensions.IsFixedLength)}()");
            }

            if (property.Relational().DefaultValue != null)
            {
                lines.Add(
                    $".{nameof(RelationalPropertyBuilderExtensions.HasDefaultValue)}" +
                    $"({_code.UnknownLiteral(property.Relational().DefaultValue)})");
            }

            if (property.Relational().DefaultValueSql != null)
            {
                lines.Add(
                    $".{nameof(RelationalPropertyBuilderExtensions.HasDefaultValueSql)}" +
                    $"({_code.Literal(property.Relational().DefaultValueSql)})");
            }

            if (property.Relational().ComputedColumnSql != null)
            {
                lines.Add(
                    $".{nameof(RelationalPropertyBuilderExtensions.HasComputedColumnSql)}" +
                    $"({_code.Literal(property.Relational().ComputedColumnSql)})");
            }

            var dummyLogger = new DiagnosticsLogger <DbLoggerCategory.Model>(
                new ScopedLoggerFactory(new LoggerFactory(), dispose: true),
                new LoggingOptions(),
                new DiagnosticListener(""),
                new LoggingDefinitions());

            var valueGenerated = property.ValueGenerated;
            var isRowVersion   = false;

            if (((Property)property).GetValueGeneratedConfigurationSource().HasValue &&
                new RelationalValueGeneratorConvention(dummyLogger).GetValueGenerated((Property)property) != valueGenerated)
            {
                string methodName;
                switch (valueGenerated)
                {
                case ValueGenerated.OnAdd:
                    methodName = nameof(PropertyBuilder.ValueGeneratedOnAdd);
                    break;

                case ValueGenerated.OnAddOrUpdate:
                    isRowVersion = property.IsConcurrencyToken;
                    methodName   = isRowVersion
                            ? nameof(PropertyBuilder.IsRowVersion)
                            : nameof(PropertyBuilder.ValueGeneratedOnAddOrUpdate);
                    break;

                case ValueGenerated.Never:
                    methodName = nameof(PropertyBuilder.ValueGeneratedNever);
                    break;

                default:
                    methodName = "";
                    break;
                }

                lines.Add($".{methodName}()");
            }

            if (property.IsConcurrencyToken &&
                !isRowVersion)
            {
                lines.Add($".{nameof(PropertyBuilder.IsConcurrencyToken)}()");
            }

            var annotationsToRemove = new List <IAnnotation>();

            foreach (var annotation in annotations)
            {
                if (annotation.Value == null ||
                    _annotationCodeGenerator.IsHandledByConvention(property, annotation))
                {
                    annotationsToRemove.Add(annotation);
                }
                else
                {
                    var methodCall = _annotationCodeGenerator.GenerateFluentApi(property, annotation);
                    if (methodCall != null)
                    {
                        lines.Add(_code.Fragment(methodCall));
                        annotationsToRemove.Add(annotation);
                    }
                }
            }

            lines.AddRange(GenerateAnnotations(annotations.Except(annotationsToRemove)));

            switch (lines.Count)
            {
            case 1:
                return;

            case 2:
                lines = new List <string>
                {
                    lines[0] + lines[1]
                };
                break;
            }

            AppendMultiLineFluentApi(property.DeclaringEntityType, lines);
        }
Exemplo n.º 29
0
 /// <summary>
 /// Log Diagnostic Message
 /// </summary>
 /// <param name="baseLogInfo"></param>
 public void LogMessage <T>(T baseLogInfo) where T : BaseLogInfo
 {
     ILogStrategy <T> logStrategy = new DiagnosticsLogger <T>();
     ILogMessage      messageCode = LogWriter <T> .Write(logStrategy, baseLogInfo);
 }
        public async Task Reports_command_diagnostic_on_exception(
            Delegate commandDelegate,
            DbCommandMethod diagnosticName,
            bool async)
        {
            var exception = new InvalidOperationException();

            var fakeDbConnection = new FakeDbConnection(
                ConnectionString,
                new FakeCommandExecutor(
                    c => throw exception,
                    c => throw exception,
                    (c, cb) => throw exception,
                    (c, ct) => throw exception,
                    (c, ct) => throw exception,
                    (c, cb, ct) => throw exception));

            var optionsExtension = new FakeRelationalOptionsExtension().WithConnection(fakeDbConnection);

            var options = CreateOptions(optionsExtension);

            var diagnostic = new List <Tuple <string, object> >();

            var fakeConnection = new FakeRelationalConnection(options);

            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                new ListLoggerFactory(),
                new FakeLoggingOptions(false),
                new ListDiagnosticSource(diagnostic),
                new TestRelationalLoggingDefinitions());

            var relationalCommand = CreateRelationalCommand(
                parameters: new[]
            {
                new TypeMappedRelationalParameter("FirstInvariant", "FirstParameter", new IntTypeMapping("int", DbType.Int32), false)
            });

            var parameterValues = new Dictionary <string, object>
            {
                { "FirstInvariant", 17 }
            };

            if (async)
            {
                await Assert.ThrowsAsync <InvalidOperationException>(
                    async()
                    => await((CommandFunc)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger));
            }
            else
            {
                Assert.Throws <InvalidOperationException>(
                    ()
                    => ((CommandAction)commandDelegate)(fakeConnection, relationalCommand, parameterValues, logger));
            }

            Assert.Equal(2, diagnostic.Count);
            Assert.Equal(RelationalEventId.CommandExecuting.Name, diagnostic[0].Item1);
            Assert.Equal(RelationalEventId.CommandError.Name, diagnostic[1].Item1);

            var beforeData = (CommandEventData)diagnostic[0].Item2;
            var afterData  = (CommandErrorEventData)diagnostic[1].Item2;

            Assert.Equal(fakeDbConnection.DbCommands[0], beforeData.Command);
            Assert.Equal(fakeDbConnection.DbCommands[0], afterData.Command);

            Assert.Equal(diagnosticName, beforeData.ExecuteMethod);
            Assert.Equal(diagnosticName, afterData.ExecuteMethod);

            Assert.Equal(async, beforeData.IsAsync);
            Assert.Equal(async, afterData.IsAsync);

            Assert.Equal(exception, afterData.Exception);
        }
        private static IHistoryRepository CreateHistoryRepository()
        {
            var optionsBuilder = new DbContextOptionsBuilder();

            optionsBuilder.UseMySQL(MySQLTestStore.rootConnectionString + "database=test;");
            var connection = new MySQLServerConnection(optionsBuilder.Options, new Logger <MySQLServerConnection>(new LoggerFactory()));

            var typeMapper = new MySQLTypeMapper();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddEntityFrameworkMySQL()
            .AddDbContext <MyTestContext>();

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var context = serviceProvider.GetRequiredService <MyTestContext>();

            var creator    = context.GetService <IRelationalDatabaseCreator>();
            var cmdBuilder = context.GetService <IRawSqlCommandBuilder>();

            var options = new DbContextOptions <DbContext>(
                new Dictionary <Type, IDbContextOptionsExtension>
            {
                {
                    typeof(MySQLOptionsExtension),
                    new MySQLOptionsExtension()
                }
            });

            var modelDiffer = new MigrationsModelDiffer(
                new MySQLTypeMapper(),
                new MySQLMigrationsAnnotationProvider(
                    new MigrationsAnnotationProviderDependencies()));

            var logger = new DiagnosticsLogger <DbLoggerCategory.Database.Command>(
                new LoggerFactory(),
                new LoggingOptions(),
                new DiagnosticListener("Fake"));

            var commandBuilderFactory = new RelationalCommandBuilderFactory(
                logger,
                typeMapper);

            var sqlGeneratorHelper = new MySQLSqlGenerationHelper(new RelationalSqlGenerationHelperDependencies());

            var migrationsSqlGeneratorDependencies = new MigrationsSqlGeneratorDependencies(
                commandBuilderFactory,
                sqlGeneratorHelper,
                typeMapper);

            var migrationsSqlGeneratior = new MySQLMigrationsSqlGenerator(migrationsSqlGeneratorDependencies);

            HistoryRepositoryDependencies dependencies = new HistoryRepositoryDependencies(
                creator,
                cmdBuilder,
                connection,
                options,
                modelDiffer,
                migrationsSqlGeneratior,
                sqlGeneratorHelper);

            return(new MySQLHistoryRepository(dependencies));
        }