public void Avoid_nested_FlowRuntimeExceptions()
        {
            var config = new FlowRuntimeConfiguration()
                         .AddAction("throw", () => { throw new ApplicationException("arg!"); })
                         .AddAction("continue", () => {}, true)
                         .AddAction("continue2", () => { }, true)
                         .AddStreamsFrom(@"
												/
												.in, continue
												continue, continue2
												continue2, throw
											 "                                            );

            using (var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                try
                {
                    fr.Process(".in");
                }
                catch (FlowRuntimeException ex)
                {
                    Assert.IsInstanceOf <UnhandledFlowRuntimeException>(ex);
                    Assert.IsTrue(ex.InnerException.GetType() != typeof(FlowRuntimeException) &&
                                  ex.InnerException.GetType() != typeof(UnhandledFlowRuntimeException));
                }
                catch (Exception ex)
                {
                    Assert.Fail("Unexpected exception type: " + ex);
                }
            }
        }
        public void High_prio_exception_message_terminates_runtime()
        {
            var config = new FlowRuntimeConfiguration()
                         .AddStreamsFrom(@"
													/
													.in, doit
													.stop, .error
													doit, .result
												 "                                                )
                         .AddAction <int, string>("doit", (int d, Action <string> continueWith) =>
            {
                continueWith(d + "x");
                continueWith(d + "y");
                throw new ApplicationException("arrrghhh!");
            });

            using (var fr = new FlowRuntime(config, new Schedule_for_async_breadthfirst_processing()))
            {
                IMessage result = null;

                fr.UnhandledException += ex => { fr.Process(new Message(".stop", ex)
                    {
                        Priority = 99
                    }); };

                fr.Process(".in", 42);

                Assert.IsTrue(fr.WaitForResult(500, _ => { if (result == null)
                                                           {
                                                               result = _;
                                                           }
                                               }));
                Assert.AreEqual("error", result.Port.Name);
            }
        }
        public void Nested_flows()
        {
            var frc = new FlowRuntimeConfiguration()
                      .AddStreamsFrom(@"
												.in, f.in // flow with explicit ports
												f.out, .out

												f
												.in, g // flow without explicit ports
												g, .out

												g
												., a // port without a name
												a, .
												"                                                )

                      .AddOperation(new Operation("a", (input, outputCont, _) => outputCont(new Message("a", input.Data.ToString() + "x"))));

            _sut.Configure(frc);

            _sut.Message += Console.WriteLine;

            _sut.Process(new Message(".in", "hello"));

            IMessage result = null;

            Assert.IsTrue(_sut.WaitForResult(500, _ => result = _));
            Assert.AreEqual("hellox", (string)result.Data);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(".in", "A");
                frc.AddStream("A", "B");
                frc.AddStream("B", "C");

                frc.AddFunc <int, int>("A", i => i + 1)
                .AddFunc <int, int>("B", i => i * 2)
                .AddAction <int>("C", (int i) => Console.WriteLine("={0}", i));
                fr.Configure(frc);

                // Trace messages selectively using Rx
                var tracer = new Subject <IMessage>();
                tracer.Where(msg => msg.Port.OperationName == "B") // message filter
                .Select(msg => (int)msg.Data)
                .Subscribe(i => Console.WriteLine("{0} -> B", i),  // message handler
                           _ => { });
                fr.Message += tracer.OnNext;


                fr.Process(new Message(".in", 1));
                fr.Process(new Message(".in", 2));
                fr.Process(new Message(".in", 3));

                fr.WaitForResult(500);
            }
        }
        public void Output_with_fan_out()
        {
            var twoResultsReceived = new AutoResetEvent(false);
            var frc = new FlowRuntimeConfiguration()
                      .AddStream(new Stream(".in", "A.in"))
                      .AddStream(new Stream(".in", "B.in"))
                      .AddStream(new Stream("A.out", ".out"))
                      .AddStream(new Stream("B.out", ".out"))

                      .AddOperation(new Operation("A", (input, outputCont, _) => outputCont(new Message("A.out", input.Data.ToString() + "x"))))
                      .AddOperation(new Operation("B", (input, outputCont, _) => outputCont(new Message("B.out", input.Data.ToString() + "y"))));

            _sut.Configure(frc);

            var results = new List <IMessage>();
            var n       = 0;

            _sut.Result += _ =>
            {
                results.Add(_);
                n++;
                if (n == 2)
                {
                    twoResultsReceived.Set();
                }
            };

            _sut.Process(new Message(".in", "hello"));

            Assert.IsTrue(twoResultsReceived.WaitOne(4000));
            Assert.That(results.Select(m => m.Data.ToString()).ToArray(), Is.EquivalentTo(new[] { "hellox", "helloy" }));
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            using(var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();

                var pageBufferContainer = new DataContainer<PageBuffer>();

                var frontend = new Frontend();

                frc.AddFlow(new Main(new Formatter(),
                                    frontend));
                frc.AddFlow(new Features(new CommandlineParser(pageBufferContainer),
                                        new TextFileAdapter(),
                                        new LineBuffer(pageBufferContainer),
                                        new Pager(pageBufferContainer)));
                fr.Configure(frc);

                frontend.displayFirstPage += fr.CreateEventProcessor(".displayFirstPage");
                frontend.displayLastPage += fr.CreateEventProcessor(".displayLastPage");
                frontend.displayNextPage += fr.CreateEventProcessor(".displayNextPage");
                frontend.displayPrevPage += fr.CreateEventProcessor(".displayPrevPage");

                //fr.Message += Console.WriteLine;

                fr.Process(new Message(".run", new[]{"test1.txt"}));

                fr.WaitForResult();
            }
        }
Beispiel #7
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /*
             * The dialog/clock is part of the flow.
             * Since it fires events without prior input it is defined as an [ActiveOperation]
             */
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();

                // Define flow
                // Feature: close application
                frc.AddStream("Dialog.closed", ".stop");

                // Feature: set alarm
                frc.AddStream("Dialog.setAlarm", "Join.in0");
                frc.AddStream("Dialog.setAlarm", "Alarm switched on");
                frc.AddStream("Clock.now", "Join.in1");
                frc.AddStream("Join", "Calc time diff");
                frc.AddStream("Calc time diff", "Display time diff");

                // Feature: stop alarm
                frc.AddStream("Dialog.stopAlarm", "Join.reset");
                frc.AddStream("Dialog.stopAlarm", "Alarm switched off");
                frc.AddStream("Dialog.stopAlarm", "Stop alarm");

                // Feature: sound alarm
                frc.AddStream("Calc time diff", "Alarm time reached");
                frc.AddStream("Alarm time reached", "Sound alarm");

                fr.Configure(frc);

                // Register operations
                var dlg    = new Dialog();
                var clock  = new npantarhei.runtime.patterns.operations.Clock();
                var player = new Soundplayer();

                frc.AddOperation(dlg)
                .AddOperation(clock)
                .AddAction("Alarm switched off", dlg.Alarm_switched_off).MakeSync()
                .AddAction("Alarm switched on", dlg.Alarm_switched_on).MakeSync()
                .AddAction <TimeSpan>("Alarm time reached", Alarm_time_reached)
                .AddFunc <Tuple <DateTime, DateTime>, TimeSpan>("Calc time diff", Calc_time_diff)
                .AddAction <TimeSpan>("Display time diff", dlg.Display_time_diff).MakeSync()
                .AddManualResetJoin <DateTime, DateTime>("Join")
                .AddAction("Sound alarm", player.Start_playing)
                .AddAction("Stop alarm", player.Stop_playing);
                fr.Configure(frc);

                fr.Message            += Console.WriteLine;
                fr.UnhandledException += Console.WriteLine;

                // Execute flow
                // Feature: start application
                Application.Run(dlg); // needs to run on this thread; cannot be done on flow runtime thread.
            }
        }
Beispiel #8
0
        public void Register_static_operations()
        {
            var config = new FlowRuntimeConfiguration()
                         .AddStaticOperations(typeof(MethodOperations))
                         .AddStreamsFrom(@"
									/
									.inProcedureVC, SProcedureVC
										SProcedureVC, .outProcedureVC
									.inFunctionV, SFunctionV
										SFunctionV, .outFunctionV
								 "                                );

            using (var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                var results = new List <IMessage>();
                fr.Result += results.Add;

                fr.Process(".inProcedureVC", 99);
                Assert.AreEqual(101, results[0].Data);

                results.Clear();
                fr.Process(".inFunctionV", 99);
                Assert.AreEqual(101, results[0].Data);
            }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            var textfileadapter = new TextfileAdapter();
            var formatter = new Formatter();

            var config = new FlowRuntimeConfiguration()
                .AddStreamsFrom("TelegramProblem.run.flow", Assembly.GetExecutingAssembly())

                .AddAction<string>("read", textfileadapter.Read).MakeAsync()
                .AddAction<string>("write", textfileadapter.Write, true)

                .AddAction<string, string>("decompose", formatter.Decompose)
                .AddAction<string, string>("concatenate", formatter.Concatenate)

                .AddAction<Tuple<string, string>>("textfileadapter_config", textfileadapter.Config)
                .AddAction<int>("formatter_config", formatter.Config);

            using(var fr = new FlowRuntime(config))
            {
                fr.UnhandledException += Console.WriteLine;

                fr.Process(".configFilenames", new Tuple<string,string>("source.txt", "target.txt"));
                fr.Process(".configLineWidth", 60);

                fr.Process(".run");

                fr.WaitForResult();

                Console.WriteLine(File.ReadAllText("target.txt"));
            }
        }
Beispiel #10
0
        public static void Main(string[] args)
        {
            var twitterops = new TwitterOperations();
            var gui = new MainWindow();
            var ironmq = new IronMQOperations("AppZwitschern", TokenRepository.LoadFrom("ironmq.credentials.txt"));
            var serialisieren = new Serialization<Versandauftrag>();
            var urlShortener = new TinyUrlOperations();
            var compressor = new TextCompressor();

            FlowRuntimeConfiguration.SynchronizationFactory = () => new SyncWithWPFDispatcher();

            var config = new FlowRuntimeConfiguration()
                .AddStreamsFrom("az.application.flows.flow", Assembly.GetExecutingAssembly())
                .AddFunc<Versandauftrag, Versandauftrag>("versandauftrag_schnueren", twitterops.Versandauftrag_um_access_token_erweitern)
                .AddFunc<Versandauftrag, string>("serialisieren", serialisieren.Serialize)
                .AddAction<string>("enqueue", ironmq.Enqueue, true)
                .AddFunc<string, string[]>("extract_urls", compressor.Extract_Urls)
                .AddFunc<Tuple<string, Tuple<string,string>[]>,string>("replace_urls", compressor.Replace_Urls)
                .AddFunc<IEnumerable<string>, Tuple<String,string>[]>("shorten_urls", urlShortener.ShortenMany)
                .AddOperation(new AutoResetJoin<string, Tuple<string,string>[]>("join"))
                .AddOperation(new Throttle("throttle", 1000))
                .AddAction<string>("display_shortened_text", gui.ShortenedText).MakeSync()
                .AddAction("versandstatus_anzeigen", () => gui.Versandstatus("Versendet!")).MakeSync();

            using (var fr = new FlowRuntime(config)) {
                fr.UnhandledException += ex => MessageBox.Show(ex.InnerException.Message);
                fr.Message += Console.WriteLine;

                gui.Versenden += fr.CreateEventProcessor<Versandauftrag>(".versenden");
                gui.ShortenText += fr.CreateEventProcessor<string>(".shortenText");

                var app = new Application { MainWindow = gui };
                app.Run(gui);
            }
        }
        public void Run()
        {
            var configServer = new FlowRuntimeConfiguration()
                                    .AddFunc<string, string>("hello", s => "hello, " + s)
                                    .AddStream(".@hello", "hello")
                                    .AddStream("hello", ".@hello");
            using (var server = new FlowRuntime(configServer))
            using (new WcfOperationHost(server, "localhost:8000"))
            {
                server.Message += Console.WriteLine;

                var configClient = new FlowRuntimeConfiguration()
                                    .AddOperation(new WcfStandInOperation("standin", "localhost:8100", "localhost:8000"))
                                    .AddStream(".in", "standin#hello")
                                    .AddStream("standin#hello", ".out");
                using (var client = new FlowRuntime(configClient))
                {
                    client.Message += Console.WriteLine;

                    client.Process(".in", "peter");

                    var result = "";
                    Assert.IsTrue(client.WaitForResult(2000, _ => result = (string)_.Data));

                    Assert.AreEqual("hello, peter", result);
                }
            }
        }
Beispiel #12
0
        public void Run()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");

            var configServer = new FlowRuntimeConfiguration()
                               .AddFunc <string, string>("hello", s => "hello, " + s)
                               .AddStream(".@hello", "hello")
                               .AddStream("hello", ".@hello");

            using (var server = new FlowRuntime(configServer))
                using (new PubnubOperationHost(server, cre, "host"))
                {
                    server.Message += Console.WriteLine;

                    var configClient = new FlowRuntimeConfiguration()
                                       .AddOperation(new PubnubStandInOperation("standin", cre, "host"))
                                       .AddStream(".in", "standin#hello")
                                       .AddStream("standin#hello", ".out");
                    using (var client = new FlowRuntime(configClient))
                    {
                        client.Message += Console.WriteLine;

                        client.Process(".in", "peter");

                        var result = "";
                        Assert.IsTrue(client.WaitForResult(5000, _ => result = (string)_.Data));

                        Assert.AreEqual("hello, peter", result);
                    }
                }
        }
        public void Run()
        {
            var config = new FlowRuntimeConfiguration()
                .AddOperations(new AssemblyCrawler(this.GetType().Assembly))
                .AddStreamsFrom(@"
                                    /
                                    .in, f
                                    f, g
                                    g, CrawlerEbc.Process
                                    CrawlerEbc.Result, .out
                                 ");

            foreach(var op in config.Operations)
                Console.WriteLine(op.Name);

            using(var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                int result = 0;
                fr.Result += _ => result = (int)_.Data;

                fr.Process(".in", 2);

                Assert.AreEqual(36, result);
            }
        }
Beispiel #14
0
        private static void Main(string[] args)
        {
            using (var repo = new az.tweetstore.ftp.Repository())
            {
                var frc = new FlowRuntimeConfiguration()
                    .AddStreamsFrom("az.receiver.application.root.flow", Assembly.GetExecutingAssembly())

                    .AddAction<string>("dequeue",
                                       new IronMQOperations("AppZwitschern",
                                                            TokenRepository.LoadFrom("ironmq.credentials.txt")).Dequeue)

                    .AddFunc<string, Versandauftrag>("deserialize", new Serialization<Versandauftrag>().Deserialize)
                    .AddAction<Versandauftrag>("speichern", repo.Store);

                using (var fr = new FlowRuntime(frc))
                {
                    fr.Message += Console.WriteLine;
                    fr.UnhandledException += e =>
                                                 {
                                                     Console.WriteLine(e.InnerException);
                                                     fr.Process(new Message(".stop") { Priority = 99 });
                                                 };

                    fr.Process(".start");
                    fr.WaitForResult();
                }
            }
        }
        public void Run_on_separate_thread()
        {
            var frc = new FlowRuntimeConfiguration();
            frc.AddStream(new Stream(".in", "asyncNop"));
            frc.AddStream(new Stream("asyncNop", ".out"));

            var cont = new FlowRuntimeConfiguration();

            long asyncThreadId = 0;
            cont.AddFunc<string, string>("asyncNop", _ =>
                                                    {
                                                        asyncThreadId = Thread.CurrentThread.GetHashCode();
                                                        return _;
                                                    }).MakeAsync();
            frc.AddOperations(cont.Operations);

            using (var sut = new FlowRuntime(frc))
            {
                IMessage result = null;
                long runtimeThreadId = 0;
                var are = new AutoResetEvent(false);
                sut.Result += _ =>
                                  {
                                      runtimeThreadId = Thread.CurrentThread.GetHashCode();
                                      result = _;
                                      are.Set();
                                  };

                sut.Process(new Message(".in", "hello"));

                Assert.IsTrue(are.WaitOne(1000));
                Assert.AreEqual("hello", result.Data.ToString());
                Assert.AreNotEqual(runtimeThreadId, asyncThreadId);
            }
        }
Beispiel #16
0
        static void Main2(string[] args)
        {
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(".in", "Find_files");
                frc.AddStream("Find_files", "scatter");
                frc.AddStream("scatter.stream", "Count_words");
                frc.AddStream("scatter.count", "gather.count");
                frc.AddStream("Count_words", "gather.stream");
                frc.AddStream("gather", "Total");
                frc.AddStream("Total", ".out");

                frc.AddFunc <string, IEnumerable <String> >("Find_files", Find_files).MakeAsync()
                .AddFunc <string, int>("Count_words", Count_words).MakeParallel()
                .AddFunc <IEnumerable <int>, Tuple <int, int> >("Total", Total)
                .AddOperation(new Scatter <string>("scatter"))
                .AddOperation(new Gather <int>("gather"));

                fr.Configure(frc);

                var start = DateTime.Now;
                fr.Process(new Message(".in", "x"));

                Tuple <int, int> result = null;
                fr.WaitForResult(5000, _ => result = (Tuple <int, int>)_.Data);
                var delta = DateTime.Now.Subtract(start);

                Console.WriteLine("{0} words in {1} files, {2}msec", result.Item2, result.Item1, delta);
            }
        }
        public void Run_flat()
        {
            using (var fr = new FlowRuntime())
            {
                /*
                 * (.in) -> (Split) -> (Map) -> (Build) -> (.out)
                 */
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(new Stream(".in", "Split"));
                frc.AddStream(new Stream("Split", "Map"));
                frc.AddStream(new Stream("Map", "Build"));
                frc.AddStream(new Stream("Build", ".out"));

                frc.AddFunc<string, IEnumerable<string>>("Split", configuration => configuration.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries));
                frc.AddAction<IEnumerable<string>, IEnumerable<KeyValuePair<string, string>>>("Map", Map);
                frc.AddFunc<IEnumerable<KeyValuePair<string, string>>, Dictionary<string, string>>("Build", Build);
                fr.Configure(frc);

                Dictionary<string, string> dict = null;
                var are = new AutoResetEvent(false);
                fr.Result += _ =>
                                {
                                    dict = (Dictionary<string, string>) _.Data;
                                    are.Set();
                                };

                fr.Process(new Message(".in", "a=1;b=2"));

                Assert.IsTrue(are.WaitOne(500));
                Assert.AreEqual(2, dict.Count);
                Assert.AreEqual("1", dict["a"]);
                Assert.AreEqual("2", dict["b"]);
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(".in", "Pushc");
                frc.AddStream("Pushc", "Find Files");
                frc.AddStream("Pushc.exception", "Handle Exception");
                frc.AddStream("Find Files", "Count Words");
                frc.AddStream("Count Words", "popc");
                frc.AddStream("Popc", "Total");
                frc.AddStream("Total", ".out");

                frc.AddFunc <IEnumerable <string>, IEnumerable <int> >("Count Words", Count_words3)
                .AddFunc <string, IEnumerable <String> >("Find Files", Find_files)
                .AddAction <FlowRuntimeException>("Handle Exception", Handle_exception)
                .AddPopCausality("Popc")
                .AddPushCausality("Pushc")
                .AddFunc <IEnumerable <int>, Tuple <int, int> >("Total", Total);
                fr.Configure(frc);

                fr.Process(new Message(".in", "x"));

                Tuple <int, int> result = null;
                fr.WaitForResult(5000, _ => result = (Tuple <int, int>)_.Data);

                if (result != null)
                {
                    Console.WriteLine("{0} words in {1} files", result.Item2, result.Item1);
                }
            }
        }
Beispiel #19
0
        public void Run()
        {
            var config = new FlowRuntimeConfiguration()
                                .AddStreamsFrom(@"
                                                    /
                                                    .in, rechenwerk.teilen
                                                    rechenwerk.resultat, .result
                                                    rechenwerk.divisionDurchNull, .fehler
                                                    ")
                                .AddEventBasedComponent("rechenwerk", new Rechenwerk());

            using(var fr = new FlowRuntime(config))
            {
                fr.Process(".in", new Tuple<int,int>(42,7));

                IMessage result = null;
                fr.WaitForResult(_ => result = _);
                Assert.AreEqual(".result", result.Port.Fullname);
                Assert.AreEqual(6, (int)result.Data);

                fr.Process(".in", new Tuple<int, int>(42, 0));

                fr.WaitForResult(_ => result = _);
                Assert.AreEqual(".fehler", result.Port.Fullname);
                Assert.AreEqual(new Tuple<int,int>(42,0), result.Data);
            }
        }
Beispiel #20
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /*
             * The dialog/clock is part of the flow.
             * Since it fires events without prior input it is defined as an [ActiveOperation]
             */
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();

                // Define flow
                // Feature: close application
                frc.AddStream("Dialog.closed", ".stop");

                // Feature: set alarm
                frc.AddStream("Dialog.setAlarm", "Join.in0");
                frc.AddStream("Dialog.setAlarm", "Alarm switched on");
                frc.AddStream("Clock.now", "Join.in1");
                frc.AddStream("Join", "Calc time diff");
                frc.AddStream("Calc time diff", "Display time diff");

                // Feature: stop alarm
                frc.AddStream("Dialog.stopAlarm", "Join.reset");
                frc.AddStream("Dialog.stopAlarm", "Alarm switched off");
                frc.AddStream("Dialog.stopAlarm", "Stop alarm");

                // Feature: sound alarm
                frc.AddStream("Calc time diff", "Alarm time reached");
                frc.AddStream("Alarm time reached", "Sound alarm");

                fr.Configure(frc);

                // Register operations
                var dlg = new Dialog();
                var clock = new npantarhei.runtime.patterns.operations.Clock();
                var player = new Soundplayer();

                frc.AddOperation(dlg)
                   .AddOperation(clock)
                   .AddAction("Alarm switched off", dlg.Alarm_switched_off).MakeSync()
                   .AddAction("Alarm switched on", dlg.Alarm_switched_on).MakeSync()
                   .AddAction<TimeSpan>("Alarm time reached", Alarm_time_reached)
                   .AddFunc<Tuple<DateTime,DateTime>,TimeSpan>("Calc time diff", Calc_time_diff)
                   .AddAction<TimeSpan>("Display time diff", dlg.Display_time_diff).MakeSync()
                   .AddManualResetJoin<DateTime, DateTime>("Join")
                   .AddAction("Sound alarm", player.Start_playing)
                   .AddAction("Stop alarm", player.Stop_playing);
                fr.Configure(frc);

                fr.Message += Console.WriteLine;
                fr.UnhandledException += Console.WriteLine;

                // Execute flow
                // Feature: start application
                Application.Run(dlg); // needs to run on this thread; cannot be done on flow runtime thread.
            }
        }
Beispiel #21
0
        public void test_cyclic_flow_with_async_EBC()
        {
            Console.WriteLine("test started for {0} flow cycles...", maxCycles);

            var config = new FlowRuntimeConfiguration()
                                .AddStreamsFrom(@"
                                                    /
                                                    .in, cyclic.run
                                                    cyclic.continue, cyclic.run
                                                    cyclic.stopOn, .out
                                                    ")
                                .AddEventBasedComponent("cyclic", new CyclicFlow());

            using(var fr = new FlowRuntime(config))
            {
                fr.UnhandledException += Console.WriteLine;

                fr.Process(".in", 1);

                IMessage result = null;
                Assert.IsTrue(fr.WaitForResult(5000, _ => result = _),
                              "result not received within 5 seconds");
                Assert.AreEqual(".out", result.Port.Fullname);
                Assert.AreEqual(maxCycles, (int)result.Data);
            }
        }
        public void Two_input_join()
        {
            var frc = new FlowRuntimeConfiguration()
                      .AddStream(new Stream(".inString", "mrj.in0"))
                      .AddStream(new Stream(".inInt", "mrj.in1"))
                      .AddStream(new Stream(".inReset", "mrj.reset"))
                      .AddStream(new Stream("mrj", ".out"))

                      .AddManualResetJoin <string, int>("mrj");

            using (var fr = new FlowRuntime(frc))
            {
                fr.UnhandledException += Console.WriteLine;

                fr.Process(new Message(".inString", "x"));
                fr.Process(new Message(".inInt", 42));

                IMessage result = null;
                Assert.IsTrue(fr.WaitForResult(500, _ => result = _));
                var tresult = (Tuple <string, int>)result.Data;
                Assert.AreEqual("x", tresult.Item1);
                Assert.AreEqual(42, tresult.Item2);

                fr.Process(new Message(".inReset", null));
                fr.Process(new Message(".inString", "y"));
                fr.Process(new Message(".inInt", 43));
                Assert.IsTrue(fr.WaitForResult(500, _ => result = _));
                tresult = (Tuple <string, int>)result.Data;
                Assert.AreEqual("y", tresult.Item1);
                Assert.AreEqual(43, tresult.Item2);
            }
        }
Beispiel #23
0
        public void Run() {
            var mailAccess = MailAccessRepository.LoadFrom("mailfollowup.receiver.application.mail.access.txt", Assembly.GetExecutingAssembly());
            var awsSecrets = SecretsRepository.LoadFrom("mailfollowup.receiver.application.awssecrets.txt", Assembly.GetExecutingAssembly());

            var frc = new FlowRuntimeConfiguration();

            frc.AddStreamsFrom("mailfollowup.receiver.application.root.flow", Assembly.GetExecutingAssembly());

            var imap = new Imap(mailAccess);
            var erinnerungsauftraege = new Erinnerungsauftraege(Now, new FollowupParser());
            var store = new MailStore(awsSecrets);

            frc.AddAction<Mail>("mail_abholen", imap.Mail_holen);
            frc.AddFunc<Mail, Erinnerungsauftrag>("erinnerungsauftrag_erstellen", erinnerungsauftraege.Erinnerungsauftrag_erstellen);
            frc.AddFunc<Erinnerungsauftrag, string>("erinnerungsauftrag_speichern", store.Save);
            frc.AddAction<string>("mail_verschieben", imap.Mail_verschieben);

            using (var fr = new FlowRuntime(frc)) {
                fr.Message += Console.WriteLine;
                fr.UnhandledException += e => {
                    Console.WriteLine(e);
                    Environment.Exit(1);
                };

                fr.Process(".start");
                fr.WaitForResult();
            }
        }
Beispiel #24
0
        public void Run()
        {
            var config = new FlowRuntimeConfiguration()
                         .AddStreamsFrom(@"
                                                    /
                                                    .in, rechenwerk.teilen
                                                    rechenwerk.resultat, .result
                                                    rechenwerk.divisionDurchNull, .fehler
                                                    ")
                         .AddEventBasedComponent("rechenwerk", new Rechenwerk());

            using (var fr = new FlowRuntime(config))
            {
                fr.Message            += Console.WriteLine;
                fr.UnhandledException += Console.WriteLine;

                fr.Process(".in", new Tuple <int, int>(42, 7));

                IMessage result = null;
                Assert.IsTrue(fr.WaitForResult(1000, _ => result = _));
                Assert.AreEqual(".result", result.Port.Fullname);
                Assert.AreEqual(6, (int)result.Data);


                fr.Process(".in", new Tuple <int, int>(42, 0));

                Assert.IsTrue(fr.WaitForResult(2000, _ => result = _));
                Assert.AreEqual(".fehler", result.Port.Fullname);
                Assert.AreEqual(new Tuple <int, int>(42, 0), result.Data);
            }
        }
Beispiel #25
0
        public void Run() {
            var mainWindowViewModel = new MainWindowViewModel();
            var mainWindow = new MainWindow();
            mainWindow.DataContext = mainWindowViewModel;
            var app = new Application {
                MainWindow = mainWindow
            };

            var mapper = new Mapper(mainWindowViewModel);

            FlowRuntimeConfiguration.DispatcherFactory = () => new DispatchForWPF();

            var flowRuntimeConfguration = new FlowRuntimeConfiguration()
                .AddStreamsFrom("fotobrowser.root.flow", Assembly.GetExecutingAssembly())
                .AddFunc("arbeitsverzeichnis_ermitteln", () => Environment.GetCommandLineArgs()[1])
                .AddFunc<string, IEnumerable<contracts.Directory>>("unterverzeichnisse_ermitteln", Drives.Verzeichnisse_ermitteln)
                .AddAction<IEnumerable<contracts.Directory>>("verzeichnisse_mappen", mapper.MapDirectories).MakeDispatched()
                .AddFunc<string, IEnumerable<string>>("bilddateien_ermitteln", Drives.Bilddateien_ermitteln)
                .AddAction<IEnumerable<string>>("bilddateien_mappen", mapper.MapFilenames).MakeDispatched();

            using (var flowRuntime = new FlowRuntime(flowRuntimeConfguration)) {
                flowRuntime.Message += Console.WriteLine;
                flowRuntime.UnhandledException += Console.WriteLine;

                mainWindow.Refresh += flowRuntime.CreateEventProcessor<string>(".refresh");

                flowRuntime.Process(".start");
                app.Run(mainWindow);
            }
        }
Beispiel #26
0
        public void Active_EBC_fires_in_flow()
        {
            var ebc = new ActiveEbc();

            var config = new FlowRuntimeConfiguration()
                         .AddStreamsFrom(@"
                                                    /
                                                    .in, subflow.in
                                                    subflow.out, .out

                                                    subflow
                                                    .in, ebc.Run
                                                    ebc.Out, .out
                                                 ")
                         .AddEventBasedComponent("ebc", ebc);

            using (var fr = new FlowRuntime(config))
            {
                fr.Process(".in", "hello");

                var result = "";
                Assert.IsTrue(fr.WaitForResult(2000, _ => result = (string)_.Data));
                Assert.AreEqual("hellox", result);
            }
        }
Beispiel #27
0
        public void Connect_transceivers_operationhost()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");

            var configServer = new FlowRuntimeConfiguration()
                               .AddFunc <string, string>("greeting", s => s + "x")
                               .AddStream(".@greeting", "greeting")
                               .AddStream("greeting", ".@greeting");

            using (var server = new FlowRuntime(configServer))
                using (var serverhost = new PubnubOperationHost(server, cre, "thehost"))
                {
                    server.Message += Console.WriteLine;

                    var config = new FlowRuntimeConfiguration()
                                 .AddOperation(new PubnubStandInOperation("op", cre, "thehost"))
                                 .AddStream(".in", "op#greeting")
                                 .AddStream("op#greeting", ".out");
                    using (var fr = new FlowRuntime(config))
                    {
                        fr.Message += Console.WriteLine;

                        fr.Process(".in", "hello");

                        var result = "";
                        Assert.IsTrue(fr.WaitForResult(5000, _ => result = _.Data as string));
                        Assert.AreEqual("hellox", result);
                    }
                }
        }
Beispiel #28
0
        public void Connect_transceivers_operationhost()
        {
            var cre = PubnubCredentials.LoadFrom("pubnub credentials.txt");

            var configServer = new FlowRuntimeConfiguration()
                        .AddFunc<string, string>("greeting", s => s + "x")
                        .AddStream(".@greeting", "greeting")
                        .AddStream("greeting", ".@greeting");
            using (var server = new FlowRuntime(configServer))
            using (var serverhost = new PubnubOperationHost(server, cre, "thehost"))
            {
                server.Message += Console.WriteLine;

                var config = new FlowRuntimeConfiguration()
                                .AddOperation(new PubnubStandInOperation("op", cre, "thehost"))
                                .AddStream(".in", "op#greeting")
                                .AddStream("op#greeting", ".out");
                using (var fr = new FlowRuntime(config))
                {
                    fr.Message += Console.WriteLine;

                    fr.Process(".in", "hello");

                    var result = "";
                    Assert.IsTrue(fr.WaitForResult(5000, _ => result = _.Data as string));
                    Assert.AreEqual("hellox", result);
                }
            }
        }
Beispiel #29
0
        public test_sync_with_dialog_win()
        {
            InitializeComponent();

            var frc = new FlowRuntimeConfiguration();

            frc.AddStream(new Stream(".inMakeSync", "gettime"));
            frc.AddStream(new Stream("gettime", "showtimeMakeSync"));
            frc.AddStream(new Stream(".inAttribute", "gettime2"));
            frc.AddStream(new Stream("gettime2", "showtimeAttribute"));
            frc.AddStream(new Stream(".inEbc", "gettime3"));
            frc.AddStream(new Stream("gettime3", "ebc.showtimeAttribute"));

            var opcont = new FlowRuntimeConfiguration();

            opcont.AddFunc("gettime", () => DateTime.Now);
            opcont.AddFunc("gettime2", () => DateTime.Now);
            opcont.AddFunc("gettime3", () => DateTime.Now);
            opcont.AddAction <DateTime>("showtimeMakeSync", (DateTime _) =>
            {
                Console.WriteLine("event handler thread: {0}",
                                  Thread.CurrentThread.GetHashCode());
                label1.Text = _.ToString();
                listBox1.Items.Add(_.ToString());
            })
            .MakeDispatched();
            opcont.AddAction <DateTime>("showtimeAttribute", this.ShowTimeAttribute);
            opcont.AddEventBasedComponent("ebc", this);

            frc.AddOperations(opcont.Operations);

            _fr = new FlowRuntime(frc);
            _fr.UnhandledException += Console.WriteLine;
        }
Beispiel #30
0
        static void Main(string[] args)
        {
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(".in", "Pushc");
                frc.AddStream("Pushc", "Find Files");
                frc.AddStream("Pushc.exception", "Handle Exception");
                frc.AddStream("Find Files", "Count Words");
                frc.AddStream("Count Words", "popc");
                frc.AddStream("Popc", "Total");
                frc.AddStream("Total", ".out");

                frc.AddFunc<IEnumerable<string>, IEnumerable<int>>("Count Words", Count_words3)
                   .AddFunc<string, IEnumerable<String>>("Find Files", Find_files)
                   .AddAction<FlowRuntimeException>("Handle Exception", Handle_exception)
                   .AddPopCausality("Popc")
                   .AddPushCausality("Pushc")
                   .AddFunc<IEnumerable<int>, Tuple<int, int>>("Total", Total);
                fr.Configure(frc);

                fr.Process(new Message(".in", "x"));

                Tuple<int, int> result = null;
                fr.WaitForResult(5000, _ => result = (Tuple<int, int>)_.Data);

                if (result != null)
                    Console.WriteLine("{0} words in {1} files", result.Item2, result.Item1);
            }
        }
        public void Run()
        {
            var config = new FlowRuntimeConfiguration()
                         .AddOperations(new AssemblyCrawler(this.GetType().Assembly))
                         .AddStreamsFrom(@"
                                    /
                                    .in, f
                                    f, g
                                    g, CrawlerEbc.Process
                                    CrawlerEbc.Result, .out
                                 ");

            foreach (var op in config.Operations)
            {
                Console.WriteLine(op.Name);
            }

            using (var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                int result = 0;
                fr.Result += _ => result = (int)_.Data;

                fr.Process(".in", 2);

                Assert.AreEqual(36, result);
            }
        }
Beispiel #32
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var operation = new Operationsschlange();
            var akku = new Zwischenergebnis();
            var ui = new WinMain();

            var config = new FlowRuntimeConfiguration()
                .AddStreamsFrom("Taschenrechner.root.flow", Assembly.GetExecutingAssembly())

                .AddFunc<int, int>("ergebnis_zwischenspeichern", akku.Merken)
                .AddFunc<Tuple<int, int, Operatoren>, int>("operanden_verknuepfen", Rechenwerk.Operanden_verknüpfen)
                .AddFunc<Rechenauftrag, int>("operation_speichern", operation.Einstellen)
                .AddPushCausality("pushc")
                .AddPopCausality("popc")
                .AddFunc<Tuple<int, int>, Tuple<int, int, Operatoren>>("vormalige_operation_laden", operation.Herausholen)
                .AddEventBasedComponent("akku", akku)
                .AddEventBasedComponent("ui", ui);

            using (var fr = new FlowRuntime(config))
            {
                fr.Message += Console.WriteLine;

                fr.UnhandledException += fr.CreateEventProcessor<FlowRuntimeException>(".error");

                Application.Run(ui);
            }
        }
Beispiel #33
0
        public void Run() {
            var awsSecrets = SecretsRepository.LoadFrom("mailfollowup.reminder.app.awssecrets.txt", Assembly.GetExecutingAssembly());
            var smtpSecrets = MailAccessRepository.LoadFrom("mailfollowup.reminder.app.mail.smtp.txt", Assembly.GetExecutingAssembly());

            var frc = new FlowRuntimeConfiguration();

            frc.AddStreamsFrom("mailfollowup.reminder.app.root.flow", Assembly.GetExecutingAssembly());

            var store = new MailStore(awsSecrets);
            var smtp = new Smtp(smtpSecrets);

            frc.AddFunc("aktuelle_zeit_ermitteln", Now);
            frc.AddAction<DateTime, Erinnerungsauftrag>("erinnerungsauftrag_holen", store.Load);
            frc.AddFunc<Erinnerungsauftrag, Erinnerungsauftrag>("erinnerung_versenden", smtp.Send);
            frc.AddAction<Erinnerungsauftrag>("erinnerungsauftrag_loeschen", store.Delete);

            using (var fr = new FlowRuntime(frc)) {
                fr.Message += Console.WriteLine;
                fr.UnhandledException += e => {
                    Console.WriteLine(e);
                    Environment.Exit(1);
                };

                fr.Process(".start");
                fr.WaitForResult();
            }
        }
Beispiel #34
0
        public void Procedure_with_2_continuations()
        {
            var sut = new FlowRuntimeConfiguration();

            sut.AddAction <int, string, bool>("opname", Bifurcate);

            var op = sut.Operations.First();

            IMessage result0 = null;
            IMessage result1 = null;

            op.Implementation(new Message("x", 2), msg =>
            {
                if (msg.Port.Name == "out0")
                {
                    result0 = msg;
                }
                if (msg.Port.Name == "out1")
                {
                    result1 = msg;
                }
            }, null);

            Assert.AreEqual("2x", (string)result0.Data);
            Assert.IsTrue((bool)result1.Data);
        }
        public void Scatter_gather()
        {
            var frc = new FlowRuntimeConfiguration();

            frc.AddStream(new Stream(".in", "scatter"));
            frc.AddStream(new Stream("scatter.stream", "sleep"));
            frc.AddStream(new Stream("scatter.count", "gather.count"));
            frc.AddStream(new Stream("sleep", "gather.stream"));
            frc.AddStream(new Stream("gather", ".out"));

            frc.AddFunc <int, int>("sleep", _ =>
            {
                Console.WriteLine("sleep {0} on {1}", _, Thread.CurrentThread.GetHashCode());
                Thread.Sleep(_);
                return(_);
            }).MakeParallel();
            frc.AddOperation(new Scatter <int>("scatter"));
            frc.AddOperation(new Gather <int>("gather"));

            using (var fr = new FlowRuntime(frc))
            {
                var list = new[] { 10, 200, 100, 30, 200, 70 };
                fr.Process(new Message(".in", list));

                IMessage result = null;
                Assert.IsTrue(fr.WaitForResult(1000, _ => result = _));
                Assert.That(list, Is.EquivalentTo(((int[])result.Data)));
            }
        }
        public test_sync_with_dialog_win()
        {
            InitializeComponent();

            var frc = new FlowRuntimeConfiguration();
            frc.AddStream(new Stream(".inMakeSync", "gettime"));
            frc.AddStream(new Stream("gettime", "showtimeMakeSync"));
            frc.AddStream(new Stream(".inAttribute", "gettime2"));
            frc.AddStream(new Stream("gettime2", "showtimeAttribute"));
            frc.AddStream(new Stream(".inEbc", "gettime3"));
            frc.AddStream(new Stream("gettime3", "ebc.showtimeAttribute"));

            var opcont = new FlowRuntimeConfiguration();
            opcont.AddFunc("gettime", () => DateTime.Now);
            opcont.AddFunc("gettime2", () => DateTime.Now);
            opcont.AddFunc("gettime3", () => DateTime.Now);
            opcont.AddAction<DateTime>("showtimeMakeSync", (DateTime _) =>
                                                       {
                                                           Console.WriteLine("event handler thread: {0}",
                                                                             Thread.CurrentThread.GetHashCode());
                                                           label1.Text = _.ToString();
                                                           listBox1.Items.Add(_.ToString());
                                                       })
                  .MakeDispatched();
            opcont.AddAction<DateTime>("showtimeAttribute", this.ShowTimeAttribute);
            opcont.AddEventBasedComponent("ebc", this);

            frc.AddOperations(opcont.Operations);

            _fr = new FlowRuntime(frc);
            _fr.UnhandledException += Console.WriteLine;
        }
        public void Run_flat()
        {
            using (var fr = new FlowRuntime())
            {
                /*
                 * (.in) -> (Split) -> (Map) -> (Build) -> (.out)
                 */
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(new Stream(".in", "Split"));
                frc.AddStream(new Stream("Split", "Map"));
                frc.AddStream(new Stream("Map", "Build"));
                frc.AddStream(new Stream("Build", ".out"));

                frc.AddFunc <string, IEnumerable <string> >("Split", configuration => configuration.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
                frc.AddAction <IEnumerable <string>, IEnumerable <KeyValuePair <string, string> > >("Map", Map);
                frc.AddFunc <IEnumerable <KeyValuePair <string, string> >, Dictionary <string, string> >("Build", Build);
                fr.Configure(frc);

                Dictionary <string, string> dict = null;
                var are = new AutoResetEvent(false);
                fr.Result += _ =>
                {
                    dict = (Dictionary <string, string>)_.Data;
                    are.Set();
                };

                fr.Process(new Message(".in", "a=1;b=2"));

                Assert.IsTrue(are.WaitOne(500));
                Assert.AreEqual(2, dict.Count);
                Assert.AreEqual("1", dict["a"]);
                Assert.AreEqual("2", dict["b"]);
            }
        }
Beispiel #38
0
        public void Run()
        {
            var config = new FlowRuntimeConfiguration()
                .AddEventBasedComponent("Op", new Op())
                .AddStream(".receive@op", "op.receive")
                .AddStream("op.send", ".send@op");

            using(var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                fr.Message += Console.WriteLine;

                var sut = new HostTranslator();

                sut.Translated_input += fr.Process;
                fr.Result += sut.Process_local_output;

                Tuple<string, HostOutput> result = null;
                sut.Translated_output += _ => result = _;

                var input = new HostInput { CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "op.receive", StandInEndpointAddress = "localhost:1234"};
                sut.Process_remote_input(input);

                Assert.AreEqual("localhost:1234", result.Item1);
                Assert.AreEqual(input.CorrelationId, result.Item2.CorrelationId);
                Assert.AreEqual("<hello>".Serialize(), result.Item2.Data);
                Assert.AreEqual("op.send", result.Item2.Portname);
            }
        }
        public void Throttle()
        {
            var frc = new FlowRuntimeConfiguration();

            frc.AddFunc <int, int>("nop1", _ =>
            {
                Console.WriteLine("nop1: {0}", _);
                return(_);
            });
            frc.AddFunc <int, int>("nop2", _ =>
            {
                Console.WriteLine("nop2: {0}", _);
                return(_);
            });

            frc.AddStream(new Stream(".in", "nop1"));
            frc.AddStream(new Stream("nop1", "nop2"));
            frc.AddStream(new Stream("nop2", ".out"));

            using (var fr = new FlowRuntime(frc))
            {
                var are = new AutoResetEvent(false);
                fr.Result += _ => { if ((int)_.Data == -1)
                                    {
                                        are.Set();
                                    }
                };

                fr.Throttle(100);

                new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1 }.ToList().ForEach(i => fr.Process(new Message(".in", i)));

                Assert.IsFalse(are.WaitOne(1000));
            }
        }
        public void Two_input_join()
        {
            var frc = new FlowRuntimeConfiguration()
                      .AddStream(new Stream(".inString", "arj.in0"))
                      .AddStream(new Stream(".inInt", "arj.in1"))
                      .AddStream(new Stream("arj", ".out"))

                      .AddAutoResetJoin <string, int>("arj");

            using (var fr = new FlowRuntime(frc))
            {
                fr.Message += _ => Console.WriteLine(_.Port);

                IMessage result = null;
                var      are    = new AutoResetEvent(false);
                fr.Result += _ =>
                {
                    result = _;
                    are.Set();
                };

                fr.Process(new Message(".inString", "x"));
                fr.Process(new Message(".inInt", 42));

                Assert.IsTrue(are.WaitOne(500));
                var tresult = (Tuple <string, int>)result.Data;
                Assert.AreEqual("x", tresult.Item1);
                Assert.AreEqual(42, tresult.Item2);
            }
        }
        public void Process_messages_on_different_threads()
        {
            Console.WriteLine("test thread: {0}", Thread.CurrentThread.GetHashCode());

            var frc = new FlowRuntimeConfiguration();

            frc.AddStream(new Stream(".in", "doParallel**"));
            frc.AddStream(new Stream("doParallel", ".out"));

            var threads = new Dictionary <long, int>();

            frc.AddFunc <int, int>("doParallel",
                                   x =>
            {
                lock (threads)
                {
                    if (
                        threads.ContainsKey(
                            Thread.CurrentThread.GetHashCode()))
                    {
                        threads[Thread.CurrentThread.GetHashCode()] += 1;
                    }
                    else
                    {
                        threads.Add(Thread.CurrentThread.GetHashCode(), 1);
                    }
                }
                Console.WriteLine("thread {0}: {1}.",
                                  Thread.CurrentThread.GetHashCode(), x);
                Thread.Sleep((DateTime.Now.Millisecond % 100 + 1) * 50);
                return(x);
            });

            using (var sut = new FlowRuntime(frc))
            {
                var are     = new AutoResetEvent(false);
                var results = new List <int>();
                sut.Result += _ =>
                {
                    Console.WriteLine("result: {0}.", _.Data);
                    lock (results)
                    {
                        results.Add((int)_.Data);
                        if (results.Count == 5)
                        {
                            are.Set();
                        }
                    }
                };

                sut.Process(new Message(".in", 1));
                sut.Process(new Message(".in", 2));
                sut.Process(new Message(".in", 3));
                sut.Process(new Message(".in", 4));
                sut.Process(new Message(".in", 5));

                Assert.IsTrue(are.WaitOne(10000), "Processing took too long; not enough numbers received");
                Assert.AreEqual(15, results.Sum(), "Wrong sum; some number got processed twice");
            }
        }
Beispiel #42
0
        static void Main(string[] args)
        {
            var textfileadapter = new TextfileAdapter();
            var formatter       = new Formatter();

            var config = new FlowRuntimeConfiguration()
                         .AddStreamsFrom("TelegramProblem.run.flow", Assembly.GetExecutingAssembly())

                         .AddAction <string>("read", textfileadapter.Read).MakeAsync()
                         .AddAction <string>("write", textfileadapter.Write, true)

                         .AddAction <string, string>("decompose", formatter.Decompose)
                         .AddAction <string, string>("concatenate", formatter.Concatenate)

                         .AddAction <Tuple <string, string> >("textfileadapter_config", textfileadapter.Config)
                         .AddAction <int>("formatter_config", formatter.Config);

            using (var fr = new FlowRuntime(config))
            {
                fr.UnhandledException += Console.WriteLine;

                fr.Process(".configFilenames", new Tuple <string, string>("source.txt", "target.txt"));
                fr.Process(".configLineWidth", 60);

                fr.Process(".run");

                fr.WaitForResult();

                Console.WriteLine(File.ReadAllText("target.txt"));
            }
        }
        public void Throttle()
        {
            var frc = new FlowRuntimeConfiguration();
            frc.AddFunc<int, int>("nop1", _ =>
                                            {
                                                Console.WriteLine("nop1: {0}", _);
                                                return _;
                                            });
            frc.AddFunc<int, int>("nop2", _ =>
                                            {
                                                Console.WriteLine("nop2: {0}", _);
                                                return _;
                                            });

            frc.AddStream(new Stream(".in", "nop1"));
            frc.AddStream(new Stream("nop1", "nop2"));
            frc.AddStream(new Stream("nop2", ".out"));

            using (var fr = new FlowRuntime(frc))
            {
                var are = new AutoResetEvent(false);
                fr.Result += _ => { if ((int)_.Data == -1) are.Set(); };

                fr.Throttle(100);

                new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -1 }.ToList().ForEach(i => fr.Process(new Message(".in", i)));

                Assert.IsFalse(are.WaitOne(1000));
            }
        }
Beispiel #44
0
        public void Run() {
            FlowRuntimeConfiguration.SynchronizationFactory = () => new SyncWithWPFDispatcher();
            var frc = new FlowRuntimeConfiguration();
            frc.AddStreamsFrom("appchatten.application.root.flow", Assembly.GetExecutingAssembly());

            var chat = new Chat(new QueueFinder<Message>());
            var mainWindow = new MainWindow();

            frc.AddAction<string>("anmelden", chat.Anmelden);
            frc.AddAction<string>("verbinden", chat.Verbinden);
            frc.AddFunc<string, Message>("absender_hinzufuegen", chat.Absender_hinzufuegen);
            frc.AddFunc<Message, Message>("versenden", chat.Versenden).MakeAsync();
            frc.AddFunc<Message, string>("formatieren", m => string.Format("{0}: {1}", m.Absender, m.Text));
            frc.AddAction<string>("anzeigen", mainWindow.MessageHinzufügen).MakeSync();
            frc.AddOperation(new Timer("timer", 500));
            frc.AddAction<Message>("empfangen", chat.Empfangen).MakeAsync();
            frc.AddAction<FlowRuntimeException>("fehler_anzeigen", ex => mainWindow.FehlerAnzeigen(ex.InnerException.Message)).MakeSync();

            using (var fr = new FlowRuntime(frc)) {
                fr.Message += Console.WriteLine;

                fr.UnhandledException += fr.CreateEventProcessor<FlowRuntimeException>(".exception");

                mainWindow.Anmelden += fr.CreateEventProcessor<string>(".anmelden");
                mainWindow.Verbinden += fr.CreateEventProcessor<string>(".verbinden");
                mainWindow.TextSenden += fr.CreateEventProcessor<string>(".senden");

                var app = new Application{MainWindow = mainWindow};
                app.Run(mainWindow);
            }
        }     
Beispiel #45
0
        static void Main(string[] args)
        {
            using(var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(".in", "A");
                frc.AddStream("A", "B");
                frc.AddStream("B", "C");

                frc.AddFunc<int, int>("A", i => i + 1)
                   .AddFunc<int, int>("B", i => i * 2)
                   .AddAction<int>("C", (int i) => Console.WriteLine("={0}", i));
                fr.Configure(frc);

                // Trace messages selectively using Rx
                var tracer = new Subject<IMessage>();
                tracer.Where(msg => msg.Port.OperationName == "B") // message filter
                      .Select(msg => (int)msg.Data)
                      .Subscribe(i => Console.WriteLine("{0} -> B", i), // message handler
                                 _ => { });
                fr.Message += tracer.OnNext;

                fr.Process(new Message(".in", 1));
                fr.Process(new Message(".in", 2));
                fr.Process(new Message(".in", 3));

                fr.WaitForResult(500);
            }
        }
Beispiel #46
0
        public void Avoid_nested_FlowRuntimeExceptions()
        {
            var config = new FlowRuntimeConfiguration()
                            .AddAction("throw", () => { throw new ApplicationException("arg!"); })
                            .AddAction("continue", () => {}, true)
                            .AddAction("continue2", () => { }, true)
                            .AddStreamsFrom(@"
                                                /
                                                .in, continue
                                                continue, continue2
                                                continue2, throw
                                             ");

            using(var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                try
                {
                    fr.Process(".in");
                }
                catch(FlowRuntimeException ex)
                {
                    Assert.IsInstanceOf<UnhandledFlowRuntimeException>(ex);
                    Assert.IsTrue(ex.InnerException.GetType() != typeof(FlowRuntimeException) &&
                                  ex.InnerException.GetType() != typeof(UnhandledFlowRuntimeException));
                }
                catch (Exception ex)
                {
                    Assert.Fail("Unexpected exception type: " + ex);
                }
            }
        }
Beispiel #47
0
        public void Run()
        {
            var configServer = new FlowRuntimeConfiguration()
                               .AddFunc <string, string>("hello", s => "hello, " + s)
                               .AddStream(".@hello", "hello")
                               .AddStream("hello", ".@hello");

            using (var server = new FlowRuntime(configServer))
                using (new WcfOperationHost(server, "localhost:8000"))
                {
                    server.Message += Console.WriteLine;

                    var configClient = new FlowRuntimeConfiguration()
                                       .AddOperation(new WcfStandInOperation("standin", "localhost:8100", "localhost:8000"))
                                       .AddStream(".in", "standin#hello")
                                       .AddStream("standin#hello", ".out");
                    using (var client = new FlowRuntime(configClient))
                    {
                        client.Message += Console.WriteLine;

                        client.Process(".in", "peter");

                        var result = "";
                        Assert.IsTrue(client.WaitForResult(2000, _ => result = (string)_.Data));

                        Assert.AreEqual("hello, peter", result);
                    }
                }
        }
Beispiel #48
0
        static void Main(string[] args)
        {
            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();

                var pageBufferContainer = new DataContainer <PageBuffer>();

                var frontend = new Frontend();

                frc.AddFlow(new Main(new Formatter(),
                                     frontend));
                frc.AddFlow(new Features(new CommandlineParser(pageBufferContainer),
                                         new TextFileAdapter(),
                                         new LineBuffer(pageBufferContainer),
                                         new Pager(pageBufferContainer)));
                fr.Configure(frc);

                frontend.displayFirstPage += fr.CreateEventProcessor(".displayFirstPage");
                frontend.displayLastPage  += fr.CreateEventProcessor(".displayLastPage");
                frontend.displayNextPage  += fr.CreateEventProcessor(".displayNextPage");
                frontend.displayPrevPage  += fr.CreateEventProcessor(".displayPrevPage");

                //fr.Message += Console.WriteLine;

                fr.Process(new Message(".run", new[] { "test1.txt" }));

                fr.WaitForResult();
            }
        }
Beispiel #49
0
        public void Active_EBC_fires_in_flow()
        {
            var ebc = new ActiveEbc();

            var config = new FlowRuntimeConfiguration()
                                .AddStreamsFrom(@"
                                                    /
                                                    .in, subflow.in
                                                    subflow.out, .out

                                                    subflow
                                                    .in, ebc.Run
                                                    ebc.Out, .out
                                                 ")
                                .AddEventBasedComponent("ebc", ebc);

            using (var fr = new FlowRuntime(config))
            {
                fr.Process(".in", "hello");

                var result = "";
                Assert.IsTrue(fr.WaitForResult(2000, _ => result = (string)_.Data));
                Assert.AreEqual("hellox", result);
            }
        }
Beispiel #50
0
        public void Run()
        {
            var config = new FlowRuntimeConfiguration()
                         .AddEventBasedComponent("Op", new Op())
                         .AddStream(".receive@op", "op.receive")
                         .AddStream("op.send", ".send@op");

            using (var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                fr.Message += Console.WriteLine;

                var sut = new HostTranslator();

                sut.Translated_input += fr.Process;
                fr.Result            += sut.Process_local_output;

                Tuple <string, HostOutput> result = null;
                sut.Translated_output += _ => result = _;

                var input = new HostInput {
                    CorrelationId = Guid.NewGuid(), Data = "hello".Serialize(), Portname = "op.receive", StandInEndpointAddress = "localhost:1234"
                };
                sut.Process_remote_input(input);

                Assert.AreEqual("localhost:1234", result.Item1);
                Assert.AreEqual(input.CorrelationId, result.Item2.CorrelationId);
                Assert.AreEqual("<hello>".Serialize(), result.Item2.Data);
                Assert.AreEqual("op.send", result.Item2.Portname);
            }
        }
Beispiel #51
0
        private static void Main(string[] args)
        {
            using (var repo = new az.tweetstore.ftp.Repository())
            {
                var frc = new FlowRuntimeConfiguration()
                          .AddStreamsFrom("az.receiver.application.root.flow", Assembly.GetExecutingAssembly())

                          .AddAction <string>("dequeue",
                                              new IronMQOperations("AppZwitschern",
                                                                   TokenRepository.LoadFrom("ironmq.credentials.txt")).Dequeue)

                          .AddFunc <string, Versandauftrag>("deserialize", new Serialization <Versandauftrag>().Deserialize)
                          .AddAction <Versandauftrag>("speichern", repo.Store);

                using (var fr = new FlowRuntime(frc))
                {
                    fr.Message            += Console.WriteLine;
                    fr.UnhandledException += e =>
                    {
                        Console.WriteLine(e.InnerException);
                        fr.Process(new Message(".stop")
                        {
                            Priority = 99
                        });
                    };

                    fr.Process(".start");
                    fr.WaitForResult();
                }
            }
        }
        private static void Main(string[] args)
        {
            _email = ConfigurationManager.AppSettings["GoogleAccount"];
            _baseDirPath = String.IsNullOrEmpty(ConfigurationManager.AppSettings["BasePath"]) ? @"c:\temp\" : ConfigurationManager.AppSettings["BasePath"];
            _deleteOlderFiles = bool.Parse(String.IsNullOrEmpty(ConfigurationManager.AppSettings["DeleteOlderFiles"]) ? "false" : ConfigurationManager.AppSettings["DeleteOlderFiles"]);
            _label = "Listen Subscriptions";
            _dateFormat = "yyyyMMddTHHmmss";
            _getFilesFromTheLastXDays =
                int.Parse(String.IsNullOrEmpty(ConfigurationManager.AppSettings["GetFilesFromTheLastXDays"]) ? "3" : ConfigurationManager.AppSettings["GetFilesFromTheLastXDays"]);
            _reader = null;

            //Console.WriteLine("Enter password");
            var password = "******";//  Console.ReadLine();

            _reader = Reader.CreateReader(_email, password, "scroll") as Reader;

            using (var fr = new FlowRuntime())
            {
                var frc = new FlowRuntimeConfiguration();
                frc.AddStream(".in", "Get_Feeds");
                frc.AddStream("Get_Feeds", ".out");

                frc.AddFunc<Reader, IEnumerable<UrlAndFeed>>("Get_Feeds", getFeedsWithGivenLabel);

                fr.Configure(frc);

                fr.Process(new Message(".in", _reader));

                fr.WaitForResult(5000, _ => Console.WriteLine(_.Data));

                Console.ReadLine();
            }
        }
        public void Scatter_gather()
        {
            var frc = new FlowRuntimeConfiguration();
            frc.AddStream(new Stream(".in", "scatter"));
            frc.AddStream(new Stream("scatter.stream", "sleep"));
            frc.AddStream(new Stream("scatter.count", "gather.count"));
            frc.AddStream(new Stream("sleep", "gather.stream"));
            frc.AddStream(new Stream("gather", ".out"));

            frc.AddFunc<int, int>("sleep", _ =>
                                            {
                                                Console.WriteLine("sleep {0} on {1}", _, Thread.CurrentThread.GetHashCode());
                                                Thread.Sleep(_);
                                                return _;
                                            }).MakeParallel();
            frc.AddOperation(new Scatter<int>("scatter"));
            frc.AddOperation(new Gather<int>("gather"));

            using(var fr = new FlowRuntime(frc))
            {

                var list = new[] {10, 200, 100, 30, 200, 70};
                fr.Process(new Message(".in", list));

                IMessage result = null;
                Assert.IsTrue(fr.WaitForResult(1000, _ => result = _));
                Assert.That(list, Is.EquivalentTo(((List<int>)result.Data).ToArray()));
            }
        }
        public void Run_on_separate_thread()
        {
            var frc = new FlowRuntimeConfiguration()
                            .AddStream(new Stream(".in", "serNop0"))
                            .AddStream(new Stream("serNop0", "serNop1"))
                            .AddStream(new Stream("serNop1", ".out"));
            var asyncThreadIds0 = new List<long>();

            frc.AddFunc<string, string>("serNop0", _ =>
                                                    {
                                                        lock (asyncThreadIds0)
                                                        {
                                                            Console.WriteLine("serNop0: {0} on {1}", _, Thread.CurrentThread.GetHashCode());
                                                            asyncThreadIds0.Add(Thread.CurrentThread.GetHashCode());
                                                        }
                                                        return _;
                                                    }).MakeSerial();

            var asyncThreadIds1 = new List<long>();
            frc.AddFunc<string, string>("serNop1", _ =>
                                                    {
                                                        lock (asyncThreadIds1)
                                                        {
                                                            Console.WriteLine("serNop1: {0} on {1}", _, Thread.CurrentThread.GetHashCode());
                                                            asyncThreadIds1.Add(Thread.CurrentThread.GetHashCode());
                                                        }
                                                        return _;
                                                    }).MakeSerial();

            using (var sut = new FlowRuntime(frc))
            {
                const int N = 5;
                var results = new List<IMessage>();
                long runtimeThreadId = 0;
                var are = new AutoResetEvent(false);
                sut.Result += _ =>
                                  {
                                      lock (results)
                                      {
                                          Console.WriteLine("res {0} on {1}", _.Data, Thread.CurrentThread.GetHashCode());
                                          runtimeThreadId = Thread.CurrentThread.GetHashCode();
                                          results.Add(_);
                                          if (results.Count == N) are.Set();
                                      }
                                  };

                for (var i = 0; i < N; i++ )
                    sut.Process(new Message(".in", "x" + i));

                Assert.IsTrue(are.WaitOne(10000));
                Assert.AreEqual(N, results.Count);
                Assert.That(results.Select(r => r.Data.ToString()).ToArray(), Is.EquivalentTo(new[]{"x0", "x1", "x2", "x3", "x4"}));
                Assert.IsFalse(asyncThreadIds0.Contains(runtimeThreadId));
                Assert.IsFalse(asyncThreadIds1.Contains(runtimeThreadId));
                Assert.AreEqual(0, asyncThreadIds0.Intersect(asyncThreadIds1).Count());
            }
        }
Beispiel #55
0
        public void Run_on_separate_thread()
        {
            var frc = new FlowRuntimeConfiguration();

            frc.AddStream(new Stream(".in", "parNop"));
            frc.AddStream(new Stream("parNop", ".out"));

            var cont = new FlowRuntimeConfiguration();

            var asyncThreadIds = new List <long>();

            cont.AddFunc <string, string>("parNop", _ =>
            {
                lock (asyncThreadIds)
                {
                    Console.WriteLine("{0} on {1}", _, Thread.CurrentThread.GetHashCode());
                    asyncThreadIds.Add(Thread.CurrentThread.GetHashCode());
                }
                Thread.Sleep((DateTime.Now.Millisecond % 100 + 1) * 50);
                return(_);
            }).MakeParallel();
            frc.AddOperations(cont.Operations);


            using (var sut = new FlowRuntime(frc, new Schedule_for_async_breadthfirst_processing()))
            {
                const int N               = 5;
                var       results         = new List <IMessage>();
                long      runtimeThreadId = 0;
                var       are             = new AutoResetEvent(false);
                sut.Result += _ =>
                {
                    lock (results)
                    {
                        Console.WriteLine("res {0} on {1}", _.Data, Thread.CurrentThread.GetHashCode());
                        runtimeThreadId = Thread.CurrentThread.GetHashCode();
                        results.Add(_);
                        if (results.Count == N)
                        {
                            are.Set();
                        }
                    }
                };

                for (var i = 0; i < N; i++)
                {
                    sut.Process(new Message(".in", "x" + i));
                }

                Assert.IsTrue(are.WaitOne(10000));
                Assert.AreEqual(N, results.Count);
                Assert.That(results.Select(r => r.Data.ToString()).ToArray(), Is.EquivalentTo(new[] { "x0", "x1", "x2", "x3", "x4" }));
                Assert.IsFalse(asyncThreadIds.Contains(runtimeThreadId));
                Assert.IsTrue(asyncThreadIds.Distinct().Count() > 1);
            }
        }
        public void Setup()
        {
            var frc = new FlowRuntimeConfiguration();

            frc.AddPushCausality("push");
            frc.AddPopCausality("pop");

            frc.AddFunc <int, int>("exOn0", i =>
            {
                if (i == 0)
                {
                    throw new ApplicationException("on0");
                }
                return(i);
            });
            frc.AddFunc <int, int>("exOn1", i =>
            {
                if (i == 1)
                {
                    throw new ApplicationException("on1");
                }
                return(i);
            });
            frc.AddAction <int>("exOn2", i =>
            {
                if (i == 2)
                {
                    throw new ApplicationException("on2");
                }
            });

            _exCausality = null;
            _are         = new AutoResetEvent(false);
            frc.AddAction <FlowRuntimeException>("handleEx", _ =>
            {
                _exCausality = _;
                _are.Set();
            });

            frc.AddStream(new Stream(".in", "push"));
            frc.AddStream(new Stream("push", "exOn0"));
            frc.AddStream(new Stream("push.exception", "handleEx"));
            frc.AddStream(new Stream("exOn0", "exOn1"));
            frc.AddStream(new Stream("exOn1", "pop"));
            frc.AddStream(new Stream("pop", "exOn2"));

            _fr = new FlowRuntime(frc);

            _exUnhandled            = null;
            _fr.UnhandledException += _ => {
                _exUnhandled = _;
                _are.Set();
            };
        }
Beispiel #57
0
        static void Main(string[] args)
        {
            var config = new FlowRuntimeConfiguration()
                                .AddStreamsFrom("SubstantiveExtrahieren.root.flow", Assembly.GetExecutingAssembly())
                                .AddOperations(new AssemblyCrawler(Assembly.GetExecutingAssembly()));

            using(var fr = new FlowRuntime(config, new Schedule_for_sync_depthfirst_processing()))
            {
                fr.Process(".run", args[0]);
            }
        }
Beispiel #58
0
        public Publisher(IRepository repository, ITwitterOperations twitterOperations)
        {
            _config = new FlowRuntimeConfiguration()
                .AddStreamsFrom("az.publisher.application.root.flow", Assembly.GetExecutingAssembly())

                .AddAction<string>("list", repository.List)
                .AddAction<string, Versandauftrag>("load", repository.Load)
                .AddFunc<Versandauftrag, Versandauftrag>("versenden", twitterOperations.Versenden)
                .AddAction<Versandauftrag>("delete", repository.Delete)

                .AddAction<Versandauftrag, Versandauftrag>("filtern", this.Filtern);
        }
Beispiel #59
0
        public Publisher(IRepository repository, ITwitterOperations twitterOperations)
        {
            _config = new FlowRuntimeConfiguration()
                      .AddStreamsFrom("az.publisher.application.root.flow", Assembly.GetExecutingAssembly())

                      .AddAction <string>("list", repository.List)
                      .AddAction <string, Versandauftrag>("load", repository.Load)
                      .AddFunc <Versandauftrag, Versandauftrag>("versenden", twitterOperations.Versenden)
                      .AddAction <Versandauftrag>("delete", repository.Delete)

                      .AddAction <Versandauftrag, Versandauftrag>("filtern", this.Filtern);
        }
        public void Register_continuation_procedure()
        {
            var sut = new FlowRuntimeConfiguration();

            sut.AddAction<string, int>("p", Process_with_continuation);

            var op = sut.Operations.First();

            IMessage result = null;
            op.Implementation(new Message("f", "hello"), _ => result = _, null);

            Assert.AreEqual(5, (int)result.Data);
        }