public void SQL_query_for_entity_is_buffered_if_execution_strategy_is_used()
        {
            var executionStrategyMock = new Mock <IDbExecutionStrategy>();

            executionStrategyMock.Setup(m => m.RetriesOnFailure).Returns(true);
            executionStrategyMock.Setup(m => m.Execute(It.IsAny <Func <ObjectResult <Product> > >()))
            .Returns <Func <ObjectResult <Product> > >(f => f());
            executionStrategyMock.Setup(m => m.Execute(It.IsAny <Action>())).Callback <Action>(f => f());

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(key => (Func <IDbExecutionStrategy>)(() => executionStrategyMock.Object));
            try
            {
                using (var context = new SimpleModelContext())
                {
                    var products = context.Products.SqlQuery("select * from Products");
                    using (var enumerator = products.GetEnumerator())
                    {
                        enumerator.MoveNext();

                        Assert.Equal(ConnectionState.Closed, context.Database.Connection.State);
                    }
                }
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }
        }
        public void Migrations_work_with_wrapping_provider_setup_by_replacing_ADO_NET_provider()
        {
            RegisterAdoNetProvider(typeof(WrappingAdoNetProvider <SqlClientFactory>));
            MutableResolver.AddResolver <DbProviderServices>(k => WrappingEfProvider <SqlClientFactory, SqlProviderServices> .Instance);
            MutableResolver.AddResolver <Func <MigrationSqlGenerator> >(WrappingEfProvider <SqlClientFactory, SqlProviderServices> .Instance);

            var log = WrappingAdoNetProvider <SqlClientFactory> .Instance.Log;

            log.Clear();

            using (var context = new MigrationsBlogContext())
            {
                context.Database.Delete();
            }

            using (var context = new MigrationsBlogContext())
            {
                Assert.False(context.Database.Exists());
            }

            var migrator          = new DbMigrator(new MigrateInitializerConfiguration());
            var appliedMigrations = migrator.GetDatabaseMigrations();

            Assert.Equal(2, appliedMigrations.Count());

            // Sanity check that the wrapping provider really did get used
            var methods = log.Select(i => i.Method).ToList();

            Assert.Contains("ExecuteReader", methods);
            Assert.Contains("Open", methods);
            Assert.Contains("Close", methods);
        }
        public void Correct_services_are_returned_when_setup_by_replacing_ADO_NET_provider()
        {
            RegisterAdoNetProvider(typeof(WrappingAdoNetProvider <SqlClientFactory>));
            MutableResolver.AddResolver <DbProviderServices>(k => WrappingEfProvider <SqlClientFactory, SqlProviderServices> .Instance);

            Assert.Same(
                WrappingAdoNetProvider <SqlClientFactory> .Instance,
                DbProviderFactories.GetFactory(SqlClientInvariantName));

            Assert.Same(
                WrappingAdoNetProvider <SqlClientFactory> .Instance,
                DbConfiguration.DependencyResolver.GetService <DbProviderFactory>(SqlClientInvariantName));

            Assert.Same(
                WrappingEfProvider <SqlClientFactory, SqlProviderServices> .Instance,
                DbConfiguration.DependencyResolver.GetService <DbProviderServices>(SqlClientInvariantName));

            Assert.Equal(
                SqlClientInvariantName,
                DbConfiguration.DependencyResolver.GetService <IProviderInvariantName>(WrappingAdoNetProvider <SqlClientFactory> .Instance).Name);

            Assert.Same(
                WrappingAdoNetProvider <SqlClientFactory> .Instance,
                DbConfiguration.DependencyResolver.GetService <IDbProviderFactoryResolver>()
                .ResolveProviderFactory(new WrappingConnection <SqlClientFactory>(new SqlConnection())));
        }
예제 #4
0
        public void Can_use_per_provider_factory()
        {
            ResetDatabase();

            try
            {
                MutableResolver.AddResolver <Func <DbConnection, string, HistoryContext> >(_ => _testHistoryContextFactoryA);

                var migrator = CreateMigrator <ShopContext_v1>();

                var generatedMigration
                    = new MigrationScaffolder(migrator.Configuration).Scaffold("Migration");

                migrator
                    = CreateMigrator <ShopContext_v1>(
                          automaticMigrationsEnabled: false,
                          scaffoldedMigrations: generatedMigration);

                migrator.Update();

                Assert.True(TableExists("MigrationsCustomers"));
                Assert.True(TableExists("__Migrations"));

                migrator.Update("0");

                Assert.False(TableExists("MigrationsCustomers"));
                Assert.False(TableExists("__Migrations"));

                AssertHistoryContextDoesNotExist();
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }
        }
예제 #5
0
        public void Uses_ExecutionStrategy()
        {
            var configuration = new DbMigrationsConfiguration
            {
                ContextType         = typeof(ShopContext_v1),
                MigrationsAssembly  = SystemComponentModelDataAnnotationsAssembly,
                MigrationsNamespace = typeof(ShopContext_v1).Namespace
            };

            var migrator = new DbMigrator(configuration);

            var executionStrategyMock = new Mock <IDbExecutionStrategy>();

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(key => (Func <IDbExecutionStrategy>)(() => executionStrategyMock.Object));
            try
            {
                migrator.ExecuteStatements(Enumerable.Empty <MigrationStatement>());
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }

            executionStrategyMock.Verify(m => m.Execute(It.IsAny <Action>()), Times.Once());
        }
예제 #6
0
        public SimpleScenariosForLocalDb()
        {
            _previousDataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory");

            AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetTempPath());
            MutableResolver.AddResolver <IDbConnectionFactory>(k => new LocalDbConnectionFactory("v11.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()));

                    MutableResolver.ClearResolvers();

                    AssertTransactionHistoryCount(c, 1);

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

                    AssertTransactionHistoryCount(c, 0);
                });
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptor);
            }
        }
예제 #8
0
        public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_verification_fail()
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));

            TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
                context => context.SaveChanges(), queryFailures: 2);
        }
예제 #9
0
        public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async()
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));

            TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
                context => context.SaveChangesAsync().Wait());
        }
예제 #10
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 "));
                }
            }
        public DatabaseExistsTests()
        {
            EnsureDatabaseExists();
            EnsureUserExists(NormalUser, allowMasterQuery: true);
            EnsureUserExists(ImpairedUser, allowMasterQuery: false);

            MutableResolver.AddResolver <IManifestTokenResolver>(
                new SingletonDependencyResolver <IManifestTokenResolver>(new BasicManifestTokenResolver()));
        }
예제 #12
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();
        }
        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));
        }
예제 #14
0
        public void CommitFailureHandler_supports_nested_transactions()
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));

            try
            {
                using (var context = new BlogContextCommit())
                {
                    ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                        () =>
                    {
                        context.Database.Delete();
                        Assert.Equal(1, context.Blogs.Count());
                    });

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

                    ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                        () =>
                    {
                        using (var transaction = context.Database.BeginTransaction())
                        {
                            using (var innerContext = new BlogContextCommit())
                            {
                                using (var innerTransaction = innerContext.Database.BeginTransaction())
                                {
                                    Assert.Equal(1, innerContext.Blogs.Count());
                                    innerContext.Blogs.Add(new BlogContext.Blog());
                                    innerContext.SaveChanges();
                                    innerTransaction.Commit();
                                }
                            }

                            context.SaveChanges();
                            transaction.Commit();
                        }
                    });
                }

                ExtendedSqlAzureExecutionStrategy.ExecuteNew(
                    () =>
                {
                    using (var context = new BlogContextCommit())
                    {
                        Assert.Equal(3, context.Blogs.Count());
                    }
                });
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
예제 #15
0
        public SimpleScenariosForLocalDb()
        {
            // TODO: Can we hardcode this somewhere like we do for the EF provider?
            DbProviderFactories.RegisterFactory("System.Data.SqlClient", SqlClientFactory.Instance);

            _previousDataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory");

            AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetTempPath());
            MutableResolver.AddResolver <IDbConnectionFactory>(k => new LocalDbConnectionFactory("mssqllocaldb"));
        }
 public static void WrapProviders()
 {
     MutableResolver.AddResolver <DbProviderServices>(k => WrappingEfProvider <SqlClientFactory, SqlProviderServices> .Instance);
     MutableResolver.AddResolver <Func <MigrationSqlGenerator> >(WrappingEfProvider <SqlClientFactory, SqlProviderServices> .Instance);
     MutableResolver.AddResolver <DbProviderFactory>(k => WrappingAdoNetProvider <SqlClientFactory> .Instance);
     MutableResolver.AddResolver <IDbProviderFactoryResolver>(k => new WrappingProviderFactoryResolver <SqlClientFactory>());
     MutableResolver.AddResolver <IProviderInvariantName>(
         k => new WrappingProviderInvariantName
     {
         Name = "System.Data.SqlClient"
     });
 }
예제 #17
0
        private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow)
        {
            var failingTransactionInterceptor = new FailingTransactionInterceptor();

            DbInterception.Add(failingTransactionInterceptor);

            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));

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

                    var objectContext      = ((IObjectContextAdapter)context).ObjectContext;
                    var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler;

                    for (var i = 0; i < transactionHandler.PruningLimit; i++)
                    {
                        context.Blogs.Add(new BlogContext.Blog());
                        context.SaveChanges();
                    }

                    AssertTransactionHistoryCount(context, transactionHandler.PruningLimit);

                    if (shouldThrow)
                    {
                        failingTransactionInterceptor.ShouldFailTimes = 1;
                        failingTransactionInterceptor.ShouldRollBack  = false;
                    }

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

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

                    AssertTransactionHistoryCount(context, 1);
                    Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries <TransactionRow>().Count());
                }
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptor);
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
예제 #18
0
            public void Static_method_returns_the_ExecutionStrategy_from_resolver()
            {
                var connectionMock = new Mock <DbConnection>();

                connectionMock.Setup(m => m.DataSource).Returns("FooSource");

                var model = new EdmModel(DataSpace.SSpace);

                model.ProviderInfo     = new DbProviderInfo("System.Data.FakeSqlClient", "2008");
                model.ProviderManifest = new SqlProviderManifest("2008");

                var storeItemCollectionMock = new Mock <StoreItemCollection>(model)
                {
                    CallBase = true
                };

                var metadataWorkspaceMock = new Mock <MetadataWorkspace>();

                metadataWorkspaceMock.Setup(m => m.GetItemCollection(DataSpace.SSpace)).Returns(storeItemCollectionMock.Object);

                var entityConnection = new EntityConnection(
                    workspace: null, connection: connectionMock.Object, skipInitialization: true, entityConnectionOwnsStoreConnection: false);

                var mockExecutionStrategy = new Mock <IExecutionStrategy>().Object;

                MutableResolver.AddResolver <Func <IExecutionStrategy> >(
                    k =>
                {
                    var key = k as ExecutionStrategyKey;
                    Assert.Equal("System.Data.FakeSqlClient", key.ProviderInvariantName);
                    Assert.Equal("FooSource", key.ServerName);
                    return((Func <IExecutionStrategy>)(() => mockExecutionStrategy));
                });

                var providerFactoryServiceMock = new Mock <IDbProviderFactoryService>();

                providerFactoryServiceMock.Setup(m => m.GetProviderFactory(It.IsAny <DbConnection>()))
                .Returns(FakeSqlProviderFactory.Instance);

                MutableResolver.AddResolver <IDbProviderFactoryService>(k => providerFactoryServiceMock.Object);
                try
                {
                    Assert.Same(mockExecutionStrategy, DbProviderServices.GetExecutionStrategy(connectionMock.Object));
                    Assert.Same(
                        mockExecutionStrategy, DbProviderServices.GetExecutionStrategy(entityConnection, metadataWorkspaceMock.Object));
                }
                finally
                {
                    MutableResolver.ClearResolvers();
                }
            }
예제 #19
0
        private void VerifyConcurrency(Action <SimpleModelContext, List <Task> > execute, bool shouldThrow)
        {
            var taskCompletionSource = new TaskCompletionSource <object>();

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(k => (Func <IDbExecutionStrategy>)(() => new BlockingStrategy(taskCompletionSource.Task)));

            // The returned tasks need to be awaited on before the test ends in case they are faulted
            var tasks = new List <Task>();

            try
            {
                // Needs MARS enabled for concurrent queries
                using (var context = new SimpleModelContext(
                           @"Data Source=.\SQLEXPRESS;Initial Catalog=SimpleModel.SimpleModelContext;Integrated Security=True;MultipleActiveResultSets=True")
                       )
                {
                    using (context.Database.BeginTransaction())
                    {
                        if (shouldThrow)
                        {
                            Assert.Throws <NotSupportedException>(
                                () => execute(context, tasks)).ValidateMessage("ConcurrentMethodInvocation");
                        }
                        else
                        {
                            execute(context, tasks);
                        }

                        taskCompletionSource.SetResult(null);
                        // Need to wait for all readers to close before disposing the transactions
                        // The exception needs to be thrown before this call
                        Task.WaitAll(tasks.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                if (!taskCompletionSource.Task.IsCompleted)
                {
                    taskCompletionSource.SetException(ex);
                }
                Task.WaitAll(tasks.ToArray());
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }
        }
예제 #20
0
        private static void Execute_commit_failure_test(
            Action <BlogContextCommit> runAndVerify, int expectedBlogs, bool useTransactionHandler, bool useExecutionStrategy,
            bool rollbackOnFail)
        {
            var failingTransactionInterceptor = new FailingTransactionInterceptor();

            DbInterception.Add(failingTransactionInterceptor);

            if (useTransactionHandler)
            {
                MutableResolver.AddResolver <Func <TransactionHandler> >(
                    new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));
            }

            if (useExecutionStrategy)
            {
                MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                    key => (Func <IDbExecutionStrategy>)(() => new SqlAzureExecutionStrategy()));
            }

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

                    FailingTransactionInterceptor.ShouldFailTimes = 1;
                    FailingTransactionInterceptor.ShouldRollBack  = rollbackOnFail;

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

                using (var context = new BlogContextCommit())
                {
                    Assert.Equal(expectedBlogs, context.Blogs.Count());
                }
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptor);
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
예제 #21
0
        private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_implementation(
            Action <BlogContextCommit> runAndVerify)
        {
            var failingTransactionInterceptorMock = new Mock <FailingTransactionInterceptor> {
                CallBase = true
            };

            DbInterception.Add(failingTransactionInterceptorMock.Object);

            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                key => (Func <IDbExecutionStrategy>)(() => new SqlAzureExecutionStrategy()));

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

                    FailingTransactionInterceptor.ShouldFailTimes = 20;
                    FailingTransactionInterceptor.ShouldRollBack  = false;

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

                    runAndVerify(context);

                    FailingTransactionInterceptor.ShouldFailTimes = 0;
                    failingTransactionInterceptorMock.Verify(
                        m => m.Committing(It.IsAny <DbTransaction>(), It.IsAny <DbTransactionInterceptionContext>()), Times.Exactly(4));
                }

                using (var context = new BlogContextCommit())
                {
                    Assert.Equal(2, context.Blogs.Count());
                }
            }
            finally
            {
                DbInterception.Remove(failingTransactionInterceptorMock.Object);
                MutableResolver.ClearResolvers();
            }

            DbDispatchersHelpers.AssertNoInterceptors();
        }
예제 #22
0
 public void Changed_default_connection_factory_that_results_in_null_connections_throws()
 {
     try
     {
         MutableResolver.AddResolver <IDbConnectionFactory>(k => new Mock <IDbConnectionFactory>().Object);
         using (var internalConnection = new LazyInternalConnection("NameNotInAppConfig"))
         {
             Assert.Equal(
                 Strings.DbContext_ConnectionFactoryReturnedNullConnection,
                 Assert.Throws <InvalidOperationException>(() => { var _ = internalConnection.Connection; }).Message);
         }
     }
     finally
     {
         MutableResolver.ClearResolvers();
     }
 }
예제 #23
0
        private void CommitFailureHandler_with_ExecutionStrategy_test(
            Action <ObjectContext, Mock <SuspendableSqlAzureExecutionStrategy> > pruneAndVerify)
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null));

            var executionStrategyMock = new Mock <SuspendableSqlAzureExecutionStrategy> {
                CallBase = true
            };

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                key => (Func <IDbExecutionStrategy>)(() => executionStrategyMock.Object));

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

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

                    context.SaveChanges();

                    AssertTransactionHistoryCount(context, 1);

                    executionStrategyMock.Verify(e => e.Execute(It.IsAny <Func <int> >()), Times.Exactly(3));
#if !NET40
                    executionStrategyMock.Verify(
                        e => e.ExecuteAsync(It.IsAny <Func <Task <int> > >(), It.IsAny <CancellationToken>()), Times.Never());
#endif

                    var objectContext = ((IObjectContextAdapter)context).ObjectContext;
                    pruneAndVerify(objectContext, executionStrategyMock);

                    using (var transactionContext = new TransactionContext(context.Database.Connection))
                    {
                        Assert.Equal(0, transactionContext.Transactions.Count());
                    }
                }
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }
        }
예제 #24
0
        private static void RegisterResolvers()
        {
            // We register new resolvers that match the defaults because the defaults cache values such as
            // the ADO.NET provider registered in the factories table that we wish to temporarily change.

            MutableResolver.AddResolver <DbProviderServices>(
                (IDbDependencyResolver)Activator.CreateInstance(
                    typeof(DbContext).Assembly.GetTypes().Single(t => t.Name == "DefaultProviderServicesResolver"), nonPublic: true));

            MutableResolver.AddResolver <DbProviderFactory>(
                (IDbDependencyResolver)Activator.CreateInstance(
                    typeof(DbContext).Assembly.GetTypes().Single(t => t.Name == "DefaultProviderFactoryResolver"), nonPublic: true));

            MutableResolver.AddResolver <IProviderInvariantName>(
                (IDbDependencyResolver)Activator.CreateInstance(
                    typeof(DbContext).Assembly.GetTypes().Single(t => t.Name == "DefaultInvariantNameResolver"), nonPublic: true));
        }
        public void GetHistoryContextFactory_should_return_per_provider_service_when_not_locally_registered()
        {
            var migrationsConfiguration = new TestMigrationsConfiguration();

            try
            {
                Func <DbConnection, string, HistoryContext> factory = (c, s) => new HistoryContext(c, s);

                MutableResolver.AddResolver <Func <DbConnection, string, HistoryContext> >(_ => factory);

                Assert.Same(factory, migrationsConfiguration.GetHistoryContextFactory("Foo"));
            }
            finally
            {
                MutableResolver.ClearResolvers();
            }
        }
        public DatabaseExistsInInitializerTests()
        {
            EnsureDatabaseExists(DatabaseWithMigrationHistory, drophistoryTable: false, outOfDate: false);
            EnsureUserExists(DatabaseWithMigrationHistory, NormalUser, allowMasterQuery: true);
            EnsureUserExists(DatabaseWithMigrationHistory, ImpairedUser, allowMasterQuery: false);

            EnsureDatabaseExists(DatabaseWithoutMigrationHistory, drophistoryTable: true, outOfDate: false);
            EnsureUserExists(DatabaseWithoutMigrationHistory, NormalUser, allowMasterQuery: true);
            EnsureUserExists(DatabaseWithoutMigrationHistory, ImpairedUser, allowMasterQuery: false);

            EnsureDatabaseExists(DatabaseOutOfDate, drophistoryTable: false, outOfDate: true);
            EnsureUserExists(DatabaseOutOfDate, NormalUser, allowMasterQuery: true);
            EnsureUserExists(DatabaseOutOfDate, ImpairedUser, allowMasterQuery: false);

            MutableResolver.AddResolver <IManifestTokenResolver>(
                new SingletonDependencyResolver <IManifestTokenResolver>(new BasicManifestTokenResolver()));
        }
예제 #27
0
            public void HistoryContextFactory_returns_factory_for_given_provider_invariant_name_if_registered()
            {
                Func <DbConnection, string, HistoryContext> newFactory = (c, s) => new HistoryContext(c, s);

                try
                {
                    MutableResolver.AddResolver <Func <DbConnection, string, HistoryContext> >(
                        new SingletonDependencyResolver <Func <DbConnection, string, HistoryContext> >(
                            newFactory, SqlProviderServices.ProviderInvariantName));

                    Assert.Same(newFactory, new MigrationsConfiguration.ContextWithoutMigrations().InternalContext.HistoryContextFactory);
                }
                finally
                {
                    MutableResolver.ClearResolvers();
                }
            }
예제 #28
0
        public void DefaultDbModelStore_saves_and_loads_DbContext_with_DbFunction_StoreModelConvention()
        {
            try
            {
                var dependencyResolver = new SingletonDependencyResolver <DbModelStore>(_store);
                MutableResolver.AddResolver <DbModelStore>(dependencyResolver);

                Assert.False(File.Exists(_location + typeof(ScalarFunctionDbContext).FullName + ".edmx"), "edmx should not exist yet");

                using (var context = new ScalarFunctionDbContext())
                {
                    context.Models.Add(new Model {
                        Id = 1
                    });
                    context.SaveChanges();

                    Assert.True(
                        context.Set <Model>().Any(model => ScalarFunction.GetSomething("inValue") == "inValue"),
                        "Value passed in should be returned from db function without error");
                }

                Assert.True(
                    File.Exists(_location + typeof(ScalarFunctionDbContext).FullName + ".edmx"), "edmx should be written to _location");

                var xdocFromStore = _store.TryGetEdmx(typeof(ScalarFunctionDbContext));
                Assert.NotNull(xdocFromStore);

                var compiledModelFromCache = _store.TryLoad(typeof(ScalarFunctionDbContext));
                Assert.NotNull(compiledModelFromCache);
                using (var context = new ScalarFunctionDbContext(compiledModelFromCache))
                {
                    Assert.True(
                        context.Set <Model>().Any(prd => ScalarFunction.GetSomething("inValue") == "inValue"),
                        "Value passed in should be returned from db function without error");
                }
            }
            finally //clean up
            {
                MutableResolver.ClearResolvers();
                if (File.Exists(_location + typeof(ScalarFunctionDbContext).FullName + ".edmx"))
                {
                    File.Delete(_location + typeof(ScalarFunctionDbContext).FullName + ".edmx");
                }
            }
        }
예제 #29
0
        public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext()
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null));
            TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation(
                context =>
            {
                context.SaveChanges();

                using (var infoContext = GetInfoContext(context))
                {
                    Assert.True(infoContext.TableExists("MyTransactions"));

                    var column = infoContext.Columns.Single(c => c.Name == "Time");
                    Assert.Equal("datetime2", column.Type);
                }
            });
        }
예제 #30
0
        public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database()
        {
            MutableResolver.AddResolver <Func <TransactionHandler> >(
                new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null));

            MutableResolver.AddResolver <Func <IDbExecutionStrategy> >(
                key => (Func <IDbExecutionStrategy>)(() => new SqlAzureExecutionStrategy()));

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

                MutableResolver.AddResolver <Func <TransactionHandler> >(
                    new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null));

                using (var context = new BlogContextCommit())
                {
                    context.Blogs.Add(new BlogContext.Blog());

                    Assert.Throws <EntityException>(() => context.SaveChanges());

                    context.Database.ExecuteSqlCommand(
                        TransactionalBehavior.DoNotEnsureTransaction,
                        ((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript());

                    context.SaveChanges();
                }

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

            DbDispatchersHelpers.AssertNoInterceptors();
        }