Program.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 = (from len in Enumerable.Range(3, 8)
  29. select "reactive".Substring(0, len)) // rea, reac, react, reacti, reactiv, reactive
  30. .ToObservable();
  31. #endif
  32. // Bridge with the web service's MatchInDict method.
  33. var svc = new DictServiceSoapClient("DictServiceSoap");
  34. var matchInDict = Observable.FromAsyncPattern<string, string, string, DictionaryWord[]>
  35. (svc.BeginMatchInDict, svc.EndMatchInDict);
  36. Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
  37. term => matchInDict("wn", term, "prefix");
  38. // The grand composition connecting the user input with the web service.
  39. var res = (from term in input
  40. select matchInWordNetByPrefix(term))
  41. .Switch();
  42. // Synchronize with the UI thread and populate the ListBox or signal an error.
  43. using (res.ObserveOn(lst).Subscribe(
  44. words =>
  45. {
  46. lst.Items.Clear();
  47. lst.Items.AddRange((from word in words select word.Word).ToArray());
  48. },
  49. ex =>
  50. {
  51. MessageBox.Show(
  52. "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
  53. );
  54. }))
  55. {
  56. Application.Run(frm);
  57. } // Proper disposal happens upon exiting the application.
  58. }
  59. }
  60. }