public void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e) { if (e.NotificationType == PushNotificationType.Toast) { this.RefreshOrders(); } }
private static void notificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { string receiver = args.RawNotification.Content; if (CommonData.session!=null && receiver == CommonData.session.Username) { if (CommonData.activeConversationPage != null) { CommonData.activeConversationPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { CommonData.activeConversationPage.refreshMessages(null, null); }); } } else { foreach (string[] credential in DataStorage.GetNotifierCredentials()) { if (receiver == credential[0]) { ToastTemplateType toastTemplate = ToastTemplateType.ToastText02; XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate); var toastTextElements = toastXml.GetElementsByTagName("text"); ResourceLoader resourceGetter = new ResourceLoader(); string appName = resourceGetter.GetString("ApplicationTitle"); string notificationText = resourceGetter.GetString("NotifierNewMessageText") + credential[0]; toastTextElements[0].AppendChild(toastXml.CreateTextNode(appName)); toastTextElements[1].AppendChild(toastXml.CreateTextNode(notificationText)); ToastNotification toast = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(toast); } } } }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="navigationParameter">The parameter value passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested. /// </param> /// <param name="pageState">A dictionary of state preserved by this page during an earlier /// session. This will be null the first time a page is visited.</param> protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState) { VM = (ParticipateLiveVM)navigationParameter; _notificationChannel = await Win8Notification.GetNotificationChannel(); _notificationChannel.PushNotificationReceived += notificationChannel_PushNotificationReceived; await VM.RegisterForNotification(_notificationChannel.Uri, "Win8", VM.CurrentSurvey.ChannelName); }
private async Task AcquirePushChannel() { CurrentChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var channelTable = MobileService.GetTable<Channel>(); Channel channel = new Channel { Uri = CurrentChannel.Uri, Type = "Windows 8" }; await channelTable.InsertAsync(channel); }
private async void AcquirePushChannel() { CurrentChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var channelTable = MobileServiceClient.GetTable<Channel>(); var channel = new Channel { Uri = CurrentChannel.Uri }; await channelTable.InsertAsync(channel); }
public async Task UpdatePushTokenIfNeeded(PushNotificationChannel pushChannel) { string tokenHash = Helpers.ComputeMD5(pushChannel.Uri); string storedTokenHash = SettingsManager.Instance.ReadFromSettings<string>(SettingsKeys.PushTokenHash); if (tokenHash != storedTokenHash) { string storedTokenId = SettingsManager.Instance.ReadFromSettings<string>(SettingsKeys.PushTokenId); if (!string.IsNullOrEmpty(storedTokenId)) await quickbloxClient.NotificationClient.DeletePushTokenAsync(storedTokenId); var settings = new CreatePushTokenRequest() { DeviceRequest = new DeviceRequest() {Platform = Platform.windows_phone, Udid = Helpers.GetHardwareId()}, PushToken = new PushToken() { Environment = Environment.production, ClientIdentificationSequence = pushChannel.Uri } }; var createPushTokenResponse = await quickbloxClient.NotificationClient.CreatePushTokenAsync(settings); if (createPushTokenResponse.StatusCode == HttpStatusCode.Created) { SettingsManager.Instance.WriteToSettings(SettingsKeys.PushTokenId, createPushTokenResponse.Result.PushToken.PushTokenId); SettingsManager.Instance.WriteToSettings(SettingsKeys.PushTokenHash, tokenHash); } } }
private void Channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { Debug.WriteLine("Push Notification Received " + args.NotificationType); JObject jobject = null; switch (args.NotificationType) { case PushNotificationType.Badge: jobject = JObject.FromObject(args.BadgeNotification, serializer); break; case PushNotificationType.Raw: jobject = JObject.FromObject(args.RawNotification, serializer); break; case PushNotificationType.Tile: jobject = JObject.FromObject(args.TileNotification, serializer); break; #if WINDOWS_UWP || WINDOWS_PHONE_APP case PushNotificationType.TileFlyout: jobject = JObject.FromObject(args.TileNotification, serializer); break; #endif case PushNotificationType.Toast: jobject = JObject.FromObject(args.ToastNotification, serializer); break; } Debug.WriteLine("Sending JObject to PushNotificationListener " + args.NotificationType); CrossPushNotification.PushNotificationListener.OnMessage(jobject, DeviceType.Windows); }
public async Task AcquirePushChannel() { await Task.Run(async () => { var credentials = _credentialsProvider.ProvideCredentials(CancellationToken.None); if (credentials == null) { return; } try { Channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); //var newParametres = new Dictionary<string, string>(); //newParametres.Add("type", "test"); //newParametres.Add("text", "Бесплатная книга из раздела Популярное теперь в вашей библиотеке!"); //newParametres.Add("spam_pack_id", "test"); //Task.Delay(10000); //ViewModels.PushNotificationsViewModel.Instance.ShowToast(newParametres); //_channel.PushNotificationReceived += (sender, args) => //{ //OpenNotification(args); //}; Debug.WriteLine($"URI: {Channel.Uri}"); await _notificationsProvider.SubscribeDevice(Channel.Uri, CancellationToken.None); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }); }
void _channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { if (PushNotificationReceived != null) { PushNotificationReceived(sender, args); } }
/// <summary> /// Handles push notifications from mobile services. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private static async void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { switch(args.NotificationType) { case PushNotificationType.Toast: // If there is a currently active game, get it and call ProcessRemoteTurn. if (MainPage.GetMainPage().Processor != null) { await MainPage.GetMainPage().Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => MainPage.GetMainPage().Processor.HandleToastNotification()); } break; case PushNotificationType.Badge: if (MainPage.GetMainPage() != null) { await MainPage.GetMainPage().Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => MainPage.GetMainPage().HandleBadgeNotification(args.BadgeNotification)); args.Cancel = true; } break; case PushNotificationType.Raw: break; } }
void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs e) { string typeString = String.Empty; string notificationContent = String.Empty; switch (e.NotificationType) { case PushNotificationType.Badge: typeString = "Badge"; notificationContent = e.BadgeNotification.Content.GetXml(); break; case PushNotificationType.Tile: notificationContent = e.TileNotification.Content.GetXml(); typeString = "Tile"; break; case PushNotificationType.Toast: notificationContent = e.ToastNotification.Content.GetXml(); typeString = "Toast"; // Setting the cancel property prevents the notification from being delivered. It's especially important to do this for toasts: // if your application is already on the screen, there's no need to display a toast from push notifications. e.Cancel = true; break; case PushNotificationType.Raw: notificationContent = e.RawNotification.Content; typeString = "Raw"; break; } string text = "Received a " + typeString + " notification, containing: " + notificationContent; var ignored = dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(text, NotifyType.StatusMessage); }); }
public async void SetupPushNotificationChannelForApplicationAsync(string token, string arguments) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentException("you should add you app token"); } //var encryptedArguments = Helper.Encrypt(arguments, "cnblogs", "somesalt"); _channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var content = new HttpFormUrlEncodedContent(new[] { new KeyValuePair<string, string>("arguments", arguments), new KeyValuePair<string, string>("token", token), new KeyValuePair<string, string>("uri", _channel.Uri), new KeyValuePair<string, string>("uuid", GetUniqueDeviceId()) }); var request = new HttpRequestMessage(HttpMethod.Post, new Uri(server)); request.Content = content; var client = new HttpClient(); var response = await client.SendRequestAsync(request); _channel.PushNotificationReceived += _channel_PushNotificationReceived; }
private async void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs e) { String notificationContent = String.Empty; switch (e.NotificationType) { case PushNotificationType.Badge: notificationContent = e.BadgeNotification.Content.GetXml(); break; case PushNotificationType.Tile: notificationContent = e.TileNotification.Content.GetXml(); break; case PushNotificationType.Toast: notificationContent = e.ToastNotification.Content.GetXml(); break; case PushNotificationType.Raw: notificationContent = e.RawNotification.Content; break; } System.Diagnostics.Debug.WriteLine("received notification:\n" + notificationContent); //e.Cancel = true; }
async void channel_PushNotificationReceived(Windows.Networking.PushNotifications.PushNotificationChannel sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs args) { if (args.ToastNotification.Content.InnerText.Contains("Event")) { } else { args.Cancel = true; items = await Table.OrderByDescending(ChatPublic => ChatPublic.CreatedAt).Take(1).ToCollectionAsync(); await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ChatPubList a = new ChatPubList(); a.date = items[0].CreatedAt.Date.ToString(); a.time = items[0].CreatedAt.TimeOfDay.ToString(); a.time = a.time.Remove(5); a.date = a.date.Remove(10); a.Message = items[0].Message; a.Name = items[0].Name; var networkProfiles = Windows.Networking.Connectivity.NetworkInformation.GetConnectionProfiles(); var adapter = networkProfiles.First <Windows.Networking.Connectivity.ConnectionProfile>().NetworkAdapter;//takes the first network adapter string networkAdapterId = adapter.NetworkAdapterId.ToString(); if (a.Name == networkAdapterId) { a.col = "#FF9B0E00"; } else { a.col = "#FF5D340C"; } MainPage.test.Insert(0, a); }); } }
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())); } }
private static void OnPushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { TypedEventHandler<PushNotificationChannel, PushNotificationReceivedEventArgs> handler = PushNotificationReceived; if (handler != null) { handler(sender, args); } }
private async void notificationChannel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { _timer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 5) }; _timer.Tick += timer_Tick; _timer.Start(); }); }
/// <summary> /// Registers for push notifications. /// </summary> public async static Task UploadChannel(MobileServiceUser user) { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); await App.mobileClient.GetPush().RegisterNativeAsync(channel.Uri , new string[] { user.UserId }); if (channel != null) { channel.PushNotificationReceived += OnPushNotificationReceived; } }
public void Unregister() { if(channel!=null) { channel.PushNotificationReceived -= Channel_PushNotificationReceived; channel = null; } CrossPushNotification.PushNotificationListener.OnUnregistered(DeviceType.Windows); }
static void channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { if (args.NotificationType == PushNotificationType.Raw) { DispatcherHelper.CheckBeginInvokeOnUI(() => { var vote = JObject.Parse(args.RawNotification.Content).ToObject<RawVote>(); Messenger.Default.Send<RawVote>(vote); }); } }
public static async void CreatePushNotificationChannel() { try { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channelUri = channel.Uri.ToString(); } catch { } }
private async void btnGetChannelURI_Click(object sender, RoutedEventArgs e) { try { btnGetChannelURI.IsEnabled = false; channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); this.tbMessage.Text = channel.Uri; } catch { //Could not create channel uri btnGetChannelURI.IsEnabled = true; } }
private async void GetChannel() { channel = null; try { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); } catch (Exception ex) { // Could not create a channel. Debug.WriteLine(ex.Message); } }
/// <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; } }
/// <summary> /// Registers a Windows 8 application to receive push notifications for incoming messages. /// </summary> /// <param name="pushNotificationChannel">The push notification channel.</param> /// <param name="pushContent">Content of the push.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task representing the async operation.</returns> public async Task RegisterPushNotificationChannelAsync(PushNotificationChannel pushNotificationChannel, string pushContent, CancellationToken cancellationToken = default(CancellationToken)) { Requires.NotNull(pushNotificationChannel, "pushNotificationChannel"); Requires.ValidState(!string.IsNullOrEmpty(this.PackageSecurityIdentifier), "PackageSecurityIdentifier must be initialized first."); var request = new HttpRequestMessage(HttpMethod.Put, this.Endpoint.PublicEndpoint.MessageReceivingEndpoint); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.Endpoint.InboxOwnerCode); request.Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "package_security_identifier", this.PackageSecurityIdentifier }, { "channel_uri", pushNotificationChannel.Uri }, { "channel_content", pushContent ?? string.Empty }, { "expiration", pushNotificationChannel.ExpirationTime.ToString(CultureInfo.InvariantCulture) }, }); var response = await this.HttpClient.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); }
private void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) { if (args.ToastNotification == null) return; var message = args.ToastNotification.Content.InnerText; var launch = args.ToastNotification.Content.GetElementsByTagName("toast")[0].Attributes.GetNamedItem("launch"); IDictionary<string, string> data = new Dictionary<string, string>(); if (launch != null) { data = UrlQueryParser.ParseQueryString(launch.InnerText); } OnPushNotification(message, data); }
private async Task<PushNotificationChannel> EnableNotifications() { Monitor.Enter(sync); //TODO: try { channel = await PushNotificationChannelManager .CreatePushNotificationChannelForApplicationAsync() .AsTask(); return channel; } finally { Monitor.Exit(sync); } }
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(); //} }
private async void Start_Loaded(object sender, RoutedEventArgs e) { channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); try { await App.Mugd_appClient.GetPush().RegisterNativeAsync(channel.Uri); //await App.Mugd_appClient.InvokeApiAsync("notifyAllUsers", // new JObject(new JProperty("toast", "Sample Toast"))); } catch (Exception exception) { HandleRegisterException(exception); } channel.PushNotificationReceived += channel_PushNotificationReceived; }
/// <summary> /// The try register channel. /// </summary> /// <returns> /// The <see cref="Task"/>. /// </returns> private static async Task<bool> TryRegisterChannel() { try { if (channel == null) { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += OnPushNotificationReceived; } } catch (Exception) { return false; } return true; }
/// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used when the application is launched to open a specific file, to display /// search results, and so forth. /// </summary> /// <param name="args">Details about the launch request and process.</param> protected async override void OnLaunched(LaunchActivatedEventArgs args) { //Must occur before MainPage activate PrimaryChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); var channelDTO = new Channel() { Id = ApplicationData.Current.LocalSettings.Values["ChannelId"] as int?, Uri = PrimaryChannel.Uri }; if (ApplicationData.Current.LocalSettings.Values["ChannelId"] == null) { await MobileService.GetTable<Channel>().InsertAsync(channelDTO); ApplicationData.Current.LocalSettings.Values["ChannelId"] = channelDTO.Id; } else { await MobileService.GetTable<Channel>().UpdateAsync(channelDTO); } // Do not repeat app initialization when already running, just ensure that // the window is active if (args.PreviousExecutionState == ApplicationExecutionState.Running) { Window.Current.Activate(); return; } if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Create a Frame to act navigation context and navigate to the first page var rootFrame = new Frame(); if (!rootFrame.Navigate(typeof(MainPage))) { throw new Exception("Failed to create initial page"); } // Place the frame in the current Window and ensure that it is active Window.Current.Content = rootFrame; Window.Current.Activate(); }
void channel_PushNotificationReceived(Windows.Networking.PushNotifications.PushNotificationChannel sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs args) { if (args.ToastNotification.Content.InnerText.Contains("Event")) { //args.Cancel = true; } else { args.Cancel = true; //items = await Table.OrderByDescending(ChatPublic => ChatPublic.CreatedAt).Take(1).ToCollectionAsync(); //await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => //{ // ChatPubList a = new ChatPubList(); // a.Message = items[0].Message; // a.Name = items[0].Name; // MainPage.test.Insert(0, a); //}); } }