// virtual for testing
        public virtual StoreSchemaDetails LoadStoreSchemaDetails(IList <EntityStoreSchemaFilterEntry> filters)
        {
            Debug.Assert(filters != null, "filters != null");

            QueryTraceOn9481Interceptor interceptor = null;

            try
            {
                _connection.Open();

                interceptor = CreateAndRegisterTrace9481InterceptorIfSqlServer();

                return(new StoreSchemaDetails(
                           LoadTableDetails(filters),
                           LoadViewDetails(filters),
                           LoadRelationships(filters),
                           LoadFunctionDetails(filters),
                           _storeSchemaModelVersion == EntityFrameworkVersion.Version3
                        ? LoadFunctionReturnTableDetails(filters)
                        : Enumerable.Empty <TableDetailsRow>()));
            }
            finally
            {
                if (interceptor != null)
                {
                    DbInterception.Remove(interceptor);
                }
                _connection.Close();
            }
        }
Esempio n. 2
0
        public void ClonedObjectContext_disposes_of_connections_in_correct_order()
        {
            var myConnectionInterceptor = new ConnectionDisposingInterceptor();

            DbInterception.Add(myConnectionInterceptor);
            try
            {
                var mockClonedContext = new Mock <ObjectContextProxy>();

                var storeConnection      = new SqlConnection();
                var mockEntityConnection = new Mock <EntityConnectionProxy>();
                mockEntityConnection.Setup(m => m.StoreConnection).Returns(storeConnection);

                mockEntityConnection.Setup(m => m.CreateNew(It.IsAny <SqlConnection>())).Returns <SqlConnection>(
                    c =>
                {
                    var mockClonedConnection = new Mock <EntityConnectionProxy>();
                    mockClonedConnection.Setup(cc => cc.StoreConnection).Returns(c);
                    mockClonedConnection.Setup(m => m.Dispose()).Callback(() => myConnectionInterceptor.IsClonedEntityConnectionDisposed = true);

                    return(mockClonedConnection.Object);
                });

                var mockContext   = CreateMockObjectContext(mockEntityConnection, mockClonedContext);
                var clonedContext = new ClonedObjectContext(mockContext.Object, null, "Database=PinkyDinkyDo");

                clonedContext.Dispose();
            }
            finally
            {
                DbInterception.Remove(myConnectionInterceptor);
            }
        }
            public void DbCreateDatabase_dispatches_commands_to_interceptors()
            {
                using (var context = new DdlDatabaseContext(SimpleCeConnection <DdlDatabaseContext>()))
                {
                    var storeItemCollection =
                        (StoreItemCollection)
                        ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

                    context.Database.Delete();

                    var interceptor = new TestNonQueryInterceptor();
                    DbInterception.Add(interceptor);
                    try
                    {
                        SqlCeProviderServices.Instance.CreateDatabase(context.Database.Connection, null, storeItemCollection);
                    }
                    finally
                    {
                        DbInterception.Remove(interceptor);
                    }

                    Assert.Equal(3, interceptor.CommandTexts.Count);

                    Assert.True(interceptor.CommandTexts.Any(t => t.StartsWith("CREATE TABLE \"Products\" ")));
                    Assert.True(interceptor.CommandTexts.Any(t => t.StartsWith("CREATE TABLE \"Categories\" ")));
                    Assert.True(interceptor.CommandTexts.Any(t => t.StartsWith("ALTER TABLE \"Products\" ADD CONSTRAINT ")));
                }
            }
Esempio n. 4
0
            public void DbDeleteDatabase_dispatches_to_interceptors()
            {
                using (var context = new DdlDatabaseContext(SimpleCeConnection <DdlDatabaseContext>()))
                {
                    context.Database.CreateIfNotExists();

                    var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>();
                    DbInterception.Add(dbConnectionInterceptorMock.Object);
                    try
                    {
                        SqlCeProviderServices.Instance.DeleteDatabase(context.Database.Connection, null, new StoreItemCollection());
                    }
                    finally
                    {
                        DbInterception.Remove(dbConnectionInterceptorMock.Object);
                    }

                    dbConnectionInterceptorMock.Verify(
                        m => m.StateGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()),
                        Times.Once());
                    dbConnectionInterceptorMock.Verify(
                        m => m.StateGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <ConnectionState> >()),
                        Times.Once());

                    dbConnectionInterceptorMock.Verify(
                        m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                        Times.Once());
                    dbConnectionInterceptorMock.Verify(
                        m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                        Times.Once());
                }
            }
Esempio n. 5
0
            public void DbCreateDatabase_dispatches_commands_to_interceptors()
            {
                using (var context = new DdlDatabaseContext())
                {
                    var storeItemCollection =
                        (StoreItemCollection)
                        ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

                    context.Database.Delete();

                    var interceptor = new TestNonQueryInterceptor();
                    DbInterception.Add(interceptor);
                    try
                    {
                        SqlProviderServices.Instance.CreateDatabase(context.Database.Connection, null, storeItemCollection);
                    }
                    finally
                    {
                        DbInterception.Remove(interceptor);
                    }

                    Assert.Equal(3, interceptor.Commands.Count);

                    var commandTexts = interceptor.Commands.Select(c => c.CommandText);
                    Assert.True(commandTexts.Any(t => t.StartsWith("create database ")));
                    Assert.True(commandTexts.Any(t => t.StartsWith("if serverproperty('EngineEdition') <> 5 execute sp_executesql ")));
                    Assert.True(commandTexts.Any(t => t.StartsWith("create table [dbo].[Categories] ")));
                }
            }
        public void TestRecordAndPlayDefault()
        {
            //Database.SetInitializer<ContextForDatabase>(new CreateDatabaseIfNotExists<ContextForDatabase>());

            Database.SetInitializer <ContextForDatabase>(null);
            #region set record EF
            var record = new InterceptionRecordOrPlay(@"a.zip", ModeInterception.Record);

            DbInterception.Add(record);
            #endregion
            var employeeFromDatabase = EmployeeWithDepartment();

            DbInterception.Remove(record);

            File.Copy("a.zip", "b.zip", true);
            #region set play what is recorded EF
            var play = new InterceptionRecordOrPlay(@"b.zip", ModeInterception.Play);
            DbInterception.Add(play);
            #endregion
            var employeeFromPlay = EmployeeWithDepartment();
            // assert id's are equal
            Assert.AreEqual(employeeFromDatabase.Id, employeeFromPlay.Id);
            Assert.AreEqual(employeeFromDatabase.Department.Id, employeeFromPlay.Department.Id);
            DbInterception.Remove(play);
        }
Esempio n. 7
0
            public void Uses_interception()
            {
                var transactionMock = new Mock <DbTransaction>();
                var transaction     = new EntityTransaction(new EntityConnection(), transactionMock.Object);

                var transactionInterceptorMock = new Mock <IDbTransactionInterceptor>();

                DbInterception.Add(transactionInterceptorMock.Object);
                try
                {
                    Assert.Null(transaction.Connection);
                }
                finally
                {
                    DbInterception.Remove(transactionInterceptorMock.Object);
                }

                transactionInterceptorMock.Verify(
                    m => m.ConnectionGetting(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext <DbConnection> >()),
                    Times.Once());
                transactionInterceptorMock.Verify(
                    m => m.ConnectionGot(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext <DbConnection> >()),
                    Times.Once());
                transactionMock.Protected().Verify <DbConnection>("DbConnection", Times.Once());
            }
Esempio n. 8
0
        protected override void Dispose(bool disposing)
        {
            DbInterception.Remove(dbLogger);
            dbLogger.StartLogging();

            base.Dispose(disposing);
        }
 public void Unregister()
 {
     if (SqlInterceptor is { } interceptor)
     {
         DbInterception.Remove(interceptor);
     }
 }
Esempio n. 10
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         DbInterception.Remove(this);
     }
 }
Esempio n. 11
0
 protected override void Dispose(bool disposing)
 {
     DbInterception.Remove(ConsoleWriterInterceptor);
     DbInterception.Remove(DatabseLogger);
     DatabseLogger.StopLogging();
     base.Dispose(disposing);
 }
Esempio n. 12
0
            public void Uses_interception()
            {
                var transactionMock = new Mock <DbTransaction>();

                transactionMock.Protected().Setup <DbConnection>("DbConnection").Returns(new Mock <DbConnection>().Object);
                var transaction = new EntityTransaction(new EntityConnection(), transactionMock.Object);
                var transactionInterceptorMock = new Mock <IDbTransactionInterceptor>();

                DbInterception.Add(transactionInterceptorMock.Object);
                try
                {
                    transaction.Commit();
                }
                finally
                {
                    DbInterception.Remove(transactionInterceptorMock.Object);
                }

                transactionInterceptorMock.Verify(
                    m => m.Committing(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()),
                    Times.Once());
                transactionInterceptorMock.Verify(
                    m => m.Committed(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()),
                    Times.Once());
                transactionMock.Verify(m => m.Commit(), Times.Once());
            }
Esempio n. 13
0
            public void DbDeleteDatabase_dispatches_commands_to_interceptors_for_connections_with_initial_catalog()
            {
                using (var context = new DdlDatabaseContext())
                {
                    context.Database.CreateIfNotExists();
                }

                var interceptor = new TestNonQueryInterceptor();

                DbInterception.Add(interceptor);
                try
                {
                    using (var connection = new SqlConnection(SimpleAttachConnectionString <DdlDatabaseContext>()))
                    {
                        SqlProviderServices.Instance.DeleteDatabase(connection, null, new StoreItemCollection());
                    }
                }
                finally
                {
                    DbInterception.Remove(interceptor);
                }

                Assert.Equal(1, interceptor.Commands.Count);

                Assert.Equal(
                    "drop database [System.Data.Entity.SqlServer.SqlProviderServicesTests+DdlDatabaseContext]",
                    interceptor.Commands.Select(c => c.CommandText).Single());
            }
Esempio n. 14
0
        public void Disposes_temporary_context_on_connection_exception()
        {
            DropDatabase();

            using (var context = CreateContext <DisposableContext>())
            {
                context.Database.Create();
            }

            var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>();

            dbConnectionInterceptorMock.Setup(c => c.Opening(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()))
            .Callback <DbConnection, DbConnectionInterceptionContext>(
                (c, ic) =>
            {
                ic.Exception = new InvalidProgramException();
            });

            DbInterception.Add(dbConnectionInterceptorMock.Object);
            try
            {
                var migrator = CreateMigrator <DisposableContext>();

                migrator.ExecuteStatements(new[] { new MigrationStatement {
                                                       Sql = ";"
                                                   } });
            }
            catch (InvalidProgramException) { }
            finally
            {
                DbInterception.Remove(dbConnectionInterceptorMock.Object);
            }

            Assert.Equal(DisposableContext.TimesCreated, DisposableContext.TimesDisposed);
        }
Esempio n. 15
0
            public void DbDatabaseExists_dispatches_commands_to_interceptors_for_connections_with_no_initial_catalog()
            {
                // See CodePlex 1554 - Handle User Instance flakiness
                MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(new ExecutionStrategyResolver <IDbExecutionStrategy>(
                                                                               SqlProviderServices.ProviderInvariantName, null, () => new SqlAzureExecutionStrategy()));
                var interceptor = new TestScalarInterceptor();

                DbInterception.Add(interceptor);
                try
                {
                    using (var connection =
                               new SqlConnection(ModelHelpers.SimpleAttachConnectionString("I.Do.Not.Exist", useInitialCatalog: false)))
                    {
                        SqlProviderServices.Instance.DatabaseExists(connection, null, new StoreItemCollection());
                    }
                }
                finally
                {
                    MutableResolver.ClearResolvers();
                    DbInterception.Remove(interceptor);
                }

                Assert.Equal(1, interceptor.Commands.Count);

                Assert.True(
                    interceptor.Commands.Select(c => c.CommandText)
                    .Single()
                    .StartsWith("SELECT Count(*) FROM sys.master_files WHERE [physical_name]=N'"));
            }
Esempio n. 16
0
        public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions()
        {
            var failingTransactionInterceptor = new FailingTransactionInterceptor();

            DbInterception.Add(failingTransactionInterceptor);

            try
            {
                CommitFailureHandler_with_ExecutionStrategy_test(
                    (c, executionStrategyMock) =>
                {
                    MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                        key => (Func <IDbExecutionStrategy>)(() => new SimpleExecutionStrategy()));

                    failingTransactionInterceptor.ShouldFailTimes = 1;
                    failingTransactionInterceptor.ShouldRollBack  = true;

                    Assert.Throws <EntityException>(
                        () => ExceptionHelpers.UnwrapAggregateExceptions(
                            () => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait()));

                    AssertTransactionHistoryCount(c, 1);

                    ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait();

                    AssertTransactionHistoryCount(c, 0);
                });
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptor);
            }
        }
        private IEnumerable <T> LoadDataTable <T>(
            string sql, Func <IEnumerable <T>, IEnumerable <T> > orderByFunc, DataTable table, EntityStoreSchemaFilterObjectTypes queryTypes,
            IEnumerable <EntityStoreSchemaFilterEntry> filters, params string[] filterAliases)
            where T : DataRow

        {
            try
            {
                if (_addOptionMergeJoinInterceptor != null)
                {
                    DbInterception.Add(_addOptionMergeJoinInterceptor);
                }
                using (var command = CreateFilteredCommand(sql, null, queryTypes, filters.ToList(), filterAliases))
                {
                    using (var reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
                    {
                        var values = new object[table.Columns.Count];
                        while (reader.Read())
                        {
                            reader.GetValues(values);
                            table.Rows.Add(values);
                        }

                        return(orderByFunc(((IEnumerable <T>)table)));
                    }
                }
            }
            finally
            {
                if (_addOptionMergeJoinInterceptor != null)
                {
                    DbInterception.Remove(_addOptionMergeJoinInterceptor);
                }
            }
        }
        [Fact] // CodePlex 2029
        public void InitializeDatabase_does_not_create_new_connections()
        {
            using (var context = new SomeContext())
            {
                context.Database.Initialize(force: false);

                using (var transactionContext = new SomeTransactionContext(context.Database.Connection))
                {
                    var initializer = new TransactionContextInitializer <TransactionContext>();

                    var recorder = new ConnectionRecorder();
                    DbInterception.Add(recorder);
                    try
                    {
                        using (transactionContext.Database.BeginTransaction())
                        {
                            initializer.InitializeDatabase(transactionContext);
                        }

                        Assert.Equal(1, recorder.Connections.Count);
                    }
                    finally
                    {
                        DbInterception.Remove(recorder);
                    }
                }
            }
        }
        public void EagerInternalConnection_Dispose_uses_interception()
        {
            var connectionMock = new Mock <DbConnection>(MockBehavior.Strict);

            connectionMock.Setup(m => m.ConnectionString).Returns("fake");
            connectionMock.Setup(m => m.Database).Returns("fakeDb");
            connectionMock.Setup(m => m.DataSource).Returns("fakeSource");
            connectionMock.Protected().Setup("Dispose", ItExpr.IsAny <bool>());
            connectionMock.Setup(m => m.ToString()).Returns("Mock Connection");

            var dbConnectionInterceptorMock = new Mock <IDbConnectionInterceptor>();

            DbInterception.Add(dbConnectionInterceptorMock.Object);
            try
            {
                using (var internalConnection = new EagerInternalConnection(
                           new DbContext(connectionMock.Object, false),
                           connectionMock.Object, connectionOwned: true))
                {
                    var _ = internalConnection.Connection;
                }
            }
            finally
            {
                DbInterception.Remove(dbConnectionInterceptorMock.Object);
            }

            dbConnectionInterceptorMock.Verify(
                m => m.Disposing(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()),
                Times.Once());
            dbConnectionInterceptorMock.Verify(
                m => m.Disposed(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext>()),
                Times.Once());
            connectionMock.Protected().Verify("Dispose", Times.Once(), ItExpr.IsAny <bool>());

            dbConnectionInterceptorMock.Verify(
                m => m.DataSourceGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                Times.Exactly(2));
            dbConnectionInterceptorMock.Verify(
                m => m.DataSourceGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                Times.Exactly(2));
            connectionMock.Verify(m => m.DataSource, Times.Exactly(2));

            dbConnectionInterceptorMock.Verify(
                m => m.DatabaseGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                Times.Exactly(2));
            dbConnectionInterceptorMock.Verify(
                m => m.DatabaseGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                Times.Exactly(2));
            connectionMock.Verify(m => m.Database, Times.Exactly(2));

            dbConnectionInterceptorMock.Verify(
                m => m.ConnectionStringGetting(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                Times.Exactly(2));
            dbConnectionInterceptorMock.Verify(
                m => m.ConnectionStringGot(It.IsAny <DbConnection>(), It.IsAny <DbConnectionInterceptionContext <string> >()),
                Times.Exactly(2));
            connectionMock.Verify(m => m.ConnectionString, Times.Exactly(2));
        }
Esempio n. 20
0
 /// <summary>
 /// Releases the resources used by this transaction handler.
 /// </summary>
 /// <param name="disposing">
 /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
 /// </param>
 protected virtual void Dispose(bool disposing)
 {
     if (!IsDisposed)
     {
         DbInterception.Remove(this);
         IsDisposed = true;
     }
 }
Esempio n. 21
0
 private static void DeAttacheInterception()
 {
     _CountDbInterception--;
     if (_CountDbInterception == 0)
     {
         DbInterception.Remove(ftsExtension);
     }
 }
Esempio n. 22
0
            public void DbDeleteDatabase_dispatches_commands_to_interceptors_for_connections_without_initial_catalog()
            {
                StoreItemCollection storeItemCollection;

                using (var context = new DdlDatabaseContext())
                {
                    storeItemCollection =
                        (StoreItemCollection)
                        ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);
                }

                using (var connection = new SqlConnection(SimpleAttachConnectionString <DdlDatabaseContext>(useInitialCatalog: false)))
                {
                    var nonQueryInterceptor = new TestNonQueryInterceptor();
                    var readerInterceptor   = new TestReaderInterceptor();

                    // See CodePlex 1554 - Handle User Instance flakiness
                    MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(new ExecutionStrategyResolver <IDbExecutionStrategy>(
                                                                                   SqlProviderServices.ProviderInvariantName, null, () => new SqlAzureExecutionStrategy()));
                    try
                    {
                        if (!SqlProviderServices.Instance.DatabaseExists(connection, null, storeItemCollection))
                        {
                            SqlProviderServices.Instance.CreateDatabase(connection, null, storeItemCollection);
                        }

                        DbInterception.Add(nonQueryInterceptor);
                        DbInterception.Add(readerInterceptor);
                        try
                        {
                            SqlProviderServices.Instance.DeleteDatabase(connection, null, storeItemCollection);
                        }
                        finally
                        {
                            DbInterception.Remove(nonQueryInterceptor);
                            DbInterception.Remove(readerInterceptor);
                        }
                    }
                    finally
                    {
                        MutableResolver.ClearResolvers();
                    }

                    Assert.Equal(2, nonQueryInterceptor.Commands.Count);

                    var commandTexts = nonQueryInterceptor.Commands.Select(c => c.CommandText);
                    Assert.True(commandTexts.Any(t => t.StartsWith("drop database [SYSTEM_DATA_ENTITY_SQLSERVER")));
                    Assert.True(
                        commandTexts.Any(t => t.Contains("SYSTEM.DATA.ENTITY.SQLSERVER.SQLPROVIDERSERVICESTESTS+DDLDATABASECONTEXT.MDF")));

                    Assert.Equal(1, readerInterceptor.Commands.Count);

                    Assert.True(
                        readerInterceptor.Commands.Select(
                            c => c.CommandText).Single().StartsWith("SELECT [d].[name] FROM sys.databases "));
                }
            }
Esempio n. 23
0
        /// <summary>
        /// Stops logging all EF SQL Calls to the Debug Output Window
        /// </summary>
        public static void SQLLoggingStop()
        {
            if (_callCounts != 0)
            {
                Debug.WriteLine($"####SQLLogging Summary: _callCounts:{_callCounts}, _callMSTotal:{_callMSTotal}, _callMSTotal/_callCounts:{_callMSTotal / _callCounts}####");
            }

            DbInterception.Remove(_debugLoggingDbCommandInterceptor);
        }
Esempio n. 24
0
        private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
            Action <BlogContextCommit> runAndVerify)
        {
            var failingTransactionInterceptorMock = new Mock <FailingTransactionInterceptor> {
                CallBase = true
            };
            var failingTransactionInterceptor = failingTransactionInterceptorMock.Object;

            DbInterception.Add(failingTransactionInterceptor);

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                key =>
                (Func <IDbExecutionStrategy>)
                    (() => new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1))));

            try
            {
                using (var context = new BlogContextCommit())
                {
                    failingTransactionInterceptor.ShouldFailTimes = 0;
                    context.Database.Delete();
                    Assert.Equal(1, context.Blogs.Count());

                    failingTransactionInterceptor.ShouldFailTimes = 2;
                    failingTransactionInterceptor.ShouldRollBack  = false;

                    context.Blogs.Add(new BlogContext.Blog());

                    runAndVerify(context);

                    failingTransactionInterceptorMock.Verify(
                        m => m.Committing(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()), Times.Exactly(3));
                }

                using (var context = new BlogContextCommit())
                {
                    Assert.Equal(2, context.Blogs.Count());

                    using (var transactionContext = new TransactionContext(context.Database.Connection))
                    {
                        using (var infoContext = GetInfoContext(transactionContext))
                        {
                            Assert.True(
                                !infoContext.TableExists("__Transactions") ||
                                !transactionContext.Transactions.Any());
                        }
                    }
                }
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptorMock.Object);
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
Esempio n. 25
0
 /// <summary>
 /// Releases the resources used by this transaction handler.
 /// </summary>
 /// <param name="disposing">
 /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
 /// </param>
 protected virtual void Dispose(bool disposing)
 {
     if (this.IsDisposed)
     {
         return;
     }
     DbInterception.Remove((IDbInterceptor)this);
     this.IsDisposed = true;
 }
Esempio n. 26
0
 protected override void Dispose(bool disposing)
 {
     if (DbLogger.IsActive)
     {
         DbInterception.Remove(DatabaseLogger);
         DatabaseLogger.StopLogging();
     }
     base.Dispose(disposing);
 }
        public void ExecuteSql_dispatches_to_interceptors()
        {
            var mockCommand = new Mock <DbCommand>();

            mockCommand.Setup(m => m.ExecuteNonQuery()).Returns(2013);

            var mockConnection = new Mock <DbConnection>();

            mockConnection.Protected().Setup <DbCommand>("CreateDbCommand").Returns(mockCommand.Object);

            var mockTransaction = new Mock <DbTransaction>(MockBehavior.Strict);

            mockTransaction.Protected().Setup <DbConnection>("DbConnection").Returns(mockConnection.Object);

            var migrator  = new DbMigrator();
            var statement = new MigrationStatement
            {
                Sql = "Some Sql"
            };

            var providerFactoryServiceMock = new Mock <IDbProviderFactoryResolver>();

            providerFactoryServiceMock.Setup(m => m.ResolveProviderFactory(It.IsAny <DbConnection>()))
            .Returns(FakeSqlProviderFactory.Instance);
            MutableResolver.AddResolver <IDbProviderFactoryResolver>(k => providerFactoryServiceMock.Object);
            var mockInterceptor = new Mock <DbCommandInterceptor> {
                CallBase = true
            };

            DbInterception.Add(mockInterceptor.Object);
            var transactionInterceptorMock = new Mock <IDbTransactionInterceptor>();

            DbInterception.Add(transactionInterceptorMock.Object);
            try
            {
                new MigratorLoggingDecorator(migrator, new Mock <MigrationsLogger>().Object)
                .ExecuteSql(mockTransaction.Object, statement, new DbInterceptionContext());
            }
            finally
            {
                MutableResolver.ClearResolvers();
                DbInterception.Remove(mockInterceptor.Object);
                DbInterception.Remove(transactionInterceptorMock.Object);
            }

            mockInterceptor.Verify(m => m.NonQueryExecuting(mockCommand.Object, It.IsAny <DbCommandInterceptionContext <int> >()), Times.Once());
            mockInterceptor.Verify(m => m.NonQueryExecuted(mockCommand.Object, It.IsAny <DbCommandInterceptionContext <int> >()), Times.Once());

            transactionInterceptorMock.Verify(
                m => m.ConnectionGetting(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext <DbConnection> >()),
                Times.Exactly(2));
            transactionInterceptorMock.Verify(
                m => m.ConnectionGot(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext <DbConnection> >()),
                Times.Exactly(2));
            mockTransaction.Protected().Verify <DbConnection>("DbConnection", Times.Exactly(2));
        }
Esempio n. 28
0
        public void ExecuteSql_with_transactions_suppressed_dispatches_commands_to_interceptors()
        {
            var mockCommand = new Mock <DbCommand>();

            mockCommand.Setup(m => m.ExecuteNonQuery()).Returns(2013);

            var mockConnection = new Mock <DbConnection>();

            mockConnection.Protected().Setup <DbCommand>("CreateDbCommand").Returns(mockCommand.Object);

            var mockTransaction = new Mock <DbTransaction>();

            mockTransaction.Protected().Setup <DbConnection>("DbConnection").Returns(mockConnection.Object);

            var mockFactory = new Mock <DbProviderFactory>();

            mockFactory.Setup(m => m.CreateConnection()).Returns(mockConnection.Object);

            var objectContext       = new ObjectContext();
            var mockInternalContext = new Mock <InternalContextForMock>();

            mockInternalContext.Setup(m => m.ObjectContext).Returns(objectContext);
            var context = mockInternalContext.Object.Owner;

            objectContext.InterceptionContext = objectContext.InterceptionContext.WithDbContext(context);

            var migrator  = new DbMigrator(context, mockFactory.Object);
            var statement = new MigrationStatement
            {
                Sql = "Some Sql",
                SuppressTransaction = true
            };

            var mockInterceptor = new Mock <DbCommandInterceptor> {
                CallBase = true
            };

            DbInterception.Add(mockInterceptor.Object);

            try
            {
                migrator.ExecuteSql(mockTransaction.Object, statement, objectContext.InterceptionContext);
            }
            finally
            {
                DbInterception.Remove(mockInterceptor.Object);
            }

            mockInterceptor.Verify(m => m.NonQueryExecuting(
                                       mockCommand.Object,
                                       It.Is <DbCommandInterceptionContext <int> >(c => c.DbContexts.Contains(context))));

            mockInterceptor.Verify(m => m.NonQueryExecuted(
                                       mockCommand.Object,
                                       It.Is <DbCommandInterceptionContext <int> >(c => c.DbContexts.Contains(context) && c.Result == 2013)));
        }
Esempio n. 29
0
 public EFDataAccessBase(DbContext dbContext, DatabaseLogger dbLogger = null)
 {
     _context = dbContext;
     _db      = _context.Database;
     if (dbLogger.NotNull_DA())
     {
         DbInterception.Remove(dbLogger);
         DbInterception.Add(dbLogger);
     }
 }
Esempio n. 30
0
 public EFDataAccessBase(string connString, DatabaseLogger dbLogger = null)
 {
     _context = new DbContext(connString);
     _db      = _context.Database;
     if (dbLogger.NotNull_DA())
     {
         DbInterception.Remove(dbLogger);
         DbInterception.Add(dbLogger);
     }
 }