private async void EnablePushNotifications(bool IsFirstLaunch) { pnChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); #if DEBUG System.Diagnostics.Debug.WriteLine("PushURI: " + pnChannel.Uri.ToString()); #endif if (!IsFirstLaunch) { UpdateUriOnServer(); } }
private async void OnRegisterForNativeNotifications(object sender, RoutedEventArgs e) { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); if (channel != null) { string result = $"Registration successfull: the channel url is {channel.Uri}"; Result.Text = result; NotificationHub hub = new NotificationHub("uwpsample", ConnectionString); await hub.RegisterNativeAsync(channel.Uri); } }
private void DisableNotifications() { lock (sync) { if (channel == null) { return; } channel.Close(); channel = null; } }
/// <summary> /// Register to Azure Push Notifications /// </summary> /// <param name="templates">Notification templates to register for</param> /// <param name="cancellationToken">Token to cancel registration</param> public override async Task <bool> RegisterAsync(IEnumerable <IAptkAmaNotificationTemplate> templates, CancellationToken cancellationToken) { if (_currentChannel == null) { _currentChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); _currentChannel.PushNotificationReceived += OnPushNotificationReceived; } var push = ((MobileServiceClient)Client).GetPush(); var xTemplates = new JObject(); // Register for notifications using the new channel foreach (var template in templates) { var xTemplate = new XElement("toast", new XElement("visual", new XElement("binding", new XAttribute("template", template.Name), template.Select(kv => new XElement(kv.Key, kv.Value))))); var body = new JObject { ["body"] = xTemplate.ToString(), ["headers"] = new JObject { ["X-WNS-Type"] = "wns/toast" } }; if (template.Tags != null) { var tags = JsonConvert.SerializeObject(template.Tags); if (tags != null) { body.Add("tags", tags); } } xTemplates.Add(template.Name, body); } await push.RegisterAsync(_currentChannel.Uri, xTemplates); Debug.WriteLine($"{xTemplates} notifications registered"); await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Configuration.NotificationHandler?.OnRegistrationSucceeded()); return(true); }
/// <summary> /// If enabled, register push channel and send URI to backend. /// Also start intercepting pushes. /// If disabled and previously enabled, stop listening for pushes (they will still be received though). /// </summary> private void ApplyEnabledState(bool enabled) { if (enabled) { // We expect caller of this method to lock on _mutex, we can't do it here as that lock is not recursive MobileCenterLog.Debug(LogTag, "Getting push token..."); var state = _mutex.State; Task.Run(async() => { var channel = await new WindowsPushNotificationChannelManager().CreatePushNotificationChannelForApplicationAsync() .AsTask().ConfigureAwait(false); try { using (await _mutex.GetLockAsync(state).ConfigureAwait(false)) { var pushToken = channel.Uri; if (!string.IsNullOrEmpty(pushToken)) { // Save channel member _channel = channel; // Subscribe to push channel.PushNotificationReceived += OnPushNotificationReceivedHandler; // Send channel URI to backend MobileCenterLog.Debug(LogTag, $"Push token '{pushToken}'"); var pushInstallationLog = new PushInstallationLog(null, null, pushToken, Guid.NewGuid()); // Do not await the call to EnqueueAsync or the UI thread can be blocked! #pragma warning disable CS4014 Channel.EnqueueAsync(pushInstallationLog); #pragma warning restore } else { MobileCenterLog.Error(LogTag, "Push service registering with Mobile Center backend has failed."); } } } catch (StatefulMutexException) { MobileCenterLog.Warn(LogTag, "Push Enabled state changed after creating channel."); } }); } else if (_channel != null) { _channel.PushNotificationReceived -= OnPushNotificationReceivedHandler; } }
private async void InitNotificationsAsync(string tag) { try { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); NotificationHub hub = new NotificationHub(txtNotification.Text, txtConnection.Text); //userTag[0] = tag; if (!String.IsNullOrWhiteSpace(tag)) { string[] userTag = tag.Split(";".ToCharArray()); var result = await hub.RegisterNativeAsync(channel.Uri, userTag); // // Displays the registration ID so you know it was successful if (result.RegistrationId != null) { //registrationID = result.RegistrationId; // txtResult.Text = ; var dialog = new MessageDialog("Registration successful: " + result.RegistrationId + ". Channel Uri = " + channel.Uri); await dialog.ShowAsync(); } else { var dialog = new MessageDialog("Registration failed"); await dialog.ShowAsync(); } } else { Registration result = await hub.RegisterNativeAsync(channel.Uri, null); // // Displays the registration ID so you know it was successful if (result.RegistrationId != null) { // txtResult.Text = ; var dialog = new MessageDialog("Registration successful: " + result.RegistrationId); await dialog.ShowAsync(); } } } catch (Exception Ex) { if (null != Ex.InnerException) { var dialog = new MessageDialog("Error when registering: " + Ex.InnerException.Message); await dialog.ShowAsync(); } } }
private static void OnChannelCreationCompleted(IAsyncOperation <PushNotificationChannel> operation, AsyncStatus asyncStatus) { try { if (operation.Status == AsyncStatus.Completed) { pushNotificationChannel = operation.GetResults(); ApplicationData.Current.LocalSettings.Values[Constants.NotificationIdKey] = pushNotificationChannel.Uri; } } catch (Exception) { } }
/// <summary> /// Register a template notification /// </summary> /// <param name="hubName">Name of the sending hub</param> /// <param name="connectionString">Connection string to the Service Bus namespace</param> /// <param name="templateName">Name of the template</param> /// <param name="metadata">Notification property holding the metadata</param> /// <param name="header">Header text of the toast</param> /// <param name="footer">Footer text of the toast</param> /// <param name="image">Url to the image</param> /// <returns></returns> public static async Task <TemplateRegistration> RegisterTemplateNotificationAsync(string hubName, string connectionString, string templateName, string metadata, string header, string footer, string image) { // Create a new push notification channel PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); // Create a new notification hub NotificationHub hub = new NotificationHub(hubName, connectionString); // Generate the template for the toast XmlDocument toastTemplate = await GenerateXmlTemplateAsync(metadata, header, footer, image); // Register the template return(await hub.RegisterTemplateAsync(channel.Uri, toastTemplate, templateName)); }
public async Task InitializeAsync(string notificationHubName, string connectionString) { _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); _hub = new NotificationHub(notificationHubName, connectionString); Token = _channel.Uri; _channel.PushNotificationReceived += OnPushNotificationReceived; // template allows to send notifications across all platforms by providing shared placeholders (title/message in this case) var template = GetTemplate(); await _hub.RegisterTemplateAsync(Token, template, "myCustomTemplate"); }
private async void btnCreateChannel_Click(object sender, RoutedEventArgs e) { // 创建一个推送通知信道,每个新建的 channel 有效期为 30 天,所以建议每次进入 app 后都重新建一个 channel(如果两次创建的间隔时间较短的话,则会复用之前的 channel 地址) PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); // 接收到通知后所触发的事件 channel.PushNotificationReceived += channel_PushNotificationReceived; // channel.Close(); // 关闭 channel // channel.ExpirationTime; // channel 的过期时间,此时间过后 channel 则失效 // channel 的 uri 地址,服务端通过此 uri 向此 app 推送通知 txtUri.Text = channel.Uri.ToString(); }
private void RemoveCallback_Click(object sender, RoutedEventArgs e) { PushNotificationChannel currentChannel = rootPage.Channel; if (currentChannel != null) { currentChannel.PushNotificationReceived -= OnPushNotificationReceived; rootPage.NotifyUser("Callback removed.", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Channel not open. Open the channel in scenario 1.", NotifyType.StatusMessage); } }
public async void UnregisterFromAzurePushNotification() { if (channel != null) { channel.PushNotificationReceived -= Channel_PushNotificationReceived; } var hub = new NotificationHub(PushNotificationCredentials.AzureNotificationHubName, PushNotificationCredentials.AzureListenConnectionString); await hub.UnregisterNativeAsync(); channel = null; }
private async Task <PushNotificationChannel> CreatePushNotificationChannelAsync() { PushNotificationChannel channel = null; try { // If this isn't the first time after installation, the notification channel is created successfully even without network. channel = await new WindowsPushNotificationChannelManager().CreatePushNotificationChannelForApplicationAsync() .AsTask().ConfigureAwait(false); } catch (Exception exception) { if (NetworkStateAdapter.IsConnected) { AppCenterLog.Error(LogTag, "Unable to create notification channel.", exception); return(null); } } if (channel != null) { return(channel); } AppCenterLog.Debug(LogTag, "The network isn't connected, another attempt will be made after the network is available."); var networkSemaphore = new SemaphoreSlim(0); void NetworkStateChangeHandler(object sender, EventArgs e) { if (NetworkStateAdapter.IsConnected) { networkSemaphore.Release(); } } NetworkStateAdapter.NetworkStatusChanged += NetworkStateChangeHandler; await networkSemaphore.WaitAsync().ConfigureAwait(false); NetworkStateAdapter.NetworkStatusChanged -= NetworkStateChangeHandler; AppCenterLog.Debug(LogTag, "Second attempt to create notification channel..."); try { // Second attempt is the last one anyway. return(await new WindowsPushNotificationChannelManager().CreatePushNotificationChannelForApplicationAsync() .AsTask().ConfigureAwait(false)); } catch (Exception exception) { AppCenterLog.Error(LogTag, "Unable to create notification channel.", exception); return(null); } }
private async void ChannelPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { if (args != null && args.RawNotification != null) { args.Cancel = true; await Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { StatusText.Text = string.Format("Received local raw notification at {0}", DateTime.Now); Local.Text = string.Format("{0}: {1}", DateTime.Now, args.RawNotification.Content); }); } }
private static void AddCallback(PushNotificationChannel currentChannel) { //PushNotificationChannel currentChannel = rootPage.Channel; if (currentChannel != null) { dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher; currentChannel.PushNotificationReceived += OnPushNotificationReceived; //rootPage.NotifyUser("Callback added.", NotifyType.StatusMessage); } else { //rootPage.NotifyUser("Channel not open. Open the channel in scenario 1.", NotifyType.ErrorMessage); } }
private async void InitNotificationsAsync() { CHANNEL = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); HUB = new NotificationHub("HubName", "ListenConnectionString"); //var result = await hub.RegisterNativeAsync(channel.Uri); // Displays the registration ID so you know it was successful //if (result.RegistrationId != null) //{ // var dialog = new MessageDialog("Registration successful: " + result.RegistrationId); // dialog.Commands.Add(new UICommand("OK")); // await dialog.ShowAsync(); //} }
/// <summary> /// Register this application to the Notification Hub Service /// </summary> private async void InitNotificationsAsync() { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); Microsoft.WindowsAzure.Messaging.NotificationHub hub = new Microsoft.WindowsAzure.Messaging.NotificationHub(hubName, hubListenEndpoint); Microsoft.WindowsAzure.Messaging.Registration result = await hub.RegisterNativeAsync(channel.Uri); //If registration was successful, subscribe to Push Notifications if (result.RegistrationId != null) { Debug.Log($"Registration Successful: {result.RegistrationId}"); channel.PushNotificationReceived += Channel_PushNotificationReceived; } }
public async Task InitNotificationsAsync() { try { _registrationTaskCompletionSource = new TaskCompletionSource <string>(); _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); _hub = new NotificationHub( Settings.NotificationHubName, Settings.NotificationHubConnectionString); } catch (Exception ex) { Debug.WriteLine("Unable to initialize GCMClient" + ex); } }
public void Register() { Debug.WriteLine("Creating Push Notification Channel For Application"); var channelTask = PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync().AsTask(); channelTask.Wait(); Debug.WriteLine("Creating Push Notification Channel For Application - Done"); _channel = channelTask.Result; Debug.WriteLine("Registering call back for Push Notification Channel"); _channel.PushNotificationReceived += Channel_PushNotificationReceived; _pushNotificationListener.OnRegistered(Token, Device.UWP); }
public async Task <string> InitNotificationsAsync() { this.channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += this.OnPushNotification; var hub = new NotificationHub("CincyAzure", "Endpoint=sb://cincyazure.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=w8KPh8QPYeCsteaHiUw85M9FZhRcpEgbq5DELUJeAQw="); var result = await hub.RegisterNativeAsync(channel.Uri, new List <string>() { "Cincinnati", "Azure" }); return(result.RegistrationId); }
private void AddCallback_Click(object sender, RoutedEventArgs e) { PushNotificationChannel currentChannel = rootPage.Channel; if (currentChannel != null) { dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher; currentChannel.PushNotificationReceived += OnPushNotificationReceived; rootPage.NotifyUser("Callback added.", NotifyType.StatusMessage); } else { rootPage.NotifyUser("Channel not open. Open the channel in scenario 1.", NotifyType.ErrorMessage); } }
public async void CreateChannel() { try { this.channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); int a = 3; a++; } catch (Exception ex) { throw ex; } }
// Handles the received push notifications, and updates the UI in case it was a Raw notification async void channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { if (args.NotificationType == PushNotificationType.Raw) { // Deserialize into a ChatMessage object XmlSerializer xmlSerializer = new XmlSerializer(typeof(ChatMessage)); StringReader stringReader = new StringReader(args.RawNotification.Content); var chatMessage = xmlSerializer.Deserialize(stringReader) as ChatMessage; // Add to the chat messages, has to run on the UI thread await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => ChatMessages.Add(chatMessage) ); } }
public void SendInvalidEndPointPushNotificationTest() { NotificationTest test = new NotificationTest(); IMobilePushNotificationServiceClient mobileServiceClient = this.CreateMobileServiceClient(); PushNotificationChannel channel = new PushNotificationChannel(mobileServiceClient, test.EventPublisher); PushNotification notification = this.CreateNotification(); NotificationAccount <Guid> account = test.AddNotificationAccount(); this.PushNotificationShouldFailAtEndPoint(mobileServiceClient); channel.SendAsync(account, notification).Wait(); this.AssertSentFailed(test, account, notification, NotificationErrorCode.RouteFailure); }
private HttpContent CreatePayload(string appId, PushNotificationChannel channel, string tileId, string clientId, string userId, string deviceType) { var payload = string.Format(K_PAYLOAD, appId, channel.Uri, channel.ExpirationTime.DateTime, tileId, clientId, userId, deviceType); var content = new StringContent("{" + payload + "}"); content.Headers.Remove("Content-Type"); content.Headers.Add("Content-Type", K_CONTENTTYPE); return(content); }
/// <summary> /// Registers the current device for a push notification chennel, it will be passed to the 3rd party server. /// </summary> public async Task <bool> RegisterForWNS() { try { // a channel will live for 30 days _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); Debug.WriteLine("Channel opened for URI: " + _channel.Uri.ToString()); return(true); } catch (Exception) { return(false); } }
private static async void CloseWNSChannel() { var settings = ApplicationData.Current.LocalSettings; if (settings.Values.ContainsKey(HAS_WNS_CHANNEL_KEY) && (bool)settings.Values[HAS_WNS_CHANNEL_KEY]) { try { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.Close(); ApplicationData.Current.LocalSettings.Values[HAS_WNS_CHANNEL_KEY] = false; } catch {} } }
/// <summary> /// Handles a push notification being received whilst the app is live. If we receive a toast, /// it is likely we have received an invite. If we receive a tile, it's probably that we /// have a new item. /// </summary> void channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { _synchronizationContext.Post(ignored => { if (args.NotificationType == PushNotificationType.Toast) { // we received a toast notification - let's check for invites LoadInvites(); } else if (args.NotificationType == PushNotificationType.Tile) { // we received a tile - reload current items in case it was for this list LoadItems(); } }, null); }
private async Task <PushNotificationChannel> EnableNotifications() { Monitor.Enter(sync); //TODO: try { channel = await PushNotificationChannelManager .CreatePushNotificationChannelForApplicationAsync() .AsTask(); return(channel); } finally { Monitor.Exit(sync); } }
public async void Bind() { PushNotificationChannel pushChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); if (pushChannel != null && !string.IsNullOrEmpty(pushChannel.Uri)) { pushChannel.PushNotificationReceived -= pushChannel_PushNotificationReceived; pushChannel.PushNotificationReceived += pushChannel_PushNotificationReceived; string uri = Global.Current.LocalSettings.LoadData(conChannelUriKey) == null ? string.Empty : Global.Current.LocalSettings.LoadData(conChannelUriKey).ToString(); if (string.IsNullOrEmpty(uri) || (!string.IsNullOrEmpty(pushChannel.Uri) && uri != pushChannel.Uri)) { Global.Current.LocalSettings.SaveData(conChannelUriKey, pushChannel.Uri); //Updata web service channelUri } } }