示例#1
0
        private async Task SendNotificationAsync_SendMpnsNativeNotification_GetSuccessfulResultBack()
        {
            LoadMockData();
            var notification = new MpnsNotification("<wp:Notification xmlns:wp=\"WPNotification\" Version=\"2.0\"><wp:Tile Id=\"TileId\" Template=\"IconicTile\"><wp:Title Action=\"Clear\">Title</wp:Title></wp:Tile></wp:Notification>");

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

            Assert.Equal(NotificationOutcomeState.Enqueued, notificationResult.State);
            RecordTestResults();
        }
        /// <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);
        }
示例#3
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);
        }
示例#4
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);
        }
        /// <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;
            }
        }
        private async void SendFeedNotification <TEntity>(
            string feed, TEntity entity, int[] entityKeys, UpdateOperations operations)
        {
            var    entityType      = entity.GetType();
            string baseTypeName    = entityType.BaseType.Name;
            string operationString = string.Empty;

            switch (operations)
            {
            case UpdateOperations.Change:
                operationString = "updated";
                break;

            case UpdateOperations.Add:
                operationString = "added";
                break;

            case UpdateOperations.Delete:
                operationString = "deleted";
                break;
            }
            string keysAsString = string.Empty;

            foreach (int key in entityKeys)
            {
                keysAsString += string.Format("{0},", key);
            }
            keysAsString = keysAsString.TrimEnd(',');
            var entityAsString = string.Format("{0}({1})", baseTypeName, keysAsString);
            var message        = string.Format("The entity '{0}' was {2} in the '{1}' feed.",
                                               entityAsString, feed, operationString);

            // Define the parameters for the notification templates.
            var parameters =
                new Dictionary <string, string>();

            parameters.Add("feed", feed);
            parameters.Add("operation", operationString);
            parameters.Add("entity", entityAsString);
            parameters.Add("message", message); // only used for iOS clients.

            // Send a cross-plaform notification by using templates,
            // including toasts to Windows Store apps.
            await hubClient.SendTemplateNotificationAsync(parameters, feed);

            // Create and send a raw notification to auto-update
            // any Windows Store or Windows Phone apps.
            var payload = await JsonConvert.SerializeObjectAsync(parameters);

            try
            {
                // Create the WNS with the header for a raw notification.
                WindowsNotification wns = new WindowsNotification(payload,
                                                                  new Dictionary <string, string>()
                {
                    { "X-WNS-Type", "wns/raw" }
                }, feed);
                wns.ContentType = "application/octet-stream";
                var result = await hubClient.SendNotificationAsync(wns);

                // Create the MPNS with the header for a raw notification.
                MpnsNotification mpns = new MpnsNotification(payload,
                                                             new Dictionary <string, string>()
                {
                    { "X-NotificationClass", "3" }
                }, feed);
                mpns.ContentType = "text/xml";
                await hubClient.SendNotificationAsync(mpns);
            }
            catch (ArgumentException ex)
            {
                // Send methods return an error response when the notification hub hasn't yet
                // been configured for a particular client platform.
            }
        }
示例#8
0
    public async Task <IHttpActionResult> TriggerCheck([FromUri] int start = 0)
    {
        var          sw = Stopwatch.StartNew();
        int          registrationCount = 0;
        const string toastTemplate     = "<?xml version=\"1.0\" encoding=\"utf-8\"?><wp:Notification xmlns:wp=\"WPNotification\"><wp:Toast><wp:Text1>{0}</wp:Text1><wp:Text2>{1}</wp:Text2><wp:Param>{2}</wp:Param></wp:Toast></wp:Notification>";


        IList <NotificationOutcome> result        = new List <NotificationOutcome>();
        IList <MpnsNotification>    notifications = new List <MpnsNotification>();

        var registrations = (await _notificationClient.GetAllRegistrationsAsync(Int32.MaxValue)).Where(x => x.Tags != null).Skip(start);
        var preferences   = _mobileClient.GetTable <PlainNumberInfo>();

        if (start == 0)
        {
            alreadyRetrieved.Clear();
        }

        foreach (var user in registrations)
        {
            notifications.Clear();
            foreach (var number in user.Tags)
            {
                try
                {
                    bool dirty = false;
                    var  data  = number.Split('_');
                    if (data.Any(x => string.IsNullOrEmpty(x)))
                    {
                        await _notificationClient.DeleteRegistrationAsync(user); //Tanto non saprei cosa cazzo farci.

                        continue;
                    }

                    CreditInfo content = null;

                    if (!alreadyRetrieved.Any(x => x.Username == data[0] && x.Type == data[data.Length - 1] && x.Password == string.Join("_", data.Skip(1).Take(data.Length - 2))))
                    {
                        content = await _retrievers.First(x => x.Type == data[data.Length - 1]).Get(data[0], string.Join("_", data.Skip(1).Take(data.Length - 2)), data[data.Length - 1], Guid.Empty); //this.GetData(null, new Q_X { q = data[0], x = data[1], t = data[2] });

                        alreadyRetrieved.Add(content);
                    }
                    else
                    {
                        content = alreadyRetrieved.First(x => x.Username == data[0] && x.Type == data[2] && x.Password == data[1]);
                        dirty   = true;
                    }

                    foreach (var accountNumber in content.NumberInfos)
                    {
                        IEnumerable <PlainNumberInfo> userPreference = await preferences.Where(x => x.Number == accountNumber.Number).ToEnumerableAsync();

                        if (userPreference.Count() == 0)
                        {
                            await preferences.InsertAsync(new PlainNumberInfo { Number = accountNumber.Number, FriendlyName = accountNumber.Number, Gigabytes = accountNumber.Gigabytes, Minutes = accountNumber.Minutes, SMS = accountNumber.SMS, Credit = accountNumber.Credit, Brush = "#000000" });
                        }
                        else
                        {
                            var dataPreference = userPreference.First();
                            accountNumber.Brush = dataPreference.Brush;
                            if (string.IsNullOrEmpty(dataPreference.Brush))
                            {
                                accountNumber.Brush = "#000000"; //Nero
                            }
                            accountNumber.FriendlyName = dataPreference.FriendlyName;

                            if (dataPreference.NotifyEnabled)
                            {
                                if (accountNumber.SMS < dataPreference.SMSLimit && dataPreference.smsShowed == false)
                                {
                                    dirty = true;
                                    dataPreference.smsShowed = true;
                                    notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite SMS", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number)))));
                                }
                                else if (accountNumber.SMS >= dataPreference.SMSLimit)
                                {
                                    dataPreference.smsShowed = false;
                                }
                                if (accountNumber.Minutes < dataPreference.MinutesLimit && dataPreference.minShowed == false)
                                {
                                    dirty = true;
                                    dataPreference.minShowed = true;
                                    notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite minuti", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number)))));
                                }
                                else if (accountNumber.Minutes >= dataPreference.MinutesLimit)
                                {
                                    dataPreference.minShowed = false;
                                }

                                if (accountNumber.Gigabytes < dataPreference.GigabytesLimit && dataPreference.gigaShowed == false)
                                {
                                    dirty = true;
                                    dataPreference.gigaShowed = true;
                                    notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite traffico", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number)))));
                                }
                                else if (accountNumber.Gigabytes >= dataPreference.GigabytesLimit)
                                {
                                    dataPreference.gigaShowed = false;
                                }

                                if (accountNumber.Credit < dataPreference.CreditLimit && dataPreference.clShowed == false)
                                {
                                    dirty = true;
                                    dataPreference.clShowed = true;
                                    notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", string.Format("{0} : raggiunto limite credito", dataPreference.FriendlyName), string.Format("/DataPage.xaml?number={0}", HttpUtility.UrlEncode(accountNumber.Number)))));
                                }
                                else if (accountNumber.Credit >= dataPreference.CreditLimit)
                                {
                                    dataPreference.clShowed = false;
                                }



                                accountNumber.CreditLimit    = dataPreference.CreditLimit;
                                accountNumber.SMSLimit       = dataPreference.SMSLimit;
                                accountNumber.GigabytesLimit = dataPreference.GigabytesLimit;
                                accountNumber.MinutesLimit   = dataPreference.MinutesLimit;
                            }

                            if (dataPreference.Credit != accountNumber.Credit ||
                                dataPreference.SMS != accountNumber.SMS ||
                                dataPreference.Gigabytes != accountNumber.Gigabytes ||
                                dataPreference.Minutes != accountNumber.Minutes)
                            {
                                dataPreference.Credit    = accountNumber.Credit;
                                dataPreference.SMS       = accountNumber.SMS;
                                dataPreference.Gigabytes = accountNumber.Gigabytes;
                                dataPreference.Minutes   = accountNumber.Minutes;

                                dirty = true;
                            }

                            if (dirty)
                            {
                                dataPreference.LastUpdate = DateTime.Now;
                                await preferences.UpdateAsync(dataPreference);
                            }
                        }


                        if (dirty)
                        {
                            var thread = new Thread(new ThreadStart(() => { XamlRendering.ConvertToJpg(accountNumber); }));

                            thread.SetApartmentState(ApartmentState.STA);
                            thread.Start();
                            thread.Join();

                            var notificationPayload =
                                string.Format(PushTemplates.NotificationTemplate,
                                              string.Format("/DataPage.xaml?number={0}", accountNumber.Number),
                                              string.Format("http://wauth.apphb.com/Tiles/{0}_159.jpg", accountNumber.Number),
                                              string.Format("http://wauth.apphb.com/Tiles/{0}_336.jpg", accountNumber.Number),
                                              string.Format("http://wauth.apphb.com/Tiles/{0}_691.jpg", accountNumber.Number));

                            var notification = new MpnsNotification(notificationPayload, new Dictionary <string, string> {
                                { "X-WindowsPhone-Target", "token" }, { "X-NotificationClass", "1" }
                            });
                            notifications.Add(notification);
                        }
                    }
                }
                catch (WrongLoginDataException)
                {
                    notifications.Add(new MpnsNotification(string.Format(toastTemplate, "Warning", "Dati di login errati.", string.Empty)));
                    _notificationClient.DeleteRegistrationAsync(user).Wait(); //Addio. Rientra nell'app e inserisci i dati giusti.
                }
                catch (Exception)
                {
                    continue;
                }

                var tasks = notifications.Select(x => _notificationClient.SendNotificationAsync(x, user.Tags));

                foreach (var item in tasks)
                {
                    result.Add(await item);
                }
            }

            registrationCount++;
            if (100 - sw.Elapsed.TotalSeconds <= 5)
            {
                break;
            }
        }

        return(Ok(new NotificationProcessInfo {
            Registrations = registrationCount, Notifications = result.Count
        }));
    }