Debian Codegraph @

external/rx/Rx/NET/Samples/HOL/CS/Excercise9/Step04/Program.cs

raw
1 using System;
2 using System.Linq;
3 using System.Reactive.Linq;
4 using System.Windows.Forms;
5 using System.Reactive.Disposables;
6 using Excercise9.DictionarySuggestService;
7
8 namespace Excercise9
9 {
10 class Program
11 {
12 static void Main()
13 {
14 var txt = new TextBox();
15 var lst = new ListBox { Top = txt.Height + 10 };
16
17 var frm = new Form()
18 {
19 Controls = { txt, lst }
20 };
21
22 #if PRODUCTION
23 // Turn the user input into a tamed sequence of strings.
24 var textChanged = from evt in Observable.FromEventPattern(txt, "TextChanged")
25 select ((TextBox)evt.Sender).Text;
26
27 var input = textChanged
28 .Throttle(TimeSpan.FromSeconds(1))
29 .DistinctUntilChanged();
30 #else
31 const string INPUT = "reactive";
32
33 var rand = new Random();
34
35 var input = Observable.Generate(
36 3,
37 len => len <= INPUT.Length,
38 len => len + 1,
39 len => INPUT.Substring(0, len),
40 _ => TimeSpan.FromMilliseconds(rand.Next(200, 1200))
41 )
42 .ObserveOn(txt)
43 .Do(term => txt.Text = term)
44 .Throttle(TimeSpan.FromSeconds(1));
45 #endif
46
47 // Bridge with the web service's MatchInDict method.
48 var svc = new DictServiceSoapClient("DictServiceSoap");
49 var matchInDict = Observable.FromAsyncPattern<string, string, string, DictionaryWord[]>
50 (svc.BeginMatchInDict, svc.EndMatchInDict);
51
52 #if PRODUCTION
53 Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
54 term => matchInDict("wn", term, "prefix");
55 #else
56 Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
57 term => Observable.Return
58 (
59 (from i in Enumerable.Range(0, rand.Next(0, 50))
60 select new DictionaryWord { Word = term + i })
61 .ToArray()
62 ).Delay(TimeSpan.FromSeconds(rand.Next(1, 10)));
63 #endif
64
65 // The grand composition connecting the user input with the web service.
66 var res = (from term in input
67 select matchInWordNetByPrefix(term))
68 .Switch();
69
70 // Synchronize with the UI thread and populate the ListBox or signal an error.
71 using (res.ObserveOn(lst).Subscribe(
72 words =>
73 {
74 lst.Items.Clear();
75 lst.Items.AddRange((from word in words select word.Word).ToArray());
76 },
77 ex =>
78 {
79 MessageBox.Show(
80 "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
81 );
82 }))
83 {
84 Application.Run(frm);
85 } // Proper disposal happens upon exiting the application.
86 }
87 }
88 }