void SendRegistrationToServer(string token) { ////We'll do this later //hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this); //var tags = new List<string>() { }; //var regID = hub.Register(token, tags.ToArray()).RegistrationId; //Log.Debug(TAG, $"Successful registration of ID {regID}"); try { NotificationHub hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this); // register device with Azure Notification Hub using the token from FCM Registration registration = hub.Register(token, Constants.SubscriptionTags); // subscribe to the SubscriptionTags list with a simple template. string pnsHandle = registration.PNSHandle; TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", Constants.FCMTemplateBody, Constants.SubscriptionTags); } catch (Exception e) { Log.Error(Constants.DebugTag, $"Error registering device: {e.Message}"); } }
static void ValidateTemplateRegistration(TemplateRegistration registration) { Assert.AreEqual(registration.BodyTemplate, BodyTemplate); foreach (KeyValuePair <string, string> header in DefaultHeaders) { Assert.IsTrue(registration.MpnsHeaders.ContainsKey(header.Key)); Assert.AreEqual(registration.MpnsHeaders[header.Key], header.Value); } foreach (KeyValuePair <string, string> header in DetectedHeaders) { Assert.IsTrue(registration.MpnsHeaders.ContainsKey(header.Key)); Assert.AreEqual(registration.MpnsHeaders[header.Key], header.Value); } Assert.AreEqual(registration.MpnsHeaders.Count, DefaultHeaders.Count + DetectedHeaders.Count); foreach (string tag in DefaultTags) { Assert.IsTrue(registration.Tags.Contains(tag)); } Assert.AreEqual(registration.Name, DefaultToastTemplateName); Assert.AreEqual(registration.TemplateName, DefaultToastTemplateName); }
public static void ValidateTemplateRegistrationAfterRegister(TemplateRegistration registration, string zumoInstallationId) { ValidateTemplateRegistration(registration); Assert.IsNotNull(registration.RegistrationId); Assert.IsTrue(registration.Tags.Contains(zumoInstallationId)); Assert.AreEqual(registration.Tags.Count, DefaultTags.Length + 1); }
static void ValidateTemplateRegistration(TemplateRegistration registration) { Assert.AreEqual(registration.BodyTemplate, BodyTemplate); foreach (KeyValuePair <string, string> header in DefaultHeaders) { string foundKey = registration.WnsHeaders.Keys.Single(s => s.ToLower() == header.Key.ToLower()); Assert.IsNotNull(foundKey); Assert.AreEqual(registration.WnsHeaders[foundKey], header.Value); } foreach (KeyValuePair <string, string> header in DetectedHeaders) { string foundKey = registration.WnsHeaders.Keys.Single(s => s.ToLower() == header.Key.ToLower()); Assert.IsNotNull(foundKey); Assert.AreEqual(registration.WnsHeaders[foundKey], header.Value); } Assert.AreEqual(registration.WnsHeaders.Count, DefaultHeaders.Count + DetectedHeaders.Count); foreach (string tag in DefaultTags) { Assert.IsTrue(registration.Tags.Contains(tag)); } Assert.AreEqual(registration.Name, DefaultToastTemplateName); Assert.AreEqual(registration.TemplateName, DefaultToastTemplateName); }
// serving fresh code void SendRegistrationToServer(string token) { if (Preferences.Get("guid", null) != null) { var tag = Preferences.Get("guid", null); Console.WriteLine("guid:" + tag); Console.WriteLine("token:" + token); return; } try { NotificationHub hub = new NotificationHub(AppConstants.NotificationHubName, AppConstants.ListenConnectionString, this); var guid = Guid.NewGuid(); var tag = "guid_" + guid.ToString(); Console.WriteLine("guid:" + tag); Console.WriteLine("token:" + token); Preferences.Set("guid", tag); string[] tags = new string[2] { "default", tag }; // register device with Azure Notification Hub using the token from FCM Registration registration = hub.Register(token, tags); // subscribe to the SubscriptionTags list with a simple template. string pnsHandle = registration.PNSHandle; TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", AppConstants.FCMTemplateBody, tags); } catch (Exception e) { Log.Error(AppConstants.DebugTag, $"Error registering device: {e.Message}"); } }
static void ValidateTemplateRegistration(TemplateRegistration registration) { Assert.AreEqual(registration.BodyTemplate, BodyTemplate); foreach (KeyValuePair<string, string> header in DefaultHeaders) { string foundKey = registration.WnsHeaders.Keys.Single(s => s.ToLower() == header.Key.ToLower()); Assert.IsNotNull(foundKey); Assert.AreEqual(registration.WnsHeaders[foundKey], header.Value); } foreach (KeyValuePair<string, string> header in DetectedHeaders) { string foundKey = registration.WnsHeaders.Keys.Single(s => s.ToLower() == header.Key.ToLower()); Assert.IsNotNull(foundKey); Assert.AreEqual(registration.WnsHeaders[foundKey], header.Value); } Assert.AreEqual(registration.WnsHeaders.Count, DefaultHeaders.Count + DetectedHeaders.Count); foreach (string tag in DefaultTags) { Assert.IsTrue(registration.Tags.Contains(tag)); } Assert.AreEqual(registration.Name, DefaultToastTemplateName); Assert.AreEqual(registration.TemplateName, DefaultToastTemplateName); }
public static void ValidateTemplateRegistrationAfterRegister(TemplateRegistration registration, string zumoInstallationId) { ValidateTemplateRegistration(registration); Assert.IsNotNull(registration.RegistrationId); // TODO: Uncomment when .Net Runtime implements installationID //Assert.IsTrue(registration.Tags.Contains(zumoInstallationId)); Assert.AreEqual(registration.Tags.Count, DefaultTags.Length + 1); }
public void InvalidBodyTemplateIfNotXml() { try { var registration = new TemplateRegistration("uri", "junkBodyTemplate", "testName"); Assert.Fail("Expected templateBody that is not XML to throw ArgumentException"); } catch (ArgumentException e) { // PASSES } }
public void InvalidBodyTemplateIfNotXml() { try { var registration = new TemplateRegistration("uri", "junkBodyTemplate", "testName"); Assert.Fail("Expected templateBody that is not XML to throw ArgumentException"); } catch { // PASSES } }
public void InvalidBodyTemplateIfImproperXml() { try { var registration = new TemplateRegistration( "uri", "<foo><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></foo>", "testName"); Assert.Fail("Expected templateBody with unexpected first XML node to throw ArgumentException"); } catch (ArgumentException e) { // PASSES } }
public void InvalidBodyTemplateIfImproperXml() { try { var registration = new TemplateRegistration( "uri", "<foo><visual><binding template=\"ToastText01\"><text id=\"1\">$(message)</text></binding></visual></foo>", "testName"); Assert.Fail("Expected templateBody with unexpected first XML node to throw ArgumentException"); } catch { // PASSES } }
void SendRegistrationToServer(string token) { try { hub = new NotificationHub(AppConstants.NotificationHubName, AppConstants.ListenConnectionString, this); // register device with Azure Notification Hub using the token from FCM Registration registration = hub.Register(token, AppConstants.SubscriptionTags.ToArray()); // subscribe to the SubscriptionTags list with a simple template. string pnsHandle = registration.PNSHandle; TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", AppConstants.FCMTemplateBody, AppConstants.SubscriptionTags.ToArray()); } catch (Exception e) { Log.Error(AppConstants.DebugTag, $"Error registering device: {e.Message}"); } }
private void SendPushTokenToAzure(string token) { try { NotificationHub hub = new NotificationHub(Covi.Configuration.Constants.PushNotificationsConstants.NotificationHubName, Covi.Configuration.Constants.PushNotificationsConstants.ListenConnectionString, this); // register device with Azure Notification Hub using the token from FCM Registration registration = hub.Register(token, Covi.Configuration.Constants.PushNotificationsConstants.SubscriptionTags); // subscribe to the SubscriptionTags list with a simple template. string pnsHandle = registration.PNSHandle; TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", Covi.Configuration.Constants.PushNotificationsConstants.FCMTemplateBody, Covi.Configuration.Constants.PushNotificationsConstants.SubscriptionTags); } catch (Exception ex) { Debugger.Break(); _logger.LogError(ex, "Failed to send push notification token to Azure Hub"); } }
private static ZumoTest CreateRegisterTemplateChannelTest(string nhNotificationType) { return(new ZumoTest("Register template " + nhNotificationType + " push channel", async delegate(ZumoTest test) { var client = ZumoTestGlobals.Instance.Client; var push = client.GetPush(); TemplateRegistration reg = null; switch (nhNotificationType.ToLower()) { case "toast": var toastTemplate = BuildXmlToastPayload("sendToastText01", "$(News_English)"); reg = new TemplateRegistration(ZumoPushTests.pushChannel.Uri, toastTemplate.ToString(), ZumoPushTestGlobals.NHToastTemplateName, "World English".Split()); break; case "raw": var rawTemplate = "<raw>$(News_French)</raw>"; IDictionary <string, string> wnsHeaders = new Dictionary <string, string>(); wnsHeaders.Add("X-WNS-Type", "wns/raw"); reg = new TemplateRegistration(ZumoPushTests.pushChannel.Uri, rawTemplate, ZumoPushTestGlobals.NHRawTemplateName, "World Mandarin".Split(), wnsHeaders); break; case "badge": var badgeTemplate = BuildBadgeXmlPayload("$(News_Badge)"); reg = new TemplateRegistration(ZumoPushTests.pushChannel.Uri, badgeTemplate.ToString(), ZumoPushTestGlobals.NHBadgeTemplateName, "World Badge".Split()); break; case "tile": var tileTemplate = BuildXmlTilePayload("TileWideImageAndText02", new[] { "tl-wiat2-1", "$(News_Mandarin)" }, new[] { wideImageUrl }, new[] { "zumowide" }); reg = new TemplateRegistration(ZumoPushTests.pushChannel.Uri, tileTemplate.ToString(), ZumoPushTestGlobals.NHTileTemplateName, "World Mandarin".Split()); break; default: throw new Exception("Template type" + nhNotificationType + "is not supported."); } await push.RegisterAsync(reg); pushChannelUri = null; test.AddLog("Registered " + nhNotificationType + " template with NH succeeded."); pushChannel.PushNotificationReceived += pushChannel_PushNotificationReceived; return true; }, ZumoTestGlobals.RuntimeFeatureNames.NH_PUSH_ENABLED)); }
// https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-windows-store-dotnet-get-started-push public async Task InitNotificationsAsync(string userId) { channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); const string toastTemplate = "<toast>" + "<visual>" + "<binding template=\"ToastText02\">" + "<text id=\"1\">$(title)</text>" + "<text id=\"2\">$(content)</text>" + "</binding>" + "</visual>" + "</toast>"; const string rawTemplate = "<root>" + "<Group>$(groupId)</Group>" + "<Message>$(messageId)</Message>" + "<Sender>$(senderId)</Sender>" + "<Action>$(action)</Action>" + "</root>"; var hub = new NotificationHub("penscrib-notification-hub", "Endpoint=sb://penscrib-notifications.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=ZRR3SXi3eQoTSPa5kpMDzeRJrWooFXbIBn5Vgs8lIdw="); string[] tags = new string[] { "userId:" + userId }; await hub.UnregisterAllAsync(channel.Uri); var toastresult = await hub.RegisterTemplateAsync(channel.Uri, toastTemplate, "toastNotification", tags); WnsHeaderCollection headers = new WnsHeaderCollection(); headers.Add("X-WNS-Type", @"wns/raw"); TemplateRegistration registration = new TemplateRegistration(channel.Uri, rawTemplate, "rawNotification", tags, headers); var rawresult = await hub.RegisterAsync(registration); channel.PushNotificationReceived += OnPushNotification; }
private void SendRegistrationToServer(string token) { try { App.DeviceId = Android.Provider.Settings.Secure.GetString( Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId); string[] tokens = Constants.SubscriptionTags.Append($"deviceid:{App.DeviceId}").ToArray(); WindowsAzure.Messaging.NotificationHub hub = new WindowsAzure.Messaging.NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString, this); // register device with Azure Notification Hub using the token from FCM Registration registration = hub.Register(token, tokens); // subscribe to the SubscriptionTags list with a simple template. string pnsHandle = registration.PNSHandle; TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", Constants.FCMTemplateBody, tokens); } catch (Exception e) { Log.Error(Constants.DebugTag, $"Error registering device: {e.Message}"); } }
private async Task SendRegistrationToServer(string token) { try { NotificationHub hub = new NotificationHub(PushNotificationConstants.NotificationHubName, PushNotificationConstants.ListenConnectionString, this); // Get countryName for subscription tags await PushNotificationHelper.UpdateCurrentCountryTag(); // register device with Azure Notification Hub using the token from FCM Registration registration = hub.Register(token, PushNotificationConstants.SubscriptionTags); // subscribe to the SubscriptionTags list with a simple template. string pnsHandle = registration.PNSHandle; TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", PushNotificationConstants.FCMTemplateBody, PushNotificationConstants.SubscriptionTags); } catch (Exception e) { Log.Error(PushNotificationConstants.DebugTag, $"Error registering device: {e.Message}"); } }
/// <summary> /// Register for push notifications or update the expiration when required /// </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> public async Task RegisterPushNotifications(string hubName, string connectionString, string templateName, string metadata, string header, string footer, string image) { bool registerTemplate = false; // Retrieve local settings ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; // Retrieve saved expiration date for this template object registerExpiration = localSettings.Values[templateName.Replace(" ", "-")]; // Flag as to-register when no value found if (registerExpiration != null) { // Try parse to datetime DateTime expirationDateTime; DateTime.TryParse(registerExpiration.ToString(), out expirationDateTime); // Register when expired if (expirationDateTime <= DateTime.Now) { registerTemplate = true; } } else { registerTemplate = true; } // Create a new registration when required if (registerTemplate == true) { TemplateRegistration tempRegistration = await PushNotificationsHelper.RegisterTemplateNotificationAsync(hubName, connectionString, templateName, metadata, header, footer, image); // Save new expiration date localSettings.Values[templateName.Replace(" ", "-")] = tempRegistration.ExpiresAt.ToString(); } }
public static void ValidateTemplateRegistrationBeforeRegister(TemplateRegistration registration) { ValidateTemplateRegistration(registration); Assert.AreEqual(registration.Tags.Count, DefaultTags.Length); Assert.IsNull(registration.RegistrationId); }
public async Task RegisterNotificationAsync() { //var hub = new NotificationHub("<<YOUR LISTEN CONNECTION STRING>>", "<<YOUR AZURE NOTIFICATION HUB NAME>>"); var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); channel.PushNotificationReceived += Channel_PushNotificationReceived; var playerTag = new string[] { "user_player1" }; var hub = new NotificationHub(AppConnections.NotificationHubPath, AppConnections.PushUrlFullPath); TemplateRegistration reg; try { reg = new TemplateRegistration( channel.Uri, "<toast>" + "<visual>" + "<binding template=\"ToastGeneric\">" + "<text id=\"1\">{'Player: ' + $(player_name)}</text>" + "<text id=\"2\">{'Jogada: ' + $(player_move)}</text>" + "</binding>" + "</visual>" + "</toast>" , "GameData", playerTag ); //new Dictionary<string, string> { { "X-WNS-Type", "wns/raw" } }); } catch (Exception e) { System.Diagnostics.Debug.Write(e.Message); throw; } var register = await RegisterPush(); async Task <string> RegisterPush() { //var result = await hub.RegisterNativeAsync(channel.Uri, playerTag); sem template try { var result = await hub.RegisterAsync(reg); register = result.RegistrationId; return(register); } catch (Exception e) { System.Diagnostics.Debug.Write(e.Message); throw; } } if (register == null) { SendStatusGame("Falha ao registrar push"); } else { SendStatusGame($"PUSH OK, TAG: {playerTag[0]}"); } }
private static ZumoTest CreateRegisterChannelTest(bool registerTemplate = false, string templateType = null) { return(new ZumoTest("Register push channel", async delegate(ZumoTest test) { string channelName = "MyPushChannel"; var pushChannel = HttpNotificationChannel.Find(channelName); if (pushChannel == null) { pushChannel = new HttpNotificationChannel(channelName); test.AddLog("Created new channel"); } else { test.AddLog("Reusing existing channel"); } ZumoWP8PushTests.pushChannel = pushChannel; if (pushChannel.ConnectionStatus == ChannelConnectionStatus.Disconnected || pushChannel.ChannelUri == null) { pushChannel.Open(); test.AddLog("Opened the push channel"); } else { test.AddLog("Channel already opened"); } if (pushChannel.IsShellToastBound) { test.AddLog("Channel is already bound to shell toast"); } else { var uris = new System.Collections.ObjectModel.Collection <Uri>(); uris.Add(new Uri(ImageUrlDomain)); pushChannel.BindToShellTile(uris); pushChannel.BindToShellToast(); test.AddLog("Bound the push channel to shell toast / tile"); } TimeSpan maxWait = TimeSpan.FromSeconds(30); await WaitForChannelUriAssignment(test, pushChannel, maxWait); if (ZumoTestGlobals.Instance.IsNHPushEnabled) { var zumoPush = ZumoTestGlobals.Instance.Client.GetPush(); TemplateRegistration reg = null; if (registerTemplate) { switch (templateType) { case "toast": reg = new TemplateRegistration(pushChannel.ChannelUri.ToString(), ZumoPushTestGlobals.NHWp8ToastTemplate, "wp8" + ZumoPushTestGlobals.NHToastTemplateName, "World English".Split()); break; case "tile": reg = new TemplateRegistration(pushChannel.ChannelUri.ToString(), ZumoPushTestGlobals.NHWp8TileTemplate, "wp8" + ZumoPushTestGlobals.NHTileTemplateName, "World Mandarin".Split()); break; case "raw": IDictionary <string, string> wp8Headers = new Dictionary <string, string>(); wp8Headers.Add("X-NotificationClass", "3"); reg = new TemplateRegistration(pushChannel.ChannelUri.ToString(), ZumoPushTestGlobals.NHWp8RawTemplate, "wp8" + ZumoPushTestGlobals.NHRawTemplateName, "World French".Split(), wp8Headers); break; } await zumoPush.RegisterAsync(reg); pushChannel.ChannelUriUpdated += new EventHandler <NotificationChannelUriEventArgs>(async(o, args) => { await zumoPush.RegisterAsync(reg); }); test.AddLog("Registered to Notification hub"); } else { await zumoPush.RegisterNativeAsync(pushChannel.ChannelUri.ToString(), "tag1 tag2".Split()); pushChannel.ChannelUriUpdated += new EventHandler <NotificationChannelUriEventArgs>(async(o, args) => { await zumoPush.RegisterNativeAsync(args.ChannelUri.ToString(), "tag1 tag2".Split()); }); test.AddLog("Registered with NH"); } } pushChannel.HttpNotificationReceived += pushChannel_HttpNotificationReceived; pushChannel.ShellToastNotificationReceived += pushChannel_ShellToastNotificationReceived; test.AddLog("Registered to raw / shell toast events"); if (pushChannel.ConnectionStatus != ChannelConnectionStatus.Connected || pushChannel.ChannelUri == null) { test.AddLog("Error, push channel isn't connected or channel URI is null"); return false; } else { return true; } }, registerTemplate ? ZumoTestGlobals.RuntimeFeatureNames.NH_PUSH_ENABLED : null)); }