Пример #1
0
        /// <summary>
        ///     Registers a device in Azure Notification Hub.
        /// </summary>
        /// <remarks>
        ///     This first unregisters all existing user registrations
        ///     for the specified <paramref name="userId"/>.
        /// </remarks>
        /// <param name="userId">The user to subscribe.</param>
        /// <param name="platform">The push notification platform.</param>
        /// <param name="handle">Device handle.</param>
        public virtual async Task RegisterAsync(Guid userId, PushNotificationPlatform platform, string handle)
        {
            // First clear the existing registration if it exists
            if (await _notificationRegistrationRepository.ExistsAsync(userId))
            {
                var currentRegistration = await _notificationRegistrationRepository.GetAsync(userId);

                await _notificationClient.UnregisterAsync(currentRegistration);

                await _notificationRegistrationRepository.DeleteAsync(currentRegistration.Id);
            }

            // Create new registration and assign external id
            var registration = await _notificationClient.RegisterAsync(new NotificationRegistration
            {
                Handle = handle,
                PushNotificationPlatform = platform,
                Id = userId
            });

            await _notificationRegistrationRepository.CreateAsync(registration);
        }
Пример #2
0
        /// <summary>
        ///     Notify a single user.
        /// </summary>
        /// <param name="context">The background context.</param>
        public override async Task ExecuteAsync(BackgroundTaskContext context)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var notificationContext = (NotificationContext)context.Value;

            // Check if we can reach the user that should be notified.
            if (!await _notificationRegistrationRepository.ExistsAsync(notificationContext.NotifiedUserId))
            {
                _logger.LogTrace($"Couldn't get notification registration for user {notificationContext.NotifiedUserId}");
                return;
            }

            var pushDetails = await _userRepository.GetPushDetailsAsync(notificationContext.NotifiedUserId);

            await _notificationClient.SendNotificationAsync(pushDetails, notificationContext.Notification);

            _logger.LogTrace($"Sent notification to user {notificationContext.NotifiedUserId}");
        }