コード例 #1
0
	void Awake()
	{
		_model = gameObject.GetComponent<NotificationViewModel>();
		if (_model == null)
		{
			throw new MissingComponentException();
		}

		_detailPresent = false;
		_scrollViewHeight = scrollViewWidget.height * -1;
	}
コード例 #2
0
        public async Task <ActionResult> getAdvertisements([FromBody] NotificationViewModel nv)
        {
            List <AdvertisementViewModel> ad = new List <AdvertisementViewModel>();
            var     html    = nv.url;
            HtmlWeb web     = new HtmlWeb();
            var     htmlDoc = await web.LoadFromWebAsync(html);

            var htmlNodes = htmlDoc.DocumentNode.SelectNodes("//*/div[2]/div[1]/p[1]");

            if (htmlNodes is null)  //scrapping got nothing
            {
                return(NotFound());
            }

            foreach (var node in htmlNodes)
            {
                AdvertisementViewModel a = new AdvertisementViewModel();
                var nodeParent           = node.ParentNode.ParentNode.ParentNode;
                var label = nodeParent.GetAttributeValue("aria-label", "");
                var id    = nodeParent.GetAttributeValue("id", "");
                var s     = label.Split("\n", StringSplitOptions.None);
                a.id = id;
                //a.Id = Convert.ToInt32(id.Replace("user-ad-", ""));
                a.title = s[0].Trim();
                var p = s[1].Trim().Replace("Price: ", "")
                        .Replace(" negotiable", "")
                        .Replace(".", "")
                        .Replace("$", "")
                        .Replace(",", "");
                var result = 0;
                if (Int32.TryParse(p, out result))
                {
                    a.price = result;
                }

                var s2 = s[2].Split(". Ad listed ");
                a.location = s2[0].Trim().Replace("Location: ", "");

                var result1 = DateTime.Now;
                if (DateTime.TryParseExact(s2[1].Trim().Replace(".", ""), "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result1))
                {
                    a.dateListed = result1;
                }
                a.seen = false;
                ad.Add(a);
            }
            nv.advertisement = ad.Where(s => s.price >= nv.min && s.price <= nv.max).ToList();
            return(Ok(nv));
        }
コード例 #3
0
        public async Task <object> Update(int ID)
        {
            var some     = _dbContext.NotificationDetails.FirstOrDefault(x => x.ID == ID);
            var user     = _dbContext.Users;
            var kpilevel = _dbContext.KPILevels;

            try
            {
                some.Seen = true;
                _dbContext.SaveChanges();
                //var detail = _dbContext.Notifications.FirstOrDefault(x => x.ID == some.NotificationID);

                var detail = await _dbContext.Notifications.FirstOrDefaultAsync(x => x.ID == some.NotificationID);

                var tag = await _dbContext.Tags.Where(x => x.CommentID == detail.CommentID).Select(x => x.UserID).ToListAsync();

                var listArr = string.Empty;
                if (tag.Count > 0)
                {
                    listArr = string.Join(",", user.Where(x => tag.Contains(x.ID)).Select(x => x.FullName).ToArray());;
                }
                var vm = new NotificationViewModel();
                vm.ID         = detail.ID;
                vm.Title      = detail.Title;
                vm.CreateTime = detail.CreateTime;
                vm.Link       = detail.Link;
                vm.Tag        = listArr;
                vm.Content    = detail.Content;
                vm.Sender     = user.Find(detail.UserID).FullName;
                vm.Recipient  = listArr;
                vm.Content    = detail.Content;
                vm.Title      = detail.Title;
                vm.KPIName    = detail.KPIName;
                vm.Owner      = kpilevel.FirstOrDefault(a => a.KPILevelCode == detail.KPILevelCode).Owner;
                vm.Manager    = kpilevel.FirstOrDefault(a => a.KPILevelCode == detail.KPILevelCode).OwnerManagerment;
                //vm.PIC = kpilevel.FirstOrDefault(a => a.KPILevelCode == detail.KPILevelCode).PIC;
                vm.PIC = detail.UserID;
                if (detail.ActionplanID > 0)
                {
                    vm.DueDate = _dbContext.ActionPlans.FirstOrDefault(x => x.ID == detail.ActionplanID).Deadline.ToString("MM/dd/yyyy");
                }

                return(new { status = true, data = vm });
            }
            catch (Exception)
            {
                return(new { status = false, data = "" });;
            }
        }
        public override void Up()
        {
            LogProvider.Log.Info("Preparing migration #22");

            var doMigration = false;

            App.SplashScreen.Dispatcher.Invoke(() =>
            {
                var notificationViewModel = new NotificationViewModel
                {
                    Title         = CommonResourceManager.Instance.GetResourceString("Message_Migration0022_Title"),
                    Message       = CommonResourceManager.Instance.GetResourceString("Message_Migration0022_Text"),
                    Button2Text   = CommonResourceManager.Instance.GetResourceString("Message_Migration0022_Run"),
                    Button2Action = () =>
                    {
                        doMigration = true;
                        App.SplashScreen.DataContext.CloseNotification();
                    },
                    Button3Text   = CommonResourceManager.Instance.GetResourceString("Message_Migration0022_Cancel"),
                    Button3Action = () => App.SplashScreen.DataContext.CloseNotification()
                };

                App.SplashScreen.DataContext.ShowNotification(notificationViewModel);
            });

            if (doMigration)
            {
                try
                {
                    App.SplashScreen.Dispatcher.Invoke(() =>
                    {
                        App.SplashScreen.DataContext.Status = CommonResourceManager.Instance.GetResourceString("Message_Migration0022_Status");
                    });

                    var migrator = new PlayerStatisticMaxPlayersMigrator();
                    migrator.Update();

                    LogProvider.Log.Info("Migration #22 executed.");
                }
                catch (Exception e)
                {
                    LogProvider.Log.Error(string.Empty, "Migration #22 failed.", e);
                }
            }
            else
            {
                LogProvider.Log.Info("Migration #22 has been skipped by user.");
            }
        }
コード例 #5
0
        public void NotificationViewModel_DestructionProcessAdvancesOverTime_WhenSelfDestructionEnabled() =>
        new TestScheduler().With(scheduler =>
        {
            var n   = new Notification("", "", NotificationLevel.Info, TimeSpan.FromSeconds(10));
            var sut = new NotificationViewModel(n);
            sut.Activator.Activate();

            Assert.Equal(0, sut.DestructionProcess);

            scheduler.AdvanceBy(TimeSpan.FromSeconds(5).Ticks);
            Assert.True(sut.DestructionProcess > 30 && sut.DestructionProcess < 70);

            scheduler.AdvanceBy(TimeSpan.FromSeconds(6).Ticks);
            Assert.Equal(100, sut.DestructionProcess);
        });
コード例 #6
0
        public void NotificationViewModel_InvokesCloseCommand_AfterTimeout() =>
        new TestScheduler().With(scheduler =>
        {
            bool invoked = false;

            var n   = new Notification("", "", NotificationLevel.Info, TimeSpan.FromSeconds(1));
            var sut = new NotificationViewModel(n);
            sut.Activator.Activate();
            sut.Close.Subscribe(_ => invoked = true);

            scheduler.AdvanceBy(1);
            Assert.False(invoked);
            scheduler.AdvanceBy(TimeSpan.FromSeconds(1.5).Ticks);
            Assert.True(invoked);
        });
コード例 #7
0
        public INotification ShowNotification()
        {
            var vm = new NotificationViewModel();

            if (!_settings.UI.TrayNotify)
            {
                return(vm);
            }

            _notificationStack.Add(new NotificationBalloon(vm));

            Show();

            return(vm);
        }
コード例 #8
0
 public NotificationPage()
 {
     InitializeComponent();
     try
     {
         NotificationsListView.HeightRequest = DeviceDisplay.MainDisplayInfo.Height;
         BindingContext = new NotificationViewModel(Navigation);
     }
     catch (System.Net.Http.HttpRequestException)
     {
         Device.BeginInvokeOnMainThread(async() => {
             await DisplayAlert("Alert", "No internet connection", "OK");
         });
     }
 }
コード例 #9
0
 public void GenerateLocalNotification(NotificationViewModel notificationViewModel, long triggerInSeconds)
 {
     HasBeenCalled[notificationViewModel.Type] = true;
     if (notificationViewModel.Type == NotificationsEnum.NewMessageReceived)
     {
         MessageUtils.SaveDateTimeToSecureStorageForKey(
             SecureStorageKeys.LAST_SENT_NOTIFICATION_UTC_KEY,
             SystemTime.Now(),
             "Unit test GenerateLocalNotification");
     }
     if (notificationViewModel.Type == NotificationsEnum.ReApproveConsents)
     {
         NewConsentsHasBeenCalledCount++;
     }
 }
コード例 #10
0
        private static NotificationViewModel CopyToNotificationViewModel(this Domain.Entries.Notification.Notification notification, bool reviewed)
        {
            var model = new NotificationViewModel
            {
                Id              = notification.Id.ToString(),
                Title           = notification.Title,
                Message         = notification.Message,
                LinkTitle       = notification.LinkTitle,
                Link            = notification.Link,
                Reviewed        = reviewed,
                DateTimeCreated = notification.DateTimeCreated
            };

            return(model);
        }
コード例 #11
0
        public async Task <IActionResult> Delete(int notificationId)
        {
            Notification notification = await _repository.FindAsync(notificationId);

            if (notification == null)
            {
                return(NotFound(notificationId));
            }
            NotificationViewModel notificationVM = _mapper.Map <NotificationViewModel>(notification);

            _repository.Delete(notification);
            await _unitOfWork.SaveChangesAsync();

            return(Ok(notificationVM));
        }
コード例 #12
0
        public List <NotificationOptionViewModel> Resolve(Notification source, NotificationViewModel destination, List <NotificationOptionViewModel> destMember, ResolutionContext context)
        {
            var config = BaseNotificationConfig.GetConfig(source.Type);
            var stored = JsonConvert.DeserializeObject <IList <NotificationOptionViewModel> >(source.Config)
                         .Select(v => new NotificationOptionViewModel(
                                     v.Value,
                                     v.Key,
                                     config.Options[v.Key].Label,
                                     config.Options[v.Key].Description,
                                     config.Options[v.Key].Required,
                                     config.Options[v.Key].ControlType
                                     ));

            return(stored.ToList());
        }
コード例 #13
0
        public virtual void OnLoaded(object sender, RoutedEventArgs e)
        {
            _notification            = ControlsHelper.FindResource <NotificationViewModel>("Notification");
            _libraryViewModel        = ControlsHelper.FindResource <MyLibraryViewModel>("MyLibrary");
            _notification.Visibility = true;

            Task <List <HqDownloadInfo> > .Factory.StartNew(() => {
                return(_downloadManager.GetDownloadedHqsInfo());
            }).ContinueWith((list) => {
                Dispatcher.Invoke(() => {
                    _libraryViewModel.DownloadInfos = new ObservableCollection <HqDownloadInfo>(list.Result);
                    _notification.Visibility        = false;
                });
            });
        }
コード例 #14
0
        //public void SendNotification(string eventName, object sendedObject, BroadcastType broadcastType, params string[] userNames)
        //{
        //    if (broadcastType != BroadcastType.All && (userNames == null || userNames.All(string.IsNullOrEmpty)))
        //        return;
        //    //string[] usersNames;// = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray();
        //    dynamic clients;
        //    switch (broadcastType)
        //    {
        //        case BroadcastType.All:
        //            clients = Clients.All;
        //            break;
        //        case BroadcastType.Others:
        //            clients = Clients.AllExcept(userNames);
        //            break;
        //        case BroadcastType.Users:
        //            var users = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray();
        //            if (!users.Any())
        //                return;
        //            clients = Clients.Users(users);
        //            break;
        //        default:
        //            throw new ArgumentOutOfRangeException(nameof(broadcastType), broadcastType, null);
        //    }
        //    clients.recieveNotification(eventName, sendedObject);
        //}

        //public void SendNotification(WorkEvent workEvent, BroadcastType broadcastType, params string[] userNames)
        //{
        //    if (broadcastType != BroadcastType.All && (userNames == null || userNames.All(string.IsNullOrEmpty)))
        //        return;
        //    //string[] usersNames;// = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray();
        //    dynamic clients;
        //    switch (broadcastType)
        //    {
        //        case BroadcastType.All:
        //            clients = Clients.All;
        //            break;
        //        case BroadcastType.Others:
        //            clients = Clients.AllExcept(userNames);
        //            break;
        //        case BroadcastType.Users:
        //            var users = userNames.Where(x => !string.IsNullOrEmpty(x)).ToArray();
        //            if (!users.Any())
        //                return;
        //            clients = Clients.Users(users);
        //            break;
        //        default:
        //            throw new ArgumentOutOfRangeException(nameof(broadcastType), broadcastType, null);
        //    }
        //    clients.recieveNotification(workEvent.Type.ToString().ToLower(), workEvent);
        //}

        public void SendNotifications(WorkEvent workEvent, ICollection <ApplicationUser> users)
        {
            foreach (var user in users)
            {
                var clients     = Clients.Users(new[] { user.UserName });
                var description = _eventService.GetEventDescription(workEvent, user);
                var model       = new NotificationViewModel
                {
                    Text       = description,
                    Type       = (int)workEvent.Type,
                    WorkItemId = workEvent.ObjectId.Value
                };
                clients.recieveNotification(workEvent.Type.ToString().ToLower(), model);
            }
        }
コード例 #15
0
        public static NotificationViewModel ToViewModel(this Notification model)
        {
            var dto = new NotificationViewModel();

            dto.Event2Id            = model.Event2.Id;
            dto.EventId             = model.Event.Id;
            dto.HasBeenViewed       = model.HasBeenViewed;
            dto.IsAllDay            = model.IsAllDay;
            dto.IsExpired           = model.IsExpired;
            dto.IsWatchNotification = model.IsWatchNotification;
            dto.PriorityCode        = model.PriorityCode;
            dto.UserId = model.User.Id;
            dto.Id     = model.Id;
            return(dto);
        }
コード例 #16
0
        public async Task <IActionResult> Notifications(NotificationViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var userSetting = await _userService.GetUserSettingUserIdAsync();

            _mapper.Map(model, userSetting);

            await _unitOfWork.CompleteAsync();

            return(RedirectToAction(nameof(Notifications)));
        }
コード例 #17
0
        private NotificationViewModel ToViewModel(NotificationData data)
        {
            var handler = GetHandler(data.NotificationType);

            if (handler is null)
            {
                return(null);
            }
            var notification = JsonConvert.DeserializeObject(ZipUtils.Unzip(data.Blob), handler.NotificationBlobType);
            var obj          = new NotificationViewModel {
                Id = data.Id, Created = data.Created, Seen = data.Seen
            };

            handler.FillViewModel(notification, obj);
            return(obj);
        }
コード例 #18
0
        public void NotificationViewModel_NeverSelfInvokesCloseCommand_WhenSelfDestructionIsFalse() =>
        new TestScheduler().With(scheduler =>
        {
            bool invoked = false;

            var n   = new Notification("", "", NotificationLevel.Info, null);
            var sut = new NotificationViewModel(n);

            Assert.False(sut.SelfDestructionEnabled);

            sut.Activator.Activate();
            sut.Close.Subscribe(_ => invoked = true);

            scheduler.Start();
            Assert.False(invoked);
        });
コード例 #19
0
        // GET: Notifications/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Notification notification = _notificationManager.FindById((int)id);

            if (notification == null)
            {
                return(HttpNotFound());
            }
            NotificationViewModel notificationViewModel = Mapper.Map <NotificationViewModel>(notification);

            return(View(notificationViewModel));
        }
コード例 #20
0
        /// <summary>
        /// Show a new notification to the user.
        /// </summary>
        /// <param name="notification"></param>
        public void ShowNotification(NotificationViewModel notification)
        {
            ////Visually Debug this window with the color
            ////this.Background = new SolidColorBrush(Color.FromArgb(255,255,255,255));

            // Bind Window parameters (Width, Height, and TopMost)
            this.DataContext = notification;

            // Set content on control template
            this.NotificationsControl.Content = notification;

            if (!this.IsActive)
            {
                this.Show();
            }
        }
コード例 #21
0
        public static void SendNotificationToParticularUsers(
            NotificationViewModel notification,
            UserAndOrganizationHubDto userOrg,
            IEnumerable <string> membersIds)
        {
            var notificationHub = GlobalHost.ConnectionManager.GetHubContext <NotificationHub>();

            var connectionIds = NotificationHubUsers
                                .Where(u => membersIds.Contains(u.Key.UserId) &&
                                       u.Key.OrganizationId == userOrg.OrganizationId &&
                                       u.Key.OrganizationName == userOrg.OrganizationName)
                                .SelectMany(u => u.Value.ConnectionIds)
                                .ToList();

            notificationHub.Clients.Clients(connectionIds).newNotification(notification);
        }
コード例 #22
0
        public async Task <NotificationViewModel> CreateNotification(NotificationViewModel notificationVM)
        {
            notification = new Notification
            {
                UserId  = notificationVM.UserId,
                IsRead  = notificationVM.IsRead,
                Title   = notificationVM.Title,
                Details = notificationVM.Details,
                Date    = DateTime.Now,
                Link    = notificationVM.Link
            };

            await _db.Notification.InsertOneAsync(notification);

            return(GetNotificationById(notification._id));
        }
コード例 #23
0
        public ActionResult Index()
        {
            var userName = GetCurrentUserName();
            var data     = new NotificationViewModel();

            //data.FilterByRequestType = RequestTypeBLO.Current
            //    .GetAll()
            //    .Select(x => new SelectListItem { Value = x.RequestTypeCode, Text = x.RequestTypeName })
            //    .ToList();
            //data.FilterByStatus = StatusBLO.Current
            //    .GetStatusByObject(Constants.Object.OBJECT_REQUEST)
            //    .Select(x => new SelectListItem { Value = x.StatusCode, Text = x.StatusName })
            //    .ToList();
            data.NotificationList = NotificationBLO.Current.ListNotification(userName);
            return(View(data));
        }
コード例 #24
0
ファイル: NotificationBL.cs プロジェクト: alonsodev/SSR
        public void Modificar(NotificationViewModel pNotificationViewModel)
        {
            notifications onotifications = oRepositorio.FindById(pNotificationViewModel.notification_id);

            onotifications.user_id = pNotificationViewModel.user_id;


            onotifications.user_id_modified = pNotificationViewModel.user_id_modified;
            onotifications.url     = pNotificationViewModel.url;
            onotifications.message = pNotificationViewModel.message;


            onotifications.date_modified = DateTime.Now;
            oRepositorio.Update(onotifications);
            oUnitOfWork.SaveChanges();
        }
コード例 #25
0
        public override async Task InitializeRepositoryAsync()
        {
            try
            {
                items = await publisherLookupDataService.GetPublisherLookupAsync(nameof(PublisherDetailViewModel));

                EntityCollection = items.OrderBy(p => p.DisplayMember).ToList();
            }
            catch (Exception ex)
            {
                var dialog = new NotificationViewModel("Exception", ex.Message);
                dialogService.OpenDialog(dialog);

                logger.Error("Message: {Message}\n\n Stack trace: {StackTrace}\n\n", ex.Message, ex.StackTrace);
            }
        }
コード例 #26
0
ファイル: NotificationBL.cs プロジェクト: alonsodev/SSR
        public void Agregar(NotificationViewModel pNotificationViewModel)
        {
            notifications onotifications = new notifications
            {
                notification_id = 0,
                user_id         = pNotificationViewModel.user_id,
                date_created    = DateTime.Now,
                user_id_created = pNotificationViewModel.user_id_created,
                url             = pNotificationViewModel.url,
                message         = pNotificationViewModel.message,
                notified        = false,
            };

            oRepositorio.Add(onotifications);
            oUnitOfWork.SaveChanges();
        }
コード例 #27
0
 public ResponseMessage CreateNotification([FromBody] NotificationViewModel notification)
 {
     if (ModelState.IsValid)
     {
         _notificationService.Add(notification);
         return(new ResponseMessage {
             IsSuccess = true
         });
     }
     else
     {
         return(new ResponseMessage {
             IsSuccess = false, Message = "Model is not valid"
         });
     }
 }
コード例 #28
0
ファイル: MainPage.xaml.cs プロジェクト: esspl-git/MSTnTAPP
        //For Notifiaction Tapped From Sys.Trey
        public MainPage(ShipmentModelView s)
        {
            if (!B2CConstants.tokenRequested)
            {
                _showSignin();
            }
            InitializeComponent();
            BindingContext = viewModel = new MainViewModel();

            if (s != null)
            {
                NotificationViewModel.UpdateNotifications(Constants.Notification_VM_Instance);
                MainViewModel.UpdateBadgeAttributes(viewModel, true);
                Navigation.PushAsync(new JobDetailsTabbedPage((ShipmentModelView)s));
            }
        }
コード例 #29
0
        public static List <NotificationViewModel> GetUpdates()
        {
            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDB"].ToString()))
            {
                try
                {
                    //                   SqlCommand command = new SqlCommand("SELECT TOP 10 NotificationText, dbo.Notifications.NotificationId, dbo.NotificationUsers.UserName, dbo.Notifications.CreatedDate, SeenDate, NotificationUrl,dbo.NotificationSubjects.NotificationSubjectName as NotificationSubject,dbo.NotificationSubjects.IconName as IconName FROM dbo.Notifications"
                    //+ "                                                     Left Join dbo.NotificationSubjects on dbo.Notifications.NotificationSubjectId = dbo.NotificationSubjects.NotificationSubjectId"
                    //+ "                                                     Left Join dbo.NotificationUsers on dbo.Notifications.NotificationId = dbo.NotificationUsers.NotificationId "
                    //+ "                                                     WHERE ReadDate IS NULL  AND IsNull(ExpiryDate,Getdate()) >= current_timestamp ORDER BY dbo.Notifications.NotificationId DESC", connection);

                    SqlCommand command = new SqlCommand("SELECT dbo.NotificationUsers.UserName, count(*) AS Count "
                                                        + "FROM dbo.Notifications "
                                                        + "Left Join dbo.NotificationUsers on dbo.Notifications.NotificationId = dbo.NotificationUsers.NotificationId "
                                                        + "WHERE ReadDate IS NULL AND SeenDate IS NULL  AND IsNull(ExpiryDate,Getdate()) >= current_timestamp "
                                                        + "GROUP BY dbo.NotificationUsers.UserName", connection);

                    connection.Open();

                    SqlDataReader reader = command.ExecuteReader();

                    List <NotificationViewModel> narr = new List <NotificationViewModel>();

                    while (reader.Read())
                    {
                        NotificationViewModel noti = new NotificationViewModel();
                        noti.UserName          = reader["UserName"].ToString();
                        noti.NotificationCount = (int)reader["Count"];
                        narr.Add(noti);
                    }

                    connection.Close();


                    return(narr);
                }

                catch (SqlException ex)
                {
                    return(null);
                }
                catch (Exception ex)
                {
                    return(null);
                }
            }
        }
コード例 #30
0
        //Build a NotificationsViewModel record from a Notification
        public static NotificationViewModel CreateNotificationsViewModel(ApplicationDbContext db, Notification notification)
        {
            string referenceInfo = "";

            switch (notification.NotificationType)
            {
            case NotificationTypeEnum.NewOfferReceived:
                Offer offer1 = OfferHelpers.GetOffer(db, notification.ReferenceKey);
                referenceInfo = offer1.ItemDescription + " x " + offer1.CurrentOfferQuantity.ToString();
                break;

            case NotificationTypeEnum.CounterOfferReceived:
                Offer offer2 = OfferHelpers.GetOffer(db, notification.ReferenceKey);
                referenceInfo = offer2.ItemDescription + " x " + offer2.CounterOfferQuantity.ToString();
                break;

            case NotificationTypeEnum.NewOrderReceived:
                Order order = OrderHelpers.GetOrder(db, notification.ReferenceKey);
                switch (order.ListingType)
                {
                case ListingTypeEnum.Available:
                    AvailableListing listingA = AvailableListingHelpers.GetAvailableListing(db, order.ListingId.Value);
                    referenceInfo = listingA.ItemDescription = " x " + order.OrderQuanity;
                    break;

                case ListingTypeEnum.Requirement:
                    RequiredListing listingB = RequiredListingHelpers.GetRequiredListing(db, order.ListingId.Value);
                    referenceInfo = listingB.ItemDescription = " x " + order.OrderQuanity;
                    break;
                }
                break;
            }

            //build view
            NotificationViewModel view = new NotificationViewModel()
            {
                NotificationId          = notification.NotificationId,
                NotificationType        = notification.NotificationType,
                NotificationDescription = notification.NotificationDescription,
                ReferenceInformation    = referenceInfo,
                AppUser   = AppUserHelpers.GetAppUser(db, notification.AppUserId.Value),
                ChangedOn = notification.RecordChangeOn,
                ChangedBy = AppUserHelpers.GetAppUserName(db, notification.RecordChangeBy)
            };

            return(view);
        }
        private void CreateLocalNotification(NotificationViewModel notificationViewModel, double timeIntervalTrigger)
        {
            InvokeOnMainThread(() =>
            {
                string requestID =
                    notificationViewModel.Type == NotificationsEnum.NewMessageReceived
                        ? NewMessageIdentifier
                        : NewNotificationIdentifier;
                if (notificationViewModel.Type == NotificationsEnum.TimedReminderFinished)
                {
                    requestID = notificationViewModel.Type.ToString();
                }
                // For already delivered Notifications, the existing Notification will get updated and promoted to the top
                // of the list on the Home and Lock screens and in the Notification Center if it has already been read by the user.

                UNUserNotificationCenter.Current.GetNotificationSettings(settings =>
                {
                    bool alertsAllowed = (settings.AlertSetting == UNNotificationSetting.Enabled);

                    if (alertsAllowed)
                    {
                        UNMutableNotificationContent content = new UNMutableNotificationContent
                        {
                            Title = notificationViewModel.Title,
                            Body  = notificationViewModel.Body,
                            Badge = 1
                        };

                        UNTimeIntervalNotificationTrigger trigger =
                            UNTimeIntervalNotificationTrigger.CreateTrigger(
                                timeIntervalTrigger == 0 ? _notificationDelay : timeIntervalTrigger, false);
                        UNNotificationRequest request =
                            UNNotificationRequest.FromIdentifier(requestID, content, trigger);

                        UNUserNotificationCenter.Current.AddNotificationRequest(request, err =>
                        {
                            if (err != null)
                            {
                                NSErrorException e = new NSErrorException(err);
                                LogUtils.LogException(LogSeverity.ERROR, e,
                                                      $"{nameof(iOSLocalNotificationsManager)}.{nameof(CreateLocalNotification)} failed");
                            }
                        });
                    }
                });
            });
        }
コード例 #32
0
ファイル: NotifierHub.cs プロジェクト: juvemar/PetCare
        public override Task OnConnected()
        {
            if (!Context.User.Identity.IsAuthenticated)
            {
                return base.OnConnected();
            }

            User currentUser = new User();
            var notifications = new List<Notification>();
            var recordedNotifications = new List<NotificationViewModel>();
            using (var db = new PetCareDbContext())
            {
                currentUser = db.Users.FirstOrDefault(x => x.UserName == Context.User.Identity.Name);
                if (currentUser.IsVet || currentUser.Pets.Count == 0)
                {
                    return base.OnConnected();
                }

                var room = db.Rooms.FirstOrDefault(x => x.UserId == currentUser.Id);
                if (room == null)
                {
                    db.Rooms.Add(room = new Room()
                    {
                        Name = currentUser.UserName + "Room",
                        UserId = currentUser.Id
                    });
                    db.SaveChanges();
                }

                Groups.Add(Context.ConnectionId, room.Name);

                var pets = currentUser.Pets.Where(x => x.HealthRecord != null).ToList();

                if (pets.Count == 0)
                {
                    return base.OnConnected();
                }

                var visits = pets
                    .SelectMany(x => x.HealthRecord.VetVisits)
                    .Where(x => x.DateTime.Day > DateTime.UtcNow.Day && x.DateTime.Day <= DateTime.UtcNow.AddDays(1).Day)
                    .ToList();

                foreach (var visit in visits)
                {
                    if (visit.Notification == null)
                    {
                        var viewModel = new NotificationViewModel()
                        {
                            DateTime = DateTime.UtcNow,
                            Message = string.Format(GlobalConstants.VetVisitNotificationInThreeDays, visit.Pet.Pet.Name, visit.Vet.FirstName, visit.Vet.LastName),
                            User = currentUser,
                            IsSeen = false,
                            VetVisitId = visit.Id
                        };

                        var notification = AutoMapper.Mapper.Map<NotificationViewModel, Notification>(viewModel);
                        db.Notifications.Add(notification);
                    }
                    else
                    {
                        notifications.Add(visit.Notification);
                    }

                }
                db.SaveChanges();

                recordedNotifications = notifications
                    .Where(x => x.User.Id == currentUser.Id)
                    .AsQueryable()
                    .ProjectTo<NotificationViewModel>()
                    .ToList();
            }

            var anonymous = recordedNotifications.Select(x => new
            {
                DateTime = x.DateTime,
                IsSeen = x.IsSeen,
                Message = x.Message,
                VetVisitId = x.VetVisitId
            }).ToList();

            var json = JsonConvert.SerializeObject(anonymous);
            Clients.Caller.notify(json);

            return base.OnConnected();
        }