private async Task InitRemoteNotificationAsync() { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += OnPushNotificatioReceived; Debug.WriteLine($"Received Token: {channel.Uri}"); }
public async Task InitializeAsync() { try { // TODO WTS: Set your Hub Name var hubName = string.Empty; // TODO WTS: Set your DefaultListenSharedAccessSignature var accessSignature = string.Empty; var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var hub = new NotificationHub(hubName, accessSignature); var result = await hub.RegisterNativeAsync(channel.Uri); if (result.RegistrationId != null) { // Registration was successful } // You can also send push notifications from Windows Developer Center targeting your app consumers // More details at https://docs.microsoft.com/windows/uwp/publish/send-push-notifications-to-your-apps-customers } catch (ArgumentNullException) { // Until a valid accessSignature and hubName are provided this code will throw an ArgumentNullException. } catch (Exception) { // TODO WTS: Channel registration call can fail, please handle exceptions as appropriate to your scenario. } }
public async Task InitializeAsync() { // The code below will throw an exception until it had correct parameters added to it. // Once that is done the try/catch can be removed if desired. try { //// See more about adding push notifications to your Windows app at //// https://docs.microsoft.com/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started-push // Specify your Hub Name here var hubName = string.Empty; // Specify your DefaultListenSharedAccessSignature here var accessSignature = string.Empty; var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var hub = new NotificationHub(hubName, accessSignature); var result = await hub.RegisterNativeAsync(channel.Uri); if (result.RegistrationId != null) { // Registration was successful } // You can also send push notifications from Windows Developer Center targeting your app consumers // Documentation: https://docs.microsoft.com/windows/uwp/publish/send-push-notifications-to-your-apps-customers } catch (Exception) { // Until a valid accessSignature and hubName are provided this code will throw an ArgumentNull Exception. } }
private async void CreateChannel() { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); Core.Lib.Helpers.Settings.Current.ChannelUriUWP = channel.Uri; Core.Lib.Helpers.Settings.Current.AppId = MPS.Core.Lib.Helpers.AppSettingsManager.Settings["PushNotificationAppID"]; channel.PushNotificationReceived += (s, e) => { Dictionary <string, object> dictionaryMessage = new Dictionary <string, object>(); string data = string.Empty; if (e.ToastNotification.Content != null && e.ToastNotification.Content.DocumentElement != null) { data = e.ToastNotification.Content.DocumentElement.Attributes.FirstOrDefault().InnerText ?? string.Empty; } var mensaje = JsonConvert.DeserializeObject <RootC>(data); dictionaryMessage.Add("MensajePrincipal", mensaje.custom.a.MensajePrincipal); dictionaryMessage.Add("CLAVE_TIPO_SERVICIO", mensaje.custom.a.ClaveTipoServicio); dictionaryMessage.Add("FECHA_SOLICITUD", mensaje.custom.a.FechaSolicitud); dictionaryMessage.Add("FOLIO_SOLICITUD", mensaje.custom.a.FolioSolicitud); dictionaryMessage.Add("GUID_CLIENTE", mensaje.custom.a.IdCliente); dictionaryMessage.Add("GUID_SOLICITUD", mensaje.custom.a.IdSolicitud); dictionaryMessage.Add("GUID_TIPO_SOLICITUD", mensaje.custom.a.IdTipoSolicitud); dictionaryMessage.Add("NOMBRE_CLIENTE", mensaje.custom.a.NombreCliente); dictionaryMessage.Add("NOMBRE_SERVICIO", mensaje.custom.a.NombreServicio); dictionaryMessage.Add("TIPO_SERVICIO", mensaje.custom.a.TipoServicio); dictionaryMessage.Add("UBICACION_1", mensaje.custom.a.Ubicacion); dictionaryMessage.Add("TIPO_NOTIFICACION", mensaje.custom.a.TipoNotificacion); Notificaciones.DelegarAccionDeNotificacion(new MensajeSocio(dictionaryMessage)); }; }
private async void InitPushService() { try { if (Channel != null) { Channel.PushNotificationReceived -= OnPushNotificationReceived; Channel = null; } Channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); Channel.PushNotificationReceived += OnPushNotificationReceived; var timeout = Config.GetValue(ConfigSetting.PushServiceExpiration, 0L, false).TimeStampToDate(); if (timeout <= DateTime.Now) { PushService.InitBmob("e9c75afb85827f7eda486d8eaa5eb304", "c88dc50c5af870db43d4de302cce50d5"); PushService.InitPushService(Channel, "Push", () => { Config.SetValue(ConfigSetting.PushServiceExpiration, Channel.ExpirationTime.LocalDateTime.GetTimeStampSeconds(), false); }); } } catch (Exception ex) { } }
public async Task RegisterAccountWithSdkAsync() { if (RegistrationState != AccountRegistrationState.InAppCacheAndSdkCache) { throw new Exception("Account must be in both SDK and App cache before it can be registered"); } var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); ConnectedDevicesNotificationRegistration registration = new ConnectedDevicesNotificationRegistration(); registration.Type = ConnectedDevicesNotificationType.WNS; registration.Token = channel.Uri; var account = new ConnectedDevicesAccount(Id, Type); var registerResult = await m_platform.NotificationRegistrationManager.RegisterAsync(account, registration); // It would be a good idea for apps to take a look at the different statuses here and perhaps attempt some sort of remediation. // For example, web failure may indicate that a web service was temporarily in a bad state and retries may be successful. // // NOTE: this approach was chosen rather than using exceptions to help separate "expected" / "retry-able" errors from real // exceptions and keep the error-channel logic clean and simple. if (registerResult.Status == ConnectedDevicesNotificationRegistrationStatus.Success) { await UserNotifications.RegisterAccountWithSdkAsync(); } }
/// <summary> /// The create or update notifications async. /// </summary> public static async void CreateOrUpdateNotificationsAsync() { try { // get the channel for the app var pushNotificationChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); pushNotificationChannel.PushNotificationReceived += PushNotificationChannelPushNotificationReceived; var hub = new NotificationHub(Constants.HubName, Constants.ConnectionString); // register the channel in NH var result = await hub.RegisterNativeAsync(pushNotificationChannel.Uri, SettingsHelper.Tags); if (result.RegistrationId != null) { await ShowRegistrationIdAsync(result); } } catch (Exception ex) { //todo handle the exception // _logManager.Log(ex); } }
private void LoadOrCreateChannelAsync(Action callback = null) { Execute.BeginOnThreadPool(async() => { try { var pushChannel = HttpNotificationChannel.Find(Constants.ToastNotificationChannelName); if (pushChannel != null) { pushChannel.UnbindToShellTile(); pushChannel.UnbindToShellToast(); } } catch (Exception ex) { Telegram.Logs.Log.Write("WNSPushService start creating channel ex " + ex); Execute.ShowDebugMessage("WNSPushService.LoadOrCreateChannelAsync ex " + ex); } Telegram.Logs.Log.Write("WNSPushService start creating channel"); _pushChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); _pushChannel.PushNotificationReceived += OnPushNotificationReceived; Telegram.Logs.Log.Write("WNSPushService stop creating channel"); callback.SafeInvoke(); }); }
private async Task init() { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync().AsTask <PushNotificationChannel>(); channel.PushNotificationReceived += channel_PushNotificationReceived; ExampleBackgroundTask.Register(); if (settings.Values[DEVICE_KEY] == null) { Guid uuid = await registerDevice(true); settings.Values.Add(DEVICE_KEY, uuid); this.DeviceId = uuid; } else { object tempId; settings.Values.TryGetValue(DEVICE_KEY, out tempId); this.DeviceId = Guid.Parse(tempId.ToString()); var device = await GetDevice(DeviceId); if (device == null) { Guid uuid = await registerDevice(true); settings.Values[DEVICE_KEY] = uuid; this.DeviceId = uuid; } else { await registerDevice(false); } } }
private async void registerButton_Click(object sender, RoutedEventArgs e) { // Disable button registerButton.IsEnabled = false; yourUsernameTextBox.IsEnabled = false; // Obtain a channel var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += channel_PushNotificationReceived; var registration = new Registration { Username = yourUsernameTextBox.Text, Channel = channel.Uri, Platform = "WindowsStore" }; // Call our server to register this channel using (var httpClient = new HttpClient()) { var serializedBody = JsonConvert.SerializeObject(registration); await httpClient.PostAsync(baseUrl + "/api/chat/register", new StringContent(serializedBody, Encoding.UTF8, "application/json")); } // Show the messages panel registerButton.Content = "Ok!"; messagesPanel.Visibility = Visibility.Visible; }
public async Task <string> openNotificationService(string username) { try { //申请通道 channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); string result = null; if (channel != null) { //将通道url上传至服务器 ConnectServer conn = new ConnectServer(); // string username = usernameInput.Text; //将post使用的参数加入字典 Dictionary <string, string> dic_param = new Dictionary <string, string>(); Debug.WriteLine(channel.Uri); // string url = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(channel.Uri)); string url = Util.UrlEncode(channel.Uri); dic_param.Add("username", username); dic_param.Add("channelurl", url); result = await conn.SendPostRequest(ConnectServer.URL_UPLOADCHANNELURL, dic_param); //添加推送收取事件 channel.PushNotificationReceived += NotificationReceived; } return(result); } catch (Exception e) { MessageDialog dialog = new MessageDialog(e.Message); await dialog.ShowAsync(); } return(null); }
private async void OpenChannelAndRegisterTask() { // Open the channel. See the "Push and Polling Notifications" sample for more detail try { if (rootPage.Channel == null) { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); String uri = channel.Uri; rootPage.Channel = channel; // This event comes back in a background thread, so we need to move to the UI thread to access any UI elements await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { OutputToTextBox(uri); rootPage.NotifyUser("Channel request succeeded!", NotifyType.StatusMessage); }); } // Clean out the background task just for the purpose of this sample UnregisterBackgroundTask(); RegisterBackgroundTask(); rootPage.NotifyUser("Task registered", NotifyType.StatusMessage); } catch (Exception ex) { rootPage.NotifyUser("Could not create a channel. Error number:" + ex.Message, NotifyType.ErrorMessage); } }
private async void LoginAndRegisterClick(object sender, RoutedEventArgs e) { SetAuthenticationTokenInLocalStorage(); var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += channel_PushNotificationReceived; // The "username:<user name>" tag gets automatically added by the message handler in the backend. // The tag passed here can be whatever other tags you may want to use. try { await new RegisterClient(BACKEND_ENDPOINT).RegisterAsync(channel.Uri, new string[] { "myTag" }); var dialog = new MessageDialog("Registered as: " + UsernameTextBox.Text); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); SendPushButton.IsEnabled = true; } catch (Exception ex) { MessageDialog alert = new MessageDialog(ex.Message, "Failed to register with RegisterClient"); alert.ShowAsync(); } }
public async Task InitializeAsync() { // TODO WTS: Set your Hub Name var hubName = "IISSNotificationHub"; // TODO WTS: Set your DefaultListenSharedAccessSignature var accessSignature = "Endpoint=sb://iissnotificationhub.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=4QRYSSvgRadFjjMqnFjs8nwiNMWidOy+GAGQtH/zuSA="; try { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var hub = new NotificationHub(hubName, accessSignature); var result = await hub.RegisterNativeAsync(channel.Uri); if (result.RegistrationId != null) { // Registration was successful } // You can also send push notifications from Windows Developer Center targeting your app consumers // More details at https://docs.microsoft.com/windows/uwp/publish/send-push-notifications-to-your-apps-customers } catch (Exception e) { Debug.WriteLine(e.Message); } }
/// <summary> /// Регистрирует устройство на получение Push-уведомлений. /// </summary> public async Task RegisterDevice() { if (channel == null) { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); } if (!String.IsNullOrEmpty(WNSChannelUri) && channel.Uri != WNSChannelUri) { await UnregisterDevice(); } var parameters = new Dictionary <string, string> { ["device_id"] = deviceInformationService.GetHardwareID(), ["token"] = channel.Uri, ["settings"] = "{\"msg\":\"on\",\"chat\":\"on\",\"friend\":\"on\",\"reply\":\"on\",\"mention\":\"on\"}" }; var request = new Request <VKOperationIsSuccess>("account.registerDevice", parameters) { HttpMethod = HttpMethod.POST }; var response = await vkService.ExecuteRequestAsync(request); if (!response.IsSuccess) { throw new Exception("Не удалось зарегистрировать устройство"); } WNSChannelUri = channel.Uri; channel.PushNotificationReceived += Channel_PushNotificationReceived; }
public static async Task RegisterForPush() { if (ConnectionHelper.IsServiceAtLocalhost()) { // F5-experience: talking to localhost, skip push registration return; } if (ApplicationData.Current.LocalSettings.Values[Constants.Settings.StorageMode].ToString() == Constants.Online && !AzureDataServices.MobileServiceUserPushRegistered) { var pushChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); pushChannel.PushNotificationReceived += PushChannel_PushNotificationReceived; var push = AzureDataServices.MobileServiceClient.GetPush(); var toastTemplate = "<toast>" + "<visual>" + "<binding template=\"ToastText01\">" + " <text id=\"1\">$(message)</text>" + "</binding>" + "</visual>" + "</toast>"; await push.RegisterTemplateAsync(pushChannel.Uri, toastTemplate.ToString(), "NewJobTemplate"); AzureDataServices.MobileServiceUserPushRegistered = true; } }
/// <summary> /// Отписывает устройство от получения Push-уведомлений /// </summary> public async Task UnregisterDevice() { if (channel == null) { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); } var parameters = new Dictionary <string, string> { ["device_id"] = deviceInformationService.GetHardwareID() }; var request = new Request <VKOperationIsSuccess>("account.unregisterDevice", parameters) { HttpMethod = HttpMethod.POST }; var response = await vkService.ExecuteRequestAsync(request); if (!response.IsSuccess) { throw new Exception("Не удалось отменить регистрацию устройства"); } channel.Close(); channel.PushNotificationReceived -= Channel_PushNotificationReceived; channel = null; WNSChannelUri = null; }
public async Task InitializeNotificationsAsync() { try { // If already registered, then just return so that we only register for push notications once if (Locator.Instance.IsPushNotificationsRegistered) { return; } var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); const string templateBodyWNS = "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(messageParam)</text></binding></visual></toast>"; JObject headers = new JObject(); headers["X-WNS-Type"] = "wns/toast"; JObject templates = new JObject(); templates["genericMessage"] = new JObject { { "body", templateBodyWNS }, { "headers", headers } // Only needed for WNS & MPNS }; channel.PushNotificationReceived += OnPushNotificationReceived; await Locator.Instance.MobileService.GetPush().RegisterAsync(channel.Uri, templates); Locator.Instance.IsPushNotificationsRegistered = true; } catch (Exception) { Locator.Instance.IsPushNotificationsRegistered = false; } }
public static async Task <string> InitAsync() { var retries = 3; var difference = 10; // In seconds var currentRetry = 0; do { try { _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); //_channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); //_channel.PushNotificationReceived += OnPushNotificationReceived; if (!_channel.Uri.Equals(ChannelUri)) { ChannelUri = _channel.Uri; //register uri to PN Service await RegisterForPushNotification(ChannelUri, "sdkapp"); RaiseChannelUriUpdated(); return(_channel.Uri); } } catch { throw new CB.Exception.CloudBoostException("Could not create channel uri"); } await Task.Delay(TimeSpan.FromSeconds(difference)); } while (currentRetry++ < retries); return(null); }
private async void InitNotificationsAsync() { // Request a push notification channel. var channel = await PushNotificationChannelManager .CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += Channel_PushNotificationReceived; // Register for notifications using the new channel System.Exception exception = null; try { await MobileService.GetPush().RegisterNativeAsync(channel.Uri); } catch (System.Exception ex) { exception = ex; } if (exception != null) { var dialog = new MessageDialog(exception.Message, "Registering Channel URI"); dialog.Commands.Add(new UICommand("OK")); await dialog.ShowAsync(); } }
public async Task <bool> Register(UserAuth userAuth) { if (!NetworkManager.IsNetworkAvailable) { return(false); } // Create a push notifications channel var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += Channel_PushNotificationReceived; var nhConnectionString = "{Notification Hub Connection String}"; var hub = new NotificationHub("blueyonder09Hub", nhConnectionString); var result = await hub.RegisterNativeAsync(channel.Uri, new string[] { $"user-{userAuth.Traveler.TravelerId}" }); return(result.ChannelUri != null); // Encode the channel uri //var encodedChannelUri = EncodeChannelUri(channel.Uri); // Send the encoded channel uri to the server //var success = await SendChannelToServer(result.ChannelUri); //return success; }
public static async Task SetupNotificationChannelAsync() { // get the notification channel... var manager = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); Debug.WriteLine("Channel: " + manager.Uri); // if either the URI we sent or the username we sent has changed, resend it... var lastUri = await SettingItem.GetValueAsync("NotificationUri"); var lastToken = await SettingItem.GetValueAsync("NotificationToken"); if (lastUri != manager.Uri || lastToken != LogonToken) { // send it... Debug.WriteLine("*** This is where you asynchronously send it! ***"); // store it... await SettingItem.SetValueAsync("NotificationUri", manager.Uri); await SettingItem.SetValueAsync("NotificationToken", LogonToken); } else { Debug.WriteLine("URI not changed."); } }
private async Task <string> GetChannelUri() { var pushChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); pushChannel.PushNotificationReceived += pushChannel_PushNotificationReceived; return(pushChannel.Uri); }
/// <summary> /// Requests a new push channel URI. /// </summary> public async Task <string> UpdateChannelUri() { var retries = 3; var difference = 10; // In seconds var currentRetry = 0; do { try { _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); _channel.PushNotificationReceived += OnPushNotificationReceived; if (!_channel.Uri.Equals(ChannelUri)) { ChannelUri = _channel.Uri; // TODO send channel uri to your server to your server this.RaiseChannelUriUpdated(); return(_channel.Uri); } } catch { // Could not create a channel } await Task.Delay(TimeSpan.FromSeconds(difference)); } while (currentRetry++ < retries); return(null); }
public static async Task <string> RegisterForPushAsync() { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += channel_PushNotificationReceived; return(channel.Uri.ToString()); }
public async Task InitializeAsync(Window currentWindow) { if (!_appIsInitialized) { using (var _ = _analyticsService.StartTrace(this, "UWP Push Notifications Initialization")) { try { currentWindow.Activated += HandleWindowActivated; _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); _channel.PushNotificationReceived += HandlePushNotificationReceived; await _pushNotificationsService.UpdatePushNotificationServiceHandleAsync(_channel.Uri); _appIsInitialized = true; } catch (Exception e) { _analyticsService.LogException(this, e); throw; } } } }
protected override async Task <string> ChannelUri() { var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += OnPushNotification; return(channel.Uri); }
private async Task AcquirePushChannel() { CurrentChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var channel = new Channel() { Uri = CurrentChannel.Uri, ExpirationTime = CurrentChannel.ExpirationTime.ToUniversalTime() }; try { var channelTable = App.MobileService.GetTable <Channel>(); if (ApplicationData.Current.LocalSettings.Values["ChannelId"] == null) { await channelTable.InsertAsync(channel); ApplicationData.Current.LocalSettings.Values["ChannelId"] = channel.Id; } else { channel.Id = (string)ApplicationData.Current.LocalSettings.Values["ChannelId"]; await channelTable.UpdateAsync(channel); } } catch (HttpRequestException) { ShowError(); } }
public async Task OpenNotificationsChannel() { UpdateStatusMessage("1. Requesting Channel from WNS: "); try { //1. Request Channel from WNS _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); UpdateStatusMessage(string.Format(" Channel URI returned by WNS: {0}", _channel.Uri)); UpdateStatusMessage(string.Format("2. Attempting to registering channel URI with Notification App Server at {0}", K_SERVERURL)); //2. Register _channel with your app server using (var client = new HttpClient()) { var payload = CreatePayload(_appId, _channel, _tileId, _clientId, _userId, _deviceType); var result = await client.PutAsync(K_SERVERURL, payload); if (result.StatusCode == System.Net.HttpStatusCode.Accepted) { UpdateStatusMessage(string.Format(" Channel URI successfully sent to Notification App Server.")); } else { UpdateStatusMessage(string.Format(" Could not send Channel URI to Notification App Server - {0}", result.StatusCode.ToString())); } } } catch (Exception ex) { UpdateStatusMessage(string.Format(" Error occured please see exception detail: {0}", ex.ToString())); } }
public async void InitNotificationsAsync() { //建立推播管道 PushChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); PushChannel.PushNotificationReceived += Channel_PushNotificationReceived; //NotificationHub名稱 及ConnectionString var hub = new NotificationHub(NotiHubName, NotiHubConnStr); ////註冊Tags var result = await hub.RegisterNativeAsync(PushChannel.Uri, new List <string> { DeviceID, SToken, "Jason" }); //成功時顯示註冊ID //if (result.RegistrationId != null) //{ // var pushStr = string.Format(pushurl, ManageWebURL, SID, SToken, DeviceID, UName, UID, UGender, UAge, Tag4); // var client = new HttpClient(); // var response = await client.GetAsync(pushStr); // var senMsg = string.Format(sendMsgUrl, SID, SToken, DeviceID); // var sendresponse = await client.GetAsync(senMsg); //} }