public async System.Threading.Tasks.Task <HttpResponseMessage> SendWindowsNativeRawNotification([Metadata("Connection String")] string connectionString, [Metadata("Hub Name")] string hubName, [Metadata("Toast RAW")] string message, [Metadata("Toast Tags")] string tags = null)
        {
            try
            {
                NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);

                Notification notification = new WindowsNotification(message);
                notification.Headers.Add("X-WNS-Type", "wns/raw");

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

                return(Request.CreateResponse <NotificationOutcome>(HttpStatusCode.OK, result));
            }
            catch (ConfigurationErrorsException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.BareMessage));
            }
        }
Пример #2
0
        static string GetMediumTile(WindowsNotification notif)
        {
            bool   hasImage;
            bool   hasTitle;
            int    numLines;
            string content = GetNotifContent(notif, out hasImage, out hasTitle, out numLines);

            string nameTemplate = MEDIUM_TILE_NAME + "{0}Text0{1}";

            int template = 0;

            if (numLines == 1)
            {
                template = hasTitle ? 2 : 4;
            }
            else if (numLines == 2 || numLines == 3)
            {
                template = 3;
            }
            else
            {
                return("");
            }

            string name = string.Format(nameTemplate, hasImage ? "PeekImageAnd" : "", template);

            if (!hasTitle && numLines == 0 && hasImage)
            {
                name = MEDIUM_TILE_NAME + "Image";
            }

            return(string.Format(BINDING_TEMPLATE, name, content));
        }
Пример #3
0
        static string GetNotifContent(WindowsNotification notif, out bool hasImage, out bool hasTitle, out int numlines)
        {
            hasImage = false;
            numlines = 1;
            hasTitle = false;

            string imageContent = string.IsNullOrEmpty(notif.ImageUri) ? "" : string.Format(IMAGE_TEMPLATE, notif.ImageUri);

            hasImage = !string.IsNullOrEmpty(imageContent);

            string textContent = "";
            int    currentLine = 1;

            hasTitle = false;
            if (!string.IsNullOrEmpty(notif.Title))
            {
                textContent = string.Format(TEXT_TEMPLATE, currentLine++, notif.Title);
                hasTitle    = true;
            }

            string[] lines = notif.Message.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            numlines = lines.Length;

            foreach (string line in lines)
            {
                textContent += string.Format(TEXT_TEMPLATE, currentLine++, line);
            }

            return(imageContent + textContent);
        }
Пример #4
0
        internal static bool Send(string secret, string sid, string uri, string action, string text, NotificationParameters props, out string log)
        {
            WindowsNotification notif = new WindowsNotification {
                Action = action, Message = text, Parameters = props
            };

            string xml = GetMessage(notif);

            log = "";
            string notificationType = "wns/toast";
            string contentType      = "text/xml";
            string tag = props.ValueOf("tag");

            if (action == "toast" || String.IsNullOrEmpty(action))
            {
                notificationType = "wns/toast";
                contentType      = "text/xml";
            }
            else if (action == "badge")
            {
                notificationType = "wns/badge";
            }
            else if (action == "tile")
            {
                notificationType = "wns/tile";
            }
            else if (action == "raw")
            {
                notificationType = "wns/raw";
                contentType      = "application/octet-stream";
            }
            return(new Win8Notifications().SendToWns(secret, sid, uri, xml, notificationType, contentType, tag, retries, ref log));
        }
Пример #5
0
        public static void GetHeaders(WindowsNotification notif, out string notificationType, out string contentType, out string tag)
        {
            notificationType = "wns/toast";
            contentType      = "text/xml";
            tag = "";

            if (!string.IsNullOrEmpty(notif.Badge))
            {
                notificationType = "wns/badge";
            }

            if (string.IsNullOrEmpty(notif.Title) && string.IsNullOrEmpty(notif.Message) && !string.IsNullOrEmpty(notif.Action))
            {
                notificationType = "wns/raw";
                contentType      = "application/octet-stream";
            }

            if (string.IsNullOrEmpty(notif.Action) && notif.Parameters.Count == 1 && notif.Parameters.Names[0] == "tile")
            {
                notificationType = "wns/tile";
            }

            if (currentInstance == null)
            {
                currentInstance = new Win8Notifications();
            }
        }
Пример #6
0
 public static void Outputs(
     [NotificationHub] out Notification notification,
     [NotificationHub(TagExpression = "tag")] out Notification notificationToTag,
     [NotificationHub] out WindowsNotification windowsNotification,
     [NotificationHub(Platform = NotificationPlatform.Wns)] out string windowsToastNotificationAsString,
     [NotificationHub] out TemplateNotification templateNotification,
     [NotificationHub] out string templateProperties,
     [NotificationHub] out Notification[] notificationsArray,
     [NotificationHub] out IDictionary <string, string> templatePropertiesDictionary,
     [NotificationHub] ICollector <Notification> collector,
     [NotificationHub] ICollector <string> collectorString,
     TraceWriter trace)
 {
     notification        = GetTemplateNotification("Hi");
     notificationToTag   = GetTemplateNotification("Hi tag");
     windowsNotification = new WindowsNotification(WindowsToastPayload);
     windowsToastNotificationAsString = WindowsToastPayload;
     templateNotification             = GetTemplateNotification("Hello");
     templateProperties           = MessagePropertiesJSON;
     templatePropertiesDictionary = GetTemplateProperties("Hello");
     notificationsArray           = new TemplateNotification[]
     {
         GetTemplateNotification("Message1"),
         GetTemplateNotification("Message2")
     };
     collector.Add(GetTemplateNotification("Hi"));
     collectorString.Add(MessagePropertiesJSON);
     trace.Warning("Outputs");
 }
Пример #7
0
        // NotificationHub binding out Notification type
        // This binding broadcasts native windows push notification to all the registered windows clients
        // when method successfully exits.
        public static void SendWindowsNotification_Out_Notification(
            [TimerTrigger("*/30 * * * * *")] TimerInfo timerInfo,
            [NotificationHub] out Notification notification)
        {
            string toastPayload = "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">Test message</text></binding></visual></toast>";

            notification = new WindowsNotification(toastPayload);
        }
Пример #8
0
        public void Write(string text)
        {
            StringBuilder content = new StringBuilder();

            content.Append(text);

            WindowsNotification.Show(content);
        }
Пример #9
0
        static string GetTileTemplate(WindowsNotification notif)
        {
            string medium = GetMediumTile(notif);
            string wide   = GetWideTile(notif);
            string large  = GetLargeTile(notif);

            return(string.Format("<tile><visual version=\"2\">{0}{1}{2}</visual></tile>", medium, wide, large));
        }
        private static RemoteNotificationResult FromWindowsNotification(WindowsNotification notification)
        {
            RemoteNotificationResult result = new RemoteNotificationResult();

            result.DeviceType  = Notifications.WPHONE;
            result.DeviceToken = notification.ChannelUri;
            return(result);
        }
Пример #11
0
        static string GetRawAction(WindowsNotification notif)
        {
            JObject js = new JObject();

            js.Put("action", notif.Action);
            js.Put("executionTime", notif.ExecutionTime);
            js.Put("params", notif.Parameters.ToJObject());

            return(js.ToString());
        }
Пример #12
0
        private async Task SendNotificationAsync_SendWindowsNativeNotification_GetSuccessfulResultBack()
        {
            LoadMockData();
            var notification = new WindowsNotification("<toast><visual><binding template=\"ToastText01\"><text id=\"1\">bodyText</text></binding>  </visual></toast>");

            var notificationResult = await _hubClient.SendNotificationAsync(notification, "someRandomTag1 && someRandomTag2");

            Assert.Equal(NotificationOutcomeState.Enqueued, notificationResult.State);
            RecordTestResults();
        }
Пример #13
0
        public async Task <HttpResponseMessage> Post(string pns, [FromBody] string message, string to_tag)
        {
            var user = User.Identity.Name;

            string[] userTag = new string[2];
            userTag[0] = to_tag;
            userTag[1] = "from:" + user;

            Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
            HttpStatusCode ret = HttpStatusCode.InternalServerError;

            switch (pns.ToLower())
            {
            case "wns":
                // Windows 8.1 / Windows Phone 8.1 / Windows 10
                var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
                            "From " + user + ": " + message + "</text></binding></visual></toast>";
                outcome = await Notifications.Instance.Hub.SendWindowsNativeNotificationAsync(toast, userTag[0]);

                break;

            case "wns/raw":
                Notification notification = new WindowsNotification(message);
                notification.Headers.Add("X-WNS-Type", "wns/raw");
                await Notifications.Instance.Hub2.SendNotificationAsync(notification, userTag[0]);

                break;

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

                break;

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

                break;
            }

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

            return(Request.CreateResponse(ret));
        }
Пример #14
0
        static string GetWideTile(WindowsNotification notif)
        {
            bool   hasImage;
            bool   hasTitle;
            int    numLines;
            string content = GetNotifContent(notif, out hasImage, out hasTitle, out numLines);

            string nameTemplate = WIDE_TILE_NAME + "{0}0{1}";
            string extra        = "Text";

            int template = 0;

            if (numLines == 0 && hasTitle)
            {
                template = 3;
                if (hasImage)
                {
                    extra = "PeekImage";
                }
            }
            else if (numLines == 1)
            {
                template = hasTitle ? 9 : 4;
                if (hasImage)
                {
                    template = 1;
                    extra    = hasTitle ? "PeekImage" : "PeekImageAndText";
                }
            }
            else if (numLines == 2 || numLines == 3 || numLines == 4)
            {
                template = hasTitle ? 1 : 5;
                if (hasImage)
                {
                    template = 2;
                    extra    = hasTitle ? "PeekImage" : "PeekImageAndText";
                }
            }
            else
            {
                return("");
            }

            string name = string.Format(nameTemplate, extra, template);

            if (!hasTitle && numLines == 0 && hasImage)
            {
                name = WIDE_TILE_NAME + "Image";
            }

            return(string.Format(BINDING_TEMPLATE, name, content));
        }
        public async Task SendNotificationAsync(string topic, MessageMemento message)
        {
            NotificationHubClient hub = NotificationHubClient
                .CreateClientFromConnectionString(
                    _connectionString, "occdist");

            var json = JsonConvert.SerializeObject(message);
            var notification = new WindowsNotification(json,
                new Dictionary<string, string> {
				{"X-WNS-Type", "wns/raw"}
			});
            await hub.SendNotificationAsync(notification, topic);
        }
Пример #16
0
        public IHttpActionResult PostMessage(MessageItem messageItem)
        {
            if (NSBQ.NSBQClient != null)
            {
                try
                {
                    BrokeredMessage sendMessage = new BrokeredMessage(messageItem);
                    if (messageItem.TargetGroup != null && messageItem.TargetGroup != string.Empty)
                    {
                        sendMessage.Properties.Add("Tags", messageItem.TargetGroup);
                    }
                    else
                    {
                        sendMessage.Properties.Add("Tags", "BROADCAST");
                    }

                    NSBQ.NSBQClient.Send(sendMessage);
                    AppLogging.Instance.Info("Message sent to Service Bus, " + messageItem.MessageItemId);
                }
                catch (Exception ex)
                {
                    AppLogging.Instance.Error("Error: Connecting to ServiceBus ", ex);
                    return InternalServerError(ex);
                }
            }
            if (NSBQ.NNHClient != null)
            {
                try
                {
                    Notification notification = new WindowsNotification(messageItem.ToString());
                    notification.Headers.Add("X-WNS-Type", "wns/raw");

                    if (messageItem.TargetGroup != null && messageItem.TargetGroup != string.Empty)
                    {
                        messageItem.TargetGroup.Replace(",", " || ");
                    }

                    NSBQ.NNHClient.SendNotificationAsync(notification);

                    AppLogging.Instance.Info("Message sent to NotificationHub, " + messageItem.MessageItemId);
                }
                catch (Exception ex)
                {
                    AppLogging.Instance.Error("Error: Connecting to ServiceBus ", ex);
                    return InternalServerError(ex);
                }
            }
            return Ok();
        }
Пример #17
0
        private static string GetLargeTile(WindowsNotification notif)
        {
            bool   hasImage;
            bool   hasTitle;
            int    numLines;
            string content = GetNotifContent(notif, out hasImage, out hasTitle, out numLines);

            string nameTemplate = LARGE_TILE_NAME + "{0}0{1}";
            string extra        = "Text";

            int template = 0;

            if (numLines == 0 && hasTitle & hasImage)
            {
                template = 1;
                extra    = "ImageAndTextOverlay";
            }
            else if (numLines == 1)
            {
                template = hasTitle ? 1 : 3;
                if (hasImage)
                {
                    template = hasTitle ? 2 : 1;
                    extra    = "ImageAndTextOverlay";
                }
            }
            else if (numLines == 2 || numLines == 3 || numLines == 4)
            {
                template = hasTitle ? 1 : 3;
                if (hasImage)
                {
                    template = hasTitle? 3 : 2;
                    extra    = hasTitle ? "ImageAndTextOverlay" : "ImageAndText";
                }
            }
            else
            {
                return("");
            }

            string name = string.Format(nameTemplate, extra, template);

            if (!hasTitle && numLines == 0 && hasImage)
            {
                name = LARGE_TILE_NAME + "Image";
            }

            return(string.Format(BINDING_TEMPLATE, name, content));
        }
Пример #18
0
        private NotificationMessage CreateNotificationMessage()
        {
            var windowsNotification = new WindowsNotification
            {
                Title = "Notification",
                Text  = "Sent",
            };

            var message = new NotificationMessage
            {
                TurnOn = true,
                WindowsNotification = windowsNotification,
            };

            return(message);
        }
        /// <summary>
        /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param>
        /// <returns>The resulting <see cref="Notification"/>.</returns>
        protected virtual Notification CreateNotification(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification        notification = null;
            ApplePushMessage    apnsPush;
            WindowsPushMessage  wnsPush;
            MpnsPushMessage     mpnsPush;
            TemplatePushMessage templatePush;

            if ((wnsPush = message as WindowsPushMessage) != null)
            {
                notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers);
            }
            else if ((mpnsPush = message as MpnsPushMessage) != null)
            {
                notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers);
            }
            else if ((apnsPush = message as ApplePushMessage) != null)
            {
                DateTime?expiration = null;
                if (apnsPush.Expiration.HasValue)
                {
                    expiration = apnsPush.Expiration.Value.DateTime;
                }
                notification = new AppleNotification(message.ToString(), expiration);
            }
            else if (message is GooglePushMessage)
            {
                notification = new GcmNotification(message.ToString());
            }
            else if ((templatePush = message as TemplatePushMessage) != null)
            {
                notification = new TemplateNotification(templatePush);
            }
            else
            {
                throw new InvalidOperationException(GetUnknownPayloadError(message));
            }

            return(notification);
        }
Пример #20
0
        public static string GetMessage(WindowsNotification notif)
        {
            if (!string.IsNullOrEmpty(notif.Badge))
            {
                return(GetBadgeTemplate(notif));
            }

            if (string.IsNullOrEmpty(notif.Title) && string.IsNullOrEmpty(notif.Message) && !string.IsNullOrEmpty(notif.Action))
            {
                return(GetRawAction(notif));
            }

            if (string.IsNullOrEmpty(notif.Action) && notif.Parameters.Count == 1 && notif.Parameters.Names[0] == "tile")
            {
                return(GetTileTemplate(notif));
            }

            return(GetToastTemplate(notif));
        }
Пример #21
0
        static string GetToastTemplate(WindowsNotification notif)
        {
            bool   hasImage;
            bool   hasTitle;
            int    numLines;
            string templateContent = GetNotifContent(notif, out hasImage, out hasTitle, out numLines);

            int template = 0;

            if (numLines == 1)
            {
                template = !hasTitle ? 1 : 2;
            }
            else if (numLines == 2 || numLines == 3)
            {
                template = 4;
            }
            else
            {
                throw new Exception("Not supported");
            }

            string templateName = string.Format("Toast{0}Text0{1}", hasImage ? "ImageAnd" : "", template);

            string sound = "<audio silent=\"true\"/>";

            if (!string.IsNullOrEmpty(notif.Sound))
            {
                sound = notif.Sound.ToLower() == "default" ? "" : string.Format(AUDIO_TEMPLATE, notif.Sound);
            }

            string launchTemplate = " launch=\"{0}\"";
            string launch         = "";

            if (!string.IsNullOrEmpty(notif.Action))
            {
                launch = string.Format(launchTemplate, HttpUtility.HtmlEncode(GetRawAction(notif)));
            }

            string binding = string.Format(BINDING_TEMPLATE, templateName, templateContent);

            return(string.Format("<toast{0}><visual>{1}</visual>{2}</toast>", launch, binding, sound));
        }
Пример #22
0
        private async Task sendNotification(string content)
        {
            if (hub == null)
                hub = NotificationHubClient.CreateClientFromConnectionString(connectionStr, hubPath);

            //var toast = @"<toast launch=""MainPage.xaml?param=neworder""><visual><binding template=""ToastText01""><text id=""1"">" + msg + @"</text></binding></visual></toast>";

            if (rawCheck.IsChecked == true)
            {
                Notification notification = new WindowsNotification(content);
                notification.Headers.Add("X-WNS-Type", "wns/raw");
                await hub.SendNotificationAsync(notification);
            }
            else
            {
                await hub.SendWindowsNativeNotificationAsync(content);
            }

            
        }
Пример #23
0
        private async Task sendNotification(string content)
        {
            if (hub == null)
            {
                hub = NotificationHubClient.CreateClientFromConnectionString(connectionStr, hubPath);
            }

            //var toast = @"<toast launch=""MainPage.xaml?param=neworder""><visual><binding template=""ToastText01""><text id=""1"">" + msg + @"</text></binding></visual></toast>";

            if (rawCheck.IsChecked == true)
            {
                Notification notification = new WindowsNotification(content);
                notification.Headers.Add("X-WNS-Type", "wns/raw");
                await hub.SendNotificationAsync(notification);
            }
            else
            {
                await hub.SendWindowsNativeNotificationAsync(content);
            }
        }
        /// <summary>
        /// Windows IoT Core用Push送信
        /// </summary>
        /// <param name="msg">装置間IFのjson文字列</param>
        /// <param name="deviceTokenList">デバイストークン</param>
        /// <returns></returns>
        public async Task SendNotificationWindowsAsync(string msg, List <string> deviceTokenList)
        {
            try
            {
#if DIRECT
                // Azure Notification HubsへのPush要求
                //var notification = new WindowsNotification(msg);
                //notification.ContentType = "application/octet-stream";
                //notification.Headers["Content-Type"] = "application/octet-stream";
                //notification.Headers["X-WNS-Type"] = "wns/raw";

                // DEBUG 1 (バッジの例)これだけなら動く
                //var notification = new WindowsNotification("<badge value=\"attention\"/>");

                // DEBUG 2 (トーストの例)これだけなら動く
                var xmlString =
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<toast><visual><binding template = \"ToastText01\">" +
                    "<text id = \"1\">" + msg + "</text>" +
                    "</binding></visual></toast>";
                var notification = new WindowsNotification(xmlString);

                await SendNotificationAsync(notification, deviceTokenList, connectionString, hubName);
#else
                // Azure Function AppへのPush要求
                using (var client = new HttpClient())
                {
                    var content             = new StringContent(msg);
                    var httpResponseMessage = await client.PostAsync(FunctionUrl, content);

                    System.Diagnostics.Debug.WriteLine($"WNS-RAW FunctionApp STATUS={httpResponseMessage.StatusCode}");
                }
#endif
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #25
0
        internal static Notification BuildNotificationFromString(string notificationAsString, NotificationPlatform platform)
        {
            Notification notification = null;

            if (platform == 0)
            {
                JObject jobj = JObject.Parse(notificationAsString);
                Dictionary <string, string> templateProperties = jobj.ToObject <Dictionary <string, string> >();
                notification = new TemplateNotification(templateProperties);
            }
            else
            {
                switch (platform)
                {
                case NotificationPlatform.Wns:
                    notification = new WindowsNotification(notificationAsString);
                    break;

                case NotificationPlatform.Apns:
                    notification = new AppleNotification(notificationAsString);
                    break;

                case NotificationPlatform.Gcm:
                    notification = new GcmNotification(notificationAsString);
                    break;

                case NotificationPlatform.Adm:
                    notification = new AdmNotification(notificationAsString);
                    break;

                case NotificationPlatform.Mpns:
                    notification = new MpnsNotification(notificationAsString);
                    break;
                }
            }

            return(notification);
        }
Пример #26
0
        public async Task SendNotificationTrapDisarmed(string email, string msg, bool owner, int points, string trapNameKey, double latitude, double longitude, string otherUserName, string otherUserImage)
        {
            try
            {
                var date = DateUtils.DateToString(DateTime.Now);

                var androidPayload = "{ \"data\" : {\"message\":\"" + msg + "\", \"owner\":\"" + (owner ? "1" : "0") + "\", \"points\":\"" + points + "\", \"show\":\"1\", \"trap\":\"" + trapNameKey + "\", \"lat\":\"" + latitude + "\", \"lng\":\"" + longitude + "\", \"date\":\"" + date + "\", \"userName\":\"" + otherUserName + "\", \"img\":\"" + otherUserImage + "\"}}";
                var windowsPayload = "{\"message\":\"" + msg + "\", \"owner\":" + (owner ? "1" : "0") + ", \"points\":" + points + ", \"show\":1, \"trap\":\"" + trapNameKey + "\", \"lat\":" + latitude.ToString(CultureInfo.InvariantCulture) + ", \"lng\":" + longitude.ToString(CultureInfo.InvariantCulture) + ", \"date\":\"" + date + "\", \"userName\":\"" + otherUserName + "\", \"img\":\"" + otherUserImage + "\"}";

                var notificationOutcomeAndroid = await _hubClient.SendGcmNativeNotificationAsync(androidPayload, email);

                WindowsNotification notificationWindows = new WindowsNotification(windowsPayload);

                notificationWindows.Headers.Add("X-NotificationClass", "3");
                notificationWindows.Headers.Add("X-WNS-Type", "wns/raw");

                var notificationOutcomeWindows = await _hubClient.SendNotificationAsync(notificationWindows, email);
            }
            catch (Exception exception)
            {
                ElmahUtils.LogToElmah(exception);
            }
        }
Пример #27
0
        internal static Notification BuildNotificationFromString(string notificationAsString, NotificationPlatform platform)
        {
            Notification notification = null;

            if (platform == 0)
            {
                return(BuildTemplateNotificationFromJsonString(notificationAsString));
            }
            else
            {
                switch (platform)
                {
                case NotificationPlatform.Wns:
                    notification = new WindowsNotification(notificationAsString);
                    break;

                case NotificationPlatform.Apns:
                    notification = new AppleNotification(notificationAsString);
                    break;

                case NotificationPlatform.Gcm:
                    notification = new GcmNotification(notificationAsString);
                    break;

                case NotificationPlatform.Adm:
                    notification = new AdmNotification(notificationAsString);
                    break;

                case NotificationPlatform.Mpns:
                    notification = new MpnsNotification(notificationAsString);
                    break;
                }
            }

            return(notification);
        }
Пример #28
0
        public async Task <HttpResponseMessage> Send(ChatMessage message)
        {
            // Do verification that both users can send messages to each other
            // For example, they are friends

            // Then prepare the toast notification payload
            string toastPayload = "<toast> "
                                  + "  <visual>"
                                  + "      <binding template=\"ToastText02\">"
                                  + "          <text id=\"1\">{0}</text>"
                                  + "          <text id=\"2\">{1}</text>"
                                  + "      </binding>"
                                  + "  </visual>"
                                  + "</toast>";

            toastPayload = string.Format(toastPayload, message.FromUsername, message.MessageText);

            // Send a Windows 8 toast notification to the "tag"
            await hub.SendWindowsNativeNotificationAsync(toastPayload, message.ToUsername);

            // Send a raw XML notification to update the UI as well in realtime, if the app is opened
            // Serialize the chat message into XML
            XmlSerializer xmlSerializer          = new XmlSerializer(typeof(ChatMessage));
            StringWriter  serializedStringWriter = new StringWriter();

            xmlSerializer.Serialize(serializedStringWriter, message);

            // Send the notification
            var rawChatNotification = new WindowsNotification(serializedStringWriter.ToString(), message.ToUsername);

            rawChatNotification.Headers.Add("X-WNS-Type", "wns/raw");
            rawChatNotification.ContentType = "application/octet-stream";
            await hub.SendNotificationAsync(rawChatNotification);

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        /// <summary>
        /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param>
        /// <returns>The resulting <see cref="Notification"/>.</returns>
        protected virtual Notification CreateNotification(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification notification = null;
            ApplePushMessage apnsPush;
            WindowsPushMessage wnsPush;
            MpnsPushMessage mpnsPush;
            TemplatePushMessage templatePush;
            if ((wnsPush = message as WindowsPushMessage) != null)
            {
                notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers);
            }
            else if ((mpnsPush = message as MpnsPushMessage) != null)
            {
                notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers);
            }
            else if ((apnsPush = message as ApplePushMessage) != null)
            {
                DateTime? expiration = null;
                if (apnsPush.Expiration.HasValue)
                {
                    expiration = apnsPush.Expiration.Value.DateTime;
                }
                notification = new AppleNotification(message.ToString(), expiration);
            }
            else if (message is GooglePushMessage)
            {
                notification = new GcmNotification(message.ToString());
            }
            else if ((templatePush = message as TemplatePushMessage) != null)
            {
                notification = new TemplateNotification(templatePush);
            }
            else
            {
                throw new InvalidOperationException(GetUnknownPayloadError(message));
            }

            return notification;
        }
        private async void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                btnRegistrations.Enabled = false;
                btnSend.Enabled = false;
                btnRefresh.Enabled = false;
                btnCreateDelete.Enabled = false;
                btnCancelUpdate.Enabled = false;
                if (notificationHubClient == null)
                {
                    return;
                }

                Notification notification = null;
                string[] tags = null;
                string tagExpression = null;
                switch (mainTabControl.SelectedTab.Name)
                {
                    case TemplateNotificationPage:
                        var properties = NotificationInfo.TemplateProperties.ToDictionary(p => p.Name, p => p.Value);
                        if (properties.Count > 0)
                        {
                            var headers = NotificationInfo.TemplateHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.TemplateTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtTemplateTagExpression.Text;
                            notification = new TemplateNotification(properties) {Headers = headers};
                        }
                        else
                        {
                            writeToLog(NotificationPayloadCannotBeNull, false);
                        }
                        break;
                    case WindowsPhoneNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(mpnsPayload))
                        {
                            var headers = NotificationInfo.MpnsHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.MpnsTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtMpnsTagExpression.Text;
                            notification = new MpnsNotification(mpnsPayload, headers);
                        }
                        else
                        {
                            writeToLog(NotificationPayloadCannotBeNull, false);
                        }
                        break;
                    case WindowsNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(wnsPayload))
                        {
                            var headers = NotificationInfo.WnsHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.WnsTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtWnsTagExpression.Text;
                            notification = new WindowsNotification(wnsPayload, headers);
                        }
                        else
                        {
                            writeToLog(NotificationPayloadCannotBeNull, false);
                        }
                        break;
                    case AppleNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(apnsPayload))
                        {
                            var serializer = new JavaScriptSerializer();
                            try
                            {
                                serializer.Deserialize<dynamic>(apnsPayload);
                            }
                            catch (Exception)
                            {
                                writeToLog(PayloadIsNotInJsonFormat);
                                return;
                            }
                            var headers = NotificationInfo.ApnsHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.ApnsTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtAppleTagExpression.Text;
                            notification = new AppleNotification(apnsPayload) { Headers = headers };
                        }
                        else
                        {
                            writeToLog(JsonPayloadTemplateCannotBeNull, false);
                        }
                        break;
                    case GoogleNativeNotificationPage:
                        if (!string.IsNullOrWhiteSpace(gcmPayload))
                        {
                            var serializer = new JavaScriptSerializer();
                            try
                            {
                                serializer.Deserialize<dynamic>(gcmPayload);
                            }
                            catch (Exception)
                            {
                                writeToLog(PayloadIsNotInJsonFormat);
                                return;
                            }
                            var headers = NotificationInfo.GcmHeaders.ToDictionary(p => p.Name, p => p.Value);
                            tags = NotificationInfo.GcmTags.Select(t => t.Tag).ToArray();
                            tagExpression = txtGcmTagExpression.Text;
                            notification = new GcmNotification(gcmPayload) { Headers = headers };
                        }
                        else
                        {
                            writeToLog(JsonPayloadTemplateCannotBeNull, false);
                        }
                        break;
                }
                if (notification == null)
                {
                    return;
                }
                NotificationOutcome notificationOutcome;
                if (!string.IsNullOrWhiteSpace(tagExpression))
                {
                    notificationOutcome = await notificationHubClient.SendNotificationAsync(notification, tagExpression);
                    WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags);
                    return;
                }
                if (tags.Any())
                {
                    notificationOutcome = await notificationHubClient.SendNotificationAsync(notification, tags);
                    WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags);
                    return;
                }
                notificationOutcome = await notificationHubClient.SendNotificationAsync(notification);
                WriteNotificationToLog(notification, notificationOutcome, tagExpression, tags);
            }
            catch (Exception ex)
            {
                writeToLog(ex.Message);
            }
            finally
            {
                btnRegistrations.Enabled = true;
                btnSend.Enabled = true;
                btnRefresh.Enabled = true;
                btnCreateDelete.Enabled = true;
                btnCancelUpdate.Enabled = true;
                Cursor.Current = Cursors.Default;
            }
        }
Пример #31
0
        public List <RemoteNotificationResult> Send()
        {
            foreach (RemoteNotification notif in m_notifications)
            {
                PlatformType platformType = PlatformConverter.FromDeviceType(notif.DeviceType);
                switch (platformType)
                {
                case PlatformType.Apple:
                    EnsureiOS();
                    AppleNotification n = NotificationFactory.Apple();
                    n.DeviceToken = notif.DeviceToken;
                    n.Payload     = new AppleNotificationPayload();
                    if (!string.IsNullOrEmpty(notif.Message))
                    {
                        n.Payload.Alert = new AppleNotificationAlert()
                        {
                            Body = notif.Message
                        }
                    }
                    ;
                    if (!string.IsNullOrEmpty(notif.Sound))
                    {
                        n.Payload.Sound = notif.Sound;
                    }
                    if (!string.IsNullOrEmpty(notif.Action) && notif.Action.Trim().Length > 0)
                    {
                        n.Payload.AddCustom("a", notif.Action);
                        if (notif.Parameters != null && notif.Parameters.Names.Count > 0)
                        {
                            n.Payload.AddCustom("p", notif.Parameters.ToJObject());
                        }
                    }
                    if (!string.IsNullOrEmpty(notif.Badge))
                    {
                        int badgeInt;
                        if (int.TryParse(notif.Badge, out badgeInt))
                        {
                            n.Payload.Badge = badgeInt;
                        }
                        else if (notif.Badge == "!")
                        {
                            n.Payload.Badge = -1;
                        }
                    }
                    if (notif.ExecutionTime != 0)
                    {
                        n.Payload.ContentAvailable = 1;
                    }

                    Service.QueueNotification(n);
                    break;

                case PlatformType.AndroidGcm:
                    EnsureAndroid();
                    GcmNotification g = NotificationFactory.Google();
                    g.RegistrationIds.Add(notif.DeviceToken);
                    g.JsonData = string.Format("{{ \"payload\":\"{0}\",\"action\":\"{1}\",\"parameters\": {2} ,\"executiontime\": {3} ,\"priority\": {4} }}"
                                               , notif.Message, notif.Action, notif.Parameters.ToJson(), notif.ExecutionTime.ToString(), notif.Delivery.Priority);
                    g.CollapseKey = "NONE";
                    Service.QueueNotification(g);
                    break;

                case PlatformType.WindowsPhone:
                    EnsureWindows();
                    WindowsNotification w = NotificationFactory.Windows();
                    w.ChannelUri    = notif.DeviceToken;
                    w.Message       = notif.Message;
                    w.Title         = notif.Title;
                    w.ImageUri      = notif.Icon;
                    w.Badge         = notif.Badge;
                    w.Sound         = notif.Sound;
                    w.Action        = notif.Action;
                    w.Parameters    = notif.Parameters;
                    w.ExecutionTime = notif.ExecutionTime;

                    Service.QueueNotification(w);
                    break;

                default:
                    RemoteNotificationResult result = RemoteNotificationResult.ForDevice(notif.DeviceType, notif.DeviceToken);
                    result.ErrorCode        = INVALID_DEVICE_TYPE;
                    result.ErrorDescription = GetErrorDescription(INVALID_DEVICE_TYPE);
                    SetResult(result);
                    break;
                }
            }

            Service.StopAllServices(true);
            return(m_results);
        }
Пример #32
0
        public async Task<IHttpActionResult> PutGame(int id, Game game)
        {

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != game.Id)
            {
                return BadRequest();
            }

            TicTacToeEngine engine = new TicTacToeEngine();
            engine.Initialise(game);

 
            if (game.UserIdOpponent == jarvisName)
            {
                var isMachineTurn = game.UserIdCurrent.ToLower().Trim() != jarvisName.ToLower().Trim();
                var isEnded = engine.MakeBestMove(isMachineTurn);
                game.Board = engine.Board;
            }

            else
            {
                game.UserIdCurrent = game.UserIdCurrent == game.UserIdCreator ? game.UserIdOpponent : game.UserIdCreator;

            }
            game.IsTerminated = engine.IsGameFullCompleted(game.Board);


            if (game.IsTerminated)
            {
                var result = engine.GetResultState(game.Board);
                if (result == TicTacToeEngine.TicTacToeResult.MachineWin)
                    game.UserIdWinner = game.UserIdOpponent;
                else
                    game.UserIdWinner = game.UserIdCreator;
            }

            db.Entry(game).State = EntityState.Modified;

            try
            {
                db.SaveChanges();

                NotificationHubClient hub = NotificationHubClient
                                .CreateClientFromConnectionString("Endpoint=sb://tictactoenotifications.servicebus.windows.net/;SharedAccessKeyName=DefaultFullSharedAccessSignature;SharedAccessKey=+Au+w96izwXkztajDDeRB4r+6hsCsN0Gt1lN0Yg7lxM=", "OfficeTicTacToeNotificationHub");

                //var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">Hello from a .NET App!</text></binding></visual></toast>";


                //await hub.SendWindowsNativeNotificationAsync(toast);

                var payload = @"<toast>
                                   <visual>
                                       <binding template=""ToastText01"">
                                           <text id=""1"">" + game.Id + @"</text>
                                       </binding>
                                   </visual>
                                </toast>";

                var tag = (game.UserIdCurrent == game.UserIdCreator) ? game.UserIdOpponent : game.UserIdCreator;

                Notification notification = new WindowsNotification(payload);
                notification.Headers.Add("X-WNS-Cache-Policy", "cache");
                notification.Headers.Add("X-WNS-Type", "wns/raw");
                notification.ContentType = "application/octet-stream";

                await hub.SendNotificationAsync(notification);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }

            return Ok(game);
        }
        public async System.Threading.Tasks.Task<HttpResponseMessage> SendWindowsNativeRawNotification([Metadata("Connection String")]string connectionString, [Metadata("Hub Name")]string hubName, [Metadata("Toast RAW")]string message, [Metadata("Toast Tags")]string tags = null)
        {
            try
            {
                NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connectionString, hubName);
                
                Notification notification = new WindowsNotification(message);
                notification.Headers.Add("X-WNS-Type", "wns/raw");

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

                return Request.CreateResponse<NotificationOutcome>(HttpStatusCode.OK, result);
            }
            catch (ConfigurationErrorsException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.BareMessage);
            }
        }
Пример #34
0
        public async Task<HttpResponseMessage> Send(ChatMessage message)
        {
            // Do verification that both users can send messages to each other
            // For example, they are friends

            // Then prepare the toast notification payload
            string toastPayload = "<toast> "
                          + "  <visual>"
                          + "      <binding template=\"ToastText02\">"
                          + "          <text id=\"1\">{0}</text>"
                          + "          <text id=\"2\">{1}</text>"
                          + "      </binding>"
                          + "  </visual>"
                          + "</toast>";

            toastPayload = string.Format(toastPayload, message.FromUsername, message.MessageText);

            // Send a Windows 8 toast notification to the "tag"
            await hub.SendWindowsNativeNotificationAsync(toastPayload,message.ToUsername);

            // Send a raw XML notification to update the UI as well in realtime, if the app is opened
            // Serialize the chat message into XML
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(ChatMessage));
            StringWriter serializedStringWriter = new StringWriter();
            xmlSerializer.Serialize(serializedStringWriter, message);

            // Send the notification
            var rawChatNotification = new WindowsNotification(serializedStringWriter.ToString(), message.ToUsername);
            rawChatNotification.Headers.Add("X-WNS-Type", "wns/raw");
            rawChatNotification.ContentType = "application/octet-stream";
            await hub.SendNotificationAsync(rawChatNotification);

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Пример #35
0
        public async Task <IActionResult> Post(PublishModel publishModel)
        {
            const int arbitraryLengthLimit = 240;

            if (string.IsNullOrWhiteSpace(publishModel.to_tag))
            {
                return(BadRequest("Must provide a target user"));
            }
            if (publishModel.to_tag.Length > arbitraryLengthLimit)
            {
                return(BadRequest("Target user name invalid"));
            }
            if (string.IsNullOrWhiteSpace(publishModel.message))
            {
                return(BadRequest("Must provide a message"));
            }
            if (publishModel.message.Length > arbitraryLengthLimit)
            {
                return(BadRequest("Message too long"));
            }

            var user = HttpContext.User.Identity.Name;

            string[] userTag = new string[2];
            userTag[0] = "username:"******"nickname:" + publishModel.to_tag; //this is a hack and should be replaced
            userTag[1] = "from:" + user;

            var rawNotification = new RawNotificationModel
            {
                Message = publishModel.message
            };
            var rawJson = JsonConvert.SerializeObject(rawNotification);

            NotificationOutcome outcome;

            // Windows 8.1 / Windows Phone 8.1
            var toast = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
                        "From " + user + ": " + publishModel.message + "</text></binding></visual></toast>";

            outcome = await _hubClientFactory.Primary.SendWindowsNativeNotificationAsync(toast, userTag);

            IDictionary <string, string> wnsHeaders = new Dictionary <string, string> {
                { "X-WNS-Type", "wns/raw" }
            };
            var windowsNotification = new WindowsNotification(rawJson, wnsHeaders);
            var windowsRawOutcome   = await _hubClientFactory.Primary.SendNotificationAsync(
                windowsNotification, userTag);

            //    // iOS
            //    var alert = "{\"aps\":{\"alert\":\"" + "From " + user + ": " + publishModel.message + "\"}}";
            //    outcome = await _hubClientFactory.Primary.SendAppleNativeNotificationAsync(alert, userTag);
            //    break;

            // Android
            var notif = "{ \"data\" : {\"message\":\"" + "From " + user + ": " + publishModel.message + "\"}}";

            outcome = await _hubClientFactory.Primary.SendFcmNativeNotificationAsync(notif, userTag);

            var fcmRawOutcome = await _hubClientFactory.Primary.SendNotificationAsync(
                new FcmNotification(rawJson), userTag);


            if (outcome != null)
            {
                if (!((outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Abandoned) ||
                      (outcome.State == Microsoft.Azure.NotificationHubs.NotificationOutcomeState.Unknown)))
                {
                    return(Ok());
                }
            }

            return(StatusCode((int)HttpStatusCode.InternalServerError));
        }
Пример #36
0
 static string GetBadgeTemplate(WindowsNotification notif)
 {
     return("<badge value=\"" + notif.Badge + "\"/>");
 }
Пример #37
0
        private static async void SendNotificationAsync()
        {
            //var hub = new NotificationHub("NotificationhuBCesar", ConnectionStringCesar);


            NotificationHubClient hubClient = NotificationHubClient.CreateClientFromConnectionString(ConnectionStringCesar, "NotificationhuBCesar", true);

            string[] userTag = new string[2];
            userTag[0] = "username: Test";
            userTag[1] = "from:  user";
            var toast      = @"<toast><visual><binding template=""ToastText01""><text id=""1"">From any .NET App!</text></binding></visual></toast>";
            var rowPayload = "Notification at " + DateTime.Now.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("it-IT"));
            var toasts     = @"<toast><visual><binding template=""ToastText01""><text id=""1"">" +
                             "From Test: Message" + "</text></binding></visual></toast>";

            try
            {
                //var outcome = hubClient.SendWindowsNativeNotificationAsync(toasts, userTag);
                var payLoad = @"From any .NET App!";
                var notif   = new WindowsNotification(payLoad);
                notif.ContentType = "application/octet-stream";
                notif.Headers.Add("X-WNS-Type", "wns/raw");
                notif.Headers.Add("ServiceBusNotification-Format", "windows");
                //notif.Headers.Add("Authorization", "wTai8dxwIiYMt+FhtoTNegYqlfFreGWMFNSykjfDhZs=");
                //notif.Headers.Add("Host", "cloud.notify.windows.com");
                notif.Body = "hi from .net";

                var ct = new CancellationToken();

                hubClient.SendNotificationAsync(notif, "@1234", ct).Wait();
            }
            catch (Exception e)
            {
                var s = "";
            }
            //            #region case 1: broadcasted
            //            /*
            //            //the payload can be whatever: the Azure Notification Hub pass through everything to WNS and possible errore could be returned froew that is not well formed.
            //            await hubClient.SendWindowsNativeNotificationAsync(toast);
            //            */
            //            #endregion case 1: broadcasted

            //            #region case 2: client subscribed by SubscribeToCategories
            //            /* */
            //            //There is not the pain for a developer to mantain the registry of tags
            //            //If we want a toast notification
            //            // await hubClient.SendWindowsNativeNotificationAsync(toast, "Torino"); // hubClient.SendWindowsNativeNotificationAsync(toast, "Torino").Wait(); //notity to clients subcribed to "World" tag
            //            // //or hubClient.SendWindowsNativeNotificationAsync(toast, "Torino &amp;amp;&amp;amp; !Politics").Wait(); //notify to clients subcribed to "World" tag but not subscribed to the Politics tag too. In expression like this (that can use also parenthesis) it can be used at maximun 6 tags in the expression

            //            //If we want to have a row notification that can be handled by code in the running client app
            //            Notification notification = new WindowsNotification(rowPayload);
            //            notification.Headers = new Dictionary<string, string> {
            //// {"Content-Type", "application/octet-stream")},
            //{"X-WNS-TTL","300"}, // e.g. 300 seconds=> 5 minutes - Specifies the TTL (expiration time) for a notification.
            //{"X-WNS-Type", "wns/raw" },
            //{"ServiceBusNotification-Format", "windows"}
            //};
            //            await hubClient.SendNotificationAsync(notification, "deskhelp");
            //            /* */
            //            #endregion case 2: client subscribed by SubscribeToCategories

            //            #region case 3: client SubscribeToCategoriesWithCustomTemplate
            //            /*
            //            //the template and internalization is own by the client that registes to have notifications
            //            //template back to the mobile app: it is the client that knows the format he will receive
            //            //you can put any property and payload you whant; you can personalize the notification, depending to the registration
            //            //we do not use anymore the var toast but a dictionary: the server code is agnostic of the type of client (IOS, Android, Windows) that has to define a similar template related to News_locale
            //            var notification = new Dictionary<string, string>() {
            //            {"News_English", "World news in English"},
            //            {"News_Italian", "Notizie dal mondo in italiano"}
            //            };
            //            //send then a template notification not a Windows one
            //            await hubClient.SendTemplateNotificationAsync(notification, "World");
            //            */
            //            #endregion case 3: client SubscribeToCategoriesWithCustomTemplate
        }