// Handle form in push
        public async Task <ActionResult> HandlePush(string members, string location, string message)
        {
            string tag = "";

            if (!(string.IsNullOrEmpty(members)))
            {
                tag = members.ToLower().Replace(" ", "_");
            }
            else if (!string.IsNullOrEmpty(location))
            {
                tag = location.ToLower().Replace(" ", "_");
            }


            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://anhdemomimins.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=Y463FsBXLAkaTvEhJSMQUDA67zyBXo0TdC5ERhesl0Q=", "fieldengineerdemomimi");
            var alert = "{\"aps\":{\"alert\":\"" + message + "\",\"sound\":\"default\"}}";

            if (string.IsNullOrEmpty(tag))
            {
                //broadcast to all
                await hub.SendAppleNativeNotificationAsync(alert);
            }
            else
            {
                //send to tag
                await hub.SendAppleNativeNotificationAsync(alert, new[] { tag });
            }

            return(RedirectToAction("Index"));
        }
예제 #2
0
        ///
        /// <summary>
        /// Send push notification to specific platform (Android, iOS or Windows)
        /// </summary>
        /// <param name="newNotification"></param>
        /// <returns></returns>
        public async Task <HubResponse <NotificationOutcome> > SendNotification(Notification newNotification)
        {
            try
            {
                NotificationOutcome outcome = null;

                switch (newNotification.Platform)
                {
                case MobilePlatform.wns:
                    if (newNotification.Tags == null)
                    {
                        outcome = await _hubClient.SendWindowsNativeNotificationAsync(newNotification.Content);
                    }
                    else
                    {
                        outcome = await _hubClient.SendWindowsNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                    }
                    break;

                case MobilePlatform.apns:
                    if (newNotification.Tags == null)
                    {
                        outcome = await _hubClient.SendAppleNativeNotificationAsync(newNotification.Content);
                    }
                    else
                    {
                        outcome = await _hubClient.SendAppleNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                    }
                    break;

                    /*case MobilePlatform.gcm:
                     *  if (newNotification.Tags == null)
                     *      outcome = await _hubClient.SendGcmNativeNotificationAsync(newNotification.Content);
                     *  else
                     *      outcome = await _hubClient.SendGcmNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                     *  break;*/
                }

                if (outcome != null)
                {
                    if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                          (outcome.State == NotificationOutcomeState.Unknown)))
                    {
                        return(new HubResponse <NotificationOutcome>());
                    }
                }

                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage("Notification was not sent due to issue. Please send again."));
            }

            catch (MessagingException ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }

            catch (ArgumentException ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }
        }
        Task SendPlatformNotificationsAsync(string androidPayload, string iOSPayload, CancellationToken token)
        {
            var sendTasks = new Task[]
            {
                _hub.SendFcmNativeNotificationAsync(androidPayload, token),
                _hub.SendAppleNativeNotificationAsync(iOSPayload, token)
            };

            return(Task.WhenAll(sendTasks));
        }
예제 #4
0
        public async Task <bool> SendToAll(Notification notification, NotificationContext context)
        {
            var finalResult = true;

            try
            {
                var payload =
                    $@"<toast><visual><binding template=""ToastText01""><text id=""1"">{notification.NotificationType.Name}</text></binding></visual></toast>";
                var result = await _hub.SendFcmNativeNotificationAsync(payload);

                if (result.State == NotificationOutcomeState.Abandoned || result.State == NotificationOutcomeState.Unknown)
                {
                    finalResult = false;
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    $"Error sending Android notification with Error: ${exception.Message}");

                finalResult = false;
            }

            try
            {
                var payload = $"{{\"aps\":{{\"alert\":\": {notification.NotificationType.Name}\"}}}}";
                var result  = await _hub.SendAppleNativeNotificationAsync(payload);

                if (result.State == NotificationOutcomeState.Abandoned || result.State == NotificationOutcomeState.Unknown)
                {
                    finalResult = false;
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    $"Error sending iOS notification with Error: ${exception.Message}");
                finalResult = false;
            }

            var relevantSubscriptions = context.Subscriptions.Where(s => s.MineSiteId == notification.MineSiteId).ToList();
            var webResultTasks        = relevantSubscriptions
                                        .Select(async subscription => await SendToSubscription(notification, subscription));

            var webResults = await Task.WhenAll(webResultTasks);

            if (!webResults.All(webRes => webRes))
            {
                finalResult = false;
            }

            return(finalResult);
        }
예제 #5
0
        /// <summary>
        /// Send push notification to specific platform (Android, iOS or Windows)
        /// </summary>
        /// <param name="newNotification"></param>
        /// <returns></returns>
        public async Task <HubResponse <NotificationOutcome> > SendNotification(Common.Notification.Notification newNotification
                                                                                , IHubContext <WebNotificationHub, ITypedHubClient> _hubSignalRContext)
        {
            string webMessage, devMessage;

            try
            {
                NotificationOutcome outcome = null;

                if (newNotification == null || newNotification?.UserIDs == null || newNotification?.UserIDs?.Count == 0)
                {
                    foreach (Dictionary <string, string> itemData in newNotification.Data)
                    {
                        devMessage = "{ \"aps\":{ \"alert\":\"Mars-Notification\",\"sound\":\"default\",\"badge\":1},\"EventID\":\"" + newNotification.EventId + "\", \"UserID\": \"\",\"Data\":{" + buildNotificationData(itemData) + " } }";

                        //Broadcast Message Dev
                        outcome = await _hubClient.SendAppleNativeNotificationAsync(devMessage);

                        //Broadcast Message Web
                        webMessage = JsonConvert.SerializeObject(new { EventID = newNotification.EventId, UserID = "", Data = itemData });
                        await _hubSignalRContext.Clients.All.BroadcastMessage(webMessage, "");
                    }
                }
                else
                {
                    IDictionary <string, string> objClientTypes = GetClientTypes(newNotification?.UserIDs);
                    if (objClientTypes != null)
                    {
                        foreach (KeyValuePair <string, string> item in objClientTypes)
                        {
                            foreach (Dictionary <string, string> itemData in newNotification.Data)
                            {
                                if (item.Value.ToUpper() == "WEB")
                                {
                                    webMessage = JsonConvert.SerializeObject(new { EventID = newNotification.EventId, UserID = item.Key, Data = itemData });
                                    await _hubSignalRContext.Clients.All.BroadcastMessage(webMessage, item.Key);
                                }
                                else
                                {
                                    devMessage = "{ \"aps\":{ \"alert\":\"Mars-Notification\",\"sound\":\"default\",\"badge\":1},\"EventID\":\"" + newNotification.EventId + "\", \"UserID\": \"" + item.Key + "\",\"Data\":{" + buildNotificationData(itemData) + " } }";
                                    outcome    = await _hubClient.SendAppleNativeNotificationAsync(devMessage, item.Key); //Key is User ID
                                }
                            }
                        }
                    }
                }
                return(new HubResponse <NotificationOutcome>());
            }
            catch (Exception ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }
        }
예제 #6
0
파일: Ntfy.cs 프로젝트: jimliuxyz/UW
        /// <summary>
        /// 發送訊息到指定tag
        /// </summary>
        /// <param name="tag"></param>
        /// <param name="pns"></param>
        /// <param name="message"></param>
        /// <param name="type">自訂動作</param>
        /// <param name="payload">自訂資料</param>
        private async Task sendToTag(string tag, PNS pns, string message, string type = null, object payload = null)
        {
            var notif  = "";
            var custom = new {
                type    = type,
                payload = payload
            };
            var custom_json = "\"custom\" : " + Newtonsoft.Json.JsonConvert.SerializeObject(custom);

            switch (pns)
            {
            case PNS.apns:
                notif = "{ \"aps\" : {\"alert\":\"" + message + "\"}, " + custom_json + "}";
                await hub.SendAppleNativeNotificationAsync(notif, new string[] { tag });

                break;

            case PNS.gcm:
                notif = "{ \"data\" : {\"message\":\"" + message + "\"}, " + custom_json + "}";
                await hub.SendGcmNativeNotificationAsync(notif, new string[] { tag });

                break;

            default:
                break;
            }
        }
예제 #7
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string   requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic  data        = JsonConvert.DeserializeObject(requestBody);
            string   post_author = data?.post.post_author;
            string   post_title  = data?.post.post_title;
            DateTime now         = DateTime.Now;

            string title      = $"{post_author} ha creado un nuevo post";
            string body       = post_title;
            string badgeValue = "1";

            // Define the notification hub.
            NotificationHubClient hub =
                NotificationHubClient.CreateClientFromConnectionString(
                    "Endpoint=sb://folderapp.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=EDydYsB/T3zVlJXKmd4LA2c1jWOX15lhl5eRapWa0Zw=",
                    "FolderApp-Xamarin");

            // Define an iOS alert
            var iOSalert =
                "{\"aps\":{\"alert\":\"" + body + "\", \"badge\":" + badgeValue + ", \"sound\":\"default\"},"
                + "\"inAppMessage\":\"" + body + "\"}";

            hub.SendAppleNativeNotificationAsync(iOSalert).Wait();

            // Define an Anroid alert.

            var androidAlert = "{\"data\":{\"title\": \"" + title + "\",\"body\":\"" + body + "\"}}";

            hub.SendFcmNativeNotificationAsync(androidAlert).Wait();

            return(new HttpResponseMessage(HttpStatusCode.OK));
        }
        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());
        }
예제 #9
0
        private static void SendAppleNotificationAsync(string subject, string content, NotificationHubClient hub)
        {
            //NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(NOTIFICATION_HUB_FULL_ACCESS_CONNECTION_STRING, NOTIFICATION_HUB_NAME);
            var alert = "{\"aps\":{\"alert\":\"" + subject + "\",\"content\":\"" + content + "\",\"badge\":1,\"sound\":\"bingbong.aiff\"}}";

            hub.SendAppleNativeNotificationAsync(alert).Wait(500);
        }
예제 #10
0
        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)
            {
                try
                {
                    var messageAndroid = JsonConvert.SerializeObject(new PayloadAndroid(new Data("Message Title", "Message Body")));
                    await hub.SendFcmNativeNotificationAsync(messageAndroid, tag);

                    var messageiOS = JsonConvert.SerializeObject(new PayloadIOS(new Aps(new Alert("Message Title", "Message Body"))));
                    await hub.SendAppleNativeNotificationAsync(messageiOS, 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();
        }
예제 #11
0
        public async Task <NotificationOutcomeState> SendAppleNotification(string title, string subTitle, string userId, string eventCode, string type, bool enableCustomSounds, int count, string color, NotificationHubClient hubClient = null)
        {
            try
            {
                if (hubClient == null)
                {
                    hubClient = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureNotificationHub_PushUrl);
                }

                string appleNotification = null;

                if (type == ((int)PushSoundTypes.CallEmergency).ToString() ||
                    type == ((int)PushSoundTypes.CallHigh).ToString() ||
                    type == ((int)PushSoundTypes.CallMedium).ToString() ||
                    type == ((int)PushSoundTypes.CallLow).ToString())
                {
                    appleNotification = "{\"aps\" : { \"alert\" : \"" + subTitle + "\", \"content-available\": 1, \"category\" : \"CALLS\", \"badge\" : " + count + ", \"sound\" : \"" + GetSoundFileNameFromType(Platforms.iPhone, type, enableCustomSounds) + "\" }, \"eventCode\": \"" + eventCode + "\" }";
                }
                else
                {
                    appleNotification = "{\"aps\" : { \"alert\" : \"" + subTitle + "\", \"badge\" : " + count + ", \"sound\" : \"" + GetSoundFileNameFromType(Platforms.iPhone, type, enableCustomSounds) + "\" }, \"eventCode\": \"" + eventCode + "\" }";
                }


                var appleOutcome = await hubClient.SendAppleNativeNotificationAsync(appleNotification, string.Format("userId:{0}", userId));

                return(appleOutcome.State);
            }
            catch (Exception ex)
            {
                string exception = ex.ToString();
            }

            return(NotificationOutcomeState.Unknown);
        }
예제 #12
0
        public async Task <IHttpActionResult> Send([FromBody] Message message)
        {
            try
            {
                var registrations = await hub.GetRegistrationsByTagAsync(message.RecipientId, 100);

                NotificationOutcome outcome;

                if (registrations.Any(r => r is GcmRegistrationDescription))
                {
                    var notif = "{ \"data\" : {\"subject\":\"Message from " + message.From + "\", \"message\":\"" + message.Body + "\"}}";
                    outcome = await hub.SendGcmNativeNotificationAsync(notif, message.RecipientId);

                    return(Ok(outcome));
                }

                if (registrations.Any(r => r is AppleRegistrationDescription))
                {
                    var notif = "{ \"aps\" : {\"alert\":\"" + message.From + ":" + message.Body + "\", \"subject\":\"Message from " + message.From + "\", \"message\":\"" + message.Body + "\"}}";
                    outcome = await hub.SendAppleNativeNotificationAsync(notif, message.RecipientId);

                    return(Ok(outcome));
                }

                return(NotFound());
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        public async Task <W8PushTestEntity> PostW8PushTestEntity(W8PushTestEntity item)
        {
            var    settings                  = this.Configuration.GetServiceSettingsProvider().GetServiceSettings();
            string notificationHubName       = settings.NotificationHubName;
            string notificationHubConnection = settings.Connections[ServiceSettingsKeys.NotificationHubConnectionString].ConnectionString;
            NotificationHubClient nhClient   = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);

            NotificationOutcome pushResponse = null;

            switch (item.NHNotificationType)
            {
            case "wns":
                pushResponse = await nhClient.SendWindowsNativeNotificationAsync(item.Payload);

                break;

            case "apns":
                pushResponse = await nhClient.SendAppleNativeNotificationAsync(item.Payload);

                break;

            default:
                throw new NotImplementedException("Push is not supported on this platform");
            }
            this.Configuration.Services.GetTraceWriter().Info("Push sent: " + pushResponse, this.Request);
            return(new W8PushTestEntity()
            {
                Id = "1",
                PushResponse = pushResponse.State.ToString() + "-" + pushResponse.TrackingId,
            });
        }
예제 #14
0
        public async Task CarEntryNotificationHub(string 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);

            // iOS payload
            var appleNotificationPayload = "{\"aps\":{\"alert\":\"" + notification + "\"}}";

            try
            {
                // Send the push notification and log the results.
                var result = await hub.SendAppleNativeNotificationAsync(appleNotificationPayload);

                // 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);
            return;
        }
예제 #15
0
        /// <summary>
        ///     Sends a <see cref="ScheduledNotification"/> to a specified user.
        /// </summary>
        /// <param name="pushDetails">Details on how to reach the user.</param>
        /// <param name="notification">The notification object.</param>
        public async Task SendNotificationAsync(UserPushNotificationDetails pushDetails, SwabbrNotification notification)
        {
            if (pushDetails is null)
            {
                throw new ArgumentNullException(nameof(pushDetails));
            }

            switch (pushDetails.PushNotificationPlatform)
            {
            case PushNotificationPlatform.APNS:
                var objApns  = NotificationJsonExtractor.Extract(PushNotificationPlatform.APNS, notification);
                var jsonApns = JsonConvert.SerializeObject(objApns, jsonSettings);
                await _hubClient.SendAppleNativeNotificationAsync(jsonApns, pushDetails.UserId.ToString());

                return;

            case PushNotificationPlatform.FCM:
                var objFcm  = NotificationJsonExtractor.Extract(PushNotificationPlatform.FCM, notification);
                var jsonFcm = JsonConvert.SerializeObject(objFcm, jsonSettings);
                await _hubClient.SendFcmNativeNotificationAsync(jsonFcm, pushDetails.UserId.ToString());

                return;

            default:
                throw new InvalidOperationException(nameof(pushDetails.PushNotificationPlatform));
            }
        }
예제 #16
0
        /// <summary>
        /// Send notification to IOS devices
        /// </summary>
        /// <param name="tag"> If tag is present the notification will go only to the device(s) that have this tag in the Notification hub registration</param>
        /// <param name="message">Notification Message</param>
        public async Task <bool> SendIOSNotificationAsync(string tag, string message)
        {
            try
            {
                String apsMsg = "{ \"aps\" : {\"alert\":\"" + message + "\"}}";
                NotificationOutcome result = await myClient.SendAppleNativeNotificationAsync(apsMsg, tag);

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
                // TODO log error
            }
        }
예제 #17
0
        public async void sendToUsersbyID(List <device> devices, RaisedNotification incoming, Instrument source)
        {
            FCMnotificationTemplate androidnoty = new FCMnotificationTemplate();

            androidnoty.data.message = "{ notiType:" + incoming.notificationType + ",body:" + incoming.Name + ",UUID:" + source.UUID.ToString() + ",name:" + source.DisplayName + ",}"; //title + " ;; " +
            //androidnoty.data2.title = title;
            string        androidString  = JsonConvert.SerializeObject(androidnoty);                                                                                                    //"{\"data\":{\"message\":\"{ \"title\":" + title + ",\"body\":" + body + "}\"}}";
            List <string> androidDevices = new List <string>();
            List <string> iOSDevices     = new List <string>();

            foreach (device dev in devices)
            {
                if (dev.Platform == "Android")
                {
                    androidDevices.Add("device:" + dev.notificationHubRegistration);
                }
                else if (dev.Platform == "iOS")
                {
                    iOSDevices.Add("device:" + dev.notificationHubRegistration);
                }
            }
            if (androidDevices.Count > 0)  ///////////////MAX  20 tags
            // var outcomeFcmByTag = await notificationhub.SendFcmNativeNotificationAsync(androidString, androidDevices);//JsonConvert.SerializeObject(androidnoty)
            // var fcmTagOutcomeDetails = await WaitForThePushStatusAsync("FCM Tags", notificationhub, outcomeFcmByTag);
            //PrintPushOutcome("FCM Tags", fcmTagOutcomeDetails, fcmTagOutcomeDetails.FcmOutcomeCounts);
            {
            }
            if (iOSDevices.Count > 0)
            {
                var outcomeApnsByTag = await notificationhub.SendAppleNativeNotificationAsync(AppleSampleNotificationContent, iOSDevices);

                // var apnsTagOutcomeDetails = await WaitForThePushStatusAsync("APNS Tags", notificationhub, outcomeApnsByTag);
                //PrintPushOutcome("APNS Tags", apnsTagOutcomeDetails, apnsTagOutcomeDetails.ApnsOutcomeCounts);
            }
        }
        public static async Task SendBroadcastNotification(string text)
        {
            var jsonGcm = string.Format("{{\"data\":{{\"message\":\"{0}\"}}}}", text);
            await notitifcationHubClient.SendGcmNativeNotificationAsync(jsonGcm);

            var jsonApns = string.Format("{{\"aps\":{{\"alert\":\" {0}\"}}}}", text);
            await notitifcationHubClient.SendAppleNativeNotificationAsync(jsonApns);
        }
예제 #19
0
        public IHttpActionResult SendMessage(Poco.Message message)
        {
            if (string.IsNullOrWhiteSpace(message.Sender))
            {
                return(BadRequest("The sender is not valid!"));
            }

            if (string.IsNullOrWhiteSpace(message.Content))
            {
                return(BadRequest("The password is not valid!"));
            }

            try
            {
                using (var ctx = new ChattyDbContext())
                {
                    string email = (this.User as ClaimsPrincipal).FindFirst(ClaimTypes.Email).Value;
                    User   user  = ctx.Users.Single(x => x.Email == email);
                    user.LastActiveDate = DateTime.Now.ToUniversalTime();

                    Message m = new Message {
                        Content = message.Content, Sender = message.Sender, SendDate = DateTime.Now.ToUniversalTime()
                    };
                    ctx.Messages.Add(m);

                    ctx.SaveChanges();

                    _nhclient.SendGcmNativeNotificationAsync(
                        Newtonsoft.Json.JsonConvert.SerializeObject(Push.Android.Make(
                                                                        "New messages",
                                                                        "You have new unread messages!",
                                                                        1,
                                                                        m.MessageId.ToString()
                                                                        )), String.Concat("!", user.Email));

                    _nhclient.SendAppleNativeNotificationAsync(
                        Newtonsoft.Json.JsonConvert.SerializeObject(Push.iOS.Make(
                                                                        "New messages",
                                                                        "You have new unread messages!",
                                                                        1,
                                                                        m.MessageId.ToString()
                                                                        )), String.Concat("!", user.Email));

                    return(Ok(Dto.Wrap(new Poco.Message
                    {
                        MessageId = m.MessageId,
                        Content = m.Content,
                        Sender = m.Sender,
                        SendDate = m.SendDate
                    })));
                }
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex));
            }
        }
        public async Task <IActionResult> SendNotification([FromBody] NotificationCreationModel notificationReq)
        {
            try
            {
                var jsonNotification = JsonConvert.SerializeObject(notificationReq);

                NotificationOutcome response = (notificationReq.Tags != null && notificationReq.Tags.Count > 0) ?
                                               await _hubClient.SendGcmNativeNotificationAsync("{\"data\":{\"message\":" + jsonNotification + "}}", notificationReq.Tags) :
                                               await _hubClient.SendGcmNativeNotificationAsync("{\"data\":{\"message\":" + jsonNotification + "}}");

                NotificationOutcome responseApple = (notificationReq.Tags != null && notificationReq.Tags.Count > 0) ?
                                                    await _hubClient.SendAppleNativeNotificationAsync("{\"aps\":{\"alert\":\"" + notificationReq.Title + ": " + notificationReq.NotificationText + "\"}}", notificationReq.Tags) :
                                                    await _hubClient.SendAppleNativeNotificationAsync("{\"aps\":{\"alert\":\"" + notificationReq.Title + ": " + notificationReq.NotificationText + "\"}}");

                var outcomes = new List <NotificationOutcome>()
                {
                    response, responseApple
                };
                NotificationModel model = null;

                if (response.Results != null && responseApple.Results != null)
                {
                    notificationReq.Status = 1;
                    model = await _notificationDataManager.CreateNotification(notificationReq);

                    return(Ok(model));
                }
                else
                {
                    notificationReq.Status = 0;
                    model = await _notificationDataManager.CreateNotification(notificationReq);

                    return(Ok(model));
                }
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status502BadGateway, e.Message));
            }
        }
        private static async void SendNotificationAsync(string message, string userid)
        {
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(
                NotificationHubConnectionString,
                NotificationHubName);

            //content-available = 1 makes sure ReceivedRemoteNotification in
            //AppDelegate.cs get executed when the app is closed
            var alert = "{\"aps\":{\"alert\":\"" + message + "\", \"content-available\" : \"1\"}}";

            //Would need to handle Windows & Android separately
            await hub.SendAppleNativeNotificationAsync(alert, userid);
        }
예제 #22
0
 public async Task sendIOSNotification(string message, IEnumerable <string> tags)
 {
     try
     {
         // Define an iOS alert.
         var alert = "{\"aps\":{\"alert\":\"" + message + "\"}}";
         await hub.SendAppleNativeNotificationAsync(alert, tags);
     }
     catch (Exception ex)
     {
         Trace.TraceError("Error while sending iOS alert: " + ex.Message);
     }
 }
예제 #23
0
        private NotificationOutcome SendAPNS(PushMessage msg)
        {
            var obj = new APNS.RootObject();

            obj.Content.Alert.Add("title", "Special Alert");
            obj.Content.Alert.Add("body", "There is a sale at Walmart");
            obj.Content.Badge            = 1;
            obj.Content.ContentAvailable = 1;

            var json = JsonConvert.SerializeObject(obj);

            return(hub.SendAppleNativeNotificationAsync(json, msg.Tag).Result);
        }
        public async System.Threading.Tasks.Task <HttpResponseMessage> SendAppleNativeNotification([Metadata("Connection String")] string connectionString, [Metadata("Hub Name")] string hubName, [Metadata("JSON Payload")] string message, [Metadata("Toast Tags")] string tags = null)
        {
            try
            {
                NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);

                NotificationOutcome result;
                if (!string.IsNullOrEmpty(tags))
                {
                    result = await hub.SendAppleNativeNotificationAsync(message, tags);
                }
                else
                {
                    result = await hub.SendAppleNativeNotificationAsync(message);
                }

                return(Request.CreateResponse <NotificationOutcome>(HttpStatusCode.OK, result));
            }
            catch (ConfigurationErrorsException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.BareMessage));
            }
        }
예제 #25
0
        public async Task <bool> SendNotificationAsync(string platform, string message, string to_tag)
        {
            var user = "******";

            string[] userTag = new string[1];
            userTag[0] = to_tag;

            NotificationOutcome outcome = null;

            switch (platform.ToLower())
            {
            case "wns":
                // Windows 8.1 / Windows Phone 8.1
                var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
                            "From " + user + ": " + message + "</text></binding></visual></toast>";
                outcome = await _hub.SendWindowsNativeNotificationAsync(toast, userTag);

                // Windows 10 specific Action Center support
                toast = @"<toast><visual><binding template=""ToastGeneric""><text id=""1"">" +
                        "From " + user + ": " + message + "</text></binding></visual></toast>";
                outcome = await _hub.SendWindowsNativeNotificationAsync(toast, userTag);

                break;

            case "apns":
                // iOS
                var alert = "{\"aps\":{\"alert\":\"" + "From " + user + ": " + message + "\"}}";
                outcome = await _hub.SendAppleNativeNotificationAsync(alert, userTag);

                break;

            case "gcm":
                // Android
                var notif = "{ \"data\" : {\"message\":\"" + "From " + user + ": " + message + "\"}}";
                outcome = await _hub.SendGcmNativeNotificationAsync(notif, userTag);

                break;
            }

            if (outcome != null)
            {
                if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                      (outcome.State == NotificationOutcomeState.Unknown)))
                {
                    return(true);
                }
            }
            return(false);
        }
예제 #26
0
        private static async Task PushMessagesToHub()
        {
            while (true)
            {
                while (msgSendQueue.Count > 0)
                {
                    try
                    {
                        PushMessage msgObject = null;
                        lock (syncObject)
                        {
                            msgObject = msgSendQueue.Dequeue();
                        }
                        if (msgObject == null)
                        {
                            continue;
                        }

                        string message = msgObject.ToString();
                        switch (msgObject.Type)
                        {
                        case PushMessage.PushType.Android:
                            await pushHub.SendGcmNativeNotificationAsync(message);

                            break;

                        case PushMessage.PushType.Apple:
                            await pushHub.SendAppleNativeNotificationAsync(message);

                            break;

                        case PushMessage.PushType.Windows:

                            await pushHub.SendWindowsNativeNotificationAsync(message);

                            break;

                        case PushMessage.PushType.WindowsPhone:
                            await pushHub.SendWindowsNativeNotificationAsync(message);

                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
예제 #27
0
        public async void SendNotificationAsync(string title, string dsc)
        {
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(defaultFullSharedAccessSignatureSASConnectionString, notificationHubName);
            string message            = "{\"title\":\"" + title + "\",\"description\":\"" + dsc + "\"}";

            await hub.SendBaiduNativeNotificationAsync(message);

            string appleMsg = "{\"aps\":{\"alert\":\"" + dsc + "\"}}";

            await hub.SendAppleNativeNotificationAsync(appleMsg);

            //string appleMsg = "";

            //await hub.SendWindowsNativeNotificationAsync();
        }
        /// <summary>
        /// Basic implementation that sends a notification to Windows Store, Android and iOS app clients.
        /// </summary>
        /// <param name="notificationText">The notification text.</param>
        /// <param name="tag">The tag.</param>
        /// <returns>Task.</returns>
        private async Task SendNotificationAsync(string notificationText, string tag)
        {
            try
            {
                // Create notifications for both Windows Store and iOS platforms.

                XNamespace wp  = "WPNotification";
                XDocument  doc = new XDocument(new XDeclaration("1.0", "utf-8", null),
                                               new XElement(wp + "Notification", new XAttribute(XNamespace.Xmlns + "wp", "WPNotification"),
                                                            new XElement(wp + "Toast",
                                                                         new XElement(wp + "Text1",
                                                                                      "Notification Hubs Sample"),
                                                                         new XElement(wp + "Text2", notificationText))));

                var toastMpns = string.Concat(doc.Declaration, doc.ToString(SaveOptions.DisableFormatting));

                var toast = new XElement("toast",
                                         new XElement("visual",
                                                      new XElement("binding",
                                                                   new XAttribute("template", "ToastText01"),
                                                                   new XElement("text",
                                                                                new XAttribute("id", "1"),
                                                                                notificationText)))).ToString(SaveOptions.DisableFormatting);
                var alert = new JObject(
                    new JProperty("aps", new JObject(new JProperty("alert", notificationText))),
                    new JProperty("inAppMessage", notificationText))
                            .ToString(Newtonsoft.Json.Formatting.None);

                var payload = new JObject(
                    new JProperty("data", new JObject(new JProperty("message", notificationText))))
                              .ToString(Newtonsoft.Json.Formatting.None);

                // Send a notification to the logged-in user on both platforms.

                var googleResult = await _notificationHubClient.SendGcmNativeNotificationAsync(payload, tag);

                var windowsResult = await _notificationHubClient.SendWindowsNativeNotificationAsync(toast, tag);

                var mpsnResult = await _notificationHubClient.SendMpnsNativeNotificationAsync(toastMpns, tag);

                var appleResult = await _notificationHubClient.SendAppleNativeNotificationAsync(alert, tag);
            }
            catch (ArgumentException ex)
            {
                // This is expected when an APNS registration doesn't exist.
                Debug.WriteLine(ex.Message);
            }
        }
예제 #29
0
        public async Task <ApiResult> Sent(SentPushDto sentPushDto)
        {
            var userId = User.Identity.GetUserId();

            string[] userTag = new string[2];
            userTag[0] = "username:"******"from:" + userId;

            Microsoft.ServiceBus.Notifications.NotificationOutcome outcome = null;
            HttpStatusCode ret = HttpStatusCode.InternalServerError;

            switch (sentPushDto.Pns.ToLower())
            {
            case "wns":
                // Windows 8.1 / Windows Phone 8.1
                var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
                            "From " + userId + ": " + sentPushDto.Message + "</text></binding></visual></toast>";
                outcome = await _hub.SendWindowsNativeNotificationAsync(toast);

                break;

            case "apns":
                // iOS
                var alert = "{\"aps\":{\"alert\":\"" + "From " + userId + ": " + sentPushDto.Message + "\"}}";
                outcome = await _hub.SendAppleNativeNotificationAsync(alert, userTag);

                break;

            case "gcm":
                // Android
                var notif = "{ \"data\" : {\"message\":\"" + "From " + userId + ": " + sentPushDto.Message + "\"}}";
                outcome = await _hub.SendGcmNativeNotificationAsync(notif, userTag);

                break;
            }

            if (outcome != null)
            {
                if (!((outcome.State == Microsoft.ServiceBus.Notifications.NotificationOutcomeState.Abandoned) ||
                      (outcome.State == Microsoft.ServiceBus.Notifications.NotificationOutcomeState.Unknown)))
                {
                    ret = HttpStatusCode.OK;
                }
            }

            return(SuccessApiResult(ret));
        }
예제 #30
0
        public async Task <List <NotificationOutcome> > Send(SendPayload payload, List <Platform> pns)
        {
            string tagExpression = "";

            if (payload.Tags != null && payload.Tags.Count > 0)
            {
                foreach (var tag in payload.Tags)
                {
                    tagExpression += tag;
                    tagExpression += "||";
                }

                tagExpression = tagExpression.Substring(0, tagExpression.Length - 2);
            }
            else if (!string.IsNullOrEmpty(payload.TagExpression))
            {
                tagExpression = payload.TagExpression;
            }

            if (!tagExpression.Contains("UserId") && !string.IsNullOrEmpty(payload.UserId))
            {
                if (!string.IsNullOrEmpty(tagExpression))
                {
                    tagExpression += "||";
                }
                tagExpression += $"UserId:{payload.UserId}";
            }

            var outcomes = new List <NotificationOutcome>();

            if (pns.Contains(Platform.iOS))
            {
                var pushMsg = "{\"aps\":{\"alert\":\"" + payload.Message + "\", \"sound\":\"default\"}}";
                var outcome = await _hub.SendAppleNativeNotificationAsync(pushMsg, tagExpression);

                outcomes.Add(outcome);
            }
            if (pns.Contains(Platform.Android))
            {
                var pushMsg = "{\"notification\": {\"body\": \"" + payload.Message + "\", \"sound\" :\"default\" }}";
                var outcome = await _hub.SendGcmNativeNotificationAsync(pushMsg, tagExpression);

                outcomes.Add(outcome);
            }

            return(outcomes);
        }