/// <inheritdoc />
        public async Task <bool> DisplayAsync(object dataContext, ICoordinationArguments coordinationArguments)
        {
            if (coordinationArguments is RegionArguments arguments)
            {
                var control = RegionManager.GetControl(arguments.RegionManagerReference, arguments.TargetRegion);

                if (control.DataContext is IBehaviorHost interactive)
                {
                    var context = new ContentChangingBehaviorContext(ServiceContext.ServiceProvider, control.DataContext, dataContext);
                    await BehaviorRunner.ExecuteAsync(interactive, context);

                    if (context.Cancelled)
                    {
                        Log.Debug($"Change prevented by {nameof(ContentChangingBehaviorContext)}.");
                        return(false);
                    }
                }

                var composer = ComposerFactory.Create(control);
                if (composer == null)
                {
                    return(false);
                }

                return(await composer.ComposeAsync(new ViewCompositionContext(control, dataContext, coordinationArguments)));
            }

            return(false);
        }
            public void Should_throw_the_specified_exception_if_unhandled()
            {
                bool compensated = false;
                var  p           = new Payload {
                    Name = "Chris"
                };
                Task <Payload> task = ComposerFactory.Compose(p, composer =>
                {
                    composer.Execute(x =>
                    {
                        x.Name = "Joe";
                        throw new InvalidOperationException("This is expected");
                    });

                    composer.Compensate(compensation =>
                    {
                        compensated = true;
                        return(compensation.Throw(new NotImplementedException("This is also expected")));
                    });
                });

                Assert.Throws <NotImplementedException>(async() => { Payload payload = await task; });

                Assert.IsTrue(compensated);
            }
Beispiel #3
0
        /// <summary>
        /// 對指定計算式策略實例化
        /// </summary>
        /// <param name="topicIdentifier">題型識別ID</param>
        /// <returns>策略實例</returns>
        public virtual ITopic CreateTopicInstance(string topicIdentifier)
        {
            // 以題型為單位取得Composer
            _composer = ComposerFactory.GetComporser(topicIdentifier);

            // 返回緩衝區中的運算符對象
            Lazy <ITopic, ITogicMetaDataView> lazyTopic = TopicCache.GetOrAdd(_composer, (o) =>
            {
                // 內部部件組合
                _composer.Compose(this);

                // 指定運算符并獲取處理類型
                IEnumerable <Lazy <ITopic, ITogicMetaDataView> > topics = Topics.Where(d =>
                {
                    return(d.Metadata.TopicIdentifier.Equals(topicIdentifier, StringComparison.CurrentCultureIgnoreCase));
                });
                // 部件是否存在
                if (!topics.Any())
                {
                    // 指定的題型策略對象未找到
                    throw new TopicNotFoundException(MessageUtil.GetMessage(() => MsgResources.E0018L, topicIdentifier));
                }
                LogUtil.LogDebug(MessageUtil.GetMessage(() => MsgResources.I0003L));

                return(topics.First());
            });

            // 返回該運算符處理類型的實例(實例化)
            var topic = lazyTopic.Value;

            // 內部部件組合(策略抽象類中的計算式工廠對象注入)
            _composer.Compose(topic);
            return(topic);
        }
        public ComposeResult <TranslationUnit> Compose(ICollection <Token> tokens)
        {
            var result = new TranslationUnit();

            var declarationComposer = ComposerFactory.Create <Declaration>();

            result.Declarations = InfiniteSequence.Create <int>()
                                  .Select(v =>
            {
                var r  = declarationComposer.Compose(tokens);
                tokens = r.Tokens;
                return(r.Result);
            })
                                  .TakeWhile(v => v.HasValue)
                                  .Select(v => v.Value)
                                  .ToList();

            var statementComposer = ComposerFactory.Create <Statement>();

            result.Statements = InfiniteSequence.Create <int>()
                                .Select(v =>
            {
                var r  = statementComposer.Compose(tokens);
                tokens = r.Tokens;
                return(r.Result);
            })
                                .TakeWhile(v => v.HasValue)
                                .Select(v => v.Value)
                                .ToList();

            return(new ComposeResult <TranslationUnit> {
                Result = result.ToMaybe(), Tokens = tokens
            });
        }
        /// <summary>
        /// <see cref="CompileController"/>構造	構築依賴組合並導入<see cref="ApiProcess"/>API處理類
        /// </summary>
        public CompileController()
        {
            // 獲取HTML支援類Composer
            Composer composer = ComposerFactory.GetComporser(this.GetType().Assembly);

            composer.Compose(this);
        }
 public void Should_throw_an_exception_without_compensation()
 {
     Task task =
         ComposerFactory.Compose(
             composer => { composer.Execute(() => { throw new InvalidOperationException("This is expected"); }); });
     var exception = Assert.Throws <InvalidOperationException>(async() => await task);
 }
Beispiel #7
0
        /// <summary>
        /// 題型指定獲取HTML支援類實例
        /// </summary>
        /// <param name="topicIdentifier">題型類型</param>
        /// <returns>HTML支援類實例</returns>
        public IHtmlSupport CreateHtmlSupportInstance(string topicIdentifier)
        {
            // 獲取HTML支援類Composer
            _composer = ComposerFactory.GetComporser(topicIdentifier);

            // 返回緩衝區中的支援類對象
            Lazy <IHtmlSupport, IHtmlSupportMetaDataView> lazyHtmlSupport = HtmlSupportCache.GetOrAdd(_composer, (o) =>
            {
                // 從MEF容器中注入本類的屬性信息(注入HTML支援類屬性)
                _composer.Compose(this);

                // 取得指定類型下的支援類類型參數
                IEnumerable <Lazy <IHtmlSupport, IHtmlSupportMetaDataView> > supports = Supports.Where(d => d.Metadata.TopicIdentifier.Equals(topicIdentifier, StringComparison.CurrentCultureIgnoreCase));
                if (!supports.Any())
                {
                    throw new HtmlSupportNotFoundException(MessageUtil.GetMessage(() => MsgResources.E0021L, topicIdentifier));
                }

                LogUtil.LogDebug(MessageUtil.GetMessage(() => MsgResources.I0008L));

                return(supports.First());
            });

            // 該題型HTML支持類實例(實例化)
            var htmlSupport = lazyHtmlSupport.Value;

            // 內部部件組合
            _composer.Compose(htmlSupport);
            // 返回該題型HTML支持類實例
            return(htmlSupport);
        }
Beispiel #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="topicIdentifier"></param>
        public void ReleaseExportsHtmlSupport(string topicIdentifier)
        {
            // 獲取HTML支援類Composer
            _composer = ComposerFactory.GetComporser(topicIdentifier);

            HtmlSupportCache.TryRemove(_composer, out Lazy <IHtmlSupport, IHtmlSupportMetaDataView> support);
            _composer.ReleaseExport(support);
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="topicIdentifier"></param>
        public void Release(string topicIdentifier)
        {
            // 獲取HTML支援類Composer
            _composer = ComposerFactory.GetComporser(topicIdentifier);

            TopicCache.TryRemove(_composer, out Lazy <ITopic, ITogicMetaDataView> topic);
            _composer.ReleaseExport(topic);
        }
Beispiel #10
0
        /// <summary>
        /// 畫面構造函數
        /// </summary>
        public FrmMain()
        {
            InitializeComponent();

            // 獲取HTML支援類Composer
            Composer composer = ComposerFactory.GetComporser(this.GetType().Assembly);

            composer.Compose(this);
        }
        /// <inheritdoc />
        public async Task <bool> DisplayAsync(object dataContext, ICoordinationArguments coordinationArguments)
        {
            if (dataContext == null)
            {
                throw new ArgumentNullException(nameof(dataContext));
            }
            if (coordinationArguments == null)
            {
                throw new ArgumentNullException(nameof(coordinationArguments));
            }

            if (coordinationArguments is WindowArguments arguments)
            {
                if (!WindowManager.TryGetWindow(arguments.WindowId, out var window))
                {
                    Log.Debug($"Creating window for {dataContext.GetType().FullName} using id [{arguments.WindowId}]");
                    foreach (var windowFactory in WindowFactories)
                    {
                        if (windowFactory.CanCreateWindow(dataContext))
                        {
                            window = windowFactory.CreateWindow(dataContext);
                            WindowManager.RegisterWindow(window, arguments.WindowId);
                        }
                    }

                    if (window == null)
                    {
                        Log.Error($"No factory was able to create a window for {dataContext.GetType().FullName}");
                        return(false);
                    }
                }

                var composer = ComposerFactory.Create(window);
                if (composer == null)
                {
                    return(false);
                }

                if (window.DataContext is IBehaviorHost interactive)
                {
                    var context = new ContentChangingBehaviorContext(ServiceContext.ServiceProvider, window.DataContext, dataContext);
                    await BehaviorRunner.ExecuteAsync(interactive, context);

                    if (context.Cancelled)
                    {
                        Log.Debug($"Change prevented by {nameof(ContentChangingBehaviorContext)}.");
                        return(false);
                    }
                }

                return(await composer.ComposeAsync(new ViewCompositionContext(window, dataContext, coordinationArguments)));
            }

            Log.Error($"Unable to visualize {dataContext} because {nameof(arguments)} is not of type {typeof(WindowArguments).FullName}");
            return(false);
        }
Beispiel #12
0
        public async void Should_execute_the_task()
        {
            bool called = false;

            Task task = ComposerFactory.Compose(composer => composer.Execute(() => called = true));

            await task;

            Assert.IsTrue(called);
        }
Beispiel #13
0
        public async void Should_execute_the_method_immediately()
        {
            bool called = false;

            Task task = ComposerFactory.Compose(composer => composer.Execute(() => called = true, ExecuteOptions.RunSynchronously));

            await task;

            Assert.IsTrue(called);
        }
Beispiel #14
0
            public async void Should_support_cool_stuff()
            {
                SideCarrier <B> factorySideCarrier = new FactorySideCarrier <B>();
                var             carrier            = new AircraftCarrier();

                Payload <A> payload = new PayloadImpl <A>(new A());

                Task <Payload <A> > task = ComposerFactory.Compose(payload, composer => { factorySideCarrier.Compose(composer, carrier); });

                await task;
            }
Beispiel #15
0
        public async void Should_include_the_handled_exception()
        {
            var tracker = new Tracker(3);

            IRetryPolicy retryPolicy = Retry.Selected <InvalidOperationException>().Immediate(5);

            Task task = ComposerFactory.Compose(composer => composer.Retry(retryPolicy, x => x.Execute(tracker.FaultingMethod)));

            await task;

            Assert.AreEqual(4, tracker.CallCount);
        }
Beispiel #16
0
        public void Should_call_the_method_three_times()
        {
            var tracker = new Tracker(3);

            IRetryPolicy retryPolicy = Retry.Immediate(5);

            Task task = ComposerFactory.Compose(composer => composer.Retry(retryPolicy, x => x.Execute(tracker.FaultingMethod)));

            task.Wait();

            Assert.AreEqual(4, tracker.CallCount);
        }
Beispiel #17
0
        public void Should_call_the_method_only_once()
        {
            var tracker = new Tracker(3);

            IRetryPolicy retryPolicy = Retry.Filter <InvalidOperationException>(x => false).Immediate(5);

            Task task = ComposerFactory.Compose(composer => composer.Retry(retryPolicy, x => x.Execute(tracker.FaultingMethod)));

            Assert.Throws <InvalidOperationException>(async() => await task);

            Assert.AreEqual(1, tracker.CallCount);
        }
Beispiel #18
0
            public void Should_call_an_async_method_nicely()
            {
                var task = ComposerFactory.Compose(new Payload(), composer =>
                {
                    composer.ExecuteAsync(async(payload, token) =>
                    {
                        var result = await SomeAsyncMethod(payload.Name);

                        payload.Result = result;
                    });
                });
            }
Beispiel #19
0
        public void Should_not_include_the_excluded()
        {
            var tracker = new Tracker(3);

            IRetryPolicy retryPolicy = Retry.Except <InvalidOperationException>().Immediate(5);

            Task task = ComposerFactory.Compose(composer => composer.Retry(retryPolicy, x => x.Execute(tracker.FaultingMethod)));

            Assert.Throws <InvalidOperationException>(async() => await task);

            Assert.AreEqual(1, tracker.CallCount);
        }
Beispiel #20
0
        public async void Should_delay_then_execute()
        {
            bool called = false;

            Task task = ComposerFactory.Compose(composer =>
            {
                composer.Delay(100);
                composer.Execute(() => called = true);
            });

            await task;

            Assert.IsTrue(called);
        }
Beispiel #21
0
        public void Should_always_be_called()
        {
            bool called = false;

            Task task = ComposerFactory.Compose(composer =>
            {
                composer.Execute(() => { throw new InvalidOperationException("This is expected"); });

                composer.Finally(status => { called = true; });
            });

            Assert.Throws <InvalidOperationException>(async() => await task);

            Assert.IsTrue(called);
        }
Beispiel #22
0
        public void Should_fault_if_not_compensated()
        {
            var tracker = new Tracker(3);

            Stopwatch timer = Stopwatch.StartNew();

            Task task = ComposerFactory.Compose(x => x.Repeat(3, composer =>
            {
                composer.Execute(tracker.RepeatedMethod);
            }, tracker.Token));

            Assert.Throws <AggregateException>(() => task.Wait());

            timer.Stop();

            Assert.AreEqual(1, tracker.CallCount);
        }
Beispiel #23
0
        public void Should_repeat_until_canceled()
        {
            var tracker = new Tracker(3);

            Stopwatch timer = Stopwatch.StartNew();

            Task task = ComposerFactory.Compose(x => x.Repeat(3, composer =>
            {
                composer.Execute(tracker.RepeatedMethod);
                composer.Compensate(comp => comp.Handled());
            }, tracker.Token));

            task.Wait();

            timer.Stop();

            Assert.AreEqual(3, tracker.CallCount);
        }
Beispiel #24
0
        public void Should_repeat_until_canceled()
        {
            var tracker = new Tracker(10);

            Stopwatch timer = Stopwatch.StartNew();

            Task task = ComposerFactory.Compose(x => x.Repeat(10, composer =>
            {
                Console.WriteLine("Timespan: {0}", timer.Elapsed);
                composer.Execute(tracker.RepeatedMethod);
            }, tracker.Token));

            task.Wait();

            timer.Stop();

            Assert.AreEqual(10, tracker.CallCount);
        }
Beispiel #25
0
        public void Should_call_the_method_for_each_timespan()
        {
            var tracker = new Tracker(3);

            IRetryPolicy retryPolicy = Retry.Intervals(10, 50, 500, 1000);

            Task task = ComposerFactory.Compose(composer => composer.Retry(retryPolicy, x => x.Execute(tracker.FaultingMethod)));

            Stopwatch timer = Stopwatch.StartNew();

            task.Wait();

            timer.Stop();

            Console.WriteLine("Timespan: {0}", timer.Elapsed);

            Assert.AreEqual(4, tracker.CallCount);
        }
        public async void Should_compensate_on_exception()
        {
            bool called = false;

            Task task = ComposerFactory.Compose(composer =>
            {
                composer.Execute(() => { throw new InvalidOperationException("This is expected"); });

                composer.Compensate(compensation =>
                {
                    called = true;

                    return(compensation.Handled());
                });
            });

            await task;

            Assert.IsTrue(called);
        }
        public void Should_throw_the_same_exception_if_not_handled()
        {
            bool called = false;

            Task task = ComposerFactory.Compose(composer =>
            {
                composer.Execute(() => { throw new InvalidOperationException("This is expected"); });

                composer.Compensate(compensation =>
                {
                    called = true;

                    return(compensation.Throw());
                });
            });

            var exception = Assert.Throws <InvalidOperationException>(async() => await task);

            Assert.IsTrue(called);
        }
Beispiel #28
0
        public async void Should_compose_a_nested_delay()
        {
            int sequenceId = 0;
            int delayed    = 0;
            int executed   = 0;

            Task task = ComposerFactory.Compose(composer =>
            {
                composer.ComposeTask(x =>
                {
                    x.ExecuteAsync(token => Task.Delay(100, token));
                    x.Execute(() => delayed = ++sequenceId);
                });

                composer.Execute(() => executed = ++sequenceId);
            });
            await task;

            Assert.AreEqual(1, delayed);
            Assert.AreEqual(2, executed);
        }
Beispiel #29
0
            public async void Should_use_async_processing()
            {
                int threadId = Thread.CurrentThread.ManagedThreadId;

                int            asyncThreadId = threadId;
                Task <Payload> task          = ComposerFactory.Compose(new Payload {
                    Name = "Chris"
                }, composer =>
                {
                    composer.Execute(x =>
                    {
                        x.Name        = "Joe";
                        asyncThreadId = Thread.CurrentThread.ManagedThreadId;
                    });
                });

                Payload payload = await task;

                Assert.AreEqual("Joe", payload.Name);
                Assert.AreNotEqual(threadId, asyncThreadId);
            }
Beispiel #30
0
            public void Should_use_async_processing_and_capture_exceptions()
            {
                int threadId      = Thread.CurrentThread.ManagedThreadId;
                int asyncThreadId = threadId;

                Task <Payload> task = ComposerFactory.Compose(new Payload {
                    Name = "Chris"
                }, composer =>
                {
                    composer.ExecuteAsync((x, token) =>
                    {
                        x.Name        = "Joe";
                        asyncThreadId = Thread.CurrentThread.ManagedThreadId;

                        throw new InvalidOperationException("This is expected");
                    });
                });

                Assert.Throws <InvalidOperationException>(async() => { Payload payload = await task; });

                Assert.AreNotEqual(threadId, asyncThreadId);
            }