1
0

Program.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. from word in matchInWordNetByPrefix(term)
  34. // .Finally(() => Console.WriteLine("Disposed request for " + term))
  35. .TakeUntil(input)
  36. select word;
  37. // Synchronize with the UI thread and populate the ListBox or signal an error.
  38. using (res.ObserveOn(lst).Subscribe(
  39. words =>
  40. {
  41. lst.Items.Clear();
  42. lst.Items.AddRange((from word in words select word.Word).ToArray());
  43. },
  44. ex =>
  45. {
  46. MessageBox.Show(
  47. "An error occurred: " + ex.Message, frm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error
  48. );
  49. }))
  50. {
  51. Application.Run(frm);
  52. } // Proper disposal happens upon exiting the application.
  53. }
  54. }
  55. }