public async Task <ActionResult> Index(Models.SendNotificationsModel model) { //get notification hub information // Get the settings for the server project. System.Web.Http.HttpConfiguration config = System.Web.Http.GlobalConfiguration.Configuration; MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Sending the message so that all template registrations that contain "messageParam" // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); templateParams["title"] = model.Title; templateParams["message"] = model.Message; try { NotificationOutcome result = null; // Send the push notification and log the results. if (model.Tags != null && model.Tags.Count > 0) { result = await hub.SendTemplateNotificationAsync(templateParams, String.Join(" || ", model.Tags)); } else { result = await hub.SendTemplateNotificationAsync(templateParams); } // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); throw; } //redirct to confirm return(View("Confirm")); }
public async Task <bool> RequestNotificationAsync(NotificationRequest notificationRequest, CancellationToken token) { if ((notificationRequest.Silent && string.IsNullOrWhiteSpace(notificationRequest?.Action)) || (!notificationRequest.Silent && (string.IsNullOrWhiteSpace(notificationRequest?.Text)) || string.IsNullOrWhiteSpace(notificationRequest?.Action))) { return(false); } var templateParams = notificationRequest.Silent ? new Dictionary <string, string> { { "silentMessage", notificationRequest.Text }, { "silentAction", notificationRequest.Action } } : new Dictionary <string, string> { { "alertMessage", notificationRequest.Text }, { "alertAction", notificationRequest.Action } }; try { if (notificationRequest.Tags.Length == 0) { // This will broadcast to all users registered in the notification hub await _hub.SendTemplateNotificationAsync(templateParams, token); } else if (notificationRequest.Tags.Length <= 20) { await _hub.SendTemplateNotificationAsync(templateParams, notificationRequest.Tags, token); } else { var notificationTasks = notificationRequest.Tags .Select((value, index) => (value, index)) .GroupBy(g => g.index / 20, i => i.value) .Select(tags => _hub.SendTemplateNotificationAsync(templateParams, tags, token)); await Task.WhenAll(notificationTasks); } return(true); } catch (Exception e) { _logger.LogError(e, "Unexpected error sending notification"); return(false); } }
async public Task <bool> SendNotification(string message, string[] tags, Dictionary <string, string> payload = null) { var notification = new Dictionary <string, string> { { "message", message } }; var json = payload != null?JsonConvert.SerializeObject(payload) : ""; notification.Add("title", "Game Update"); notification.Add("badge", "0"); notification.Add("payload", ""); var outcome = await _hub.SendTemplateNotificationAsync(notification, tags); return(true); }
private static async void SendTemplateNotificationAsync() { // Define the notification hub. NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>"); // Apple requires the apns-push-type header for all requests var headers = new Dictionary <string, string> { { "apns-push-type", "alert" } }; // Create an array of different areas the average temperature notficiations should go for. var areas = new string[] { "Oslo", "Stockholm", "Copenhagen" }; // Send the notification as a template notification. All template registrations that contain // "messageParam" and the proper tags will receive the notifications. // This includes APNS, GCM/FCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); foreach (var area in areas) { templateParams["messageParam"] = "Area " + area + " Temperature Update!"; await hub.SendTemplateNotificationAsync(templateParams, area); } }
// POST tables/TodoItem public async Task <IHttpActionResult> PostTodoItem(TodoItem item) { TodoItem current = await InsertAsync(item); HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName); Dictionary <string, string> templateParams = new Dictionary <string, string>(); templateParams["messageParam"] = item.Text + " was added to the list"; try { var result = await hub.SendTemplateNotificationAsync(templateParams); config.Services.GetTraceWriter().Info(result.State.ToString()); } catch { } return(CreatedAtRoute("Tables", new { id = current.Id }, current)); }
private static async Task SendTemplateNotificationsAsync() { NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(DispatcherConstants.FullAccessConnectionString, DispatcherConstants.NotificationHubName); Dictionary <string, string> templateParameters = new Dictionary <string, string>(); messageCount++; // Send a template notification to each tag. This will go to any devices that // have subscribed to this tag with a template that includes "messageParam" // as a parameter foreach (var tag in DispatcherConstants.SubscriptionTags) { templateParameters["messageParam"] = $"Notification #{messageCount} to {tag} category subscribers!"; try { await hub.SendTemplateNotificationAsync(templateParameters, tag); Console.WriteLine($"Sent message to {tag} subscribers."); } catch (Exception ex) { Console.WriteLine($"Failed to send template notification: {ex.Message}"); } } Console.WriteLine($"Sent messages to {DispatcherConstants.SubscriptionTags.Length} tags."); WriteSeparator(); }
private static async void SendTemplateNotificationAsync() { // Define the notification hub. NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://kfarubaiotdemo.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=swt17mfcWP9zh8pOwJ5zAzzJTwnNfDRpKG5aDv07SjM=", "kfnotificationhub"); // Sending the notification as a template notification. All template registrations that contain // "messageParam" or "News_<local selected>" and the proper tags will receive the notifications. // This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); // Create an array of breaking news categories. var categories = new string[] { "World", "Politics", "Business", "Technology", "Science", "Sports" }; var locales = new string[] { "English", "French", "Mandarin", "kimforssmac" }; foreach (var category in categories) { templateParams["messageParam"] = "Breaking " + category + " News!"; // Sending localized News for each tag too... foreach (var locale in locales) { string key = "News_" + locale; // Your real localized news content would go here. templateParams[key] = "Breaking " + category + " News in " + locale + "!"; } await hub.SendTemplateNotificationAsync(templateParams, category); } }
private async Task SendNotification(string notificationText, string tag) { var notification = new Dictionary <string, string> { { "message", notificationText } }; await _hubClient.SendTemplateNotificationAsync(notification, tag); }
private async Task SendPushNotificationAsync(Post post) { string senderName = null; string senderImageUrl = null; using (var db = new timelineformsContext()) { var sender = db.Users.Find(post.SenderId); senderName = sender.FullName; senderImageUrl = sender.ImageUrl; } // Sending the message so that all template registrations that contain the following params // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. var templateParams = new Dictionary <string, string> { ["action"] = $"post:{post.Id}", ["title"] = $"New post from {senderName}", ["message"] = post.Text, ["image"] = senderImageUrl }; try { // Sends the push notification. var receivers = $"!{User.GetNotificationTag()}"; var result = await hubClient.SendTemplateNotificationAsync(templateParams, receivers); } catch { } }
protected void btnSendNotifications_Click(object sender, EventArgs e) { // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = "nhcostarica"; string notificationHubConnection = "Endpoint=sb://notificationhcostarica.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=STGsww+qrKoNp53NsCwGGGdbPwJ2DpdCKTVd1uvmOJY="; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Sending the message so that all template registrations that contain "messageParam" // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); templateParams["messageParam"] = txtToSend.Text; try { // Send the push notification and log the results. hub.SendTemplateNotificationAsync(templateParams).Wait(); // Write the success result to the logs. // config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { /* Write the failure result to the logs. * config.Services.GetTraceWriter() * .Error(ex.Message, null, "Push.SendAsync Error"); */ } }
// POST tables/User public async Task <IHttpActionResult> PostUser(User item) { User current = await InsertAsync(item); HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName, true); Dictionary <string, string> templateParams = new Dictionary <string, string>(); templateParams["messageParam"] = item.Username + " was added to the list."; try { // Send the push notification and log the results. var result = await hub.SendTemplateNotificationAsync(templateParams); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } return(CreatedAtRoute("Tables", new { id = current.Id }, current)); }
private async Task SentPushNotificationAsync(ToDoItem item) { HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName); Dictionary <string, string> templateParams = new Dictionary <string, string> { ["messageParam"] = item.TaskName + " was added to the list." }; try { // Send the push notification and log the results. var result = await hub.SendTemplateNotificationAsync(templateParams); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } }
public async Task <NotificationOutcome> PushNotification(PushNotificationRequest pushRequest) { // Sending the message so that all template registrations that contain "messageParam", "silentMessageParam", or "actionParam" // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); if (pushRequest.Silent) { templateParams["silentMessageParam"] = "1"; templateParams["actionParam"] = pushRequest.Action; } else { templateParams["message"] = pushRequest.Text; } try { // Send the push notification and log the results. var result = await _hubClient.SendTemplateNotificationAsync(templateParams, string.Join(" || ", pushRequest.Tags)); return(result); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Send(NotificationRequest request) { if (request.Message is SimpleNotificationMessage simpleMessage) { foreach (var message in simpleMessage.GetPlatformMessages()) { switch (message.Item1) { case "wns": await _hub.SendWindowsNativeNotificationAsync(message.Item2, $"username:{request.Destination}"); break; case "aps": await _hub.SendAppleNativeNotificationAsync(message.Item2, $"username:{request.Destination}"); break; case "fcm": await _hub.SendFcmNativeNotificationAsync(message.Item2, $"username:{request.Destination}"); break;; } } } else if (request.Message is TemplateNotificationMessage templateMessage) { await _hub.SendTemplateNotificationAsync(templateMessage.Parameters, $"username:{request.Destination}"); } return(Ok()); }
public async Task NotifyByTags(string message, List <string> tags, NotificationPayload payload = null, int?badgeCount = null) { var notification = new Dictionary <string, string> { { "message", message } }; if (payload != null) { var json = JsonConvert.SerializeObject(payload); notification.Add("payload", json); } else { notification.Add("payload", ""); } if (badgeCount == null) { badgeCount = 0; } notification.Add("badge", badgeCount.Value.ToString()); try { await _hub.SendTemplateNotificationAsync(notification, tags); } catch (Exception e) { Console.WriteLine(e); } }
private static async void SendTemplateNotificationAsync() { // Define the notification hub. string Hubname = "tripnotification"; string Connectionstring = "Endpoint=sb://moognotificationhub.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=ukXpfw/GWF//fy6plp+yYdkSE+KYMhImcZ5hA0e2jHw="; NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(Connectionstring, Hubname); // Apple requires the apns-push-type header for all requests var headers = new Dictionary <string, string> { { "apns-push-type", "alert" } }; // Create an array of breaking news categories. var categories = new string[] { "World", "Politics", "Business", "Technology", "Science", "Sports" }; // Send the notification as a template notification. All template registrations that contain // "messageParam" and the proper tags will receive the notifications. // This includes APNS, GCM/FCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); foreach (var category in categories) { templateParams["messageParam"] = "Breaking " + category + " News!"; await hub.SendTemplateNotificationAsync(templateParams, category); Console.WriteLine("sent notification of category :{0}", category); } }
public async Task <bool> SendPushNotification(string message) { // Enviamos el mensaje. Esto incluye APNS, GCM, WNS, y MPNS. Dictionary <string, string> templateParams = new Dictionary <string, string>(); templateParams["messageParam"] = message; try { // Enviamos la notificacion y obenemos el resultado var result = await _hub.SendTemplateNotificationAsync(templateParams); // Escribimos el resultado en los logs. _config.Services.GetTraceWriter().Info(result.State.ToString()); return(true); } catch (Exception ex) { // Escribimos el fallo en los logs. _config.Services.GetTraceWriter() .Error(ex.Message, null, "SendPushNotification Error"); return(false); } }
public async Task SendTextNotification(string message, string destinationTag) { var templateValues = new Dictionary <string, string> { { "message", message } }; await hubClient.SendTemplateNotificationAsync(templateValues, $"({destinationTag})&&text"); }
private async Task SendPayloadAsync(string tag, PushType type, object payload) { await _client.SendTemplateNotificationAsync( new Dictionary <string, string> { { "type", ((byte)type).ToString() }, { "payload", JsonConvert.SerializeObject(payload) } }, tag); }
private async void OnSendTemplateNotification(object sender, RoutedEventArgs e) { NotificationHubClient client = NotificationHubClient.CreateClientFromConnectionString(ConnectionString, "uwpsample"); Dictionary <string, string> properties = new Dictionary <string, string>(); properties.Add("title", "Template notification"); properties.Add("message", "This is a template notification"); await client.SendTemplateNotificationAsync(properties); }
private static void SendTemplateToast() { _hub = NotificationHubClient.CreateClientFromConnectionString(_ep, _notHubPath); Dictionary<string, string> temp = new Dictionary<string, string>(); temp.Add("meters", "10"); temp.Add("feet", "33"); _hub.SendTemplateNotificationAsync(temp).Wait(); }
public async Task <NotificationOutcome> SendNotificationAsync(string tag, string messageBody) { NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(_connectionstring, _hubName, true); var notification = new Dictionary <string, string> { { "messageParam", messageBody } }; return(await hub.SendTemplateNotificationAsync(notification, tag)); }
public async Task SendNotification(Dictionary <string, string> templateParams, string tag) { try { var result = await hub.SendTemplateNotificationAsync(templateParams, tag); } catch (Exception ex) { } }
/// <summary> /// Send a template notification (Platform independent) /// </summary> /// <param name="properties">Set of properties</param> public async Task SendTemplateNotificationAsync(Dictionary <string, string> properties) { if (properties == null) { throw new ArgumentException("Properties cannot be Null."); } // Send await _hubClient.SendTemplateNotificationAsync(properties); }
async public Task <bool> SendNotification(string message, string[] tags, Dictionary <string, string> payload = null) { var notification = new Dictionary <string, string> { { "message", message } }; var json = payload != null?JsonConvert.SerializeObject(payload) : ""; notification.Add("title", "Game Update"); notification.Add("badge", "0"); notification.Add("payload", json); var data = new Event("Push notification sent"); data.Add("msg", message).Add("tags", string.Join(", ", tags).Trim()); await EventHubService.Instance.SendEvent(data); var outcome = await _hub.SendTemplateNotificationAsync(notification, tags); return(true); }
// POST tables/NotificationItem public async Task <IHttpActionResult> PostNotificationItem(NotificationItem item) { NotificationItem current = await InsertAsync(item); // Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the Mobile App. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Sending the message so that all template registrations that contain "messageParam" // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); if (item.MessageType.Equals("request")) { templateParams["senderParam"] = item.SenderId; templateParams["messageParam"] = item.SenderId + " wants to know your status."; templateParams["receiveParam"] = item.RespondentId; templateParams["messageType"] = item.MessageType; } else { templateParams["senderParam"] = item.SenderId; templateParams["messageParam"] = " " + item.SenderMessage; templateParams["receiveParam"] = item.RespondentId; templateParams["messageType"] = item.MessageType; } try { // Send the push notification and log the results. var result = await hub.SendTemplateNotificationAsync(templateParams); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } return(CreatedAtRoute("Tables", new { id = current.Id }, current)); }
private async Task SendTemplateNotificationsAsync(string message, string messageTitle, string[] tags) { NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(MobilePushNotificationConfig.FullAccessConnectionString, MobilePushNotificationConfig.NotificationHubName); Dictionary <string, string> templateParameters = new Dictionary <string, string>(); // Send a template notification to each tag. This will go to any devices that // have subscribed to this tag with a template that includes "messageParam" // as a parameter foreach (var tag in tags) { templateParameters["messageParam"] = message; templateParameters["messageTitle"] = messageTitle; await hub.SendTemplateNotificationAsync(templateParameters, tag.ToLowerInvariant()); } }
public async Task <bool> SendTemplateNotification(Dictionary <string, string> notification, IEnumerable <string> tags) { NotificationOutcome outcome = null; try { outcome = await hub.SendTemplateNotificationAsync(notification, tags); } catch (Exception ex) { Trace.TraceError("Error while sending template notifications: " + ex.Message); } return(outcome.Success > 0 && outcome.Failure == 0); }
/// <summary> /// テンプレート登録は使用しない方針 /// </summary> /// <param name="msg"></param> /// <param name="deviceTokenList"></param> private static async void SendTemplateNotificationAsync(string msg, List <string> deviceTokenList) { // Define the notification hub. NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>"); // Send the notification as a template notification. All template registrations that contain // "messageParam" and the proper tags will receive the notifications. // This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); foreach (var deviceToken in deviceTokenList) { templateParams[deviceToken] = msg; await hub.SendTemplateNotificationAsync(templateParams); } }
// POST tables/Item public async Task <IHttpActionResult> PostBoleta(Boletas boleta) { Boletas current = await InsertAsync(boleta); // Adding push notification // Get the settings for the server project. HttpConfiguration config = this.Configuration; MobileAppSettingsDictionary settings = this.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings(); // Get the Notification Hubs credentials for the mobile app. string notificationHubName = settings.NotificationHubName; string notificationHubConnection = settings .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString; // Create a new Notification Hub client. NotificationHubClient hub = NotificationHubClient .CreateClientFromConnectionString(notificationHubConnection, notificationHubName); // Send the message so that all template registrations that contain "messageParam" // receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations. Dictionary <string, string> templateParams = new Dictionary <string, string>(); templateParams["messageParam"] = "Boleta Id:" + boleta.idBoleta + " fue agregada"; try { // Send the push notification and log the results. var result = await hub.SendTemplateNotificationAsync(templateParams); // Write the success result to the logs. config.Services.GetTraceWriter().Info(result.State.ToString()); } catch (System.Exception ex) { // Write the failure result to the logs. config.Services.GetTraceWriter() .Error(ex.Message, null, "Push.SendAsync Error"); } // return(CreatedAtRoute("Tables", new { id = current.Id }, current)); }
public async Task Enviar(Notificacion msj) { var properties = new Dictionary <string, string> { { "titulo", msj.Titulo }, { "contenido", msj.Contenido } }; if (msj.DatosExtra != null) { var datos = JObject.Parse(msj.DatosExtra); foreach (var x in datos) { string name = x.Key; string value = (string)x.Value; properties.Add(name, value); } } await hubClient.SendTemplateNotificationAsync(properties, msj.Suscripcion); }