public async System.Threading.Tasks.Task <HttpResponseMessage> SendWindowsNativeRawNotification([Metadata("Connection String")] string connectionString, [Metadata("Hub Name")] string hubName, [Metadata("Toast RAW")] string message, [Metadata("Toast Tags")] string tags = null) { try { NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName); Notification notification = new WindowsNotification(message); notification.Headers.Add("X-WNS-Type", "wns/raw"); NotificationOutcome result; if (!string.IsNullOrEmpty(tags)) { result = await hub.SendNotificationAsync(notification, tags); } else { result = await hub.SendNotificationAsync(notification); } return(Request.CreateResponse <NotificationOutcome>(HttpStatusCode.OK, result)); } catch (ConfigurationErrorsException ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.BareMessage)); } }
/// <summary> /// Sends a toast to Windows over the WNS using the Azure notification hub. /// </summary> public static async Task SendWindowsNotificationAsync(Device device, string text) { string payload = "<?xml version=\"1.0\" encoding=\"utf-8\"?><toast>" + "<visual><binding template=\"ToastText01\"><text id=\"1\">" + text + "</text></binding></visual></toast>"; await HubClient.SendNotificationAsync(new WindowsNotification(payload), new[] { device.Tag }); }
public async Task FlushAsync(CancellationToken cancellationToken = default) { foreach (var item in notificationsPool) { if (item.Tags.Any()) { await client.SendNotificationAsync(item.Notification, item.Tags, cancellationToken); } else { await client.SendNotificationAsync(item.Notification, cancellationToken); } } notificationsPool.Clear(); }
/// <summary> /// 新しく通知を送信します /// </summary> public async Task <IHttpActionResult> Post(SendFormModel data) { // 送信されたデータが正しいか検証する if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var notifications = new List <Notification>(); // 送信するペイロードを作成 if (data.Windows > 0) { notifications.Add(Payloads.Windows.Create(data.Windows, data.Message)); } if (data.WindowsPhone > 0) { notifications.Add(Payloads.WindowsPhone.Create(data.WindowsPhone, data.Message)); } if (data.Apple > 0) { notifications.Add(Payloads.Apple.Create(data.Apple, data.Message)); } if (data.Android > 0) { notifications.Add(Payloads.Android.Create(data.Android, data.Message)); } // 送信先が 1 つもない場合にはエラー if (notifications.Count == 0) { return(BadRequest("Required Platform select.")); } // 通知ハブへ通知リクエストを非同期で送信 var tasks = notifications.Select(p => _client.SendNotificationAsync(p, data.TagExpression)); // 全ての通知リクエストの完了を待機する var results = await Task.WhenAll(tasks); // 送信結果を DB に保存 var sendLog = new SendLog { Message = data.Message, TagExpression = data.TagExpression, Success = results.Sum(p => p.Success), Failure = results.Sum(p => p.Failure), CreatedOn = DateTimeOffset.UtcNow }; _context.SendLogs.Add(sendLog); await _context.SaveChangesAsync(); return(Ok()); }
private async Task SendNotificationAsync_SendAdmNativeNotification_GetSuccessfulResultBack() { LoadMockData(); var notification = new AdmNotification("{\"data\":{\"key1\":\"value1\"}}"); var notificationResult = await _hubClient.SendNotificationAsync(notification, "someRandomTag1 && someRandomTag2"); Assert.Equal(NotificationOutcomeState.Enqueued, notificationResult.State); RecordTestResults(); }
private static async void gSendNotificationAsync(string tag) { string conf = ConfigurationManager.AppSettings["Microsoft.Azure.NotificationHubs.ConnectionString"]; NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://hmihub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=3kr9bLYgGwFWAUPn6boBYw8IRiYoAkPoPbPRA849o7A=", "emeahminofificationhub"); var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from a .NET App!</text></binding></visual></toast>"; //await hub.SendWindowsNativeNotificationAsync(toast,"myTag"); GcmNotification gcm = new GcmNotification("{\"data\":{\"message\":\"Hej Robin\"}}"); gcm.Headers.Add("tag", tag); await hub.SendNotificationAsync(gcm, tag); //await hub.SendGcmNativeNotificationAsync(", tag); }
private async Task NotifyAboutNewData(string user) { // 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); string userTag = "_UserId:" + user; try { //// 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"] = user + " has added an item to the list."; // // Send the push notification and log the results. // var result1 = await hub.SendTemplateNotificationAsync(templateParams); // Send the push notification and log the results. var result = await hub.SendNotificationAsync(new WindowsNotification("update", new Dictionary <string, string> { { "X-WNS-Type", "wns/raw" } }), userTag); // { "Content-Type", "application/octet-stream"}, // 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"); } }
private async Task sendNotification(string content) { if (hub == null) { hub = NotificationHubClient.CreateClientFromConnectionString(connectionStr, hubPath); } //var toast = @"<toast launch=""MainPage.xaml?param=neworder""><visual><binding template=""ToastText01""><text id=""1"">" + msg + @"</text></binding></visual></toast>"; if (rawCheck.IsChecked == true) { Notification notification = new WindowsNotification(content); notification.Headers.Add("X-WNS-Type", "wns/raw"); await hub.SendNotificationAsync(notification); } else { await hub.SendWindowsNativeNotificationAsync(content); } }
static async Task TrySendAppleSilentNotification(NotificationHubClient client, ILogger log) { try { log.LogInformation("Sending Silent Apple Push Notifications"); var jsonPayload = JsonConvert.SerializeObject(new ApplePushNotification()); var notification = new AppleNotification(jsonPayload, new Dictionary <string, string> { { "apns-push-type", "background" }, { "apns-priority", "5" } }); var appleNotificationResult = await client.SendNotificationAsync(notification).ConfigureAwait(false); log.LogInformation("Apple Notifications Sent"); } catch (Exception e) { log.LogInformation($"Apple Notification Failed\n{e}"); } }
public async Task SendNotificationTrapDisarmed(string email, string msg, bool owner, int points, string trapNameKey, double latitude, double longitude, string otherUserName, string otherUserImage) { try { var date = DateUtils.DateToString(DateTime.Now); var androidPayload = "{ \"data\" : {\"message\":\"" + msg + "\", \"owner\":\"" + (owner ? "1" : "0") + "\", \"points\":\"" + points + "\", \"show\":\"1\", \"trap\":\"" + trapNameKey + "\", \"lat\":\"" + latitude + "\", \"lng\":\"" + longitude + "\", \"date\":\"" + date + "\", \"userName\":\"" + otherUserName + "\", \"img\":\"" + otherUserImage + "\"}}"; var windowsPayload = "{\"message\":\"" + msg + "\", \"owner\":" + (owner ? "1" : "0") + ", \"points\":" + points + ", \"show\":1, \"trap\":\"" + trapNameKey + "\", \"lat\":" + latitude.ToString(CultureInfo.InvariantCulture) + ", \"lng\":" + longitude.ToString(CultureInfo.InvariantCulture) + ", \"date\":\"" + date + "\", \"userName\":\"" + otherUserName + "\", \"img\":\"" + otherUserImage + "\"}"; var notificationOutcomeAndroid = await _hubClient.SendGcmNativeNotificationAsync(androidPayload, email); WindowsNotification notificationWindows = new WindowsNotification(windowsPayload); notificationWindows.Headers.Add("X-NotificationClass", "3"); notificationWindows.Headers.Add("X-WNS-Type", "wns/raw"); var notificationOutcomeWindows = await _hubClient.SendNotificationAsync(notificationWindows, email); } catch (Exception exception) { ElmahUtils.LogToElmah(exception); } }
private async Task CleanupInstallations() { var emptyNotif = new FcmNotification("{\"data\":{\"message\":\"ola\"}}"); await _hub.SendNotificationAsync(emptyNotif, "default"); var allRegistrations = await _hub.GetAllRegistrationsAsync(0); foreach (var registration in allRegistrations) { var installationId = string.Empty; var tags = registration.Tags; foreach (var tag in tags) { if (tag.Contains("InstallationId:")) { installationId = tag.Substring(tag.IndexOf('{') + 1, 32); } } if (installationId == String.Empty) { return; } else { Trace.TraceError(installationId); } var receivedInstallation = await _hub.GetInstallationAsync(installationId); if (receivedInstallation.PushChannelExpired == true) { await _hub.DeleteInstallationAsync(receivedInstallation.InstallationId); } } }
public async Task <HttpResponseMessage> Send(ChatMessage message) { // Do verification that both users can send messages to each other // For example, they are friends // Then prepare the toast notification payload string toastPayload = "<toast> " + " <visual>" + " <binding template=\"ToastText02\">" + " <text id=\"1\">{0}</text>" + " <text id=\"2\">{1}</text>" + " </binding>" + " </visual>" + "</toast>"; toastPayload = string.Format(toastPayload, message.FromUsername, message.MessageText); // Send a Windows 8 toast notification to the "tag" await hub.SendWindowsNativeNotificationAsync(toastPayload, message.ToUsername); // Send a raw XML notification to update the UI as well in realtime, if the app is opened // Serialize the chat message into XML XmlSerializer xmlSerializer = new XmlSerializer(typeof(ChatMessage)); StringWriter serializedStringWriter = new StringWriter(); xmlSerializer.Serialize(serializedStringWriter, message); // Send the notification var rawChatNotification = new WindowsNotification(serializedStringWriter.ToString(), message.ToUsername); rawChatNotification.Headers.Add("X-WNS-Type", "wns/raw"); rawChatNotification.ContentType = "application/octet-stream"; await hub.SendNotificationAsync(rawChatNotification); return(Request.CreateResponse(HttpStatusCode.OK)); }
public async Task SendAsync(TrackingUpdate trackingUpdate) { FcmNotification notification = new FcmNotification(JsonConvert.SerializeObject(trackingUpdate)); await _hub.SendNotificationAsync(notification, new List <string>() { trackingUpdate.trackingNumber }); }
public Task <NotificationOutcome> SendNotificationAsync(Notification notification, string tagExpression) { return(_notificationHubClient.SendNotificationAsync(notification, tagExpression)); }
public async Task <IHttpActionResult> TriggerCheck([FromUri] int start = 0) { var sw = Stopwatch.StartNew(); int registrationCount = 0; const string toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\"><wp:Toast><wp:Text1>{0}</wp:Text1><wp:Text2>{1}</wp:Text2><wp:Param>{2}</wp:Param></wp:Toast></wp:Notification>"; IList <NotificationOutcome> result = new List <NotificationOutcome>(); IList <MpnsNotification> notifications = new List <MpnsNotification>(); var registrations = (await _notificationClient.GetAllRegistrationsAsync(Int32.MaxValue)).Where(x => x.Tags != null).Skip(start); var preferences = _mobileClient.GetTable <PlainNumberInfo>(); if (start == 0) { alreadyRetrieved.Clear(); } foreach (var user in registrations) { notifications.Clear(); foreach (var number in user.Tags) { try { bool dirty = false; var data = number.Split('_'); if (data.Any(x => string.IsNullOrEmpty(x))) { await _notificationClient.DeleteRegistrationAsync(user); //Tanto non saprei cosa cazzo farci. continue; } CreditInfo content = null; if (!alreadyRetrieved.Any(x => x.Username == data[0] && x.Type == data[data.Length - 1] && x.Password == string.Join("_", data.Skip(1).Take(data.Length - 2)))) { content = await _retrievers.First(x => x.Type == data[data.Length - 1]).Get(data[0], string.Join("_", data.Skip(1).Take(data.Length - 2)), data[data.Length - 1], Guid.Empty); //this.GetData(null, new Q_X { q = data[0], x = data[1], t = data[2] }); alreadyRetrieved.Add(content); } else { content = alreadyRetrieved.First(x => x.Username == data[0] && x.Type == data[2] && x.Password == data[1]); dirty = true; } foreach (var accountNumber in content.NumberInfos) { IEnumerable <PlainNumberInfo> userPreference = await preferences.Where(x => x.Number == accountNumber.Number).ToEnumerableAsync(); if (userPreference.Count() == 0) { await preferences.InsertAsync(new PlainNumberInfo { Number = accountNumber.Number, FriendlyName = accountNumber.Number, Gigabytes = accountNumber.Gigabytes, Minutes = accountNumber.Minutes, SMS = accountNumber.SMS, Credit = accountNumber.Credit, Brush = "#000000" }); } else { var dataPreference = userPreference.First(); accountNumber.Brush = dataPreference.Brush; if (string.IsNullOrEmpty(dataPreference.Brush)) { accountNumber.Brush = "#000000"; //Nero } accountNumber.FriendlyName = dataPreference.FriendlyName; if (dataPreference.NotifyEnabled) { if (accountNumber.SMS < dataPreference.SMSLimit && dataPreference.smsShowed == false) { dirty = true; dataPreference.smsShowed = true; notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite SMS", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number))))); } else if (accountNumber.SMS >= dataPreference.SMSLimit) { dataPreference.smsShowed = false; } if (accountNumber.Minutes < dataPreference.MinutesLimit && dataPreference.minShowed == false) { dirty = true; dataPreference.minShowed = true; notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite minuti", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number))))); } else if (accountNumber.Minutes >= dataPreference.MinutesLimit) { dataPreference.minShowed = false; } if (accountNumber.Gigabytes < dataPreference.GigabytesLimit && dataPreference.gigaShowed == false) { dirty = true; dataPreference.gigaShowed = true; notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite traffico", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number))))); } else if (accountNumber.Gigabytes >= dataPreference.GigabytesLimit) { dataPreference.gigaShowed = false; } if (accountNumber.Credit < dataPreference.CreditLimit && dataPreference.clShowed == false) { dirty = true; dataPreference.clShowed = true; notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite credito", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number))))); } else if (accountNumber.Credit >= dataPreference.CreditLimit) { dataPreference.clShowed = false; } accountNumber.CreditLimit = dataPreference.CreditLimit; accountNumber.SMSLimit = dataPreference.SMSLimit; accountNumber.GigabytesLimit = dataPreference.GigabytesLimit; accountNumber.MinutesLimit = dataPreference.MinutesLimit; } if (dataPreference.Credit != accountNumber.Credit || dataPreference.SMS != accountNumber.SMS || dataPreference.Gigabytes != accountNumber.Gigabytes || dataPreference.Minutes != accountNumber.Minutes) { dataPreference.Credit = accountNumber.Credit; dataPreference.SMS = accountNumber.SMS; dataPreference.Gigabytes = accountNumber.Gigabytes; dataPreference.Minutes = accountNumber.Minutes; dirty = true; } if (dirty) { dataPreference.LastUpdate = DateTime.Now; await preferences.UpdateAsync(dataPreference); } } if (dirty) { var thread = new Thread(new ThreadStart(() => { XamlRendering.ConvertToJpg(accountNumber); })); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); var notificationPayload = string.Format(PushTemplates.NotificationTemplate, string.Format("/DataPage.xaml?number={0}", accountNumber.Number), string.Format("http://wauth.apphb.com/Tiles/{0}_159.jpg", accountNumber.Number), string.Format("http://wauth.apphb.com/Tiles/{0}_336.jpg", accountNumber.Number), string.Format("http://wauth.apphb.com/Tiles/{0}_691.jpg", accountNumber.Number)); var notification = new MpnsNotification(notificationPayload, new Dictionary <string, string> { { "X-WindowsPhone-Target", "token" }, { "X-NotificationClass", "1" } }); notifications.Add(notification); } } } catch (WrongLoginDataException) { notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", "Dati di login errati.", string.Empty))); _notificationClient.DeleteRegistrationAsync(user).Wait(); //Addio. Rientra nell'app e inserisci i dati giusti. } catch (Exception) { continue; } var tasks = notifications.Select(x => _notificationClient.SendNotificationAsync(x, user.Tags)); foreach (var item in tasks) { result.Add(await item); } } registrationCount++; if (100 - sw.Elapsed.TotalSeconds <= 5) { break; } } return(Ok(new NotificationProcessInfo { Registrations = registrationCount, Notifications = result.Count })); }
private async void SendFeedNotification <TEntity>( string feed, TEntity entity, int[] entityKeys, UpdateOperations operations) { var entityType = entity.GetType(); string baseTypeName = entityType.BaseType.Name; string operationString = string.Empty; switch (operations) { case UpdateOperations.Change: operationString = "updated"; break; case UpdateOperations.Add: operationString = "added"; break; case UpdateOperations.Delete: operationString = "deleted"; break; } string keysAsString = string.Empty; foreach (int key in entityKeys) { keysAsString += string.Format("{0},", key); } keysAsString = keysAsString.TrimEnd(','); var entityAsString = string.Format("{0}({1})", baseTypeName, keysAsString); var message = string.Format("The entity '{0}' was {2} in the '{1}' feed.", entityAsString, feed, operationString); // Define the parameters for the notification templates. var parameters = new Dictionary <string, string>(); parameters.Add("feed", feed); parameters.Add("operation", operationString); parameters.Add("entity", entityAsString); parameters.Add("message", message); // only used for iOS clients. // Send a cross-plaform notification by using templates, // including toasts to Windows Store apps. await hubClient.SendTemplateNotificationAsync(parameters, feed); // Create and send a raw notification to auto-update // any Windows Store or Windows Phone apps. var payload = await JsonConvert.SerializeObjectAsync(parameters); try { // Create the WNS with the header for a raw notification. WindowsNotification wns = new WindowsNotification(payload, new Dictionary <string, string>() { { "X-WNS-Type", "wns/raw" } }, feed); wns.ContentType = "application/octet-stream"; var result = await hubClient.SendNotificationAsync(wns); // Create the MPNS with the header for a raw notification. MpnsNotification mpns = new MpnsNotification(payload, new Dictionary <string, string>() { { "X-NotificationClass", "3" } }, feed); mpns.ContentType = "text/xml"; await hubClient.SendNotificationAsync(mpns); } catch (ArgumentException ex) { // Send methods return an error response when the notification hub hasn't yet // been configured for a particular client platform. } }
private static async void SendNotificationAsync() { //var hub = new NotificationHub("NotificationhuBCesar", ConnectionStringCesar); NotificationHubClient hubClient = NotificationHubClient.CreateClientFromConnectionString(ConnectionStringCesar, "NotificationhuBCesar", true); string[] userTag = new string[2]; userTag[0] = "username: Test"; userTag[1] = "from: user"; var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">From any .NET App!</text></binding></visual></toast>"; var rowPayload = "Notification at " + DateTime.Now.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("it-IT")); var toasts = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" + "From Test: Message" + "</text></binding></visual></toast>"; try { //var outcome = hubClient.SendWindowsNativeNotificationAsync(toasts, userTag); var payLoad = @"From any .NET App!"; var notif = new WindowsNotification(payLoad); notif.ContentType = "application/octet-stream"; notif.Headers.Add("X-WNS-Type", "wns/raw"); notif.Headers.Add("ServiceBusNotification-Format", "windows"); //notif.Headers.Add("Authorization", "wTai8dxwIiYMt+FhtoTNegYqlfFreGWMFNSykjfDhZs="); //notif.Headers.Add("Host", "cloud.notify.windows.com"); notif.Body = "hi from .net"; var ct = new CancellationToken(); hubClient.SendNotificationAsync(notif, "@1234", ct).Wait(); } catch (Exception e) { var s = ""; } // #region case 1: broadcasted // /* // //the payload can be whatever: the Azure Notification Hub pass through everything to WNS and possible errore could be returned froew that is not well formed. // await hubClient.SendWindowsNativeNotificationAsync(toast); // */ // #endregion case 1: broadcasted // #region case 2: client subscribed by SubscribeToCategories // /* */ // //There is not the pain for a developer to mantain the registry of tags // //If we want a toast notification // // await hubClient.SendWindowsNativeNotificationAsync(toast, "Torino"); // hubClient.SendWindowsNativeNotificationAsync(toast, "Torino").Wait(); //notity to clients subcribed to "World" tag // // //or hubClient.SendWindowsNativeNotificationAsync(toast, "Torino &amp;&amp; !Politics").Wait(); //notify to clients subcribed to "World" tag but not subscribed to the Politics tag too. In expression like this (that can use also parenthesis) it can be used at maximun 6 tags in the expression // //If we want to have a row notification that can be handled by code in the running client app // Notification notification = new WindowsNotification(rowPayload); // notification.Headers = new Dictionary<string, string> { //// {"Content-Type", "application/octet-stream")}, //{"X-WNS-TTL","300"}, // e.g. 300 seconds=> 5 minutes - Specifies the TTL (expiration time) for a notification. //{"X-WNS-Type", "wns/raw" }, //{"ServiceBusNotification-Format", "windows"} //}; // await hubClient.SendNotificationAsync(notification, "deskhelp"); // /* */ // #endregion case 2: client subscribed by SubscribeToCategories // #region case 3: client SubscribeToCategoriesWithCustomTemplate // /* // //the template and internalization is own by the client that registes to have notifications // //template back to the mobile app: it is the client that knows the format he will receive // //you can put any property and payload you whant; you can personalize the notification, depending to the registration // //we do not use anymore the var toast but a dictionary: the server code is agnostic of the type of client (IOS, Android, Windows) that has to define a similar template related to News_locale // var notification = new Dictionary<string, string>() { // {"News_English", "World news in English"}, // {"News_Italian", "Notizie dal mondo in italiano"} // }; // //send then a template notification not a Windows one // await hubClient.SendTemplateNotificationAsync(notification, "World"); // */ // #endregion case 3: client SubscribeToCategoriesWithCustomTemplate }