Ejemplo n.º 1
0
        public async Task EnsurePropertExecutionOrder_2()
        {
            List<string> target = new List<string>();

            PipelineBuilder<ActionContextBase> builder = new PipelineBuilder<ActionContextBase>();
            PipelineResult<ActionContextBase> pipeline = builder.Use(
                async (next, ctxt) =>
                    {
                        await next(ctxt);
                        target.Add("third");

                    }).Use(async (next, ctxt) =>
                            {
                                target.Add("first");
                                await next(ctxt);
                                target.Add("second");

                            }).Build();

            await pipeline.Instance(new TestActionContext());

            Assert.Equal(3, target.Count);

            Assert.Equal("first", target[0]);
            Assert.Equal("second", target[1]);
            Assert.Equal("third", target[2]);
        }
 public void Handle(PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedEventArgsContract args)
 {
     DocumentOpenedEventArgsContractToViewAddInAdapter adaptedArgs;
     adaptedArgs = new DocumentOpenedEventArgsContractToViewAddInAdapter(args);
     object[] argsArray = new object[1];
     argsArray[0] = adaptedArgs;
     _event.Invoke(_view, argsArray);
 }
 public virtual void DocumentOpenedRemove(PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedHandlerContract handler)
 {
     System.EventHandler<PipelineBuilder.Samples.Events.DocumentOpenedEventArgs> adaptedHandler;
     if (DocumentOpened_handlers.TryGetValue(handler, out adaptedHandler)) {
         DocumentOpened_handlers.Remove(handler);
         _view.DocumentOpened -= adaptedHandler;
     }
 }
 internal virtual void Fire_DocumentOpened(PipelineBuilder.Samples.Events.DocumentOpenedEventArgs args)
 {
     if ((_DocumentOpened == null)) {
     }
     else {
         _DocumentOpened.Invoke(this, args);
     }
 }
 internal static PipelineBuilder.Samples.Events.Contracts.IAppObjectContract ViewToContractAdapter(PipelineBuilder.Samples.Events.IAppObject view)
 {
     if (view.GetType().Equals(typeof(IAppObjectContractToViewHostAdapter))) {
         return ((IAppObjectContractToViewHostAdapter)(view)).GetSourceContract();
     }
     else {
         return new IAppObjectViewToContractHostAdapter(view);
     }
 }
 internal static PipelineBuilder.Samples.Events.Contracts.ISampleAddInContract ViewToContractAdapter(PipelineBuilder.Samples.Events.ISampleAddIn view)
 {
     if (view.GetType().Equals(typeof(ISampleAddInContractToViewAddInAdapter))) {
         return ((ISampleAddInContractToViewAddInAdapter)(view)).GetSourceContract();
     }
     else {
         return new ISampleAddInViewToContractAddInAdapter(view);
     }
 }
 internal static PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedEventArgsContract ViewToContractAdapter(PipelineBuilder.Samples.Events.DocumentOpenedEventArgs view)
 {
     if (view.GetType().Equals(typeof(DocumentOpenedEventArgsContractToViewHostAdapter))) {
         return ((DocumentOpenedEventArgsContractToViewHostAdapter)(view)).GetSourceContract();
     }
     else {
         return new DocumentOpenedEventArgsViewToContractHostAdapter(view);
     }
 }
 internal static PipelineBuilder.Samples.Events.ISampleAddIn ContractToViewAdapter(PipelineBuilder.Samples.Events.Contracts.ISampleAddInContract contract)
 {
     if (((System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(contract) != true)
                 && contract.GetType().Equals(typeof(ISampleAddInViewToContractAddInAdapter)))) {
         return ((ISampleAddInViewToContractAddInAdapter)(contract)).GetSourceView();
     }
     else {
         return new ISampleAddInContractToViewAddInAdapter(contract);
     }
 }
 internal static PipelineBuilder.Samples.Events.DocumentOpenedEventArgs ContractToViewAdapter(PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedEventArgsContract contract)
 {
     if (((System.Runtime.Remoting.RemotingServices.IsObjectOutOfAppDomain(contract) != true)
                 && contract.GetType().Equals(typeof(DocumentOpenedEventArgsViewToContractHostAdapter)))) {
         return ((DocumentOpenedEventArgsViewToContractHostAdapter)(contract)).GetSourceView();
     }
     else {
         return new DocumentOpenedEventArgsContractToViewHostAdapter(contract);
     }
 }
Ejemplo n.º 10
0
        public IPipeline<ClientActionContext> CreatePipeline(Func<ActionDelegate<ClientActionContext>, ClientActionContext, Task> next = null)
        {
            PipelineBuilder<ClientActionContext> builder = new PipelineBuilder<ClientActionContext>();
            builder.Use(new SessionMiddleware(SessionHandler.Object, SessionErrorHandling.Object));
            if (next != null)
            {
                builder.Use(next);
            }

            return builder.Build();
        } 
Ejemplo n.º 11
0
        public IPipeline<ServerActionContext> Build()
        {
            PipelineBuilder<ServerActionContext> builder = new PipelineBuilder<ServerActionContext>();

            builder.Use(new HandleErrorMiddleware());
            builder.Use(new SerializationMiddleware());
            builder.Use(new InstanceProviderMiddleware());
            builder.Use(new ActionInvokerMiddleware());

            return builder.Build();
        }
Ejemplo n.º 12
0
        public IPipeline<ServerActionContext> Build(IEnumerable<IMiddleware<ServerActionContext>> middlewares)
        {
            if (middlewares == null) throw new ArgumentNullException(nameof(middlewares));

            PipelineBuilder<ServerActionContext> builder = new PipelineBuilder<ServerActionContext>();

            foreach (var middleware in middlewares)
            {
                builder.Use(middleware);
            }

            return builder.Build();
        }
Ejemplo n.º 13
0
        public override void Build(IConfiguration configuration)
        {
            var channel = configuration.Attributes["channel"];
            var uri = configuration.Attributes["uri"];
            var concurrency = configuration.Attributes["concurrency"];
            var frequency = configuration.Attributes["frequency"];
            var scheduled = configuration.Attributes["scheduled"];

            // build the pipeline for the receive port:
            var pipelineBuilder = new PipelineBuilder(this.Kernel, configuration);
            var pipeline = pipelineBuilder.BuildReceivePipeline();

            Port = this.CreatePort(pipeline, channel, uri, concurrency, frequency, scheduled);
        }
Ejemplo n.º 14
0
        public void Pipeline_ExecutionStatusNotification_Test()
        {
            //Arrange
            PipelineComponentResolver.Add(new FooComponent(), new BarExceptionComponent());

            var receiver = Substitute.For <IPipelineComponentExecutionStatusReceiver>();

            var sut = PipelineBuilder <TestPayload> .InitializePipeline(receiver)
                      .WithComponent <FooComponent>()
                      .WithComponent <BarExceptionComponent>()
                      .WithComponentResolver(PipelineComponentResolver)
                      .WithoutSettings()
                      .Build();

            //Act
            Action act = () => sut.Execute(new TestPayload());

            //Assert
            act.Should()
            .ThrowExactly <PipelineExecutionException>()
            .WithInnerExceptionExactly <NotImplementedException>();

            receiver.Received(2)
            .ReceiveExecutionStarting(Arg.Is <PipelineComponentExecutionStartingInfo>(info =>
                                                                                      info.PipelineComponentName == nameof(FooComponent) ||
                                                                                      info.PipelineComponentName == nameof(BarExceptionComponent)));

            receiver.Received()
            .ReceiveExecutionCompleted(
                Arg.Is <PipelineComponentExecutionCompletedInfo>(info =>
                                                                 info.PipelineComponentName == nameof(FooComponent) &&
                                                                 info.ExecutionTime != TimeSpan.Zero &&
                                                                 info.Exception == null));

            receiver.Received()
            .ReceiveExecutionCompleted(
                Arg.Is <PipelineComponentExecutionCompletedInfo>(info =>
                                                                 info.PipelineComponentName == nameof(BarExceptionComponent) &&
                                                                 info.ExecutionTime != TimeSpan.Zero &&
                                                                 info.Exception is NotImplementedException));
        }
Ejemplo n.º 15
0
        public void PipelineBuilder_BuildFromConfiguration_ServiceCollection()
        {
            var element = new ElementOptions()
            {
                BuilderName = "MultiplyByElementBuilder"
            };

            element.BuildParameters.Add("multiple", "3");

            // Create the configuration object.
            PipelineOptions opts = new PipelineOptions();

            opts.Elements = new List <ElementOptions>
            {
                element
            };

            Mock <IServiceProvider> services = new Mock <IServiceProvider>();

            services.Setup(s => s.GetService(typeof(MultiplyByElementBuilder)))
            .Returns(new MultiplyByElementBuilder());

            // Pass the configuration to the builder to create the pipeline.
            var pipeline = new PipelineBuilder(_loggerFactory, services.Object)
                           .BuildFromConfiguration(opts);

            // Get the element
            var multiplyByElement = pipeline.GetElement <MultiplyByElement>();

            // Create, populate and process flow data.
            var flowData = pipeline.CreateFlowData();

            flowData
            .AddEvidence(multiplyByElement.EvidenceKeys[0], 25)
            .Process();

            // Get the results and verify them.
            var multiplyByData = flowData.GetFromElement(multiplyByElement);

            Assert.AreEqual(75, multiplyByData.Result);
        }
Ejemplo n.º 16
0
        public void Pipeline_without_external_dependencies_runs_all_steps_till_completion()
        {
            UniqueStepId firstStepId  = null;
            UniqueStepId secondStepId = null;

            var pipeline = new PipelineBuilder()
                           .AddStage(StageTriggerMode.Automatic)
                           .AddActivity()
                           .AddStepWithoutDependencies(x => firstStepId  = x)
                           .AddStepWithoutDependencies(x => secondStepId = x)
                           .Build();

            var result = pipeline.Run(EventSink, null, DateTime.UtcNow);

            Assert.AreEqual(StageState.Finished, result);

            Expect(new StepExecutedEvent(firstStepId))
            .ThenExpect(new StepExecutedEvent(secondStepId))
            .ThenExpectAny <StageFinishedEvent>()
            .AndNothingElse();
        }
        public PipelineForeignAttributesTests()
        {
            var registry = new SubscriberRegistry();

            registry.Register <MyCommand, MyObsoleteCommandHandler>();

            var container = new ServiceCollection();

            container.AddTransient <MyObsoleteCommandHandler>();
            container.AddTransient <MyValidationHandler <MyCommand> >();
            container.AddTransient <MyLoggingHandler <MyCommand> >();
            container.AddSingleton <IBrighterOptions>(new BrighterOptions()
            {
                HandlerLifetime = ServiceLifetime.Transient
            });

            var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider());

            _pipelineBuilder = new PipelineBuilder <MyCommand>(registry, (IAmAHandlerFactorySync)handlerFactory);
            PipelineBuilder <MyCommand> .ClearPipelineCache();
        }
Ejemplo n.º 18
0
        public PipelineGlobalInboxTests()
        {
            _inbox = new InMemoryInbox();

            var registry = new SubscriberRegistry();

            registry.Register <MyCommand, MyCommandHandler>();

            var container      = new TinyIoCContainer();
            var handlerFactory = new TinyIocHandlerFactory(container);

            container.Register <IHandleRequests <MyCommand>, MyCommandHandler>();
            container.Register <IAmAnInbox>(_inbox);

            _requestContext = new RequestContext();

            _inboxConfiguration = new InboxConfiguration();

            _chainBuilder = new PipelineBuilder <MyCommand>(registry, handlerFactory, _inboxConfiguration);
            PipelineBuilder <MyCommand> .ClearPipelineCache();
        }
        public void Initialise()
        {
            var loggerFactory = new TestLoggerFactory();
            var builder       = new PipelineBuilder(loggerFactory);
            var httpClient    = new HttpClient();

            var dataUpdateService = new DataUpdateService(
                loggerFactory.CreateLogger <DataUpdateService>(),
                httpClient);

            _engine = new EmptyEngineBuilder(loggerFactory)
                      .Build();

            var shareUsage = new ShareUsageBuilder(loggerFactory, httpClient)
                             .Build();

            _pipeline = builder
                        .AddFlowElement(_engine)
                        .AddFlowElement(shareUsage)
                        .Build();
        }
        public PipelineGlobalInboxTestsAsync()
        {
            _inbox = new InMemoryInbox();
            var handler = new MyCommandHandlerAsync(new Dictionary <string, Guid>());

            var registry = new SubscriberRegistry();

            registry.RegisterAsync <MyCommand, MyCommandHandlerAsync>();

            var container      = new TinyIoCContainer();
            var handlerFactory = new TinyIocHandlerFactoryAsync(container);

            container.Register <MyCommandHandlerAsync>(handler);
            container.Register <IAmAnInboxAsync>(_inbox);

            _requestContext = new RequestContext();

            _inboxConfiguration = new InboxConfiguration();

            _chainBuilder = new PipelineBuilder <MyCommand>(registry, handlerFactory, _inboxConfiguration);
        }
Ejemplo n.º 21
0
        public static IApplicationBuilder UseExtendMiddleware(this IApplicationBuilder builder)
        {
            //配置文件初始化
            InitConfiguration(builder);

            //中间件初始化
            var pipelineBuilder = new PipelineBuilder(builder.ApplicationServices);

            pipelineBuilder.InitPipeline();

            var firstDelegate = pipelineBuilder.Build();

            builder.Use(async(context, task) =>
            {
                var downstreamContext = new DownstreamContext(context);
                await firstDelegate.Invoke(downstreamContext);
            });


            return(builder);
        }
Ejemplo n.º 22
0
        public void Pipeline_requests_retry_when_allowed()
        {
            UniqueStepId firstStepId  = null;
            UniqueStepId failedStepId = null;

            var pipeline = new PipelineBuilder()
                           .AddStage(StageTriggerMode.Automatic)
                           .AddActivity()
                           .AddStepWithoutDependencies(id => firstStepId = id)
                           .AddStep <FailingStep>(id => failedStepId     = id)
                           .AddStepWithoutDependencies()
                           .Build(new RetryOnceFailureHandlingStrategy());

            var result = pipeline.Run(EventSink, null, DateTime.UtcNow);

            Assert.AreEqual(StageState.RequestsRetry, result);

            Expect(new StepExecutedEvent(firstStepId))
            .ThenExpect(new StepAttemptFailedEvent(failedStepId))
            .AndNothingElse();
        }
Ejemplo n.º 23
0
        public PublishingToMultipleSubscribersAsyncTests()
        {
            var registry = new SubscriberRegistry();

            registry.RegisterAsync <MyEvent, MyEventHandlerAsync>();
            registry.RegisterAsync <MyEvent, MyOtherEventHandlerAsync>();
            registry.RegisterAsync <MyEvent, MyThrowingEventHandlerAsync>();

            var container = new ServiceCollection();

            container.AddTransient <MyEventHandlerAsync>();
            container.AddTransient <MyOtherEventHandlerAsync>();
            container.AddTransient <MyThrowingEventHandlerAsync>();
            container.AddSingleton(_receivedMessages);

            var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider());


            _commandProcessor = new CommandProcessor(registry, (IAmAHandlerFactoryAsync)handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry());
            PipelineBuilder <MyEvent> .ClearPipelineCache();
        }
        public CommandProcessorPipelineStepsTests()
        {
            var registry = new SubscriberRegistry();

            registry.Register <MyCommand, MyStepsPreAndPostDecoratedHandler>();

            var container = new ServiceCollection();

            container.AddTransient <MyStepsPreAndPostDecoratedHandler>();
            container.AddTransient <MyStepsValidationHandler <MyCommand> >();
            container.AddTransient <MyStepsLoggingHandler <MyCommand> >();
            container.AddSingleton <IBrighterOptions>(new BrighterOptions()
            {
                HandlerLifetime = ServiceLifetime.Transient
            });

            var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider());

            _commandProcessor = new CommandProcessor(registry, handlerFactory, new InMemoryRequestContextFactory(), new PolicyRegistry());
            PipelineBuilder <MyCommand> .ClearPipelineCache();
        }
Ejemplo n.º 25
0
        public PipelinePreAndPostFiltersAsyncTests()
        {
            var registry = new SubscriberRegistry();

            registry.RegisterAsync <MyCommand, MyPreAndPostDecoratedHandlerAsync>();

            var container = new ServiceCollection();

            container.AddTransient <MyPreAndPostDecoratedHandlerAsync>();
            container.AddTransient <MyValidationHandlerAsync <MyCommand> >();
            container.AddTransient <MyLoggingHandlerAsync <MyCommand> >();
            container.AddSingleton <IBrighterOptions>(new BrighterOptions()
            {
                HandlerLifetime = ServiceLifetime.Transient
            });

            var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider());

            _pipelineBuilder = new PipelineBuilder <MyCommand>(registry, (IAmAHandlerFactoryAsync)handlerFactory);
            PipelineBuilder <MyCommand> .ClearPipelineCache();
        }
Ejemplo n.º 26
0
        public PipelineGlobalInboxNoInboxAttributeTests()
        {
            _inbox = new InMemoryInbox();

            var registry = new SubscriberRegistry();

            registry.Register <MyCommand, MyNoInboxCommandHandler>();

            var container = new ServiceCollection();

            container.AddTransient <MyNoInboxCommandHandler>();
            container.AddSingleton <IAmAnInbox>(_inbox);

            var handlerFactory = new ServiceProviderHandlerFactory(container.BuildServiceProvider());

            _requestContext = new RequestContext();

            _inboxConfiguration = new InboxConfiguration();

            _chainBuilder = new PipelineBuilder <MyCommand>(registry, (IAmAHandlerFactory)handlerFactory, _inboxConfiguration);
        }
Ejemplo n.º 27
0
            public void Run(string resourceKey, string cloudEndPoint = "")
            {
                Console.WriteLine("This example shows the details of devices " +
                                  "associated with a given 'Type Allocation Code' or 'TAC'.");
                Console.WriteLine("More background information on TACs can be " +
                                  "found through various online sources such as Wikipedia: " +
                                  "https://en.wikipedia.org/wiki/Type_Allocation_Code");
                Console.WriteLine("----------------------------------------");

                ILoggerFactory loggerFactory = new LoggerFactory();
                HttpClient     httpClient    = new HttpClient();

                // Create a cloud request engine builder
                var cloudRequestEngineBuilder = new CloudRequestEngineBuilder(loggerFactory, httpClient)
                                                .SetResourceKey(resourceKey);

                // If a cloud endpoint has been provided then set the
                // cloud pipeline endpoint.
                if (string.IsNullOrWhiteSpace(cloudEndPoint) == false)
                {
                    cloudRequestEngineBuilder.SetEndPoint(cloudEndPoint);
                }

                // Create the cloud request engine
                using (var cloudEngine = cloudRequestEngineBuilder.Build())
                    // Create the property-keyed engine to process the
                    // response from the request engine.
                    using (var propertyKeyedEngine = new HardwareProfileCloudEngineBuilder(loggerFactory)
                                                     .Build())
                        // Create the pipeline using the engines.
                        using (var pipeline = new PipelineBuilder(loggerFactory)
                                              .AddFlowElement(cloudEngine)
                                              .AddFlowElement(propertyKeyedEngine)
                                              .Build())
                        {
                            // Pass a TAC into the pipeline and list the matching devices.
                            AnalyseTac(TAC, pipeline);
                            AnalyseTac(TAC2, pipeline);
                        }
            }
        public CommandProcessorBuildDefaultInboxPublishTests()
        {
            var handler = new MyGlobalInboxEventHandler(new Dictionary <string, Guid>());

            var subscriberRegistry = new SubscriberRegistry();

            //This handler has no Inbox attribute
            subscriberRegistry.Add(typeof(MyEvent), typeof(MyGlobalInboxEventHandler));

            var container      = new TinyIoCContainer();
            var handlerFactory = new TinyIocHandlerFactory(container);

            container.Register <MyGlobalInboxEventHandler>(handler);
            container.Register <IAmAnInbox>(_inbox);

            var retryPolicy = Policy
                              .Handle <Exception>()
                              .Retry();

            var circuitBreakerPolicy = Policy
                                       .Handle <Exception>()
                                       .CircuitBreaker(1, TimeSpan.FromMilliseconds(1));

            var inboxConfiguration = new InboxConfiguration(
                InboxScope.All,                      //grab all the events
                onceOnly: true,                      //only allow once
                actionOnExists: OnceOnlyAction.Throw //throw on duplicates (we should  be the only entry after)
                );

            _commandProcessor = new CommandProcessor(
                subscriberRegistry,
                handlerFactory,
                new InMemoryRequestContextFactory(),
                new PolicyRegistry {
                { CommandProcessor.RETRYPOLICY, retryPolicy }, { CommandProcessor.CIRCUITBREAKER, circuitBreakerPolicy }
            },
                inboxConfiguration: inboxConfiguration
                );
            PipelineBuilder <MyEvent> .ClearPipelineCache();
        }
        private static IServiceCollection AddAsyncPipelineInternal <TPayload>(this IServiceCollection services,
                                                                              Action <AsyncPipelineComponentConfiguration <TPayload> > configAction,
                                                                              IDictionary <string, IDictionary <string, string> > settings,
                                                                              string pipelineName,
                                                                              ServiceLifetime lifetime)
        {
            var config = new AsyncPipelineComponentConfiguration <TPayload>();

            configAction(config);
            config.Validate();

            services.AddComponentServices <IAsyncPipelineComponent <TPayload> >(config, lifetime);
            services.Add(new ServiceDescriptor(
                             typeof(IAsyncPipeline <TPayload>),
                             provider => BuildAsyncPipeline(provider, settings, pipelineName),
                             lifetime));

            return(services);

            IAsyncPipeline <TPayload> BuildAsyncPipeline(
                IServiceProvider provider,
                IDictionary <string, IDictionary <string, string> > pipelineSettings,
                string name)
            {
                var initialBuilder =
                    (IAdditionalPipelineComponentHolder <IAsyncPipeline <TPayload>, IAsyncPipelineComponent <TPayload>, TPayload>)
                    PipelineBuilder <TPayload> .InitializeAsyncPipeline(
                        provider.GetService <IAsyncPipelineComponentExecutionStatusReceiver>());

                initialBuilder =
                    config.Components.Aggregate(initialBuilder, (current, component) => current.WithComponent(component));

                var settingsHolder = initialBuilder.WithComponentResolver(provider.GetService <IPipelineComponentResolver>());
                var builder        = pipelineSettings != null
                    ? settingsHolder.WithSettings(pipelineSettings)
                    : settingsHolder.WithoutSettings();

                return(builder.Build(name));
            }
        }
Ejemplo n.º 30
0
        public static void AddNamedEntity(List <Book> books)
        {
            var pipeline = PipelineBuilder.GetPipeLineWithNamedEntities();
            int counter  = 1;

            foreach (var book in books)
            {
                Dictionary <string, int> entities = new Dictionary <string, int>();
                var annotation = new Annotation(book.Text);
                pipeline.annotate(annotation);
                var sentences = annotation.get(new CoreAnnotations.SentencesAnnotation().getClass()) as ArrayList;
                foreach (CoreMap sentence in sentences)
                {
                    var tokens = sentence.get(new
                                              CoreAnnotations.TokensAnnotation().getClass()) as ArrayList;
                    foreach (CoreLabel token in tokens)
                    {
                        var ner = token.get(new
                                            CoreAnnotations.NamedEntityTagAnnotation().getClass()) as string;
                        if (entities.ContainsKey(ner))
                        {
                            entities[ner]++;
                        }
                        else
                        {
                            entities.Add(ner, 1);
                        }
                    }
                }

                foreach (var entity in entities)
                {
                    book.NamedEntities.Add(new NamedEntity()
                    {
                        NamedEntityID = counter, BookID = book.BookID, NamedEntity1 = entity.Key, NumberOfOccurences = entity.Value
                    });
                    counter++;
                }
            }
        }
Ejemplo n.º 31
0
        public void AspectEngineLazyLoad_Itegrated_AsDictionary()
        {
            // Arrange
            var processCostMs = _timeoutMS / 2;

            _engine.SetProcessCost(TimeSpan.TicksPerMillisecond * processCostMs);
            var pipeline = new PipelineBuilder(_loggerFactory)
                           .AddFlowElement(_engine)
                           .Build();

            // Act
            var stopwatch = new Stopwatch();
            var flowData  = pipeline.CreateFlowData();

            Trace.WriteLine("Process starting");
            stopwatch.Start();
            flowData.Process();
            long processTimeMs = stopwatch.ElapsedMilliseconds;

            Trace.WriteLine($"Process complete in {processTimeMs} ms");

            // Assert
            var data = flowData.Get <EmptyEngineData>();

            Assert.IsNotNull(data);
            var  dictionary = data.AsDictionary();
            long dictTimeMs = stopwatch.ElapsedMilliseconds;

            Trace.WriteLine($"Dictionary retrieved after {dictTimeMs} ms");
            Assert.AreEqual(1, dictionary[EmptyEngineData.VALUE_ONE_KEY]);
            Assert.AreEqual(2, dictionary[EmptyEngineData.VALUE_TWO_KEY]);

            // Note - this should really take at least 'processCostMs'
            // but the accuracy of the timer seems to cause issues
            // if we are being that exact.
            Assert.IsTrue(dictTimeMs > processCostMs / 2,
                          $"Accessing the dictionary should have taken at least " +
                          $"{processCostMs / 2} ms from the time the Process method" +
                          $"was called but it only took {dictTimeMs} ms.");
        }
Ejemplo n.º 32
0
        public void Will_send_data_through_ws_publisher_at_the_end_of_the_pipeline()
        {
            var sourceElement = new TxPoolPipelineSource <Transaction>(_txPool);
            var element       = new TxPoolPipelineElement <Transaction, Transaction>();
            var publisher     = new WebSocketsPublisher <Transaction, Transaction>("testPublisher", Substitute.For <IJsonSerializer>());

            var mockWebSocket = Substitute.For <WebSocket>();

            mockWebSocket.State.Returns(WebSocketState.Open);
            publisher.CreateClient(mockWebSocket, "testClient");

            Transaction transactionToEmit = new() { To = new Address("0x92A3c5e7Cee811C3402b933A6D43aAF2e56f2823") };

            var builder = new PipelineBuilder <Transaction, Transaction>(sourceElement);

            builder.AddElement(element).AddElement(publisher);
            var pipeline = builder.Build();

            _txPool.NewPending += Raise.EventWith(new object(), new TxEventArgs(transactionToEmit));

            mockWebSocket.Received().SendAsync(Arg.Any <ArraySegment <byte> >(), WebSocketMessageType.Text, true, CancellationToken.None);
        }
Ejemplo n.º 33
0
        public void Will_send_data_through_log_publisher_at_the_end_of_the_pipeline()
        {
            string      filePath    = "path";
            Transaction transaction = new() { To = new Address("0x92A3c5e7Cee811C3402b933A6D43aAF2e56f2823") };

            IFileSystem fileSystemSub = Substitute.For <IFileSystem>();

            fileSystemSub.File.Exists(filePath).Returns(true);
            fileSystemSub.File.ReadLines(filePath).Returns(new[] { "0x92A3c5e7Cee811C3402b933A6D43aAF2e56f2823" });

            var sourceElement = new TxPoolPipelineSource <Transaction>(_txPool);
            var element       = new TxPoolPipelineElement <Transaction, Transaction>();
            var publisher     = new LogPublisher <Transaction, Transaction>(Substitute.For <IJsonSerializer>(), Substitute.For <ILogManager>(), fileSystemSub);

            var builder = new PipelineBuilder <Transaction, Transaction>(sourceElement);

            builder.AddElement(element).AddElement(publisher);
            var pipeline = builder.Build();

            _txPool.NewPending += Raise.EventWith(new object(), new TxEventArgs(transaction));
            fileSystemSub.Received().File.AppendAllText(filePath, "0x92A3c5e7Cee811C3402b933A6D43aAF2e56f2823");
        }
        public async Task HandlingCommandWithNoRegisteredHandlerShouldRunNoMatchingRegistrationHandler()
        {
            var busSettings     = new BusSettings();
            var updater         = new OuterPipelineDetector();
            var dependencyScope = new TestDependencyScope();

            var handler     = new TestEventHandler();
            var handlerShim = new EventHandlerShim <NoMatchingRegistrationEvent, TestEventHandler>(handler);

            dependencyScope.AddObject(handlerShim);

            var busBuilder = new BusBuilder()
                             .RegisterEventHandler <NoMatchingRegistrationEvent, TestEventHandler>();
            var pipelineBuilder    = new PipelineBuilder(busBuilder);
            var pipelineRunBuilder = new PipelineRunBuilder(busSettings, pipelineBuilder, updater, dependencyScope);

            var runner = pipelineRunBuilder.GetRunnerForPipeline(typeof(TestCommand), default(CancellationToken));

            await runner.Handle(new TestCommand());

            handler.CallsToHandle.Should().Be(1);
        }
        public async Task Pipeline_Should_Preserve_OwnPipelineComponents_AfterBuild()
        {
            // arrange
            var sp = new ServiceCollection().BuildServiceProvider();

            var pipelineBuilder = new PipelineBuilder <TestCtx>();

            pipelineBuilder.Use <Middleware1>();

            var firstPipeline = pipelineBuilder.Build(sp);

            pipelineBuilder.Use(async(ctx, next) =>
            {
                ctx.Msg += "Before_LambdaMiddleware";

                await next();

                ctx.Msg += "After_LambdaMiddleware";
            });

            var secondPipeline = pipelineBuilder.Build(sp);

            var testContext = new TestCtx();

            // act
            await firstPipeline.ExecuteAsync(testContext); // this pipeline has no lambda middleware in pipeline.

            Assert.AreEqual("Before_Middleware1After_Middleware1", testContext.Msg);

            testContext.Msg = null;                         // clear before second pipeline execution

            await secondPipeline.ExecuteAsync(testContext); // this has full pipeline.

            // assert
            Assert.AreEqual(
                "Before_Middleware1Before_LambdaMiddlewareAfter_LambdaMiddlewareAfter_Middleware1",
                testContext.Msg
                );
        }
Ejemplo n.º 36
0
        public async void Should_pass_execution_parameters_to_middleware()
        {
            //Arrange
            var mockedServiceProvider = Mock.Of <IServiceProvider>();

            IData             receivedData1 = null, receivedData2 = null;
            CancellationToken receivedCancellationToken1, receivedCancellationToken2;

            var pipeline = new PipelineBuilder <IData>(mockedServiceProvider)
                           .Use(async(data, cancellationToken, next) =>
            {
                receivedData1 = data;
                receivedCancellationToken1 = cancellationToken;
                await next();
            })
                           .Use(async(data, cancellationToken, next) =>
            {
                receivedData2 = data;
                receivedCancellationToken2 = cancellationToken;
                await Task.Yield();
            })
                           .Pipeline;

            var sentData = Mock.Of <IData>();

            using (var ts = new CancellationTokenSource())
            {
                var sentCancellationToken = ts.Token;

                //Act
                await pipeline(sentData, sentCancellationToken);

                //Assert
                receivedCancellationToken1.Should().Be(sentCancellationToken);
                receivedCancellationToken2.Should().Be(sentCancellationToken);
                receivedData1.Should().Be(sentData);
                receivedData2.Should().Be(sentData);
            }
        }
Ejemplo n.º 37
0
        private static async Task InvokePipelineAsync(IPipelineComponentResolver resolver, IDictionary <string, IDictionary <string, string> > settings)
        {
            Console.WriteLine("Executing pipeline asynchronously.\n");

            var payload = new ExamplePipelinePayload();

            using (var pipeline = PipelineBuilder <ExamplePipelinePayload>
                                  .InitializeAsyncPipeline()
                                  .WithComponent <FooComponent>()
                                  .WithComponent <DelayComponent>()
                                  .WithComponent <BarComponent>()
                                  .WithComponentResolver(resolver)
                                  .WithSettings(settings)
                                  .Build())
            {
                payload = await pipeline.ExecuteAsync(payload);
            }

            payload.Messages.ForEach(Console.WriteLine);

            Console.WriteLine("\n");
        }
Ejemplo n.º 38
0
        public async void should_unsubscribe_wiretap_correctly()
        {
            var dummyPipeline = new PipelineBuilder()
                                .StartFrom(x => Task.FromResult((object)"hello"))
                                .ThenInvoke(x => Task.FromResult((object)"there"))
                                .Build()
                                .AsWireTappable();

            var sub1 = dummyPipeline.StartWiretap(1, (x, y) =>
            {
                Assert.True(false);
            });
            var sub2 = dummyPipeline.StartWiretap(2, (x, y) =>
            {
                Assert.True(false);
            });

            sub1.Unsubscribe();
            sub2.Unsubscribe();

            dummyPipeline.Execute();
        }
Ejemplo n.º 39
0
        public async void should_correctly_fork_stream_for_object_with_builder()
        {
            var expectedString = "hello there some new pipeline";
            var data           = "hello";
            var dummyPipeline  = new PipelineBuilder()
                                 .StartFromInput()
                                 .ThenInvoke(x => Task.FromResult((object)(x + " there")))
                                 .ThenInvoke(x => Task.FromResult((object)(x + " some")))
                                 .ThenInvoke(x => Task.FromResult((object)(x + " old")))
                                 .ThenInvoke(x => Task.FromResult((object)(x + " pipeline")))
                                 .Build();

            var forkedPipeline = new PipelineBuilder()
                                 .ForkObjectFrom(dummyPipeline, 2)
                                 .ThenInvoke(x => Task.FromResult((object)(x + " new")))
                                 .ThenInvoke(x => Task.FromResult((object)(x + " pipeline")))
                                 .Build();

            var actualOutput = await forkedPipeline.Execute(data);

            Assert.Equal(expectedString, actualOutput);
        }
Ejemplo n.º 40
0
    public async Task RunAsync()
    {
        try
        {
            _logger.LogInformation("Application started");

            var context  = new PipelineContext <TestResult>(new TestResult());
            var pipeline = PipelineBuilder <TestResult> .Create <TestResult>()
                           .Use(_testRuntimeLibraryHandler)
                           .Use(_testDbHandler)
                           .Use(_testWebApiHandler)
                           .Build();

            await pipeline.RunAsync(context);

            PrintInfo(context.Data);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Необработанная ошибка {0}", ex.Message);
        }
    }
Ejemplo n.º 41
0
        public void InvokePipeline()
        {
            var testObject1 = new TestObject {
                Name = "TestObject1"
            };
            var option = new PSRuleOption();

            option.Rule.Include = new string[] { "FromFile1" };
            var builder  = PipelineBuilder.Invoke(GetSource(), option);
            var pipeline = builder.Build();

            pipeline.Begin();

            var actual = new List <InvokeResult>();

            for (var i = 0; i < 100; i++)
            {
                pipeline.Process(PSObject.AsPSObject(testObject1));
            }

            pipeline.End();
        }
Ejemplo n.º 42
0
        public void Step_should_timeout_after_500_seconds()
        {
            UniqueStepId firstRetryStepId = null;

            var pipeline = new PipelineBuilder()
                           .AddStage(StageTriggerMode.Automatic)
                           .AddActivity()
                           .AddStep <WaitingForExternalDependencyStep>(id => firstRetryStepId = id)
                           .Build(new NoRetryFailureHandlingStrategy());

            var startTime = DateTime.UtcNow;
            var retryTime = startTime + TimeSpan.FromSeconds(501);

            pipeline.Run(EventSink, null, startTime);
            pipeline.Run(EventSink, null, retryTime);

            Expect((new StepWaitingForExternalDependencyEvent(firstRetryStepId, startTime)))
            .ThenExpect(new StepAttemptFailedEvent(firstRetryStepId))
            .ThenExpect(new StepFailedEvent(firstRetryStepId))
            .ThenExpectAny <StageFailedEvent>()
            .AndNothingElse();
        }
Ejemplo n.º 43
0
        public async Task Should_BeCorrect_PipelineExecutionOrder()
        {
            // arrange
            var pipelineBuilder = new PipelineBuilder <TestCtx>();

            pipelineBuilder.Use <Middleware1>();
            pipelineBuilder.Use <Middleware2>();
            pipelineBuilder.Use(async(ctx, next) =>
            {
                ctx.ExecutedMiddlewaresCount++;

                ctx.Msg += "Before_LambdaMiddleware";

                await next();
                ctx.Msg += "After_LambdaMiddleware";
            });

            var pipeline = pipelineBuilder.Build(new ServiceCollection().BuildServiceProvider());

            var testContext = new TestCtx();

            Assert.IsNull(testContext.Msg);
            Assert.Zero(testContext.ExecutedMiddlewaresCount);

            // act
            await pipeline.ExecuteAsync(testContext);

            // assert
            const string expectedMessage = "Before_" + nameof(Middleware1) +
                                           "Before_" + nameof(Middleware2) +
                                           "Before_LambdaMiddleware" +
                                           "After_LambdaMiddleware" +
                                           "After_" + nameof(Middleware2) +
                                           "After_" + nameof(Middleware1);

            Assert.AreEqual(expectedMessage, testContext.Msg, "Pipeline execution order is not match");
            Assert.AreEqual(3, testContext.ExecutedMiddlewaresCount, "ExecutedMiddlewaresCount is not match");
        }
 public IAppObjectViewToContractHostAdapter(PipelineBuilder.Samples.Events.IAppObject view)
 {
     _view = view;
     DocumentOpened_handlers = new System.Collections.Generic.Dictionary<PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedHandlerContract, System.EventHandler<PipelineBuilder.Samples.Events.DocumentOpenedEventArgs>>();
 }
 public ISampleAddInContractToViewAddInAdapter(PipelineBuilder.Samples.Events.Contracts.ISampleAddInContract contract)
 {
     _contract = contract;
     _handle = new System.AddIn.Pipeline.ContractHandle(contract);
 }
Ejemplo n.º 46
0
        private Project CreateAddInProject(DTE2 dte, String destPath, PipelineBuilder.PipelineSegmentSource pipelineComponent)
        {
            destPath += "\\" + pipelineComponent.Name;
            String generatedDestPath = destPath + "\\Generated Files";

            Project proj = null;
            foreach (Project p in ProjectHelpers.GetProjectsFromSolution(dte))
            {
                if (p.Name.Trim().Equals((pipelineComponent.Name)))
                {
                    proj = p;
                }
            }
            if (proj == null)
            {
                if (Directory.Exists(destPath))
                {
                    throw new InvalidOperationException("The directory for this project already exists but is not part of the current solution. Please either add it back to the current solution or delete it manually: " + destPath);
                }
                else
                {
                    Directory.CreateDirectory(destPath);
                }

                dte.Solution.AddFromTemplate(ProjectHelpers.Pop(this.GetType().Assembly.Location) + "\\Template.csproj", destPath, pipelineComponent.Name + ".csproj", false);

                foreach (Project p in ProjectHelpers.GetProjectsFromSolution(dte))
                {
                    if (p.Name.Trim().Equals((pipelineComponent.Name)))
                    {
                        proj = p;
                    }
                }

                proj.Properties.Item("AssemblyName").Value = pipelineComponent.Name;
            }

            if (Directory.Exists(generatedDestPath))
            {
                CheckSumValidator.ValidateCheckSum(generatedDestPath);
            }
            if (proj != null)
            {
                try
                {
                    proj.ProjectItems.Item("Generated Files").Delete();
                }
                catch (ArgumentException)
                {
                    //If there is no generated files project item then we should just ignore this step.
                }
                if (Directory.Exists(generatedDestPath))
                {
                    throw new InvalidOperationException("Generated Files directory exists but is not part of project. Please save required files and delete manually: " + generatedDestPath);
                }
                Directory.CreateDirectory(generatedDestPath);
                proj.ProjectItems.AddFolder("Generated Files", null);
                foreach (PipelineBuilder.SourceFile source in pipelineComponent.Files)
                {
                    String path = generatedDestPath + "\\" + source.Name;
                    StreamWriter sw = new StreamWriter(path);
                    sw.WriteLine(source.Source);
                    sw.Close();

                }
                proj.ProjectItems.AddFromDirectory(generatedDestPath);
                CheckSumValidator.StoreCheckSum(generatedDestPath);
            }
            return proj;
        }
 internal static void SetOutputPath(Project p, PipelineBuilder.SegmentType type, String root)
 {
     foreach (Configuration c in p.ConfigurationManager)
     {
         Property prop = c.Properties.Item("OutputPath");
         prop.Value = root;
         switch (type)
         {
             case PipelineBuilder.SegmentType.AIB:
                 prop.Value += "\\AddInViews";
                 break;
             case PipelineBuilder.SegmentType.ASA:
                 prop.Value += "\\AddInSideAdapters";
                 break;
             case PipelineBuilder.SegmentType.HSA:
                 prop.Value += "\\HostSideAdapters";
                 break;
             case PipelineBuilder.SegmentType.HAV:
                 break;
             case PipelineBuilder.SegmentType.VIEW:
                 prop.Value += "\\AddInViews";
                 break;
             default:
                 throw new InvalidOperationException("Not a valid pipeline component: " + p.Name);
         }
     }
 }
 public void Initialize(PipelineBuilder.Samples.Events.IAppObject appObject)
 {
     _contract.Initialize(PipelineBuilder.Samples.EventsAddInAdapters.IAppObjectAddInAdapter.ViewToContractAdapter(appObject));
 }
 public virtual void Initialize(PipelineBuilder.Samples.Events.Contracts.IAppObjectContract appObject)
 {
     _view.Initialize(PipelineBuilder.Samples.EventsAddInAdapters.IAppObjectAddInAdapter.ContractToViewAdapter(appObject));
 }
 public ISampleAddInViewToContractAddInAdapter(PipelineBuilder.Samples.Events.ISampleAddIn view)
 {
     _view = view;
 }
 public virtual void DocumentOpenedAdd(PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedHandlerContract handler)
 {
     System.EventHandler<PipelineBuilder.Samples.Events.DocumentOpenedEventArgs> adaptedHandler = new System.EventHandler<PipelineBuilder.Samples.Events.DocumentOpenedEventArgs>(new IDocumentOpenedHandlerContractToViewHostAdapter(handler).Handler);
     _view.DocumentOpened += adaptedHandler;
     DocumentOpened_handlers[handler] = adaptedHandler;
 }
Ejemplo n.º 52
0
        public IPipeline<ClientActionContext> CreatePipeline(int retries)
        {
            PipelineBuilder<ClientActionContext> builder = new PipelineBuilder<ClientActionContext>();
            builder.Use(new RetryRequestMiddleware(ErrorHandling.Object) {Retries = retries});
            builder.Use(
                (next, ctxt) =>
                    {
                        Callback.Object.Handle(ctxt);
                        return next(ctxt);
                    });

            return builder.Build();
        }
 public IAppObjectContractToViewAddInAdapter(PipelineBuilder.Samples.Events.Contracts.IAppObjectContract contract)
 {
     _contract = contract;
     _handle = new System.AddIn.Pipeline.ContractHandle(contract);
     DocumentOpened_Handler = new IDocumentOpenedHandlerViewToContractAddInAdapter(this, s_DocumentOpenedAddFire);
 }
 public DocumentOpenedEventArgsViewToContractHostAdapter(PipelineBuilder.Samples.Events.DocumentOpenedEventArgs view)
 {
     _view = view;
 }
 public IDocumentOpenedHandlerContractToViewHostAdapter(PipelineBuilder.Samples.Events.Contracts.IDocumentOpenedHandlerContract contract)
 {
     _contract = contract;
     _handle = new System.AddIn.Pipeline.ContractHandle(contract);
 }
        public void Initialize()
        {
            var builder = this.Builder;
            if (builder == null)
            {
                builder = new PipelineBuilder();
            }

            this.requestPipeline = builder.Build(this.requestProcessors, GetRequestInArguments(), this.GetRequestOutArguments());
            this.responsePipeline = builder.Build(this.responseProcessors, this.GetResponseInArguments(), Enumerable.Empty<ProcessorArgument>());
        }
 public void Handler(object sender, PipelineBuilder.Samples.Events.DocumentOpenedEventArgs args)
 {
     _contract.Handle(PipelineBuilder.Samples.EventsHostAdapers.DocumentOpenedEventArgsHostAdapter.ViewToContractAdapter(args));
 }