Beispiel #1
0
        public void StartListener()
        {
            isStopped = false;
            IntPtr context;

            Interception.Stroke stroke = new Interception.Stroke();
            context = Interception.interception_create_context();
            int device;

            Interception.InterceptionPredicate del = Interception.interception_is_keyboard;
            Interception.interception_set_filter(
                context,
                del,
                (ushort)Interception.FilterKeyState.KeyDown);
            while (!isStopped) //Start listening for keyboard strokes
            {
                Interception.interception_receive(context, device = Interception.interception_wait(context), ref stroke, 1);
                Interception.KeyStroke kstroke = stroke;
                byte[] strokeBytes             = Interception.getBytes(kstroke);
                Interception.interception_send(context, device, strokeBytes, 1);
                if (kstroke.code == pauseKey)
                {
                    OnPauseKeyPressed(); //If the registered key matches the pause key invoke the pausekey event
                }
                if (kstroke.code == stopKey)
                {
                    OnStopKeyPressed();
                }
            }
            Interception.interception_destroy_context(context);
        }
        private async Task <CodeResult> ExecuteInternally()
        {
            CodeResult result = null;

            // Preprocess this code
            if (!Flags.HasFlag(CodeFlags.IsPreProcessed))
            {
                result = await Interception.Intercept(this, InterceptionMode.Pre);

                Flags |= CodeFlags.IsPreProcessed;

                if (result != null)
                {
                    InternallyExecuted = true;
                    return(await OnCodeExecuted(result));
                }
            }

            // Attempt to process the code internally
            switch (Type)
            {
            case CodeType.GCode:
                result = await GCodes.Process(this);

                break;

            case CodeType.MCode:
                result = await MCodes.Process(this);

                break;

            case CodeType.TCode:
                result = await TCodes.Process(this);

                break;
            }

            if (result != null)
            {
                InternallyExecuted = true;
                return(await OnCodeExecuted(result));
            }

            // If the could not be interpreted, post-process it
            if (!Flags.HasFlag(CodeFlags.IsPostProcessed))
            {
                result = await Interception.Intercept(this, InterceptionMode.Post);

                Flags |= CodeFlags.IsPostProcessed;

                if (result != null)
                {
                    InternallyExecuted = true;
                    return(await OnCodeExecuted(result));
                }
            }

            // Code has not been interpreted yet
            return(null);
        }
Beispiel #3
0
            public void DbDeleteDatabase_dispatches_commands_to_interceptors_for_connections_with_initial_catalog()
            {
                using (var context = new DdlDatabaseContext())
                {
                    context.Database.CreateIfNotExists();
                }

                var interceptor = new TestNonQueryInterceptor();

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

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

                Assert.Equal(
                    "drop database [System.Data.Entity.SqlServer.SqlProviderServicesTests+DdlDatabaseContext]",
                    interceptor.Commands.Select(c => c.CommandText).Single());
            }
Beispiel #4
0
            public void DbCreateDatabase_dispatches_commands_to_interceptors()
            {
                using (var context = new DdlDatabaseContext(SimpleCeConnection <DdlDatabaseContext>()))
                {
                    var storeItemCollection =
                        (StoreItemCollection)
                        ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

                    context.Database.Delete();

                    var interceptor = new TestNonQueryInterceptor();
                    Interception.AddInterceptor(interceptor);
                    try
                    {
                        SqlCeProviderServices.Instance.CreateDatabase(context.Database.Connection, null, storeItemCollection);
                    }
                    finally
                    {
                        Interception.RemoveInterceptor(interceptor);
                    }

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

                    Assert.True(interceptor.CommandTexts.Any(t => t.StartsWith("CREATE TABLE \"Products\" ")));
                    Assert.True(interceptor.CommandTexts.Any(t => t.StartsWith("CREATE TABLE \"Categories\" ")));
                    Assert.True(interceptor.CommandTexts.Any(t => t.StartsWith("ALTER TABLE \"Products\" ADD CONSTRAINT ")));
                }
            }
Beispiel #5
0
            public void DbCreateDatabase_dispatches_commands_to_interceptors()
            {
                using (var context = new DdlDatabaseContext())
                {
                    var storeItemCollection =
                        (StoreItemCollection)
                        ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.SSpace);

                    context.Database.Delete();

                    var interceptor = new TestNonQueryInterceptor();
                    Interception.AddInterceptor(interceptor);
                    try
                    {
                        SqlProviderServices.Instance.CreateDatabase(context.Database.Connection, null, storeItemCollection);
                    }
                    finally
                    {
                        Interception.RemoveInterceptor(interceptor);
                    }

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

                    var commandTexts = interceptor.Commands.Select(c => c.CommandText);
                    Assert.True(commandTexts.Any(t => t.StartsWith("create database ")));
                    Assert.True(commandTexts.Any(t => t.StartsWith("if serverproperty('EngineEdition') <> 5 execute sp_executesql ")));
                    Assert.True(commandTexts.Any(t => t.StartsWith("create table [dbo].[Categories] ")));
                }
            }
Beispiel #6
0
            public void DbDatabaseExists_dispatches_commands_to_interceptors_for_connections_with_no_initial_catalog()
            {
                var interceptor = new TestScalarInterceptor();

                Interception.AddInterceptor(interceptor);
                try
                {
                    using (var connection =
                               new SqlConnection(ModelHelpers.SimpleAttachConnectionString("I.Do.Not.Exist", useInitialCatalog: false)))
                    {
                        SqlProviderServices.Instance.DatabaseExists(connection, null, new StoreItemCollection());
                    }
                }
                finally
                {
                    Interception.RemoveInterceptor(interceptor);
                }

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

                Assert.True(
                    interceptor.Commands.Select(c => c.CommandText)
                    .Single()
                    .StartsWith("SELECT Count(*) FROM sys.master_files WHERE [physical_name]=N'"));
            }
Beispiel #7
0
        public object Interceptor(Interception details)
        {
            MethodInfo interceptorT = GetType().GetMethod("TypedInterceptor");
            MethodInfo interceptor  = interceptorT.MakeGenericMethod(details.Method.ReturnType.GenericTypeArguments[0]);

            return(interceptor.Invoke(this, new object[] { details }));
        }
Beispiel #8
0
        public void BasicBeforeOverridenMethodStateful()
        {
            lock (Interception.Handle)
            {
                var _method = Metadata <Overriden> .Method(_Overriden => _Overriden.Method(Argument <int> .Value, Argument <int> .Value));

                var _instance = new Overriden();
                Interception.Initialize();
                _instance.Method(2, 3);
                Assert.AreEqual(Interception.Done, false);
                Aspect.Weave <Before.Interceptor.Parameterized>(_method);
                Interception.Initialize();
                var _return = _instance.Method(2, 3);
                Assert.AreEqual(_return, 1);
                Assert.AreEqual(Interception.Done, true);
                Assert.AreEqual(Interception.Instance, _instance);
                Assert.AreEqual(Interception.Arguments.Length, 2);
                Assert.AreEqual(Interception.Arguments[0], 2);
                Assert.AreEqual(Interception.Arguments[1], 3);
                Aspect.Release <Before.Interceptor.Parameterized>(_method);
                Interception.Initialize();
                _instance.Method(2, 3);
                Assert.AreEqual(Interception.Done, false);
            }
        }
        public TDelegate Build()
        {
            var parameterTypesForCache = _explicitParameterTypes;

            if (parameterTypesForCache == null)
            {
                parameterTypesForCache = Interception.ParamsToTypes(_parameters);
            }

            var cacheKey = new Key(
                callingModule: _resolutionModule,
                mdToken: _mdToken,
                callOpCode: _opCode,
                concreteType: _concreteType,
                explicitParameterTypes: parameterTypesForCache,
                methodGenerics: _methodGenerics,
                declaringTypeGenerics: _declaringTypeGenerics);

            return(Cache.GetOrAdd(cacheKey, key =>
            {
                // Validate requirements at the last possible moment
                // Don't do more than needed before checking the cache
                ValidateRequirements();
                return EmitDelegate();
            }));
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            // 這裡將會建立 DI 容器
            IUnityContainer container = new UnityContainer();

            var fooInterception = new Interception();

            container.AddExtension(fooInterception);

            // 進行抽象型別與具體實作類別的註冊
            // 在進行註冊抽象與具體實作類別的時候,我們需要進行攔截行為的設定,告知要啟用 Unity 攔截功能
            container.RegisterType <IMessage, ConsoleMessage>(
                new Interceptor <InterfaceInterceptor>(),
                new InterceptionBehavior <AppLog>(),
                new InterceptionBehavior <VirtualLog>());

            // 進行抽象型別的具體實作物件的解析
            IMessage message = container.Resolve <IMessage>();

            Console.WriteLine($"{Environment.NewLine}呼叫 IMessage.Write");

            // 執行取得物件的方法
            message.Write("Hi Vulcan");
            Console.WriteLine($"{Environment.NewLine}呼叫 IMessage.Empty");
            message.Empty();

            Console.WriteLine("Press any key for continuing...");
            Console.ReadKey();
        }
Beispiel #11
0
        public void AnyModelTableExists_dispatches_to_interceptors()
        {
            var connectionMock = new Mock <DbConnection>
            {
                CallBase = true
            };
            var internalContextMock = new Mock <InternalContext>();
            var dbCommandMock       = new Mock <DbCommand>();

            SetupMocksForTableChecking(dbCommandMock, connectionMock, internalContextMock);

            var interceptorMock = new Mock <DbInterceptor>
            {
                CallBase = true
            };

            Interception.AddInterceptor(interceptorMock.Object);
            try
            {
                new DatabaseTableChecker().AnyModelTableExists(new FakeContext(connectionMock.Object, internalContextMock.Object));
            }
            finally
            {
                Interception.RemoveInterceptor(interceptorMock.Object);
            }

            interceptorMock.Verify(
                m => m.ReaderExecuting(
                    dbCommandMock.Object, CommandBehavior.Default,
                    It.Is <DbInterceptionContext>(c => c.ObjectContexts.Contains(internalContextMock.Object.ObjectContext))));
        }
Beispiel #12
0
 public IEnumerable <IAdvice> Advise(MethodBase method)
 {
     yield return(Advice.Basic.Before(() =>
     {
         Interception.Sequence();
         Interception.Done = true;
     }));
 }
 static H容器()
 {
     _IUnityContainer  = new UnityContainer();
     _Interception     = _IUnityContainer.AddNewExtension <Interception>().Configure <Interception>();
     _PolicyDefinition = _Interception.AddPolicy("MyPolicy");
     _PolicyDefinition.AddMatchingRule <AlwaysMatchingRule>();
     _PolicyDefinition.AddCallHandler <LoggerCallHandler>(new ContainerControlledLifetimeManager());
 }
Beispiel #14
0
        private async Task <bool> ProcessInternally()
        {
            // Pre-process this code
            if (!Flags.HasFlag(CodeFlags.IsPreProcessed))
            {
                bool intercepted = await Interception.Intercept(this, InterceptionMode.Pre);

                Flags |= CodeFlags.IsPreProcessed;

                if (intercepted)
                {
                    InternallyProcessed = true;
                    return(true);
                }
            }

            // Attempt to process the code internally
            switch (Type)
            {
            case CodeType.GCode:
                Result = await GCodes.Process(this);

                break;

            case CodeType.MCode:
                Result = await MCodes.Process(this);

                break;

            case CodeType.TCode:
                Result = await TCodes.Process(this);

                break;
            }

            if (Result != null)
            {
                InternallyProcessed = true;
                return(true);
            }

            // If the code could not be interpreted internally, post-process it
            if (!Flags.HasFlag(CodeFlags.IsPostProcessed))
            {
                bool intercepted = await Interception.Intercept(this, InterceptionMode.Post);

                Flags |= CodeFlags.IsPostProcessed;

                if (intercepted)
                {
                    InternallyProcessed = true;
                    return(true);
                }
            }

            // Code has not been interpreted yet - let RRF deal with it
            return(false);
        }
        public void ExecuteSql_with_transactions_suppressed_dispatches_commands_to_interceptors()
        {
            var mockCommand = new Mock <DbCommand>();

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

            var mockConnection = new Mock <DbConnection>();

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

            var mockTransaction = new Mock <DbTransaction>();

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

            var mockFactory = new Mock <DbProviderFactory>();

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

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

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

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

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

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

            Interception.AddInterceptor(mockInterceptor.Object);

            try
            {
                migrator.ExecuteSql(mockTransaction.Object, statement);
            }
            finally
            {
                Interception.RemoveInterceptor(mockInterceptor.Object);
            }

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

            mockInterceptor.Verify(m => m.NonQueryExecuted(
                                       mockCommand.Object,
                                       2013,
                                       It.Is <DbInterceptionContext>(c => c.DbContexts.Contains(context))));
        }
Beispiel #16
0
        public MethodBuilder <TDelegate> WithParameters(params object[] parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException(nameof(parameters));
            }

            return(WithParameters(Interception.ParamsToTypes(parameters)));
        }
Beispiel #17
0
 public static void KeyUp(DeviceID deviceID, params Key[] keys)
 {
     foreach (Key key in keys)
     {
         Interception.Stroke stroke = new Interception.Stroke();
         stroke.Key = ToKeyStroke(key, false);
         Interception.Send(context, deviceID, ref stroke, 1);
     }
 }
Beispiel #18
0
 public IEnumerable <IAdvice> Advise(MethodBase method)
 {
     yield return(Advice.Basic.Before((_Instance, _Arguments) =>
     {
         Interception.Sequence();
         Interception.Done = true;
         Interception.Instance = _Instance;
         Interception.Arguments = _Arguments;
     }));
 }
Beispiel #19
0
        private async Task CodeExecuted()
        {
            // Start the next code if that hasn't happened yet
            StartNextCode();

            if (Result != null)
            {
                // Process the code result
                switch (Type)
                {
                case CodeType.GCode:
                    await GCodes.CodeExecuted(this);

                    break;

                case CodeType.MCode:
                    await MCodes.CodeExecuted(this);

                    break;

                case CodeType.TCode:
                    await TCodes.CodeExecuted(this);

                    break;
                }

                // RepRapFirmware generally prefixes error messages with the code itself.
                // Do this only for error messages that originate either from a print or from a macro file
                if (Flags.HasFlag(CodeFlags.IsFromMacro) || Channel == CodeChannel.File)
                {
                    foreach (Message msg in Result)
                    {
                        if (msg.Type == MessageType.Error)
                        {
                            msg.Content = ToShortString() + ": " + msg.Content;
                        }
                    }
                }

                // Log warning and error replies after the code has been processed internally
                if (InternallyProcessed)
                {
                    foreach (Message msg in Result)
                    {
                        if (msg.Type != MessageType.Success && Channel != CodeChannel.File)
                        {
                            await Utility.Logger.Log(msg);
                        }
                    }
                }
            }

            // Done
            await Interception.Intercept(this, InterceptionMode.Executed);
        }
        public void Async_commands_that_are_canceled_are_still_intercepted()
        {
            var logger = new CommandLogger();

            Interception.AddInterceptor(logger);

            var cancellation      = new CancellationTokenSource();
            var cancellationToken = cancellation.Token;

            try
            {
                using (var context = new BlogContextNoInit())
                {
                    context.Database.Connection.Open();

                    cancellation.Cancel();

                    var command = context.Database.ExecuteSqlCommandAsync("update Blogs set Title = 'No' where Id = -1", cancellationToken);

                    try
                    {
                        command.Wait();
                    }
                    catch (AggregateException)
                    {
                        // Ignore
                    }

                    Assert.True(command.IsCanceled);

                    context.Database.Connection.Close();
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

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

            var executingLog = logger.Log[0];

            Assert.Equal(CommandMethod.NonQueryExecuting, executingLog.Method);
            Assert.True(executingLog.IsAsync);
            Assert.Null(executingLog.Result);
            Assert.Null(executingLog.Exception);

            var executedLog = logger.Log[1];

            Assert.Equal(CommandMethod.NonQueryExecuted, executedLog.Method);
            Assert.True(executedLog.IsAsync);
            Assert.Equal(0, executedLog.Result);
            Assert.Null(executedLog.Exception);
            Assert.True(executedLog.TaskStatus.HasFlag(TaskStatus.Canceled));
        }
Beispiel #21
0
        public object TypedInterceptor <T>(Interception details)
        {
            T result = default(T);

            Task task = dataStore.RunTransaction(async() =>
            {
                result = await(Task <T>) details.Invoke(details.Target, details.Args);
            });

            return(task.ContinueWith(_ => result));
        }
Beispiel #22
0
        public void AddInterceptor(string policy, IMatchingRule matchingRule, params Type[] classTypes)
        {
            Interception interception = uContainer.Configure <Interception>();

            foreach (Type classType in classTypes)
            {
                interception = interception.SetInterceptorFor(classType, new VirtualMethodInterceptor());
            }
            interception.AddPolicy(policy)
            .AddMatchingRule(matchingRule);
        }
        /// <summary>
        /// Create a task that waits until this code can be executed.
        /// It may be cancelled if this code is supposed to be cancelled before it is started
        /// </summary>
        /// <returns>Lock to maintain while the code is being executed internally</returns>
        /// <exception cref="OperationCanceledException">Code has been cancelled</exception>
        private Task <IDisposable> WaitForExecution()
        {
            // Get a cancellation token
            lock (_cancellationTokenSources)
            {
                CancellationToken = _cancellationTokenSources[(int)Channel].Token;
            }

            // Codes from interceptors do not have any order control to avoid deadlocks
            Code codeBeingIntercepted = Interception.GetCodeBeingIntercepted(SourceConnection);

            if (codeBeingIntercepted != null)
            {
                if (codeBeingIntercepted.Flags.HasFlag(CodeFlags.IsFromMacro))
                {
                    Flags |= CodeFlags.IsFromMacro;
                    File   = codeBeingIntercepted.File;
                    Macro  = codeBeingIntercepted.Macro;
                }
                return(Task.FromResult <IDisposable>(null));
            }

            // Wait for pending high priority codes
            if (Flags.HasFlag(CodeFlags.IsPrioritized))
            {
                _codeType = InternalCodeType.Prioritized;
                _logger.Debug("Waiting for execution of {0} (prioritized)", this);
                return(_codeStartLocks[(int)Channel, (int)InternalCodeType.Prioritized].LockAsync(CancellationToken));
            }

            // Wait for pending codes from the current macro
            if (Flags.HasFlag(CodeFlags.IsFromMacro))
            {
                _codeType = InternalCodeType.Macro;
                _logger.Debug("Waiting for execution of {0} (macro code)", this);
                return((Macro == null) ? _codeStartLocks[(int)Channel, (int)InternalCodeType.Macro].LockAsync(CancellationToken) : Macro.WaitForCodeStart());
            }

            // Wait for pending codes for message acknowledgements
            // FIXME M0/M1 are not meant to be used while a message box is open
            if (!Flags.HasFlag(CodeFlags.IsFromFirmware) && Interface.IsWaitingForAcknowledgement(Channel) &&
                (Type != CodeType.MCode || (MajorNumber != 0 && MajorNumber != 1)))
            {
                _codeType = InternalCodeType.Acknowledgement;
                _logger.Debug("Waiting for execution of {0} (acknowledgement)", this);
                return(_codeStartLocks[(int)Channel, (int)InternalCodeType.Acknowledgement].LockAsync(CancellationToken));
            }

            // Wait for pending regular codes
            _codeType = InternalCodeType.Regular;
            _logger.Debug("Waiting for execution of {0}", this);
            return(_codeStartLocks[(int)Channel, (int)InternalCodeType.Regular].LockAsync(CancellationToken));
        }
Beispiel #24
0
    public static void Update()
    {
        // Повторяем цикл, пока есть необработанные нажатия
        while (true)
        {
            DeviceID deviceID = Interception.WaitWithTimeout(context, 0);
            if (deviceID == 0)
            {
                break;
            }

            currentDeviceID = deviceID;

            Interception.Stroke stroke = new Interception.Stroke();

            while (Interception.Receive(context, deviceID, ref stroke, 1) > 0)
            {
                Key key = ToKey(stroke.Key);

                if (showKeys)
                {
                    Console.WriteLine("Key: {0}; Scancode: 0x{1:X2}; State: {2}", key, stroke.Key.Code, stroke.Key.State);
                }

                bool processed;

                KeyList deviceDownedKeys = GetOrCreateKeyList(downedKeys, deviceID);

                if (stroke.Key.State.IsKeyDown())
                {
                    if (!deviceDownedKeys.Contains(key))
                    {
                        deviceDownedKeys.Add(key);
                        processed = OnKeyDown(key, false);
                    }
                    else
                    {
                        processed = OnKeyDown(key, true);
                    }
                }
                else
                {
                    deviceDownedKeys.Remove(key);
                    processed = OnKeyUp(key);
                }

                if (!processed)
                {
                    Interception.Send(context, deviceID, ref stroke, 1);
                }
            }
        }
    }
Beispiel #25
0
        public static void RegisterType(string assemblyName, Interception interception)
        {
            var types = Assembly.Load(assemblyName).GetTypes();

            foreach (var type in types)
            {
                var attrs = Attribute.GetCustomAttributes(type);
                foreach (var attr in attrs)
                {
                    if (attr is RegisterToContainerAttribute)
                    {
                        var attribute = attr as RegisterToContainerAttribute;
                        var baseTypes = new List <Type>();
                        if (attribute.RegisterType != null)
                        {
                            baseTypes.Add(attribute.RegisterType);
                        }
                        else if (type.GetInterfaces().Any())
                        {
                            baseTypes.AddRange(type.GetInterfaces());
                        }
                        if (type.BaseType != null && type.BaseType != typeof(Object))
                        {
                            var bt = type.BaseType;
                            while (bt.BaseType != null && bt.BaseType != typeof(Object))
                            {
                                bt = bt.BaseType;
                            }
                            baseTypes.Add(bt);
                        }
                        if (baseTypes.Count <= 0)
                        {
                            throw new FrameworkException(string.Format("类型\"{0}\"没有基类型", type));
                        }
                        foreach (var baseType in baseTypes)
                        {
                            if (string.IsNullOrEmpty(attribute.Name))
                            {
                                Current.RegisterType(baseType, type);
                            }
                            else
                            {
                                Current.RegisterType(baseType, type, attribute.Name);
                            }
                        }
                    }
                }
            }
        }
        public void Initialization_and_simple_query_and_update_commands_can_be_logged()
        {
            var logger = new CommandLogger();

            Interception.AddInterceptor(logger);

            try
            {
                using (var context = new BlogContextLogAll())
                {
                    BlogContext.DoStuff(context);
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

            var commandsUsed = new bool[Enum.GetValues(typeof(CommandMethod)).Length];

            for (var i = 0; i < logger.Log.Count; i++)
            {
                var method = logger.Log[i].Method;
                commandsUsed[(int)method] = true;

                if (method.ToString().EndsWith("Executing"))
                {
                    Assert.Equal(method + 1, logger.Log[i + 1].Method);
                    Assert.Same(logger.Log[i].Command, logger.Log[i + 1].Command);
                }
            }

            // Check that every type of command used has log entries
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.NonQueryExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ReaderExecuted]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuting]);
            Assert.True(commandsUsed[(int)CommandMethod.ScalarExecuted]);

            // Sanity check on command text
            var commandTexts = logger.Log.Select(l => l.CommandText.ToLowerInvariant());

            Assert.True(commandTexts.Any(c => c.StartsWith("select")));
            Assert.True(commandTexts.Any(c => c.StartsWith("create")));
            Assert.True(commandTexts.Any(c => c.StartsWith("alter")));
            Assert.True(commandTexts.Any(c => c.StartsWith("insert")));
        }
        public void Command_trees_for_initialization_and_simple_query_and_update_commands_can_be_logged()
        {
            // Make sure that HistoryContext has been used to ensure test runs consistently regardless of
            // whether or not other tests have run before it.
            using (var initContext = new BlogContextNoInit())
            {
                initContext.Database.Initialize(force: false);
            }

            var logger = new CommandTreeLogger();

            Interception.AddInterceptor(logger);

            BlogContextLogAll context;

            try
            {
                using (context = new BlogContextLogAll())
                {
                    BlogContext.DoStuff(context);
                }
            }
            finally
            {
                Interception.RemoveInterceptor(logger);
            }

            // Sanity check that we got tree creations logged
            Assert.True(logger.Log.OfType <DbQueryCommandTree>().Any(t => t.DataSpace == DataSpace.CSpace));
            Assert.True(logger.Log.OfType <DbQueryCommandTree>().Any(t => t.DataSpace == DataSpace.SSpace));
            Assert.True(logger.Log.OfType <DbInsertCommandTree>().Any(t => t.DataSpace == DataSpace.SSpace));
#if !NET40
            Assert.True(logger.Log.OfType <DbUpdateCommandTree>().Any(t => t.DataSpace == DataSpace.SSpace));

            Assert.True(
                logger.Log.OfType <DbUpdateCommandTree>()
                .Any(
                    t => t.SetClauses.OfType <DbSetClause>()
                    .Any(
                        c => ((DbPropertyExpression)c.Property).Property.Name == "Title" &&
                        (string)((DbConstantExpression)c.Value).Value == "I'm a logger and I'm okay...")));
#endif

            foreach (var interceptionContext in logger.LogWithContext.Select(t => t.Item2))
            {
                Assert.Contains(context, interceptionContext.DbContexts);
            }
        }
        /// <summary>
        /// Start the next available G/M/T-code and wait until this code may finish
        /// </summary>
        /// <returns>Awaitable disposable</returns>
        private AwaitableDisposable <IDisposable> WaitForFinish()
        {
            if (!Flags.HasFlag(CodeFlags.Unbuffered))
            {
                StartNextCode();
            }

            if (Interception.IsInterceptingConnection(SourceConnection))
            {
                return(new AwaitableDisposable <IDisposable>(Task.FromResult <IDisposable>(null)));
            }

            AwaitableDisposable <IDisposable> finishTask = (Macro == null) ? _codeFinishLocks[(int)Channel, (int)_codeType].LockAsync(CancellationToken) : Macro.WaitForCodeFinish();

            return(finishTask);
        }
Beispiel #29
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)))
                {
                    if (!SqlProviderServices.Instance.DatabaseExists(connection, null, storeItemCollection))
                    {
                        SqlProviderServices.Instance.CreateDatabase(connection, null, storeItemCollection);
                    }

                    var nonQueryInterceptor = new TestNonQueryInterceptor();
                    var readerInterceptor   = new TestReaderInterceptor();
                    Interception.AddInterceptor(nonQueryInterceptor);
                    Interception.AddInterceptor(readerInterceptor);
                    try
                    {
                        SqlProviderServices.Instance.DeleteDatabase(connection, null, storeItemCollection);
                    }
                    finally
                    {
                        Interception.RemoveInterceptor(nonQueryInterceptor);
                        Interception.RemoveInterceptor(readerInterceptor);
                    }

                    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 void Executes_reader_from_store_provider_command_and_returns_it()
            {
                var entityCommand = InitializeEntityCommand();

                var dbDataReader  = new Mock <DbDataReader>().Object;
                var dbCommandMock = new Mock <DbCommand>();

                dbCommandMock.Protected().Setup <DbDataReader>("ExecuteDbDataReader", It.IsAny <CommandBehavior>()).Returns(dbDataReader);
                var dbCommandDefinitionMock = new Mock <DbCommandDefinition>();

                dbCommandDefinitionMock.Setup(m => m.CreateCommand()).Returns(dbCommandMock.Object);
                var mappedCommandDefinitions = new List <DbCommandDefinition>
                {
                    dbCommandDefinitionMock.Object
                };

                var entityCommandDefinitionMock = new Mock <EntityCommandDefinition>(null, null, mappedCommandDefinitions)
                {
                    CallBase = true
                };

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

                Interception.AddInterceptor(mockInterceptor.Object);

                try
                {
                    Assert.Same(
                        dbDataReader, entityCommandDefinitionMock.Object.ExecuteStoreCommands(entityCommand, CommandBehavior.Default));
                }
                finally
                {
                    Interception.RemoveInterceptor(mockInterceptor.Object);
                }

                dbCommandMock.Protected().Verify("ExecuteDbDataReader", Times.Once(), CommandBehavior.Default);
                mockInterceptor.Verify(
                    m => m.ReaderExecuting(dbCommandMock.Object, CommandBehavior.Default, entityCommand.InterceptionContext));
                mockInterceptor.Verify(
                    m =>
                    m.ReaderExecuted(
                        dbCommandMock.Object, CommandBehavior.Default, It.IsAny <DbDataReader>(), entityCommand.InterceptionContext));
            }