Program.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Linq;
  3. using System.Reactive.Linq;
  4. using System.Windows.Forms;
  5. using System.Reactive.Disposables;
  6. using Excercise8.DictionarySuggestService;
  7. namespace Excercise8
  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. // Turn the user input into a tamed sequence of strings.
  20. var textChanged = from evt in Observable.FromEventPattern(txt, "TextChanged")
  21. select ((TextBox)evt.Sender).Text;
  22. var input = textChanged
  23. .Throttle(TimeSpan.FromSeconds(1))
  24. .DistinctUntilChanged();
  25. // Bridge with the web service's MatchInDict method.
  26. var svc = new DictServiceSoapClient("DictServiceSoap");
  27. var matchInDict = Observable.FromAsyncPattern<string, string, string, DictionaryWord[]>
  28. (svc.BeginMatchInDict, svc.EndMatchInDict);
  29. Func<string, IObservable<DictionaryWord[]>> matchInWordNetByPrefix =
  30. term => matchInDict("wn", term, "prefix");
  31. // The grand composition connecting the user input with the web service.
  32. var res = (from term in input
  33. select matchInWordNetByPrefix(term))
  34. .Switch();
  35. // Synchronize with the UI thread and populate the ListBox or signal an error.
  36. using (res.ObserveOn(lst).Subscribe(
  37. words =>
  38. {
  39. lst.Items.Clear();
  40. lst.Items.AddRange((from word in words select word.Word).ToArray());
  41. },
  42. ex =>
  43. {
  44. MessageBox.Show(
  45. "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
  46. );
  47. }))
  48. {
  49. Application.Run(frm);
  50. } // Proper disposal happens upon exiting the application.
  51. }
  52. }
  53. }