Exemple #1
0
        //public static void MiddleWareAnalysis()
        //{
        //    Console.WriteLine(" ** 模拟 Middleware **");
        //    var context = new RequestContext() { name = "xx", id = 1 };

        //    MiddleWareBuild middleWareEvent = new MiddleWareBuild();
        //    //PipeLineExtensions.ActionExcutingEvent += c => middleWareEvent.ActionExcutingEventHanlder(c);
        //    //PipeLineExtensions.ActionExcutedEvent += c => middleWareEvent.ActionExcutedEventHanlder(c);
        //    //PipeLineExtensions.ExceptionEvent += c => middleWareEvent.ExceptionEventHanlder(c);

        //    IList<Func<Action<RequestContext>, Action<RequestContext>>> _pipeline
        //       = new List<Func<Action<RequestContext>, Action<RequestContext>>>();
        //    Action<RequestContext, Action> ac1 = (context, next) =>
        //    {
        //        Console.WriteLine("1 Before");
        //        next();
        //        Console.WriteLine("1 After");
        //    };
        //    Action<RequestContext, Action> ac2 = (context, next) =>
        //    {
        //        Console.WriteLine("2 Before");
        //        next();
        //        Console.WriteLine("2 After");
        //    };

        //    Func<Action<RequestContext>, Action<RequestContext>> func1 = (next) =>
        //    context =>
        //    ac1(context, () => { next(context); });
        //    _pipeline.Add(func1);

        //    Func<Action<RequestContext>, Action<RequestContext>> func2 = (next) =>
        //    context =>
        //    ac2(context, () => next(context));
        //    _pipeline.Add(func2);

        //    Action<RequestContext> ac = context => Console.WriteLine($"{nameof(context.name)} {context.name}");
        //    foreach (var item in _pipeline.Reverse())
        //        ac = item(ac);
        //    ac(context);
        //}

        public static void BuildUse()
        {
            Console.WriteLine(" *** Use MiddleWare ***");
            var context = new RequestContext <CheckProductMode>()
            {
                Mode = new CheckProductMode {
                    AliexpressRule = "1"
                }
            };

            //MiddleWareBuild middleWareEvent = new MiddleWareBuild();
            //PipeLineExtensions.ActionExcutingEvent += c => middleWareEvent.ActionExcutingEventHanlder(c);
            //PipeLineExtensions.ActionExcutedEvent += c => middleWareEvent.ActionExcutedEventHanlder(c);
            //PipeLineExtensions.ExceptionEvent += c => middleWareEvent.ExceptionEventHanlder(c);

            var builder = PipelineBuilder <RequestContext <CheckProductMode> > .Create(context =>
            {
            });

            builder.UseMiddleware <RequestContext <CheckProductMode>, CustomExceptionMiddleWare <RequestContext <CheckProductMode> > >();
            builder.UseMiddleware <RequestContext <CheckProductMode>, CustomMiddleWare>();
            builder.UseMiddleware <RequestContext <CheckProductMode>, CustomMiddleWare2>();

            var app = builder.Build();

            app(context);
            Console.WriteLine(context.ExceptionInfo.Message);

            Console.ReadLine();
        }
Exemple #2
0
        public async Task ExampleTest()
        {
            T LogStep <T>(T prev)
            {
                Console.WriteLine(prev.ToString());
                return(prev);
            }

            Pipeline <string, int> stringLengthPipeline = PipelineBuilder
                                                          .Create <string>()
                                                          .AddStep(new ConcatStringPipelineStep(", let's count "))
                                                          .AddStep(new ConcatStringPipelineStep("this string length!"))
                                                          .AddStep(LogStep)
                                                          .AddStep(new StringLengthPipelineStep())
                                                          .Build();

            Pipeline <string, string> pipeline = PipelineBuilder
                                                 .Create <string>()
                                                 .AddStep(LogStep)
                                                 .AddStep(stringLengthPipeline)
                                                 .AddStep(length => $"So, result is {length}")
                                                 .Build();

            string result = await pipeline.ExecuteAsync("Hello");

            Console.WriteLine(result);

            Assert.Equal("So, result is 38", result);
        }
    public static void Test()
    {
        var requestContext = new RequestContext()
        {
            RequesterName = "Kangkang",
            Hour          = 12,
        };

        var builder = PipelineBuilder.Create <RequestContext>(context =>
        {
            Console.WriteLine($"{context.RequesterName} {context.Hour}h apply failed");
        })
                      .Use((context, next) =>
        {
            if (context.Hour <= 2)
            {
                Console.WriteLine("pass 1");
            }
            else
            {
                next();
            }
        })
                      .Use((context, next) =>
        {
            if (context.Hour <= 4)
            {
                Console.WriteLine("pass 2");
            }
            else
            {
                next();
            }
        })
                      .Use((context, next) =>
        {
            if (context.Hour <= 6)
            {
                Console.WriteLine("pass 3");
            }
            else
            {
                next();
            }
        })
        ;
        var requestPipeline = builder.Build();

        Console.WriteLine();
        foreach (var i in Enumerable.Range(1, 8))
        {
            Console.WriteLine($"--------- h:{i} apply Pipeline------------------");
            requestContext.Hour = i;
            requestPipeline.Invoke(requestContext);
            Console.WriteLine("----------------------------");
        }
    }
Exemple #4
0
        static void Main(string[] args)
        {
            var pipeline = PipelineBuilder.Create <LoadXmlStage>()
                           .Extend <SpecParserStage>()
                           .Extend <CollationStage>()
                           .Extend <GenerationStage>()
                           .Extend <EmissionStage>()
                           .Build();

            pipeline.Run();
        }
Exemple #5
0
        public void AddStep_WhenCallsChained_ShouldForwardStepsToNextBuilder()
        {
            // Arrange
            var step1 = new ConcatStringPipelineStep("Hey");
            PipelineBuilder <string, string> builder = PipelineBuilder.Create <string>();

            // Act
            builder = builder.AddStep(step1);

            // Assert
            Assert.Equal(1, builder.Steps.Count);
            Assert.Equal(step1, builder.Steps.First());
        }
Exemple #6
0
        public void AddStep_ShouldAddStep()
        {
            // Arrange
            var step1   = new ConcatStringPipelineStep("Hey");
            var builder = PipelineBuilder.Create <string>();

            // Act
            builder.AddStep(step1);

            // Assert
            Assert.Equal(1, builder.Steps.Count);
            Assert.Equal(step1, builder.Steps.First());
        }
        public static void InvokeAspectDelegate(MethodInvocationContext context)
        {
            var action = _aspectDelegates.GetOrAdd($"{context.ProxyMethod.DeclaringType}.{context.ProxyMethod}", m =>
            {
                var aspects = new List <AbstractAspect>(8);
                if (context.MethodBase != null)
                {
                    foreach (var aspect in context.MethodBase.GetCustomAttributes <AbstractAspect>())
                    {
                        if (!aspects.Exists(x => x.GetType() == aspect.GetType()))
                        {
                            aspects.Add(aspect);
                        }
                    }
                }

                var methodParameterTypes = context.ProxyMethod.GetParameters().Select(p => p.GetType()).ToArray();
                foreach (var implementedInterface in context.ProxyTarget.GetType().GetImplementedInterfaces())
                {
                    var method = implementedInterface.GetMethod(context.ProxyMethod.Name, methodParameterTypes);
                    if (null != method)
                    {
                        foreach (var aspect in method.GetCustomAttributes <AbstractAspect>())
                        {
                            if (!aspects.Exists(x => x.GetType() == aspect.GetType()))
                            {
                                aspects.Add(aspect);
                            }
                        }
                    }
                }

                var builder = PipelineBuilder.Create <MethodInvocationContext>(x => x.Invoke());
                foreach (var aspect in aspects)
                {
                    builder.Use(aspect.Invoke);
                }
                return(builder.Build());
            });

            action.Invoke(context);

            // check for return value
            if (context.ProxyMethod.ReturnType != typeof(void))
            {
                if (context.ReturnValue == null && context.ProxyMethod.ReturnType.IsValueType)
                {
                    context.ReturnValue = Activator.CreateInstance(context.ProxyMethod.ReturnType);
                }
            }
        }
Exemple #8
0
        public void Build_ShouldCreatePipelineWithCurrentSteps()
        {
            // Arrange
            PipelineBuilder <string, string> builder = PipelineBuilder.Create <string>()
                                                       .AddStep(arg => arg + "sync")
                                                       .AddStep(async arg => await Task.FromResult(arg + "async"));

            // Act
            Pipeline <string, string> pipeline = builder.Build();

            // Assert
            Assert.IsType <DelegatePipelineStep <string, string> >(pipeline.Steps[0]);
            Assert.IsType <AsyncDelegatePipelineStep <string, string> >(pipeline.Steps[1]);
        }
Exemple #9
0
        public void AddStep_WhenFuncPassed_ShouldAddDelegateStep()
        {
            // Arrange
            var builder = PipelineBuilder.Create <string>();

            // Act
            builder = builder
                      .AddStep(arg => arg + "sync")
                      .AddStep(async arg => await Task.FromResult(arg + "async"));

            // Assert
            Assert.IsType <DelegatePipelineStep <string, string> >(builder.Steps[0]);
            Assert.IsType <AsyncDelegatePipelineStep <string, string> >(builder.Steps[1]);
        }
Exemple #10
0
        public void AddStep_WhenCallsChained_CanReuseSameSteps()
        {
            // Arrange
            var step1 = new ConcatStringPipelineStep("Hey");
            PipelineBuilder <string, string> builder = PipelineBuilder.Create <string>();

            // Act
            builder = builder
                      .AddStep(step1)
                      .AddStep(step1)
                      .AddStep(step1);

            // Assert
            Assert.Equal(3, builder.Steps.Count);
        }
Exemple #11
0
        public void AddStep_WhenCalledMultipleTimes_ShouldReplaceLastStep()
        {
            // Arrange
            var step1 = new ConcatStringPipelineStep("Hey");
            var step2 = new ConcatStringPipelineStep("Hey 2");
            PipelineBuilder <string, string> builder = PipelineBuilder.Create <string>();

            // Act
            builder.AddStep(step1);
            builder.AddStep(step2);

            // Assert
            Assert.Equal(1, builder.Steps.Count);
            Assert.Equal(step2, builder.Steps.First());
        }
    public static void TestV2()
    {
        var requestContext = new RequestContext()
        {
            RequesterName = "Kangkang",
            Hour          = 12,
        };

        var builder = PipelineBuilder.Create <RequestContext>(context =>
        {
            Console.WriteLine($"{context.RequesterName} {context.Hour}h apply failed");
        })
                      .When(context => context.Hour <= 2, pipeline =>
        {
            pipeline.Use((_, next) =>
            {
                Console.WriteLine("This should be invoked");
                next();
            });
            pipeline.Run(_ => Console.WriteLine("pass 1"));
            pipeline.Use((_, next) =>
            {
                Console.WriteLine("This should not be invoked");
                next();
                Console.WriteLine("will this invoke?");
            });
        })
                      .When(context => context.Hour <= 4, pipeline =>
        {
            pipeline.Run(_ => Console.WriteLine("pass 2"));
        })
                      .When(context => context.Hour <= 6, pipeline =>
        {
            pipeline.Run(_ => Console.WriteLine("pass 3"));
        })

        ;
        var requestPipeline = builder.Build();

        Console.WriteLine();
        foreach (var i in Enumerable.Range(1, 8))
        {
            Console.WriteLine($"--------- h:{i} apply Pipeline------------------");
            requestContext.Hour = i;
            requestPipeline.Invoke(requestContext);
            Console.WriteLine("----------------------------");
        }
    }
Exemple #13
0
        public void Build_WhenStepReplaced_WillNotReflectChanges()
        {
            // Arrange
            var builder = PipelineBuilder.Create <string>();

            builder.AddStep(arg => "string");
            Pipeline <string, string> pipeline = builder.Build();

            // Act
            // ReSharper disable once MustUseReturnValue
            builder.AddStep(_ => 0);

            // Assert
            Assert.IsType <DelegatePipelineStep <string, string> >(pipeline.Steps.First());
            Assert.IsType <DelegatePipelineStep <string, int> >(builder.Steps.First());
        }
Exemple #14
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);
        }
    }