Program.cs 2.8 KB

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