Exemplo n.º 1
0
        // POST tables/SensorData
        public async Task <IHttpActionResult> PostSensorData(SensorData item)
        {
            SensorData current = await InsertAsync(item);

            // Create a WNS native toast.
            var message = new WindowsPushMessage();

            // Define the XML paylod for a WNS native toast notification
            // that contains the text of the inserted item.
            message.XmlPayload = @"<?xml version=""1.0"" encoding=""utf-8""?>" +
                                 @"<toast><visual><binding template=""ToastText01"">" +
                                 @"<text id=""1"">" + "Temperature: " + item.Temperature + @"</text>" +
                                 @"</binding></visual></toast>";
            try
            {
                NotificationOutcome result = await Services.Push.SendAsync(message);

                Services.Log.Info(result.State.ToString());
            }
            catch (Exception ex)
            {
                Services.Log.Error(ex.Message, null, "Push.SendAsync Error");
            }

            return(CreatedAtRoute("Tables", new { id = current.Id }, current));
        }
Exemplo n.º 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));
            }
        }
Exemplo n.º 3
0
        public IHttpActionResult NotifyHub(PushMessage msg)
        {
            try
            {
                var connStr = "Endpoint=sb://azdevelop.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=XquAb+oTzm4huD0htIMeV+mCG/o8ekm6958RTPvYCpQ=";
                var hubName = "referenceguide";
                hub = NotificationHubClient.CreateClientFromConnectionString(connStr, hubName);
                NotificationOutcome outcome = null;
                if (msg.DeviceType == 1)
                {
                    outcome = SendAPNS(msg);
                }
                else
                {
                    outcome = SendGCM(msg);
                }
                msg.Success = outcome.State == NotificationOutcomeState.Completed ? true : false;
            }
            catch (Exception ex)
            {
                var x = ex.Message;
            }

            return(Ok(msg));
        }
        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,
            });
        }
Exemplo n.º 5
0
        public async Task <bool> SendNotificationAsync(string message, string to_tag)
        {
            string[] userTag = new string[1];
            userTag[0] = to_tag;

            string defaultFullSharedAccessSignature = "Endpoint=sb://hbscr13.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=hS+NQ17Qu8CwNBVxzSWVY3ORJ4nK2lMNTFENbFc5Vck=";
            string hubName = "hbPedidos";

            _hub = NotificationHubClient.CreateClientFromConnectionString(defaultFullSharedAccessSignature, hubName);

            NotificationOutcome outcome = null;

            // Android
            var notif = "{ \"data\" : {\"message\":\"" + message + "\"}}";

            outcome = await _hub.SendGcmNativeNotificationAsync(notif, userTag);

            if (outcome != null)
            {
                if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                      (outcome.State == NotificationOutcomeState.Unknown)))
                {
                    return(true);
                }
            }
            return(false);
        }
        public async Task AddAsync_SendNotification_EnableTestSend_Results_Empty()
        {
            var notification = GetTemplateNotification();

            NotificationOutcome outcome = new NotificationOutcome
            {
                Results = new List <RegistrationResult>()
            };

            // Arrange
            var mockNhClientService = new Mock <INotificationHubClientService>(MockBehavior.Strict);

            mockNhClientService.Setup(x => x.SendNotificationAsync(notification, "foo||bar"))
            .Returns(Task.FromResult(outcome));

            TestTraceWriter trace = new TestTraceWriter(TraceLevel.Info);

            IAsyncCollector <Notification> collector = new NotificationHubAsyncCollector(mockNhClientService.Object, "foo||bar", true, trace);

            // Act
            await collector.AddAsync(notification);

            // Assert
            Assert.Equal(1, trace.Events.Count);
            Assert.True(trace.Events[0].Message.Equals(debugLogNoResults));

            mockNhClientService.VerifyAll();
        }
Exemplo n.º 7
0
        public static async Task <bool> SendNotificationAsync(string message, string idNotificacao, bool broadcast = false)
        {
            string[] userTag = new string[1];

            // Obs importantíssima: O username tá na primeira parte do id da
            // notificação antes do ":"(dois pontos). Para mandar broadcast é só
            //enviar o username em branco
            userTag[0] = string.Empty;


            string defaultFullSharedAccessSignature = util.configTools.getConfig("hubnotificacao");
            string hubName = util.configTools.getConfig("hubname");
            string handle  = idNotificacao;//hubName;

            NotificationHubClient _hub = NotificationHubClient.CreateClientFromConnectionString(defaultFullSharedAccessSignature, hubName);
            //await _hub.DeleteRegistrationAsync(idNotificacao);

            //Excluindo registros
            var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100);

            foreach (RegistrationDescription xregistration in registrations)
            {
                try
                {
                    await _hub.DeleteRegistrationAsync(xregistration);
                }
                catch (Exception ex) { string sm = ex.Message; }
            }


            if (!broadcast)
            {
                string to_tag = idNotificacao.Split(':')[0];
                userTag[0] = "username:"******"{ \"data\" : {\"message\":\"" + message + "\"}}";

            outcome = await _hub.SendGcmNativeNotificationAsync(notif, userTag);

            if (outcome != null)
            {
                if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                      (outcome.State == NotificationOutcomeState.Unknown)))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 8
0
 public async Task SendMessage(UserDevice device, string message)
 {
     try
     {
         NotificationOutcome outcome = await Hub.SendFcmNativeNotificationAsync(message, device.Registration.Keys.FirstOrDefault());
     }
     catch (Exception e)
     {
     }
 }
        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"));
        }
Exemplo n.º 10
0
        public async Task <HttpResponseMessage> Post(HttpRequestMessage req)
        {
            var    hub         = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://popbookings.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=YMcwcPP8fCefQR/5cjope5OMM39gZr9kY5P5aB1VX3U=", "pb-nh-eastus");
            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);

            string[] userTag = new string[2];
            userTag[0] = "username:"******"from:" + data.fromUser;

            var pns      = data.pns;
            var fromUser = data.fromUser;
            var message  = data.message;
            NotificationOutcome outcome = null;
            HttpStatusCode      ret     = HttpStatusCode.InternalServerError;

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

                break;

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

                break;

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

                break;
            }

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

            return(Request.CreateResponse(ret));
        }
Exemplo n.º 11
0
        public List <NotificationResponse> SendNotification(NotificationRequest request)
        {
            List <NotificationResponse> response = new List <NotificationResponse>();

            if (request.Types != null)
            {
                foreach (var type in request.Types)
                {
                    NotificationOutcome send = new NotificationOutcome();

                    string notification =
                        NotificationMessage.SetNotification(type, request.Message, request.WindowsNotificationId);

                    Exception e = null;

                    try
                    {
                        switch (type)
                        {
                        case NotificationType.FCM:
                            send = _hub.SendFcmNativeNotificationAsync(notification).Result;
                            break;

                        case NotificationType.WND:
                            send = _hub.SendWindowsNativeNotificationAsync(notification).Result;
                            break;

                        default:
                            send = _hub.SendFcmNativeNotificationAsync(notification).Result;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        e = ex;

                        continue;
                    }
                    finally
                    {
                        response.Add(new NotificationResponse
                        {
                            Type    = type,
                            Success = (e == null),
                            Error   = e?.Message
                        });
                    }
                }
            }


            return(response);
        }
Exemplo n.º 12
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));
            }
        }
Exemplo n.º 13
0
        async Task <NotificationOutcome> SendNotification(string message, string installationId)
        {
            // Get the settings for the server project.
            HttpConfiguration config = this.Configuration;

#if USE_APP_SETTINGS
            var settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            // Get the Notification Hubs credentials for the Mobile App.
            string notificationHubName       = settings.NotificationHubName;
            string notificationHubConnection = settings.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
#else
            // The name of the Notification Hub from the overview page.
            string notificationHubName = "xamarinpushnotifhub";
            // Use "DefaultFullSharedAccessSignature" from the portal's Access Policies.
            string notificationHubConnection = "Endpoint=sb://xamarinpushnotifhubnamespace.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=hWvLPIb2207cRtNoy/k4ViGkXxy53M9UI7pZCfurR3g=";
#endif

            // Create a new Notification Hub client.
            var hub = NotificationHubClient.CreateClientFromConnectionString(
                notificationHubConnection,
                notificationHubName,
                // Don't use this in RELEASE builds. The number of devices is limited.
                // If TRUE, the send method will return the devices a message was
                // delivered to.
                enableTestSend: true);

            // Sending the message so that all template registrations that contain "messageParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            var templateParams = new Dictionary <string, string>
            {
                ["messageParam"] = message
            };

            // Send the push notification and log the results.

            NotificationOutcome result = null;
            if (string.IsNullOrWhiteSpace(installationId))
            {
                result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
            }
            else
            {
                result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
            }


            // Write the success result to the logs.
            config.Services.GetTraceWriter().Info(result.State.ToString());
            return(result);
        }
Exemplo n.º 14
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);
        }
Exemplo n.º 15
0
        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);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Send notification to Android 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> SendGcmSilentNotificationAsync(string tag, int val)
        {
            try
            {
                NotificationOutcome result = await myClient.SendGcmNativeNotificationAsync("{ \"data\" : {\"content-available\":" + val.ToString() + "}}", tag);

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
                // TODO log error
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Send Trip Start notification to Android 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>
        /// <param name="tripId">Trip ID</param>
        public async Task <bool> SendGcmTripStartNotificationAsync(string tag, string message, string tripId)
        {
            try
            {
                NotificationOutcome result = await myClient.SendGcmNativeNotificationAsync("{ \"data\" : {\"message\":\"" + message + "\",\"tripid\":" + tripId + "}}", tag);

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
                // TODO log error
            }
        }
Exemplo n.º 18
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
            }
        }
        async Task <NotificationOutcome> InternalSendNotificationAsync(string message, string installationId = "")
        {
            var hub = NotificationHubClient.CreateClientFromConnectionString(Constants.FullAccessConnectionString, Constants.NotificationHubName, true);

            //var regs = await hub.GetAllRegistrationsAsync(0);

            var templateParams = new Dictionary <string, string>
            {
                ["messageParam"] = message
            };

            NotificationOutcome result = (string.IsNullOrWhiteSpace(installationId)) ?
                                         await hub.SendTemplateNotificationAsync(templateParams) :
                                         await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}");

            return(result);
        }
Exemplo n.º 20
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> SendIOSSilentNotificationAsync(string tag, int val)
        {
            try
            {
                String message = "Start tracking user location for " + val.ToString() + " seconds";

                NotificationOutcome result = await myClient.SendAppleNativeNotificationAsync("{ \"aps\" : {\"content-available\":" + val.ToString() + "}}", tag);

                return(true);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(false);
                // TODO log error
            }
        }
Exemplo n.º 21
0
        /// TODO: Exercise 12.3: Pushing a message to a Service Bus Notification Hub
        public async Task SendNotification()
        {
            NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("Endpoint=sb://contosoevents.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=j1toC1FXT/kECuAEzaBuKLOzYT9KXsWKmbXPiKWmddo=", "events");

            String message = String.Format("Event: {0} has been updated.", this.Event.Title);

            string toastXml = GetXml();

            toastXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                       "<wp:Notification xmlns:wp=\"WPNotification\">" +
                       "<wp:Toast>" +
                       "<wp:Text1>Hello from a .NET App!</wp:Text1>" +
                       "</wp:Toast> " +
                       "</wp:Notification>";

            NotificationOutcome result = await hub.SendMpnsNativeNotificationAsync(toastXml);
        }
Exemplo n.º 22
0
        async Task <NotificationOutcome> SendNotification(string message, string installationId)
        {
            // Get the settings for the server project.
            //HttpConfiguration config = this.Configuration;

            // The name of the Notification Hub from the overview page.
            string notificationHubName = "VmsPlus";
            // Use "DefaultFullSharedAccessSignature" from the portal's Access Policies.
            string notificationHubConnection = "Endpoint=sb://vmsplus.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=3SWWzpHBge4CMEV/mCxi1g9uJLaWUJm+dXuG8o33G1g=";

            // Create a new Notification Hub client.
            var hub = NotificationHubClient.CreateClientFromConnectionString(
                notificationHubConnection,
                notificationHubName,
                // Don't use this in RELEASE builds. The number of devices is limited.
                // If TRUE, the send method will return the devices a message was
                // delivered to.
                enableTestSend: true);

            // Sending the message so that all template registrations that contain "messageParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            //byte[] bytes = Encoding.Default.GetBytes(message);
            //message = Encoding.UTF8.GetString(bytes);
            var templateParams = new Dictionary <string, string>
            {
                ["messageParam"] = message
            };

            // Send the push notification and log the results.

            NotificationOutcome result = null;

            if (string.IsNullOrWhiteSpace(installationId))
            {
                result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
            }
            else
            {
                result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
            }


            // Write the success result to the logs.
            //config.Services.GetTraceWriter().Info(result.State.ToString());
            return(result);
        }
Exemplo n.º 23
0
        public static async Task <bool> SendPushNotification(string message)
        {
            NotificationOutcome outcome = null;

            var payload = "{ \"data\" : {\"message\":\"" + message + "\"}}";

            outcome = await GetHubClient().SendFcmNativeNotificationAsync(payload);

            if (outcome != null)
            {
                if (!((outcome.State == NotificationOutcomeState.Abandoned) || (outcome.State == NotificationOutcomeState.Unknown)))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 24
0
        public async Task <HttpStatusCode> sendToAll()
        {
            var notif = " { \"notification\":{ \"title\":\"Alarm\", \"body\":\"test message\" }, \"data\":{ \"property1\":\"value1\", \"property2\":42 } }";

            NotificationOutcome outcome = await Hub.SendFcmNativeNotificationAsync(notif);

            HttpStatusCode ret = HttpStatusCode.InternalServerError;

            if (outcome != null)
            {
                if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
                      (outcome.State == NotificationOutcomeState.Unknown)))
                {
                    ret = HttpStatusCode.OK;
                }
            }
            return(ret);
        }
Exemplo n.º 25
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(PushNotificationIntegrationEvent newNotification)
        {
            try
            {
                // For Apple iOS Push Notification; Other platform will be configured after PoC
                NotificationOutcome outcome = null;
                var alert = "{\"aps\":{\"alert\":\"" + newNotification + "\"}}";

                if (newNotification.Tags == null)
                {
                    outcome = await _hubClient.SendAppleNativeNotificationAsync(alert);
                }
                else
                {
                    outcome = await _hubClient.SendAppleNativeNotificationAsync(alert, newNotification.Tags);
                }

                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));
            }

            catch (Exception ex)
            {
                return(new HubResponse <NotificationOutcome>().SetAsFailureResponse().AddErrorMessage(ex.Message));
            }
        }
        public async Task <HubResponse <NotificationOutcome> > SendNotification(Notification newNotification)
        {
            try
            {
                NotificationOutcome outcome = null;
                string jsonPayload          =
                    "{" +
                    getQuotedString("data") + ":" +
                    "{" +
                    getQuotedString("title") + ":" + getQuotedString(newNotification.Title) + "," +
                    getQuotedString("content") + ":" + getQuotedString(newNotification.Content) +
                    "}" +
                    "}";
                if (newNotification.Tags == null)
                {
                    outcome = await _hubClient.SendFcmNativeNotificationAsync(jsonPayload);
                }
                else
                {
                    outcome = await _hubClient.SendFcmNativeNotificationAsync(newNotification.Content, newNotification.Tags);
                }

                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));
            }
        }
        async Task <NotificationOutcome> SendNotification(string message, string installationId)
        {
            // Get the settings for the server project.
            HttpConfiguration config = this.Configuration;
            var 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.
            var hub = NotificationHubClient.CreateClientFromConnectionString(
                notificationHubConnection,
                notificationHubName,
                // Don't use this in RELEASE builds. The number of devices is limited.
                // If TRUE, the send method will return the devices a message was
                // delivered to.
                enableTestSend: true);

            // Sending the message so that all template registrations that contain "messageParam"
            // will receive the notifications. This includes APNS, GCM, WNS, and MPNS template registrations.
            var templateParams = new Dictionary <string, string>
            {
                ["messageParam"] = message
            };

            // Send the push notification and log the results.

            NotificationOutcome result = null;

            if (string.IsNullOrWhiteSpace(installationId))
            {
                result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
            }
            else
            {
                result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
            }


            // Write the success result to the logs.
            config.Services.GetTraceWriter().Info(result.State.ToString());
            return(result);
        }
        public async Task AddAsync_SendNotification_EnableTestSend_Results_NotNull()
        {
            var notification       = GetTemplateNotification();
            RegistrationResult reg = new RegistrationResult
            {
                ApplicationPlatform = "Windows",
                Outcome             = "Successfully sent Push notification",
                PnsHandle           = "Some-GUID",
                RegistrationId      = "Another-GUID"
            };

            var registrationList = new List <RegistrationResult>();

            registrationList.Add(reg);

            NotificationOutcome notificationOutcome = new NotificationOutcome
            {
                Results = registrationList,
            };
            string registrationOutcome = $"NotificationHubs Test Send\r\n" +
                                         $"  TrackingId = {notificationOutcome.TrackingId}\r\n" +
                                         $"  State = {notificationOutcome.State}\r\n" +
                                         $"  Results (Success = {notificationOutcome.Success}, Failure = {notificationOutcome.Failure})\r\n" +
                                         $"    ApplicationPlatform:{reg.ApplicationPlatform}, RegistrationId:{reg.RegistrationId}, Outcome:{reg.Outcome}\r\n";

            // Arrange
            var mockNhClientService = new Mock <INotificationHubClientService>(MockBehavior.Strict);

            mockNhClientService.Setup(x => x.SendNotificationAsync(notification, "foo||bar"))
            .Returns(Task.FromResult(notificationOutcome));

            TestTraceWriter trace = new TestTraceWriter(TraceLevel.Info);

            IAsyncCollector <Notification> collector = new NotificationHubAsyncCollector(mockNhClientService.Object, "foo||bar", true, trace);

            // Act
            await collector.AddAsync(notification);

            // Assert
            Assert.Equal(1, trace.Events.Count);
            Assert.True(trace.Events[0].Message.Equals(registrationOutcome));

            mockNhClientService.VerifyAll();
        }
Exemplo n.º 29
0
        private async Task SendPush(Job job)
        {
            TemplatePushMessage message = new TemplatePushMessage()
            {
                { "message", "New job assigned: " + job.Title },
            };

            try
            {
                this.Services.Log.Info("Sending push to user: "******"Push sent: " + pushResponse);
            }
            catch (Exception ex)
            {
                this.Services.Log.Error("Error sending push: " + ex.Message);
            }
        }
Exemplo n.º 30
0
        private async Task GetPushDetailsAndPrintOutcome(
            string pnsType,
            NotificationHubClient nhClient,
            NotificationOutcome notificationOutcome)
        {
            // The Notification ID is only available for Standard SKUs. For Basic and Free SKUs the API to get notification outcome details can not be called.
            if (string.IsNullOrEmpty(notificationOutcome.NotificationId))
            {
                PrintPushNoOutcome(pnsType);
                return;
            }

            var details = await WaitForThePushStatusAsync(pnsType, nhClient, notificationOutcome);

            NotificationOutcomeCollection collection = null;

            switch (pnsType)
            {
            case "FCM":
            case "FCM Silent":
            case "FCM Tags":
            case "FCM Direct":
                collection = details.FcmOutcomeCounts;
                break;

            case "APNS":
            case "APNS Silent":
            case "APNS Tags":
            case "APNS Direct":
                collection = details.ApnsOutcomeCounts;
                break;

            case "WNS":
                collection = details.WnsOutcomeCounts;
                break;

            default:
                _logger.LogInformation("Invalid Sendtype");
                break;
            }

            PrintPushOutcome(pnsType, details, collection);
        }
 private void WriteNotificationToLog(Notification notification, NotificationOutcome notificationOutcome, string tagExpression, string[] tags)
 {
     if (notification == null)
     {
         return;
     }
     var builder = new StringBuilder();
     builder.AppendFormat(NotificationSentHeader, notificationHubDescription.Path);
     if (notificationOutcome != null)
     {
         builder.AppendLine(string.Format(OutcomeFormat,
                                          notificationOutcome.State,
                                          notificationOutcome.Success,
                                          notificationOutcome.Failure,
                                          notificationOutcome.TrackingId));
         if (!string.IsNullOrWhiteSpace(tagExpression))
         {
             builder.AppendLine(string.Format(TagsExpressionFormat, tagExpression));
         }
         else if (tags != null &&
             tags.Any())
         {
             builder.AppendLine(TagsLogHeader);
             foreach (var tag in tags)
             {
                 builder.AppendLine(string.Format(TagFormat, tag));
             }
         }
         if (notificationOutcome.Results != null &&
             notificationOutcome.Results.Count > 0)
         {
             builder.AppendLine(ResultsHeader);
             foreach (var item in notificationOutcome.Results)
             {
                 builder.AppendLine(string.Format(ResultFormat,
                                                  item.RegistrationId,
                                                  item.PnsHandle,
                                                  item.ApplicationPlatform,
                                                  item.Outcome));
             }
         }
     }
     if (!string.IsNullOrWhiteSpace(notification.Body))
     {
         builder.AppendLine(BodyHeader);
         builder.AppendLine(XmlHelper.Indent(notification.Body));
     }
     if (notification.Headers != null &&
         notification.Headers.Count > 0)
     {
         builder.AppendLine(HeadersHeader);
         foreach (var key in notification.Headers.Keys)
         {
             builder.AppendLine(string.Format(HeaderFormat, key, notification.Headers[key]));
         }
     }
     writeToLog(builder.ToString());
 }