UserLoginView.xaml.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Windows;
  6. using System.Windows.Controls;
  7. using System.Windows.Documents;
  8. using System.Windows.Input;
  9. using System.Windows.Media;
  10. using System.Windows.Media.Animation;
  11. using System.Windows.Shapes;
  12. using System.IO.IsolatedStorage;
  13. using WindowsPhone.Recipes.Push.Client.Services;
  14. using System.Threading;
  15. namespace WindowsPhone.Recipes.Push.Client.Views
  16. {
  17. public partial class UserLoginView : UserControl
  18. {
  19. #region Fields
  20. private readonly IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
  21. #endregion
  22. #region Properties
  23. public string UserName { get; set; }
  24. #endregion
  25. #region Events
  26. public event EventHandler<LoginEventArgs> Login;
  27. #endregion
  28. public UserLoginView()
  29. {
  30. DataContext = this;
  31. InitializeComponent();
  32. Loaded += UserLoginView_Loaded;
  33. }
  34. private void UserLoginView_Loaded(object sender, RoutedEventArgs e)
  35. {
  36. string userName;
  37. if (!Settings.TryGetValue("LoginPage.UserName", out userName))
  38. {
  39. login.Visibility = Visibility.Visible;
  40. }
  41. else
  42. {
  43. UserName = userName;
  44. InternalLogin();
  45. }
  46. }
  47. private void ButtonLogin_Click(object sender, RoutedEventArgs args)
  48. {
  49. Settings["LoginPage.UserName"] = UserName;
  50. login.Visibility = Visibility.Collapsed;
  51. InternalLogin();
  52. }
  53. private void OnLogin(LoginEventArgs args)
  54. {
  55. if (Login != null)
  56. {
  57. Login(this, args);
  58. }
  59. }
  60. private void InternalLogin()
  61. {
  62. login.Visibility = Visibility.Collapsed;
  63. progress.Visibility = Visibility.Visible;
  64. var pushContext = PushContext.Current;
  65. pushContext.Connect(c => RegisterClient(c.ChannelUri));
  66. }
  67. private void RegisterClient(Uri channelUri)
  68. {
  69. // Register the URI with 3rd party web service.
  70. try
  71. {
  72. var pushService = new PushServiceClient();
  73. pushService.RegisterCompleted += (s, e) =>
  74. {
  75. pushService.CloseAsync();
  76. Completed(e.Error);
  77. };
  78. pushService.RegisterAsync(UserName, channelUri);
  79. }
  80. catch (Exception ex)
  81. {
  82. Completed(ex);
  83. }
  84. }
  85. private void Completed(Exception ex)
  86. {
  87. login.Visibility = Visibility.Visible;
  88. progress.Visibility = Visibility.Collapsed;
  89. Dispatcher.BeginInvoke(() => OnLogin(new LoginEventArgs(ex)));
  90. }
  91. }
  92. }