Ejemplo n.º 1
0
        public bool CommandExecuting(DbCommand command, DbInterceptionContext interceptionContext)
        {
            if (interceptionContext.DbContexts.Contains(_context, ReferenceEquals))
            {
                _commands.Add(command);

                return false; // cancel execution
            }

            return true;
        }
        internal override DbCommandDefinition CreateDbCommandDefinition(
            DbProviderManifest providerManifest,
            DbCommandTree commandTree,
            DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(providerManifest);
            DebugCheck.NotNull(commandTree);
            DebugCheck.NotNull(interceptionContext);

            var storeMetadata = (StoreItemCollection)commandTree.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);
            return CreateCommandDefinition(storeMetadata.ProviderFactory, commandTree, interceptionContext);
        }
        internal static EntityCommandDefinition CreateCommandDefinition(
            DbProviderFactory storeProviderFactory,
            DbCommandTree commandTree,
            DbInterceptionContext interceptionContext,
            IDbDependencyResolver resolver = null)
        {
            DebugCheck.NotNull(storeProviderFactory);
            DebugCheck.NotNull(interceptionContext);
            DebugCheck.NotNull(commandTree);

            return new EntityCommandDefinition(storeProviderFactory, commandTree, interceptionContext, resolver);
        }
        /// <inheritdoc />
        public string ResolveManifestToken(DbConnection connection)
        {
            Check.NotNull(connection, "connection");

            var interceptionContext = new DbInterceptionContext();
            var key = Tuple.Create(connection.GetType(),
                DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext),
                DbInterception.Dispatch.Connection.GetDatabase(connection, interceptionContext));

            return _cachedTokens.GetOrAdd(
                key,
                k => DbProviderServices.GetProviderServices(connection).GetProviderManifestTokenChecked(connection));
        }
Ejemplo n.º 5
0
        public void ExecuteScalar_should_dispatch_to_interceptor_and_optionally_execute()
        {
            var mockCommand = new Mock <DbCommand>();

            mockCommand.Setup(m => m.ExecuteScalar()).Returns(11);

            var mockCancelable        = new Mock <ICancelableDbCommandInterceptor>();
            var mockPublicInterceptor = new Mock <DbInterceptor> {
                CallBase = true
            };

            var dispatchers = new Dispatchers();

            dispatchers.AddInterceptor(mockCancelable.Object);
            dispatchers.AddInterceptor(mockPublicInterceptor.Object);

            var interceptionContext    = new DbInterceptionContext();
            var interceptableDbCommand = new InterceptableDbCommand(mockCommand.Object, interceptionContext, dispatchers);

            mockCancelable.Setup(m => m.CommandExecuting(mockCommand.Object, interceptionContext)).Returns(false);

            interceptableDbCommand.ExecuteScalar();

            mockCommand.Verify(m => m.ExecuteScalar(), Times.Never());

            mockCancelable.Verify(m => m.CommandExecuting(mockCommand.Object, interceptionContext), Times.Once());

            mockPublicInterceptor.Verify(
                m => m.ScalarExecuting(It.IsAny <DbCommand>(), It.IsAny <DbInterceptionContext>()), Times.Never());

            mockPublicInterceptor.Verify(
                m => m.ScalarExecuted(It.IsAny <DbCommand>(), It.IsAny <int>(), It.IsAny <DbInterceptionContext>()), Times.Never());

            mockCancelable.Setup(m => m.CommandExecuting(mockCommand.Object, interceptionContext)).Returns(true);

            Assert.Equal(11, interceptableDbCommand.ExecuteScalar());

            mockCommand.Verify(m => m.ExecuteScalar(), Times.Once());

            mockCancelable.Verify(m => m.CommandExecuting(mockCommand.Object, interceptionContext), Times.Exactly(2));

            mockPublicInterceptor.Verify(
                m => m.ScalarExecuting(mockCommand.Object, interceptionContext), Times.Once());

            mockPublicInterceptor.Verify(
                m => m.ScalarExecuted(mockCommand.Object, 11, interceptionContext), Times.Once());
        }
Ejemplo n.º 6
0
        private InterceptableDbCommand ConfigureCommand(DbCommand command, string commandText)
        {
            command.CommandText = commandText;

            if (_configuration.CommandTimeout.HasValue)
            {
                command.CommandTimeout = _configuration.CommandTimeout.Value;
            }

            var interceptionContext = new DbInterceptionContext();

            if (_contextForInterception != null)
            {
                interceptionContext = interceptionContext.WithDbContext(_contextForInterception);
            }
            return(new InterceptableDbCommand(command, interceptionContext));
        }
        private static void setBaseInfo(DbInterceptionContext interceptionContext, DbContextBase info)
        {
            if (interceptionContext.ObjectContexts == null || !interceptionContext.ObjectContexts.Any())
            {
                return;
            }

            var context = interceptionContext.ObjectContexts.First();  //todo: ??

            info.ObjectContextId = UniqueIdExtensions <ObjectContext> .GetUniqueId(context).ToInt();

            info.ObjectContextName = context.DefaultContainerName;
            if (context.TransactionHandler != null && context.TransactionHandler.Connection != null)
            {
                info.ConnectionId = UniqueIdExtensions <DbConnection> .GetUniqueId(context.TransactionHandler.Connection).ToInt();
            }
        }
Ejemplo n.º 8
0
        internal EntityCommand(DbInterceptionContext interceptionContext, EntityDataReaderFactory factory)
        {
            DebugCheck.NotNull(interceptionContext);

            // Initalize the member field with proper default values
            _designTimeVisible   = true;
            _commandType         = CommandType.Text;
            _updatedRowSource    = UpdateRowSource.Both;
            _parameters          = new EntityParameterCollection();
            _interceptionContext = interceptionContext;

            // Future Enhancement: (See SQLPT #300004256) At some point it would be
            // really nice to read defaults from a global configuration, but we're not
            // doing that today.
            _enableQueryPlanCaching = true;

            _entityDataReaderFactory = factory ?? new EntityDataReaderFactory();
        }
        private void UpdateToSlave(DbCommand command, DbInterceptionContext interceptionContext)
        {
            var isDistributedTran = null != Transaction.Current &&
                                    Transaction.Current.TransactionInformation.Status != TransactionStatus.Committed;

            foreach (var context in interceptionContext.DbContexts)
            {
                var isDbTran      = null != context.Database.CurrentTransaction;
                var isCommandTran = null != command.Transaction;
                var isTrans       = isDistributedTran || isDbTran || isCommandTran;

                var connectionString = isTrans ?
                                       MasterConnectionString :
                                       SlaveConnectionString;

                UpdateConnectionStringIfNeed(context.Database.Connection, connectionString);
            }
        }
Ejemplo n.º 10
0
 internal override void ExecuteSql(
     MigrationStatement migrationStatement,
     DbConnection connection,
     DbTransaction transaction,
     DbInterceptionContext interceptionContext)
 {
     this._logger.Verbose(migrationStatement.Sql);
     DbProviderServices.GetProviderServices(connection)?.RegisterInfoMessageHandler(connection, (Action <string>)(message =>
     {
         if (string.Equals(message, this._lastInfoMessage, StringComparison.OrdinalIgnoreCase))
         {
             return;
         }
         this._logger.Warning(message);
         this._lastInfoMessage = message;
     }));
     base.ExecuteSql(migrationStatement, connection, transaction, interceptionContext);
 }
Ejemplo n.º 11
0
 internal override void ExecuteSql(
     MigrationStatement migrationStatement,
     DbConnection connection,
     DbTransaction transaction,
     DbInterceptionContext interceptionContext)
 {
     if (string.IsNullOrWhiteSpace(migrationStatement.Sql))
     {
         return;
     }
     using (InterceptableDbCommand interceptableDbCommand = this.ConfigureCommand(connection.CreateCommand(), migrationStatement.Sql, interceptionContext))
     {
         if (transaction != null)
         {
             interceptableDbCommand.Transaction = transaction;
         }
         interceptableDbCommand.ExecuteNonQuery();
     }
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Executes the future queries.
        /// </summary>
        /// <param name="context">The <see cref="ObjectContext" /> to run the queries against.</param>
        /// <param name="futureQueries">The future queries list.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task ExecuteFutureQueriesAsync(ObjectContext context, IList <IFutureQuery> futureQueries, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (futureQueries == null)
            {
                throw new ArgumentNullException("futureQueries");
            }

            // used to call internal methods
            dynamic contextProxy = new DynamicProxy(context);

            contextProxy.EnsureConnection(false);

            //the (internal) InterceptionContext contains the registered loggers
            DbInterceptionContext interceptionContext = contextProxy.InterceptionContext;

            try
            {
                using (var command = CreateFutureCommand(context, futureQueries))
                    using (var reader = await DbInterception.Dispatch.Command.ReaderAsync(
                               command, new DbCommandInterceptionContext(interceptionContext), cancellationToken
                               )
                                        .ConfigureAwait(false)
                           )
                    {
                        foreach (var futureQuery in futureQueries)
                        {
                            await futureQuery.SetResultAsync(context, reader, cancellationToken).ConfigureAwait(false);

                            await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);
                        }
                    }
            }
            finally
            {
                contextProxy.ReleaseConnection();
                // once all queries processed, clear from queue
                futureQueries.Clear();
            }
        }
Ejemplo n.º 13
0
        // <summary>
        // Internal constructor used by EntityCommandDefinition
        // </summary>
        // <param name="commandDefinition"> The prepared command definition that can be executed using this EntityCommand </param>
        internal EntityCommand(EntityCommandDefinition commandDefinition, DbInterceptionContext context, EntityDataReaderFactory factory = null)
            : this(context, factory)
        {
            // Assign other member fields from the parameters
            _commandDefinition = commandDefinition;
            _parameters        = new EntityParameterCollection();

            // Make copies of the parameters
            foreach (var parameter in commandDefinition.Parameters)
            {
                _parameters.Add(parameter.Clone());
            }

            // Reset the dirty flag that was set to true when the parameters were added so that it won't say
            // it's dirty to start with
            _parameters.ResetIsDirty();

            // Track the fact that this command was created from and represents an already prepared command definition
            _isCommandDefinitionBased = true;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Executes the future queries.
        /// </summary>
        /// <param name="context">The <see cref="ObjectContext" /> to run the queries against.</param>
        /// <param name="futureQueries">The future queries list.</param>
        public void ExecuteFutureQueries(ObjectContext context, IList <IFutureQuery> futureQueries)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            if (futureQueries == null)
            {
                throw new ArgumentNullException("futureQueries");
            }

            // used to call internal methods
            dynamic contextProxy = new DynamicProxy(context);

            contextProxy.EnsureConnection(false);

            //the (internal) InterceptionContext contains the registered loggers
            DbInterceptionContext interceptionContext = contextProxy.InterceptionContext;

            try
            {
                using (var command = CreateFutureCommand(context, futureQueries))
                    using (
                        var reader = DbInterception.Dispatch.Command.Reader(command,
                                                                            new DbCommandInterceptionContext(interceptionContext)))
                    {
                        foreach (var futureQuery in futureQueries)
                        {
                            futureQuery.SetResult(context, reader);
                            reader.NextResult();
                        }
                    }
            }
            finally
            {
                contextProxy.ReleaseConnection();

                // once all queries processed, clear from queue
                futureQueries.Clear();
            }
        }
Ejemplo n.º 15
0
        internal void Create(DatabaseExistenceState existenceState)
        {
            using (var clonedObjectContext = _internalContext.CreateObjectContextForDdlOps())
            {
                if (existenceState == DatabaseExistenceState.Unknown)
                {
                    if (_internalContext.DatabaseOperations.Exists(clonedObjectContext.ObjectContext))
                    {
                        var interceptionContext = new DbInterceptionContext();
                        interceptionContext = interceptionContext.WithDbContext(_internalContext.Owner);
                        interceptionContext = interceptionContext.WithObjectContext(clonedObjectContext.ObjectContext);

                        throw Error.Database_DatabaseAlreadyExists(
                                  DbInterception.Dispatch.Connection.GetDatabase(_internalContext.Connection, interceptionContext));
                    }
                    existenceState = DatabaseExistenceState.DoesNotExist;
                }

                _internalContext.CreateDatabase(clonedObjectContext.ObjectContext, existenceState);
            }
        }
Ejemplo n.º 16
0
        private void ExecuteStatementsInternal(
            IEnumerable <MigrationStatement> migrationStatements,
            DbConnection connection)
        {
            DbContext             context             = this._usersContext ?? this._usersContextInfo.CreateInstance();
            DbInterceptionContext interceptionContext = new DbInterceptionContext().WithDbContext(context);
            TransactionHandler    transactionHandler  = (TransactionHandler)null;

            try
            {
                if (DbInterception.Dispatch.Connection.GetState(connection, interceptionContext) == ConnectionState.Broken)
                {
                    DbInterception.Dispatch.Connection.Close(connection, interceptionContext);
                }
                if (DbInterception.Dispatch.Connection.GetState(connection, interceptionContext) == ConnectionState.Closed)
                {
                    DbInterception.Dispatch.Connection.Open(connection, interceptionContext);
                }
                if (!(context is TransactionContext))
                {
                    Func <TransactionHandler> service = DbConfiguration.DependencyResolver.GetService <Func <TransactionHandler> >((object)new ExecutionStrategyKey(DbConfiguration.DependencyResolver.GetService <IProviderInvariantName>((object)DbProviderServices.GetProviderFactory(connection)).Name, DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext)));
                    if (service != null)
                    {
                        transactionHandler = service();
                        transactionHandler.Initialize(context, connection);
                    }
                }
                this.ExecuteStatementsInternal(migrationStatements, connection, interceptionContext);
                this._committedStatements = true;
            }
            finally
            {
                transactionHandler?.Dispose();
                if (this._usersContext == null)
                {
                    context.Dispose();
                }
            }
        }
Ejemplo n.º 17
0
        private void ExecuteStatementsWithinNewTransaction(
            IEnumerable <MigrationStatement> migrationStatements,
            DbConnection connection,
            DbInterceptionContext interceptionContext)
        {
            BeginTransactionInterceptionContext interceptionContext1 = new BeginTransactionInterceptionContext(interceptionContext).WithIsolationLevel(IsolationLevel.Serializable);
            DbTransaction transaction = (DbTransaction)null;

            try
            {
                transaction = DbInterception.Dispatch.Connection.BeginTransaction(connection, interceptionContext1);
                this.ExecuteStatementsWithinTransaction(migrationStatements, transaction, interceptionContext);
                DbInterception.Dispatch.Transaction.Commit(transaction, interceptionContext);
            }
            finally
            {
                if (transaction != null)
                {
                    DbInterception.Dispatch.Transaction.Dispose(transaction, interceptionContext);
                }
            }
        }
Ejemplo n.º 18
0
            public void InterceptionContext_can_be_set_in_constructors()
            {
                var interceptionContext = new DbInterceptionContext();

                Assert.Same(interceptionContext, new EntityCommand(interceptionContext).InterceptionContext);

                Assert.Same(
                    interceptionContext,
                    new EntityCommand(interceptionContext, new EntityCommand.EntityDataReaderFactory()).InterceptionContext);

                var mockCommandDef = new Mock <EntityCommandDefinition>();

                mockCommandDef.Setup(m => m.Parameters).Returns(Enumerable.Empty <EntityParameter>);

                Assert.Same(
                    interceptionContext,
                    new EntityCommand(
                        mockCommandDef.Object, interceptionContext,
                        new EntityCommand.EntityDataReaderFactory()).InterceptionContext);

                Assert.Same(
                    interceptionContext,
                    new EntityCommand("12", interceptionContext, new EntityCommand.EntityDataReaderFactory()).InterceptionContext);
            }
Ejemplo n.º 19
0
        private void ExecuteStatementsWithinNewTransaction(
            IEnumerable<MigrationStatement> migrationStatements, DbConnection connection,
            DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(migrationStatements);
            DebugCheck.NotNull(connection);

            var beginTransactionInterceptionContext
                = new BeginTransactionInterceptionContext(interceptionContext)
                    .WithIsolationLevel(IsolationLevel.Serializable);

            DbTransaction transaction = null;
            try
            {
                transaction
                    = DbInterception.Dispatch.Connection.BeginTransaction(
                        connection, beginTransactionInterceptionContext);

                ExecuteStatementsWithinTransaction(migrationStatements, transaction, interceptionContext);

                DbInterception.Dispatch.Transaction.Commit(transaction, interceptionContext);
            }
            finally
            {
                if (transaction != null)
                {
                    DbInterception.Dispatch.Transaction.Dispose(transaction, interceptionContext);
                }
            }
        }
Ejemplo n.º 20
0
        private void ExecuteStatementsInternal(
            IEnumerable<MigrationStatement> migrationStatements, DbConnection connection,
            DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(migrationStatements);
            DebugCheck.NotNull(connection);

            var pendingStatements = new List<MigrationStatement>();

            foreach (var statement in migrationStatements.Where(s => !string.IsNullOrEmpty(s.Sql)))
            {
                if (!statement.SuppressTransaction)
                {
                    pendingStatements.Add(statement);

                    continue;
                }

                if (pendingStatements.Any())
                {
                    ExecuteStatementsWithinNewTransaction(pendingStatements, connection, interceptionContext);

                    pendingStatements.Clear();
                }

                base.ExecuteSql(statement, connection, null, interceptionContext);
            }

            if (pendingStatements.Any())
            {
                ExecuteStatementsWithinNewTransaction(pendingStatements, connection, interceptionContext);
            }
        }
Ejemplo n.º 21
0
        internal DbMigrator(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, bool calledByCreateDatabase)
            : base(null)
        {
            Check.NotNull(configuration, "configuration");
            Check.NotNull(configuration.ContextType, "configuration.ContextType");

            _configuration = configuration;
            _calledByCreateDatabase = calledByCreateDatabase;
            _existenceState = existenceState;

            if (usersContext != null)
            {
                _usersContextInfo = new DbContextInfo(usersContext);
            }
            else
            {
                _usersContextInfo
                    = configuration.TargetDatabase == null
                        ? new DbContextInfo(configuration.ContextType)
                        : new DbContextInfo(configuration.ContextType, configuration.TargetDatabase);

                if (!_usersContextInfo.IsConstructible)
                {
                    throw Error.ContextNotConstructible(configuration.ContextType);
                }
            }

            _modelDiffer = _configuration.ModelDiffer;

            var context = usersContext ?? _usersContextInfo.CreateInstance();
            _usersContext = context;

            try
            {
                _migrationAssembly
                    = new MigrationAssembly(
                        _configuration.MigrationsAssembly,
                        _configuration.MigrationsNamespace);

                _currentModel = context.GetModel();

                _connection = context.Database.Connection;

                _providerFactory = DbProviderServices.GetProviderFactory(_connection);

                _defaultSchema
                    = context.InternalContext.DefaultSchema
                      ?? EdmModelExtensions.DefaultSchema;

                _historyContextFactory
                    = _configuration
                        .GetHistoryContextFactory(_usersContextInfo.ConnectionProviderName);

                _historyRepository
                    = new HistoryRepository(
                        context.InternalContext,
                        _usersContextInfo.ConnectionString,
                        _providerFactory,
                        _configuration.ContextKey,
                        _configuration.CommandTimeout,
                        _historyContextFactory,
                        schemas: new[] { _defaultSchema }.Concat(GetHistorySchemas()),
                        contextForInterception: _usersContext,
                        initialExistence: _existenceState);

                _providerManifestToken
                    = context.InternalContext.ModelProviderInfo != null
                        ? context.InternalContext.ModelProviderInfo.ProviderManifestToken
                        : DbConfiguration
                            .DependencyResolver
                            .GetService<IManifestTokenResolver>()
                            .ResolveManifestToken(_connection);

                var modelBuilder
                    = context.InternalContext.CodeFirstModel.CachedModelBuilder;

                _modificationCommandTreeGenerator
                    = new Lazy<ModificationCommandTreeGenerator>(
                        () =>
                            new ModificationCommandTreeGenerator(
                                modelBuilder.BuildDynamicUpdateModel(
                                    new DbProviderInfo(
                                        _usersContextInfo.ConnectionProviderName,
                                        _providerManifestToken)),
                                CreateConnection()));

                var interceptionContext = new DbInterceptionContext();
                interceptionContext = interceptionContext.WithDbContext(_usersContext);

                _targetDatabase
                    = Strings.LoggingTargetDatabaseFormat(
                        DbInterception.Dispatch.Connection.GetDataSource(_connection, interceptionContext),
                        DbInterception.Dispatch.Connection.GetDatabase(_connection, interceptionContext),
                        _usersContextInfo.ConnectionProviderName,
                        _usersContextInfo.ConnectionStringOrigin == DbConnectionStringOrigin.DbContextInfo
                            ? Strings.LoggingExplicit
                            : _usersContextInfo.ConnectionStringOrigin.ToString());

                _legacyContextKey = context.InternalContext.DefaultContextKey;
                _emptyModel = GetEmptyModel();
            }
            finally
            {
                if (usersContext == null)
                {
                    _usersContext = null;
                    context.Dispose();
                }
            }
        }
Ejemplo n.º 22
0
 public InternalConnection(DbInterceptionContext interceptionContext)
 {
     InterceptionContext = interceptionContext ?? new DbInterceptionContext();
 }
Ejemplo n.º 23
0
 public bool ConnectionOpening(EntityConnection connection, DbInterceptionContext interceptionContext)
 {
     return(!interceptionContext.DbContexts.Contains(_context, ReferenceEquals));
 }
        protected override void DbCreateDatabase(DbConnection connection, int? timeOut, StoreItemCollection storeItemCollection)
        {
            Check.NotNull(connection, "connection");
            Check.NotNull(storeItemCollection, "storeItemCollection");

            // Validate that connection is a SqlCeConnection.
            ValidateConnection(connection);

            // We don't support create/delete database operations inside a transaction as they can't be rolled back.
            if (InTransactionScope())
            {
                throw ADP1.CreateDatabaseNotAllowedWithinTransaction();
            }

            if (_isLocalProvider)
            {
                var engine = new SqlCeEngine(DbInterception.Dispatch.Connection.GetConnectionString(connection, new DbInterceptionContext()));
                engine.CreateDatabase();
                engine.Dispose();
            }
            else
            {
                try
                {
                    Type rdpType;

                    // If we are working with RDP, then we will need to invoke the APIs through reflection.
                    var engine = RemoteProviderHelper.GetRemoteSqlCeEngine(
                        DbInterception.Dispatch.Connection.GetConnectionString(connection, new DbInterceptionContext()),
                        out rdpType);
                    Debug.Assert(engine != null);

                    // Invoke the required method on SqlCeEngine.
                    var mi = rdpType.GetMethod("CreateDatabase", new[] { typeof(int?) });
                    Debug.Assert(mi != null);

                    // We will pass 'timeout' to RDP, this will be used as timeout period for connecting and executing on TDSServer.
                    mi.Invoke(engine, new object[] { timeOut });
                }
                catch (Exception e)
                {
                    throw e.GetBaseException();
                }
            }

            // Create the command object depending on provider.
            var command = connection.CreateCommand();

            // Create the command texts from StoreItemCollection.
            var commandTextCollection = SqlDdlBuilder.CreateObjectsScript(storeItemCollection, false);

            DbTransaction transaction = null;

            var interceptionContext = new DbInterceptionContext();
            try
            {
                // Open the connection.
                DbInterception.Dispatch.Connection.Open(connection, interceptionContext);

                // Open a transaction and attach to the command.
                transaction = DbInterception.Dispatch.Connection.BeginTransaction(connection, new BeginTransactionInterceptionContext());
                command.Transaction = transaction;

                // Execute each statement.
                foreach (var text in commandTextCollection)
                {
                    command.CommandText = text;
                    DbInterception.Dispatch.Command.NonQuery(command, new DbCommandInterceptionContext());
                }

                // Commit the transaction.
                DbInterception.Dispatch.Transaction.Commit(transaction, interceptionContext);
            }
            catch (Exception e)
            {
                if (transaction != null)
                {
                    // Rollback the transaction.
                    DbInterception.Dispatch.Transaction.Rollback(transaction, interceptionContext);
                }

                // Throw IOE with SqlCeException embedded as inner exception.
                throw new InvalidOperationException(EntityRes.GetString(EntityRes.IncompleteDatabaseCreation), e);
            }
            finally
            {
                // Close connection and cleanup objects.
                if (command != null)
                {
                    command.Dispose();
                }
                if (transaction != null)
                {
                    DbInterception.Dispatch.Transaction.Dispose(transaction, interceptionContext);
                }
                if (connection != null)
                {
                    DbInterception.Dispatch.Connection.Close(connection, interceptionContext);
                }
            }
        }
Ejemplo n.º 25
0
        public void ExecuteReaderAsync_should_dispatch_to_interceptor_and_optionally_execute()
        {
            var result = Task.FromResult(new Mock <DbDataReader>().Object);

            var mockCommand = new Mock <DbCommand>();

            mockCommand.Protected()
            .Setup <Task <DbDataReader> >(
                "ExecuteDbDataReaderAsync", CommandBehavior.SingleRow, ItExpr.IsAny <CancellationToken>())
            .Returns(result);

            var mockCancelable        = new Mock <ICancelableDbCommandInterceptor>();
            var mockPublicInterceptor = new Mock <DbCommandInterceptor> {
                CallBase = true
            };

            var dispatchers = new Dispatchers();

            dispatchers.AddInterceptor(mockCancelable.Object);
            dispatchers.AddInterceptor(mockPublicInterceptor.Object);

            var interceptionContext    = new DbInterceptionContext();
            var interceptableDbCommand = new InterceptableDbCommand(mockCommand.Object, interceptionContext, dispatchers);

            mockCancelable.Setup(m => m.CommandExecuting(mockCommand.Object, It.IsAny <DbInterceptionContext>())).Returns(false);

            Assert.NotSame(result, interceptableDbCommand.ExecuteReaderAsync(CommandBehavior.SingleRow));

            mockCommand.Protected().Verify(
                "ExecuteDbDataReaderAsync", Times.Never(), CommandBehavior.SingleRow, ItExpr.IsAny <CancellationToken>());

            mockCancelable.Verify(m => m.CommandExecuting(mockCommand.Object, interceptionContext), Times.Once());

            mockPublicInterceptor.Verify(
                m => m.ReaderExecuting(
                    It.IsAny <DbCommand>(),
                    It.IsAny <DbCommandInterceptionContext <DbDataReader> >()), Times.Never());

            mockPublicInterceptor.Verify(
                m => m.ReaderExecuted(
                    It.IsAny <DbCommand>(),
                    It.IsAny <DbCommandInterceptionContext <DbDataReader> >()), Times.Never());

            mockCancelable.Setup(m => m.CommandExecuting(mockCommand.Object, It.IsAny <DbInterceptionContext>())).Returns(true);

            var interceptResult = interceptableDbCommand.ExecuteReaderAsync(CommandBehavior.SingleRow);

            interceptResult.Wait();
            Assert.Same(result.Result, interceptResult.Result);

            mockCommand.Protected().Verify(
                "ExecuteDbDataReaderAsync", Times.Once(), CommandBehavior.SingleRow, ItExpr.IsAny <CancellationToken>());

            mockCancelable.Verify(m => m.CommandExecuting(mockCommand.Object, interceptionContext), Times.Exactly(2));

            mockPublicInterceptor.Verify(
                m => m.ReaderExecuting(
                    mockCommand.Object,
                    It.Is <DbCommandInterceptionContext <DbDataReader> >(c => c.IsAsync && c.CommandBehavior == CommandBehavior.SingleRow)),
                Times.Once());

            mockPublicInterceptor.Verify(
                m => m.ReaderExecuted(
                    mockCommand.Object,
                    It.Is <DbCommandInterceptionContext <DbDataReader> >(
                        c => c.IsAsync && c.CommandBehavior == CommandBehavior.SingleRow && c.Result == result.Result)), Times.Once());
        }
Ejemplo n.º 26
0
        internal virtual DbCommand CreateCommand(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(commandTree);
            DebugCheck.NotNull(interceptionContext);

            var commandDefinition = CreateCommandDefinition(commandTree, interceptionContext);
            var command = commandDefinition.CreateCommand();
            return command;
        }
Ejemplo n.º 27
0
 public InternalConnection(DbInterceptionContext interceptionContext)
 {
     InterceptionContext = interceptionContext ?? new DbInterceptionContext();
 }
        protected override void DbCreateDatabase(DbConnection connection, int?timeOut, StoreItemCollection storeItemCollection)
        {
            Check.NotNull(connection, "connection");
            Check.NotNull(storeItemCollection, "storeItemCollection");

            // Validate that connection is a SqlCeConnection.
            ValidateConnection(connection);

            // We don't support create/delete database operations inside a transaction as they can't be rolled back.
            if (InTransactionScope())
            {
                throw ADP1.CreateDatabaseNotAllowedWithinTransaction();
            }

            if (_isLocalProvider)
            {
                var engine = new SqlCeEngine(DbInterception.Dispatch.Connection.GetConnectionString(connection, new DbInterceptionContext()));
                engine.CreateDatabase();
                engine.Dispose();
            }
            else
            {
                try
                {
                    Type rdpType;

                    // If we are working with RDP, then we will need to invoke the APIs through reflection.
                    var engine = RemoteProviderHelper.GetRemoteSqlCeEngine(
                        DbInterception.Dispatch.Connection.GetConnectionString(connection, new DbInterceptionContext()),
                        out rdpType);
                    Debug.Assert(engine != null);

                    // Invoke the required method on SqlCeEngine.
                    var mi = rdpType.GetMethod("CreateDatabase", new[] { typeof(int?) });
                    Debug.Assert(mi != null);

                    // We will pass 'timeout' to RDP, this will be used as timeout period for connecting and executing on TDSServer.
                    mi.Invoke(engine, new object[] { timeOut });
                }
                catch (Exception e)
                {
                    throw e.GetBaseException();
                }
            }

            // Create the command object depending on provider.
            var command = connection.CreateCommand();

            // Create the command texts from StoreItemCollection.
            var commandTextCollection = SqlDdlBuilder.CreateObjectsScript(storeItemCollection, false);

            DbTransaction transaction = null;

            var interceptionContext = new DbInterceptionContext();

            try
            {
                // Open the connection.
                DbInterception.Dispatch.Connection.Open(connection, interceptionContext);

                // Open a transaction and attach to the command.
                transaction         = DbInterception.Dispatch.Connection.BeginTransaction(connection, new BeginTransactionInterceptionContext());
                command.Transaction = transaction;

                // Execute each statement.
                foreach (var text in commandTextCollection)
                {
                    command.CommandText = text;
                    DbInterception.Dispatch.Command.NonQuery(command, new DbCommandInterceptionContext());
                }

                // Commit the transaction.
                DbInterception.Dispatch.Transaction.Commit(transaction, interceptionContext);
            }
            catch (Exception e)
            {
                if (transaction != null)
                {
                    // Rollback the transaction.
                    DbInterception.Dispatch.Transaction.Rollback(transaction, interceptionContext);
                }

                // Throw IOE with SqlCeException embedded as inner exception.
                throw new InvalidOperationException(EntityRes.GetString(EntityRes.IncompleteDatabaseCreation), e);
            }
            finally
            {
                // Close connection and cleanup objects.
                if (command != null)
                {
                    command.Dispose();
                }
                if (transaction != null)
                {
                    DbInterception.Dispatch.Transaction.Dispose(transaction, interceptionContext);
                }
                if (connection != null)
                {
                    DbInterception.Dispatch.Connection.Close(connection, interceptionContext);
                }
            }
        }
Ejemplo n.º 29
0
        internal virtual void ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(transaction);
            DebugCheck.NotNull(migrationStatement);

            _this.ExecuteSql(transaction, migrationStatement, interceptionContext);
        }
Ejemplo n.º 30
0
 public override void OnDeleted(DbCommand command, DbInterceptionContext interceptionContext)
 {
     DeletedCalled  = true;
     DeletedCommand = command;
     DeletedContext = interceptionContext;
 }
Ejemplo n.º 31
0
 public override void OnUpdated(DbCommand command, DbInterceptionContext interceptionContext)
 {
     UpdatedCalled  = true;
     UpdatedCommand = command;
     UpdatedContext = interceptionContext;
 }
Ejemplo n.º 32
0
 public override void OnInserted(DbCommand command, DbInterceptionContext interceptionContext)
 {
     InsertedCalled  = true;
     InsertedCommand = command;
     InsertedContext = interceptionContext;
 }
Ejemplo n.º 33
0
        private InterceptableDbCommand ConfigureCommand(DbCommand command, string commandText, DbInterceptionContext interceptionContext)
        {
            command.CommandText = commandText;

            if (_configuration.CommandTimeout.HasValue)
            {
                command.CommandTimeout = _configuration.CommandTimeout.Value;
            }

            return new InterceptableDbCommand(command, interceptionContext);
        }
Ejemplo n.º 34
0
 public override void OnNonQueryExecuted(DbCommand command, DbInterceptionContext interceptionContext)
 {
     NonQueryExecutedCalled  = true;
     NonQueryExecutedCommand = command;
     NonQueryExecutedContext = interceptionContext;
 }
Ejemplo n.º 35
0
        internal override void ExecuteSql(
            DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(transaction);
            DebugCheck.NotNull(migrationStatement);

            if (string.IsNullOrWhiteSpace(migrationStatement.Sql))
            {
                return;
            }

            if (!migrationStatement.SuppressTransaction)
            {
                var dbCommand = DbInterception.Dispatch.Transaction.GetConnection(transaction, interceptionContext).CreateCommand();
                using (var command = ConfigureCommand(dbCommand, migrationStatement.Sql, interceptionContext))
                {
                    command.Transaction = transaction;

                    command.ExecuteNonQuery();
                }
            }
            else
            {
                DbConnection connection = null;
                try
                {
                    connection = CreateConnection();
                    var dbCommand = connection.CreateCommand();
                    using (var command = ConfigureCommand(dbCommand, migrationStatement.Sql, interceptionContext))
                    {
                        DbInterception.Dispatch.Connection.Open(connection, interceptionContext);

                        command.ExecuteNonQuery();
                    }
                }
                finally
                {
                    if (connection != null)
                    {
                        DbInterception.Dispatch.Connection.Dispose(connection, interceptionContext);
                    }
                }
            }
        }
        internal DbCommandDefinition CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(commandTree);
            DebugCheck.NotNull(interceptionContext);

            ValidateDataSpace(commandTree);

            var storeMetadata = (StoreItemCollection)commandTree.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

            Debug.Assert(
                storeMetadata.StoreProviderManifest != null,
                "StoreItemCollection has null StoreProviderManifest?");

            commandTree = _treeDispatcher.Created(commandTree, interceptionContext);

            return(CreateDbCommandDefinition(storeMetadata.StoreProviderManifest, commandTree));
        }
Ejemplo n.º 37
0
 internal virtual DbCommandDefinition CreateDbCommandDefinition(
     DbProviderManifest providerManifest,
     DbCommandTree commandTree,
     DbInterceptionContext interceptionContext)
 {
     return CreateDbCommandDefinition(providerManifest, commandTree);
 }
 private bool ShouldLog(DbInterceptionContext interceptionContext)
 {
     return(_context == null || interceptionContext.DbContexts.Contains(_context));
 }
        internal EntityCommandDefinition(
            DbProviderFactory storeProviderFactory,
            DbCommandTree commandTree,
            DbInterceptionContext interceptionContext,
            IDbDependencyResolver resolver = null,
            BridgeDataReaderFactory bridgeDataReaderFactory = null,
            ColumnMapFactory columnMapFactory = null)
        {
            DebugCheck.NotNull(storeProviderFactory);
            DebugCheck.NotNull(commandTree);
            DebugCheck.NotNull(interceptionContext);

            _bridgeDataReaderFactory = bridgeDataReaderFactory ?? new BridgeDataReaderFactory();
            _columnMapFactory        = columnMapFactory ?? new ColumnMapFactory();

            _storeProviderServices =
                (resolver != null
                     ? resolver.GetService <DbProviderServices>(storeProviderFactory.GetProviderInvariantName())
                     : null) ??
                storeProviderFactory.GetProviderServices();

            try
            {
                if (DbCommandTreeKind.Query
                    == commandTree.CommandTreeKind)
                {
                    // Next compile the plan for the command tree
                    var       mappedCommandList = new List <ProviderCommandInfo>();
                    ColumnMap columnMap;
                    int       columnCount;
                    PlanCompiler.Compile(commandTree, out mappedCommandList, out columnMap, out columnCount, out _entitySets);
                    _columnMapGenerators = new IColumnMapGenerator[] { new ConstantColumnMapGenerator(columnMap, columnCount) };
                    // Note: we presume that the first item in the ProviderCommandInfo is the root node;
                    Debug.Assert(mappedCommandList.Count > 0, "empty providerCommandInfo collection and no exception?");
                    // this shouldn't ever happen.

                    // Then, generate the store commands from the resulting command tree(s)
                    _mappedCommandDefinitions = new List <DbCommandDefinition>(mappedCommandList.Count);

                    _mappedCommandReturnTypes = new List <RowType>();
                    foreach (var providerCommandInfo in mappedCommandList)
                    {
                        var providerCommandDefinition = _storeProviderServices.CreateCommandDefinition(
                            providerCommandInfo.CommandTree, interceptionContext);
                        _mappedCommandReturnTypes.Add(this.GetRowTypeFromCommandTree(providerCommandInfo.CommandTree));

                        if (null == providerCommandDefinition)
                        {
                            throw new ProviderIncompatibleException(Strings.ProviderReturnedNullForCreateCommandDefinition);
                        }

                        _mappedCommandDefinitions.Add(providerCommandDefinition);
                    }
                }
                else
                {
                    Debug.Assert(
                        DbCommandTreeKind.Function == commandTree.CommandTreeKind, "only query and function command trees are supported");
                    var entityCommandTree = (DbFunctionCommandTree)commandTree;

                    // Retrieve mapping and metadata information for the function import.
                    var mapping = GetTargetFunctionMapping(entityCommandTree);
                    IList <FunctionParameter> returnParameters = entityCommandTree.EdmFunction.ReturnParameters;
                    var resultSetCount = returnParameters.Count > 1 ? returnParameters.Count : 1;
                    _columnMapGenerators = new IColumnMapGenerator[resultSetCount];
                    var storeResultType = DetermineStoreResultType(mapping, 0, out _columnMapGenerators[0]);
                    for (var i = 1; i < resultSetCount; i++)
                    {
                        DetermineStoreResultType(mapping, i, out _columnMapGenerators[i]);
                    }

                    // Copy over parameters (this happens through a more indirect route in the plan compiler, but
                    // it happens nonetheless)
                    var providerParameters = new List <KeyValuePair <string, TypeUsage> >();
                    foreach (var parameter in entityCommandTree.Parameters)
                    {
                        providerParameters.Add(parameter);
                    }

                    // Construct store command tree usage.
                    var providerCommandTree = new DbFunctionCommandTree(
                        entityCommandTree.MetadataWorkspace, DataSpace.SSpace,
                        mapping.TargetFunction, storeResultType, providerParameters);

                    var storeCommandDefinition = _storeProviderServices.CreateCommandDefinition(providerCommandTree);
                    _mappedCommandDefinitions = new List <DbCommandDefinition>(1)
                    {
                        storeCommandDefinition
                    };

                    var firstResultEntitySet = mapping.FunctionImport.EntitySets.FirstOrDefault();
                    if (firstResultEntitySet != null)
                    {
                        _entitySets = new Set <EntitySet>();
                        _entitySets.Add(mapping.FunctionImport.EntitySets.FirstOrDefault());
                        _entitySets.MakeReadOnly();
                    }
                }

                // Finally, build a list of the parameters that the resulting command should have;
                var parameterList = new List <EntityParameter>();

                foreach (var queryParameter in commandTree.Parameters)
                {
                    var parameter = CreateEntityParameterFromQueryParameter(queryParameter);
                    parameterList.Add(parameter);
                }

                _parameters = new ReadOnlyCollection <EntityParameter>(parameterList);
            }
            catch (EntityCommandCompilationException)
            {
                // No need to re-wrap EntityCommandCompilationException
                throw;
            }
            catch (Exception e)
            {
                // we should not be wrapping all exceptions
                if (e.IsCatchableExceptionType())
                {
                    // we don't wan't folks to have to know all the various types of exceptions that can
                    // occur, so we just rethrow a CommandDefinitionException and make whatever we caught
                    // the inner exception of it.
                    throw new EntityCommandCompilationException(Strings.EntityClient_CommandDefinitionPreparationFailed, e);
                }

                throw;
            }
        }
                public override void ReaderExecuting(DbCommand command, CommandBehavior behavior, DbInterceptionContext interceptionContext)
                {
                    Commands.Add(command);

                    Assert.Empty(interceptionContext.DbContexts);
                    Assert.Empty(interceptionContext.ObjectContexts);
                }
Ejemplo n.º 41
0
 private bool ShouldLog(DbInterceptionContext interceptionContext)
 {
     return _context == null || interceptionContext.DbContexts.Contains(_context);
 }
Ejemplo n.º 42
0
        private void ExecuteStatementsInternal(IEnumerable<MigrationStatement> migrationStatements, DbConnection connection)
        {
            DebugCheck.NotNull(migrationStatements);
            DebugCheck.NotNull(connection);

            var context = _usersContext ?? _usersContextInfo.CreateInstance();

            var interceptionContext = new DbInterceptionContext();
            interceptionContext = interceptionContext.WithDbContext(context);

            TransactionHandler transactionHandler = null;
            try
            {
                if (DbInterception.Dispatch.Connection.GetState(connection, interceptionContext) == ConnectionState.Broken)
                {
                    DbInterception.Dispatch.Connection.Close(connection, interceptionContext);
                }

                if (DbInterception.Dispatch.Connection.GetState(connection, interceptionContext) == ConnectionState.Closed)
                {
                    DbInterception.Dispatch.Connection.Open(connection, interceptionContext);
                }

                if (!(context is TransactionContext))
                {
                    var providerInvariantName =
                        DbConfiguration.DependencyResolver.GetService<IProviderInvariantName>(
                            DbProviderServices.GetProviderFactory(connection))
                            .Name;

                    var dataSource = DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext);

                    var transactionHandlerFactory = DbConfiguration.DependencyResolver.GetService<Func<TransactionHandler>>(
                        new ExecutionStrategyKey(providerInvariantName, dataSource));

                    if (transactionHandlerFactory != null)
                    {
                        transactionHandler = transactionHandlerFactory();
                        transactionHandler.Initialize(context, connection);
                    }
                }

                ExecuteStatementsInternal(migrationStatements, connection, interceptionContext);

                _committedStatements = true;
            }
            finally
            {
                if (transactionHandler != null)
                {
                    transactionHandler.Dispose();
                }

                if (_usersContext == null)
                {
                    context.Dispose();
                }
            }
        }
Ejemplo n.º 43
0
 // <summary>
 // Constructs a new EntityCommand given a EntityConnection and an EntityCommandDefition. This
 // constructor is used by ObjectQueryExecution plan to execute an ObjectQuery.
 // </summary>
 // <param name="connection"> The connection against which this EntityCommand should execute </param>
 // <param name="entityCommandDefinition"> The prepared command definition that can be executed using this EntityCommand </param>
 internal EntityCommand(
     EntityConnection connection, EntityCommandDefinition entityCommandDefinition, DbInterceptionContext context, EntityDataReaderFactory factory = null)
     : this(entityCommandDefinition, context, factory)
 {
     _connection = connection;
 }
Ejemplo n.º 44
0
        private void ExecuteStatementsInternal(
            IEnumerable<MigrationStatement> migrationStatements,
            DbConnection connection,
            DbTransaction transaction,
            DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(migrationStatements);
            DebugCheck.NotNull(connection);

            foreach (var migrationStatement in migrationStatements)
            {
                base.ExecuteSql(migrationStatement, connection, transaction, interceptionContext);
            }
        }
Ejemplo n.º 45
0
 internal EntityCommand(DbInterceptionContext interceptionContext)
     : this(interceptionContext, new EntityDataReaderFactory())
 {
 }
Ejemplo n.º 46
0
        private void ExecuteStatementsWithinTransaction(
            IEnumerable<MigrationStatement> migrationStatements, DbTransaction transaction,
            DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(migrationStatements);
            DebugCheck.NotNull(transaction);

            var connection = DbInterception.Dispatch.Transaction.GetConnection(transaction, interceptionContext);

            ExecuteStatementsInternal(migrationStatements, connection, transaction, interceptionContext);
        }
Ejemplo n.º 47
0
        private static void UsingConnection(DbConnection sqlConnection, Action<DbConnection> act)
        {
            var interceptionContext = new DbInterceptionContext();
            // remember the connection string so that we can reset if credentials are wiped
            var holdConnectionString = DbInterception.Dispatch.Connection.GetConnectionString(sqlConnection, interceptionContext);

            GetExecutionStrategy(sqlConnection, ProviderInvariantName).Execute(
                () =>
                {
                    var openingConnection = DbInterception.Dispatch.Connection.GetState(sqlConnection, interceptionContext)
                                            == ConnectionState.Closed;
                    if (openingConnection)
                    {
                        // If Open() fails the original credentials need to be restored before retrying
                        if (DbInterception.Dispatch.Connection.GetState(sqlConnection, new DbInterceptionContext())
                            == ConnectionState.Closed
                            && !DbInterception.Dispatch.Connection.GetConnectionString(sqlConnection, interceptionContext)
                                .Equals(holdConnectionString, StringComparison.Ordinal))
                        {
                            DbInterception.Dispatch.Connection.SetConnectionString(
                                sqlConnection,
                                new DbConnectionPropertyInterceptionContext<string>().WithValue(holdConnectionString));
                        }

                        DbInterception.Dispatch.Connection.Open(sqlConnection, interceptionContext);
                    }
                    try
                    {
                        act(sqlConnection);
                    }
                    finally
                    {
                        if (openingConnection
                            && DbInterception.Dispatch.Connection.GetState(sqlConnection, interceptionContext) == ConnectionState.Open)
                        {
                            // if we opened the connection, we should close it
                            DbInterception.Dispatch.Connection.Close(sqlConnection, interceptionContext);

                            // Can only change the connection string if the connection is closed
                            if (!DbInterception.Dispatch.Connection.GetConnectionString(sqlConnection, interceptionContext)
                                .Equals(holdConnectionString, StringComparison.Ordinal))
                            {
                                DbInterception.Dispatch.Connection.SetConnectionString(
                                    sqlConnection,
                                    new DbConnectionPropertyInterceptionContext<string>().WithValue(holdConnectionString));
                            }
                        }
                    }
                });
        }
Ejemplo n.º 48
0
        internal override void ExecuteSql(
            MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction,
            DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(migrationStatement);
            DebugCheck.NotNull(connection);

            if (string.IsNullOrWhiteSpace(migrationStatement.Sql))
            {
                return;
            }

            var dbCommand = connection.CreateCommand();

            using (var command = ConfigureCommand(dbCommand, migrationStatement.Sql, interceptionContext))
            {
                if (transaction != null)
                {
                    command.Transaction = transaction;
                }

                command.ExecuteNonQuery();
            }
        }
Ejemplo n.º 49
0
 internal EntityCommand(string statement, DbInterceptionContext context, EntityDataReaderFactory factory)
     : this(context, factory)
 {
     _esqlCommandText = statement;
 }
Ejemplo n.º 50
0
        internal void ExecuteStatements(IEnumerable<MigrationStatement> migrationStatements, DbTransaction existingTransaction)
        {
            DebugCheck.NotNull(migrationStatements);

            DbConnection connection = null;
            try
            {
                if (existingTransaction != null)
                {
                    var interceptionContext = new DbInterceptionContext();
                    interceptionContext = interceptionContext.WithDbContext(_usersContext);
                    ExecuteStatementsWithinTransaction(migrationStatements, existingTransaction, interceptionContext);
                }
                else
                {
                    connection = CreateConnection();
                    DbProviderServices.GetExecutionStrategy(connection).Execute(
                        () => ExecuteStatementsInternal(migrationStatements, connection));
                }
            }
            finally
            {
                if (connection != null)
                {
                    DbInterception.Dispatch.Connection.Dispose(connection, new DbInterceptionContext());
                }
            }
        }
Ejemplo n.º 51
0
        internal DbCommandDefinition CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext)
        {
            DebugCheck.NotNull(commandTree);
            DebugCheck.NotNull(interceptionContext);

            ValidateDataSpace(commandTree);

            var storeMetadata = (StoreItemCollection)commandTree.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

            Debug.Assert(
                storeMetadata.ProviderManifest != null,
                "StoreItemCollection has null ProviderManifest?");

            commandTree = _treeDispatcher.Value.Created(commandTree, interceptionContext);

            return CreateDbCommandDefinition(storeMetadata.ProviderManifest, commandTree, interceptionContext);
        }
Ejemplo n.º 52
0
 public bool ConnectionOpening(EntityConnection connection, DbInterceptionContext interceptionContext)
 {
     return !interceptionContext.DbContexts.Contains(_context, ReferenceEquals);
 }
Ejemplo n.º 53
0
        /// <summary>
        /// Checks whether the supplied interception context contains the target context
        /// or the supplied connection is the same as the one used by the target context.
        /// </summary>
        /// <param name="connection">A connection.</param>
        /// <param name="interceptionContext">An interception context.</param>
        /// <returns>
        /// <c>true</c> if the supplied interception context contains the target context or
        /// the supplied connection is the same as the one used by the target context if
        /// the supplied interception context doesn't contain any contexts; <c>false</c> otherwise.
        /// </returns>
        /// <remarks>
        /// Note that calling this method will trigger initialization of any DbContext referenced from the <paramref name="interceptionContext"/>
        /// </remarks>
        protected internal virtual bool MatchesParentContext(DbConnection connection, DbInterceptionContext interceptionContext)
        {
            Check.NotNull(connection, "connection");
            Check.NotNull(interceptionContext, "interceptionContext");

            if (DbContext != null
                && interceptionContext.DbContexts.Contains(DbContext, ReferenceEquals))
            {
                return true;
            }

            if (ObjectContext != null
                && interceptionContext.ObjectContexts.Contains(ObjectContext, ReferenceEquals))
            {
                return true;
            }

            if (Connection != null
                && !interceptionContext.ObjectContexts.Any()
                && !interceptionContext.DbContexts.Any())
            {
                return ReferenceEquals(connection, Connection);
            }

            return false;
        }