Program.cs 3.0 KB

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