Debian Codegraph @

external/rx/Rx/NET/Samples/HOL/CS/Excercise9/Step03/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 // Test input
32 const string INPUT = "reactive";
33
34 var rand = new Random();
35
36 var input = Observable.Generate(
37 3,
38 len => len <= INPUT.Length,
39 len => len + 1,
40 len => INPUT.Substring(0, len),
41 _ => TimeSpan.FromMilliseconds(rand.Next(200, 1200))
42 )
43 .ObserveOn(txt)
44 .Do(term => txt.Text = term)
45 .Throttle(TimeSpan.FromSeconds(1));
46 #endif
47
48 // Bridge with the web service's MatchInDict method.
49 var svc = new DictServiceSoapClient("DictServiceSoap");
50 var matchInDict = Observable.FromAsyncPattern<string, string, string, DictionaryWord[]>
51 (svc.BeginMatchInDict, svc.EndMatchInDict);
52
53 Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
54 term => matchInDict("wn", term, "prefix");
55
56 // The grand composition connecting the user input with the web service.
57 var res = (from term in input
58 select matchInWordNetByPrefix(term))
59 .Switch();
60
61 // Synchronize with the UI thread and populate the ListBox or signal an error.
62 using (res.ObserveOn(lst).Subscribe(
63 words =>
64 {
65 lst.Items.Clear();
66 lst.Items.AddRange((from word in words select word.Word).ToArray());
67 },
68 ex =>
69 {
70 MessageBox.Show(
71 "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
72 );
73 }))
74 {
75 Application.Run(frm);
76 } // Proper disposal happens upon exiting the application.
77 }
78 }
79 }