1
0

Program.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. namespace Excercise9
  8. {
  9. class Program
  10. {
  11. static void Main()
  12. {
  13. var txt = new TextBox();
  14. var lst = new ListBox { Top = txt.Height + 10 };
  15. var frm = new Form()
  16. {
  17. Controls = { txt, lst }
  18. };
  19. #if PRODUCTION
  20. // Turn the user input into a tamed sequence of strings.
  21. var textChanged = from evt in Observable.FromEventPattern(txt, "TextChanged")
  22. select ((TextBox)evt.Sender).Text;
  23. var input = textChanged
  24. .Throttle(TimeSpan.FromSeconds(1))
  25. .DistinctUntilChanged();
  26. #else
  27. // Test input
  28. var input = new[] { "reac", "reactive", "bing" }.ToObservable();
  29. #endif
  30. // Bridge with the web service's MatchInDict method.
  31. var svc = new DictServiceSoapClient("DictServiceSoap");
  32. var matchInDict = Observable.FromAsyncPattern<string, string, string, DictionaryWord[]>
  33. (svc.BeginMatchInDict, svc.EndMatchInDict);
  34. Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
  35. term => matchInDict("wn", term, "prefix");
  36. // The grand composition connecting the user input with the web service.
  37. var res = (from term in input
  38. select matchInWordNetByPrefix(term))
  39. .Switch();
  40. // Synchronize with the UI thread and populate the ListBox or signal an error.
  41. using (res.ObserveOn(lst).Subscribe(
  42. words =>
  43. {
  44. lst.Items.Clear();
  45. lst.Items.AddRange((from word in words select word.Word).ToArray());
  46. },
  47. ex =>
  48. {
  49. MessageBox.Show(
  50. "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
  51. );
  52. }))
  53. {
  54. Application.Run(frm);
  55. } // Proper disposal happens upon exiting the application.
  56. }
  57. }
  58. }