예제 #1
0
        public void Compare_Repos_July_vs_Today(string owner)
        {
            NotificationBuilder         nbuilder        = new NotificationBuilder();
            NotificationChannelsBuilder channelsBuilder = new NotificationChannelsBuilder().UseSmtpPickupDirectory(@"c:\work").UseSmtpPickupDirectory(@"c:\work2\send");

            List <RepositoryEvent> Events = new List <RepositoryEvent>();
            ITableSnapshotBuilder  builder;

            builder = RepositoryListSnapshotBuilder.CreateInMemorySnapshotFromRequest(Resources.GetRepositoryResponse(owner, RepositoryResponseGeneration.July));
            ITableSnapshot microsoftSnapshotJuly = builder.Build();

            builder = RepositoryListSnapshotBuilder.CreateInMemorySnapshotFromRequest(this.Extractor.GetMetadataAsynch(this.Token, owner).Result);
            ITableSnapshot microsoftSnapshotToday = builder.Build();

            TableDiffByLookup differ = new TableDiffByLookup(microsoftSnapshotJuly, microsoftSnapshotToday);


            differ.DifferencesDelegate = (deletedRecord, inserted) =>
            {
                EventType   et       = EventType.Created;
                IDataRecord template = inserted;
                if ((deletedRecord != null) && (inserted != null))
                {
                    et       = EventType.Modified;
                    template = inserted;
                }

                if ((deletedRecord != null) && (inserted == null))
                {
                    et       = EventType.Deleted;
                    template = deletedRecord;
                    //RepositoryTableSnapshot.CreatedAtFieldName
                }

                RepositoryEvent ev = EventFactory.CreateRepositoryEvent(template, et);
                nbuilder.AddEvent(ev);
            };
            differ.Execute();
            //Assert.Equal(1312, differ.OldSnapshotRecordCount);

            //create Notification
            //Deliver Notification

            nbuilder.AddChannels(channelsBuilder);

            List <Notification> toSend = new List <Notification>();

            for (int i = 0; i < 5; i++)
            {
                Notification noti = nbuilder.Build();
                noti.From = new NotificationAddress()
                {
                    Identifier = "*****@*****.**"
                };
                noti.To = new NotificationAddress[] { noti.From };
                toSend.Add(noti);
            }

            Postman.DeliverNotification(toSend);
        }
예제 #2
0
        public static INotificationBuilder AddNotifications(this IServiceCollection services)
        {
            var ret = new NotificationBuilder(services);

            services.AddSingleton(isp => ret.Build(isp));
            return(ret);
        }
예제 #3
0
        public void scheduleAction()
        {
            updateValues();

            NotificationBuilder builder = new NotificationBuilder(id, title, body);

            builder
            .setTicker(ticker)
            .setDefaults(flags)
            .setAlertOnlyOnce(alertOnce.isOn)
            .setDelay(delay * 1000)
            .setRepeating(repeating.isOn)
            .setAutoCancel(autoCancel.isOn)
            .setGroup(group)
            .setColor(color)
            .setSound("ses")
            .setInterval(interval * 1000);


            if (repeating.isOn && interval == 0)
            {
                AndroidNotifications.showToast("Enter interval");
            }
            else
            {
                AndroidNotifications.scheduleNotification(builder.build());

                AndroidNotifications.showToast("Notification scheduled");
            }
        }
        /// <summary>
        /// Dismiss a notification (warns subscribers that a notification was dismissed by a user)
        /// </summary>
        /// <param name="notificationId"></param>
        public void Dismiss(long notificationId)
        {
            NotificationBuilder notificationBuilderToRemove = null;

            for (var i = 0; i < m_NotificationBuilders.Count; i++)
            {
                if (m_NotificationBuilders[i].id == notificationId)
                {
                    notificationBuilderToRemove = m_NotificationBuilders[i];
                    m_NotificationBuilders.RemoveAt(i);
                    break;
                }
            }

            if (notificationBuilderToRemove != null)
            {
                //TODO eventually: add analytics to keep track of this notification dismissal
                foreach (var subscriber in m_SubscribersByTopic[notificationBuilderToRemove.topic])
                {
                    try
                    {
                        //We can be vulnerable here since subscribers could crash and prevent other subscribers to receive the dismissal
                        //Hopefully each Subscriber will be robust enough that it won't happen. But worst case, we will output the error.
                        subscriber.DismissNotification(notificationId);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(ex);
                    }
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Creates a tile notification using the Notification Builder.
        /// </summary>
        /// <param name="build">How to build the notification</param>
        /// <returns></returns>
        public static TileNotification Create(Action <INotificationBuilder> build)
        {
            var builder = new NotificationBuilder();

            build(builder);

            return(builder.Build());
        }
        public NotificationBuilder RegisterNotification <TNotification>(Func <Notification> factory = null) where TNotification : Notification
        {
            var typeInfo = AbstractTypeFactory <Notification> .RegisterType <TNotification>();

            var builder = new NotificationBuilder(_serviceProvider, typeof(TNotification), factory);

            typeInfo.WithFactory(() => builder.Build());
            return(builder);
        }
예제 #7
0
        public async Task <List <Notification> > AddNotifications(List <Order> orders)
        {
            // Start watch
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            // Now
            var now = DateTime.UtcNow.StripSeconds();

            // Create notifications
            var notifications = new List <Notification>();

            // Orders pending to notify
            var ordersPendingToNotify = orders.Where(OrderExpression.PendingToNotify()).ToList();

            // For each order pending to notify
            foreach (var order in ordersPendingToNotify)
            {
                // Get user
                var user = await _mainDbContext.Users.FindAsync(order.UserId);

                // Create message
                var message = NotificationBuilder.BuildMessage(
                    OrderMessage.OrderNotification,
                    order.CurrencyId,
                    order.OrderType,
                    order.Price);

                // Create notification
                var notification = new Notification(user.UserId, user.PhoneNumber, message, now);

                // Add notification
                notifications.Add(notification);

                // Mark order as notified
                order.MarkAsNotified();

                // Update order
                _mainDbContext.Orders.Update(order);
            }

            // Add notifications
            await _mainDbContext.Notifications.AddRangeAsync(notifications);

            // Save
            await _mainDbContext.SaveChangesAsync();

            // Stop watch
            stopwatch.Stop();

            // Log
            _logger.LogInformation("{@Event}, {@Count}, {@ExecutionTime}", "NotificationsAdded", notifications.Count, stopwatch.Elapsed.TotalSeconds);

            // Return
            return(notifications);
        }
예제 #8
0
        public override void OnPerformSync(Account account, Bundle extras, string authority, ContentProviderClient provider, SyncResult syncResult)
        {
            if (_servicoAtualizacao.Notificacao == null)
            {
                _servicoAtualizacao.Notificacao += notificacao => NotificationBuilder.ShowNotification(Context, notificacao);
            }

            _servicoAtualizacao.IniciarDownloadDados();
        }
        public NotificationBuilder OverrideNotificationType <TOldNotificationType, TNewNotificationType>(Func <Notification> factory = null) where TOldNotificationType : Notification where TNewNotificationType : Notification
        {
            var typeInfo = AbstractTypeFactory <Notification> .OverrideType <TOldNotificationType, TNewNotificationType>();

            var builder = new NotificationBuilder(_serviceProvider, typeof(TNewNotificationType), factory);

            typeInfo.WithFactory(() => builder.Build());

            return(builder);
        }
예제 #10
0
        public async Task <Notification> Push(string text, int userId, string details = null)
        {
            var notification = new NotificationBuilder()
                               .SetText(text)
                               .SentTo(userId)
                               .SetDetails(details)
                               .Build();

            return(await database.NotificationRepository.Insert(notification) ? notification : null);
        }
        public void AddProvider_WithHttp_NoHttpClientFactory()
        {
            _notification.Setup(n => n.AddProvider(It.IsAny <NotificationProvider>()))
            .Returns(_notification.Object);

            _services.AddSingleton(_notification.Object);

            var builder   = new NotificationBuilder(_services);
            var exception = Record.Exception(() => builder.AddProvider <DummyHttpProvider, NotificationProviderOptions>(options => { }));

            Assert.IsType <NoHttpClientFactoryException>(exception);
        }
예제 #12
0
        GetResumedNotifications(int userId)
        {
            var data = await
                       Get_notifications(userId, true, true);

            var notifications = data
                                .GroupBy(n => n.Type)
                                .ToDictionary(g => g.Key,
                                              g => g.ToList());

            return(NotificationBuilder.ResumeNotifications(notifications));
        }
예제 #13
0
 public AskModel(ILogger <AskModel> logger, HomeAssistantService homeAssistant, NotificationBuilder notificationBuilder, HtmlSanitizer sanitizer, IConfiguration configuration, CaptchaValidator validator, MarkdownPipeline markdown, Database database)
 {
     _logger                  = logger;
     this.homeAssistant       = homeAssistant;
     this.notificationBuilder = notificationBuilder;
     this.sanitizer           = sanitizer;
     this.configuration       = configuration;
     this.validator           = validator;
     this.markdown            = markdown;
     this.database            = database;
     SiteKey                  = configuration.GetValue <string>("Captcha:SiteKey");
 }
예제 #14
0
        //Notifications

        public void Do_PushNotification(NotificationType type,
                                        int userId,
                                        Dictionary <string, string> values)
        {
            Task.Run(() =>
            {
                var not = NotificationBuilder.CreateNotification(type,
                                                                 userId, values);
                Add_Notification(not);
                _notificationCtx.SaveChangesAsync().Wait();
            });
        }
        public void AddProvider_WithHttp_Success()
        {
            _notification.Setup(n => n.AddProvider(It.IsAny <NotificationProvider>()))
            .Returns(_notification.Object);

            _services.AddSingleton(_notification.Object);

            var builder = new NotificationBuilder(_services);

            builder.AddProvider <DummyHttpProvider, NotificationProviderOptions>(options => { }, true);

            _notification.Verify(n => n.AddProvider(It.IsAny <DummyHttpProvider>()), Times.Once);
        }
예제 #16
0
        public void ManageNotification(TaskAssignment taskAssignment)
        {
            if (!taskAssignment.ExistNotification)
            {
                var notification = new NotificationBuilder(this.Strategy.Session).WithTitle(
                    "Approval: " + this.WorkItem.WorkItemDescription)
                                   .WithDescription("Approval: " + this.WorkItem.WorkItemDescription)
                                   .WithTarget(this)
                                   .Build();

                taskAssignment.Notification = notification;
                taskAssignment.User.NotificationList.AddNotification(notification);
            }
        }
        public Task Execute(BehaviorContext <TInstance, TData> context, Behavior <TInstance, TData> next, Document document)
        {
            var notificationDto = new NotificationBuilder()
                                  .SetNotificationType(_notificationProvider.GetNotificationType())
                                  .SetTitle(_notificationProvider.GetTitle(document))
                                  .SetMessage(_notificationProvider.GetMessage(document))
                                  .Build()
                                  .ToDto();

            var sendNotificationCommand = new SendNotificationCommand(context.Instance.CorrelationId, notificationDto);

            context.Send(sendNotificationCommand);
            return(next.Execute(context));
        }
예제 #18
0
        public void ManageNotification(TaskAssignment taskAssignment)
        {
            if (!taskAssignment.ExistNotification && this.CommunicationEvent.SendNotification == true && this.CommunicationEvent.RemindAt < this.Strategy.Session.Now())
            {
                var notification = new NotificationBuilder(this.Strategy.Session)
                                   .WithTitle("CommunicationEvent: " + this.WorkItem.WorkItemDescription)
                                   .WithDescription("CommunicationEvent: " + this.WorkItem.WorkItemDescription)
                                   .WithTarget(this)
                                   .Build();

                taskAssignment.Notification = notification;
                taskAssignment.User.NotificationList.AddNotification(notification);
            }
        }
예제 #19
0
 protected override void OnModelCreating(ModelBuilder builder)
 {
     MessageBuilder.Build(builder);
     UserBuilder.Build(builder);
     ConversationBuilder.Build(builder);
     FriendsRequestBuilder.Build(builder);
     MessageBuilder.Build(builder);
     UserContactBuilder.Build(builder);
     ContactBuilder.Build(builder);
     NotificationBuilder.Build(builder);
     NotificationTypeBuilder.Build(builder);
     ParticipantBuilder.Build(builder);
     FileStorageBuilder.Build(builder);
     ReadReceiptBuilder.Build(builder);
     MemberBuilder.Build(builder);
 }
예제 #20
0
        public async Task AddNotification_ShouldAddNotificationInRepository()
        {
            // Arrange
            var person   = new PersonBuilder().WithId(1).Build();
            var employer = new EmployerBuilder().WithId(1).Build();
            var job      = new JobBuilder().WithId(1).Build();

            var notification = new NotificationBuilder().WithId(1).WithEmployer(employer).WithPerson(person)
                               .WithJob(job).Build();

            // Act
            await _notificationService.AddNotification(notification);

            // Assert
            _notificationRepositoryMock.Verify(n => n.AddNotification(notification), Times.Once);
            _notificationRepositoryMock.Verify(m => m.SaveAsync(), Times.Once());
        }
예제 #21
0
        public void ScheduleFromList()
        {
            string notificationName     = "FirstNotif";
            NotificationBuilder builder = AndroidNotifications.GetNotificationBuilderByName(notificationName);

            if (builder != null)
            {
                Notification notif = builder.build();
                AndroidNotifications.scheduleNotification(notif);

                Debug.Log(notif);
            }
            else
            {
                Debug.LogError("Notification with name " + notificationName + " wasn't found");
            }
        }
        public static NotificationBuilder WithTemplatesFromPath(this NotificationBuilder builder, string path, string fallbackPath = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }
            var templateLoader = builder.ServiceProvider.GetService <FileSystemNotificationTemplateLoader>();

            if (builder.Notification.Templates == null)
            {
                builder.Notification.Templates = new List <NotificationTemplate>();
            }

            builder.WithTemplates(templateLoader.LoadTemplates(builder.Notification, path, fallbackPath).ToArray());

            return(builder);
        }
예제 #23
0
        public async Task GetNotification_ShouldReturnNotificatoinFromRepository()
        {
            // Arrange
            var person   = new PersonBuilder().WithId(1).Build();
            var employer = new EmployerBuilder().WithId(1).Build();
            var job      = new JobBuilder().WithId(1).Build();

            var notification = new NotificationBuilder().WithId(1).WithEmployer(employer).WithPerson(person)
                               .WithJob(job).Build();

            _notificationRepositoryMock.Setup(n => n.GetNotification(It.IsAny <long>())).ReturnsAsync(notification);

            // Act
            var result = await _notificationService.GetNotification(1);

            // Assert
            Assert.That(result, Is.Not.Null);
            Assert.That(result, Is.EqualTo(result));
            _notificationRepositoryMock.Verify(n => n.GetNotification(1), Times.Once);
        }
예제 #24
0
        public void DeleteNotification_ShouldDeleteNotificationInRepository()
        {
            // Arrange
            var person   = new PersonBuilder().WithId(1).Build();
            var employer = new EmployerBuilder().WithId(1).Build();
            var job      = new JobBuilder().WithId(1).Build();

            var notification = new NotificationBuilder().WithId(1).WithEmployer(employer).WithPerson(person)
                               .WithJob(job).Build();

            _notificationRepositoryMock.Setup(n => n.GetNotification(It.IsAny <long>())).ReturnsAsync(notification);

            // Act
            _notificationService.DeleteNotification(1);

            // Assert
            _notificationRepositoryMock.Verify(n => n.GetNotification(1), Times.Once);
            _notificationRepositoryMock.Verify(n => n.DeleteNotification(notification), Times.Once);
            _notificationRepositoryMock.Verify(m => m.SaveAsync(), Times.Once());
        }
예제 #25
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.main);

            _tbMenu = FindViewById <Toolbar>(Resource.Id.main_tbmenu);

            SetSupportActionBar(_tbMenu);

            var servicoatualizacao = new ServicoAtualizacaoViewModel();

            servicoatualizacao.Notificacao += dto =>
            {
                NotificationBuilder.ShowNotification(this, dto);

                OnResume();
            };

            servicoatualizacao.IniciarDownloadDados();
        }
예제 #26
0
        /// <summary>
        /// Publish a new notification
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="severity"></param>
        /// <param name="rawMessage"></param>
        /// <param name="populateNotificationMessage"></param>
        /// <param name="avoidDuplicates"></param>
        public void Publish(Notification.Topic topic, Notification.Severity severity, string rawMessage, Notification.PopulateNotificationMessage populateNotificationMessage, bool avoidDuplicates = true)
        {
            var publishedOn = DateTime.Now.ToUniversalTime();

            foreach (var existingNotificationBuilder in m_NotificationBuilders)
            {
                if (existingNotificationBuilder.topic == topic &&
                    existingNotificationBuilder.severity == severity &&
                    existingNotificationBuilder.rawMessage == rawMessage &&
                    (avoidDuplicates || (publishedOn - existingNotificationBuilder.publishedOn) <= TimeSpan.FromMilliseconds(k_DuplicateNotificationMillisecondsThreshold))
                    )
                {
                    //Duplicate messages should at least be a minimum amount of time apart and specifically requested. We don't want spam.
                    return;
                }
            }

            var notificationBuilder = new NotificationBuilder(GetNextNotificationId(), publishedOn, topic, severity, rawMessage, populateNotificationMessage);

            //TODO eventually: add analytics to keep track of this notification
            //TODO eventually: if we want to add auto-dismissal, a notification should either be listening on events or another system needs to keep track of auto-dismiss notifications
            //Chances are the new notification is actually the most recent, so add it as the last element, then sort by desc date if required,
            //but most likely won't do anything and won't take too much time
            m_NotificationBuilders.Add(notificationBuilder);
            m_NotificationBuilders.Sort((notification1, notification2) => notification2.publishedOn.CompareTo(notification1.publishedOn));
            foreach (var subscriber in m_SubscribersByTopic[topic])
            {
                try
                {
                    //We can be vulnerable here since subscribers could crash and prevent other subscribers to receive the notification
                    //Hopefully each Subscriber will be robust enough that it won't happen. But worst case, we will output the error.
                    subscriber.ReceiveNotification(notificationBuilder.BuildNotification());
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }
        }
예제 #27
0
        private string ScheduleNotification(string notificationTitle, DateTimeOffset dateTime)
        {
            XmlDocument notificationStructure = NotificationBuilder.BuildNoTitleNotification(notificationTitle);

            return(NotificationScheduler.ScheduleNotification(notificationStructure, dateTime));
        }
예제 #28
0
        public static int HandleWork <T>(IConsole console, WorkDescription currentWork, ILogger logger, Func <WorkDescription, string, IEvent[]> callback) where T : IEvent
        {
            Guard.ArgumentNotNull(currentWork, nameof(currentWork));
            Guard.ArgumentNotNull(logger, nameof(logger));
            Guard.ArgumentNotNull(currentWork.Channels, "currentWork.Channels");

            List <IEvent> FullList = new List <IEvent>();
            List <Task <Tuple <IEvent[], TimeSpan> > > TaskList = new List <Task <Tuple <IEvent[], TimeSpan> > >();
            List <Task> continuations = new List <Task>();

            foreach (string item in currentWork.Items)
            {
                lock (console)
                {
                    console.WriteLine(string.Format("  {0} Task started...", item), null, null);
                }

                Task <Tuple <IEvent[], TimeSpan> > task = Task.Factory.StartNew <Tuple <IEvent[], TimeSpan> >(() =>
                {
                    Stopwatch sw = Stopwatch.StartNew();
                    IEvent[] ev  = callback(currentWork, item);
                    sw.Stop();
                    return(new Tuple <IEvent[], TimeSpan>(ev, sw.Elapsed));
                });

                Task ct = task.ContinueWith((prec) =>
                {
                    lock (console)
                    {
                        console.WriteLine(string.Format("  {0} Task completed", item), null, null);
                        console.WriteLine(string.Format("    {0} Events identified in {1}ms", prec.Result.Item1.Length, Convert.ToInt64(prec.Result.Item2.TotalMilliseconds)), null, null);
                    }
                }, TaskContinuationOptions.NotOnFaulted);
                TaskList.Add(task);
                continuations.Add(ct);
            }

            Task.WaitAll(TaskList.ToArray());
            Task.WaitAll(continuations.ToArray());

            NotificationBuilder nbuilder = new NotificationBuilder().UseHtmlRenderer();

            //Date Hierarchy (Year/Month/Day) created by Blogger, we must only provide a meaningfull subject

            string itemsAsString = string.Join(",", currentWork.Items);

            nbuilder.UseSubject(string.Format("{0} {1}", itemsAsString, Pluralize(currentWork.ItemType.ToString())));

            foreach (Task <Tuple <IEvent[], TimeSpan> > t in TaskList)
            {
                nbuilder.AddEvents(t.Result.Item1);
            }

            if (nbuilder.HasEvents == false)
            {
                console.WriteLine("Now changes found", null, null);
                return(0); //NO NOTIFICATION required!
            }
            nbuilder.AddChannels(currentWork.Channels);
            Notification noti = nbuilder.Build();

            noti.From = currentWork.From;
            noti.To   = currentWork.To;

            Postman.DeliverNotification(new Notification[] { noti });
            console.WriteLine("", null, null);
            console.WriteLine(string.Format("{0} changes delivered", nbuilder.EventCount), null, null);
            return(0);
        }
예제 #29
0
        static void Main(string[] args)
        {
            User roni   = new User("Roni", "1234567", 0);
            User maayan = new User("Maayan", "1234567", 1);
            User fibi   = new User("Fibi", "1234567", 2);
            User jack   = new User("Jack", "1234567", 3);

            //make all users players
            roni.ChangePlayerState(PlayerState.Player);
            maayan.ChangePlayerState(PlayerState.Player);
            fibi.ChangePlayerState(PlayerState.Player);
            jack.ChangePlayerState(PlayerState.Player);


            Collection <User> C1 = new Collection <User>();
            Collection <User> C2 = new Collection <User>();

            C1.Add(roni);
            C1.Add(maayan);
            C2.Add(fibi);
            C2.Add(jack);

            GameClient game1 = new GameClient(C1, GameType.Limit, 0, 10, 2, 10, true, new Chip(30));
            GameClient game2 = new GameClient(C2, GameType.Limit, 2, 10, 2, 4, true, new Chip(10));


            //make game active
            GameServer.GameCenter.Instance.ActivateGame(game1);
            GameServer.GameCenter.Instance.ActivateGame(game2);


            //register players to games notification service
            game1.Subscribe(roni);
            game1.Subscribe(maayan);
            game2.Subscribe(fibi);
            game2.Subscribe(jack);

            //gets data from server -->this function should run when server creates
            NotificationBuilder serverNotifications = new NotificationBuilder();

            serverNotifications.Notify();

            /*
             *
             * ////create data TODO:replace the data loading from manual to server////
             * PlayerNotification data1 = new PlayerNotification();
             * PlayerNotification data2 = new PlayerNotification();
             *
             * data1.AddNotification("Hello");
             * data1.AddNotification("Maayan Fold");
             * data2.AddNotification("Hello to game number 2 !!!!!");
             * data2.AddNotification("jack rasid by 10 chips are you ready to tack action?");
             *
             *
             * game1.UpdatePlayersFromServer(data1);
             * game2.UpdatePlayersFromServer(data2);
             *
             * //delete notification after update
             * data1.ClearNotifaictions();
             * data2.ClearNotifaictions();
             *
             *
             * //add roni to game 2
             * IDisposable roniChannal = game2.Subscribe(roni);
             *
             * data1.AddNotification("Hello from game 1");
             * data2.AddNotification("Hello from game 2");
             *
             * game1.UpdatePlayersFromServer(data1);
             * game2.UpdatePlayersFromServer(data2);
             *
             * //unsabscribe rony from game 2 updates
             * roniChannal.Dispose();
             *
             *
             * //sopust to notify fibi and jack witout ronny
             * game2.UpdatePlayersFromServer(data2);
             */


            while (true)
            {
                ;
            }
        }
예제 #30
0
    /// <summary>
    /// Local recurring notification. Recurring weekly once you havent touched the app in more than 7 days
    /// Also populates rate app notification
    /// </summary>
    public void ScheduleLocalNotification()
    {
                #if UNITY_IOS
        // Reset the badge icon
        UnityEngine.iOS.LocalNotification resetNotif = new UnityEngine.iOS.LocalNotification();
        resetNotif.applicationIconBadgeNumber = -1;
        resetNotif.hasAction = false;
        NotificationServices.PresentLocalNotificationNow(resetNotif);

        // Clear and cancel
        NotificationServices.ClearLocalNotifications();                                                            // Clear all received notifications
        foreach (UnityEngine.iOS.LocalNotification localNotif in NotificationServices.scheduledLocalNotifications) // Remove reminder notifications
        {
            if (localNotif.repeatInterval == UnityEngine.iOS.CalendarUnit.Week)
            {
                NotificationServices.CancelLocalNotification(localNotif);
                Debug.Log("CANCELLING RECURRING NOTIFICATIONS");
            }
        }

        // Prepare to fire new notification
        string iOSAction = "visit " + DataManager.Instance.GameData.PetInfo.PetName;            // Action (ie. slide to _)
        string iOSBody   = DataManager.Instance.GameData.PetInfo.PetName + " misses you!";

        DateTime fireDate = LgDateTime.GetTimeNow().AddDays(7);                 // Schedule for 7 days from now

        UnityEngine.iOS.LocalNotification notif = new UnityEngine.iOS.LocalNotification();
        notif.fireDate                   = fireDate;
        notif.alertAction                = iOSAction;
        notif.alertBody                  = iOSBody;
        notif.soundName                  = UnityEngine.iOS.LocalNotification.defaultSoundName;
        notif.repeatInterval             = UnityEngine.iOS.CalendarUnit.Week;
        notif.applicationIconBadgeNumber = -1;
        NotificationServices.ScheduleLocalNotification(notif);


        // Also check if we need to push the rate app notification
        // Conditions - passed day 7 retention, only seen once
        TimeSpan difference = LgDateTime.GetTimeNow().Subtract(DataManager.Instance.GameData.PlayPeriod.FirstPlayPeriod);
        if (!DataManager.Instance.GameData.PlayPeriod.IsDisplayedAppNotification &&                     // Displayed for first time
            DataManager.Instance.GameData.PlayPeriod.IsFirstPlayPeriodAux &&                            // Started first play session in
            difference > new TimeSpan(7, 0, 0, 0))                                                      // Past 7 days

        {
            UnityEngine.iOS.LocalNotification rateNotif = new UnityEngine.iOS.LocalNotification();

            // Shoot for next 8:47am
            DateTime now        = LgDateTime.GetTimeNow();
            DateTime today847am = now.Date.AddHours(8).AddMinutes(47);
            DateTime next847am  = now <= today847am ? today847am : today847am.AddDays(1);

            rateNotif.fireDate    = next847am;
            rateNotif.alertAction = "open game";
            rateNotif.alertBody   = "Is 'Wizdy Pets' helping your kids with asthma? Leave us a review in the AppStore!";
            rateNotif.soundName   = UnityEngine.iOS.LocalNotification.defaultSoundName;
            rateNotif.applicationIconBadgeNumber = -1;

            NotificationServices.ScheduleLocalNotification(rateNotif);
            DataManager.Instance.GameData.PlayPeriod.IsDisplayedAppNotification = true;
        }
#endif

#if UNITY_ANDROID && !UNITY_EDITOR
        string title = DataManager.Instance.GameData.PetInfo.PetName + " misses you!";
        string body  = "Why not stop by and visit?";

        AndroidNotifications.cancelNotification(1);
        int id = 1;
        NotificationBuilder build    = new NotificationBuilder(id, title, body);
        TimeSpan            interval = new TimeSpan(168, 0, 0);
        build.setInterval(interval);
        build.setAutoCancel(false);
        build.setDelay(interval);
        AndroidNotifications.scheduleNotification(build.build());
#endif
    }