/// <summary>
        /// Gets a set of unique tags associated with the specified installation id from all the associated registrations.
        /// </summary>
        /// <param name="installationId">The installation id to get tags for.</param>
        /// <returns>A set of tags associated with the specified installation Id.  If installation id doesn't exist, set will have zero elements.</returns>
        internal virtual async Task <HashSet <string> > GetTagsAssociatedWithInstallationId(string installationId)
        {
            HashSet <string> tagsAssociatedWithInstallationId = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase);
            string           installationIdAsTag = string.Format(InstallationIdTagPlaceholder, installationId);

            string continuationToken = null;

            do
            {
                CollectionQueryResult <RegistrationDescription> registrations = await this.PushClient.GetRegistrationsByTagAsync(installationIdAsTag, continuationToken, RegistrationPageSize);

                continuationToken = registrations.ContinuationToken;
                foreach (RegistrationDescription registration in registrations)
                {
                    if (registration.Tags != null)
                    {
                        // Copy the tags
                        foreach (string tag in registration.Tags)
                        {
                            tagsAssociatedWithInstallationId.Add(tag);
                        }
                    }
                }
            }while (continuationToken != null);
            return(tagsAssociatedWithInstallationId);
        }
예제 #2
0
        public async Task <HttpResponseMessage> GetRegisteredTags()
        {
            CollectionQueryResult <RegistrationDescription> outcome = null;

            outcome = await Notifications.Instance.Hub.GetAllRegistrationsAsync(0);

            return(Request.CreateResponse(outcome));
        }
        public async Task <IActionResult> GetRegisteredDevices([FromQuery] int pageSize, string continuationToken)
        {
            try
            {
                CollectionQueryResult <RegistrationDescription> devices = string.IsNullOrEmpty(continuationToken) ?
                                                                          await _hubClient.GetAllRegistrationsAsync(pageSize) :
                                                                          await _hubClient.GetAllRegistrationsAsync(continuationToken, pageSize);

                return(Ok(devices));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status502BadGateway, e.Message));
            }
        }
예제 #4
0
        private async Task RefreshDevices()
        {
            NotificationHubClient client = NotificationHubClient.CreateClientFromConnectionString(ConnectionString, "uwpsample");
            CollectionQueryResult <RegistrationDescription> results = await client.GetAllRegistrationsAsync(0);

            var devicesList = results.Select(x => new DeviceRegistration
            {
                RegistrationId = x.RegistrationId,
                ExpirationTime = x.ExpirationTime.Value,
                Tags           = RetrieveTags(x.Tags)
            });

            devices             = new ObservableCollection <DeviceRegistration>(devicesList);
            Devices.ItemsSource = devices;
        }
예제 #5
0
        private async Task <bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient)
        {
            IPrincipal user = this.User;
            int        expectedTagsCount = 1;

            if (user.Identity != null && user.Identity.IsAuthenticated)
            {
                expectedTagsCount = 2;
            }

            string continuationToken = null;

            do
            {
                CollectionQueryResult <RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100);

                continuationToken = regsForChannel.ContinuationToken;
                foreach (RegistrationDescription reg in regsForChannel)
                {
                    RegistrationDescription registration = await nhClient.GetRegistrationAsync <RegistrationDescription>(reg.RegistrationId);

                    if (registration.Tags == null || registration.Tags.Count() < expectedTagsCount)
                    {
                        return(false);
                    }
                    if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}"))
                    {
                        return(false);
                    }

                    ClaimsIdentity identity    = user.Identity as ClaimsIdentity;
                    Claim          userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
                    string         userId      = (userIdClaim != null) ? userIdClaim.Value : string.Empty;

                    if (user.Identity != null && user.Identity.IsAuthenticated && !registration.Tags.Contains("_UserId:" + userId))
                    {
                        return(false);
                    }
                }
            } while (continuationToken != null);
            return(true);
        }
예제 #6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string hubName = req.Query["hubName"];

            var     requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            hubName = hubName ?? data?.hubName;
            if (hubName == null)
            {
                return(new BadRequestObjectResult("Please pass a Hub name on the query string or in the request body"));
            }

            var hub = NotificationHubClient.CreateClientFromConnectionString(
                Parameters.ConnectionString,
                hubName);

            CollectionQueryResult <RegistrationDescription> regs = await hub.GetAllRegistrationsAsync(0);

            var result   = "";
            var quantity = 0;

            foreach (RegistrationDescription reg in regs)
            {
                result += $"{reg.RegistrationId}";
                if (reg.Tags != null)
                {
                    result += $"-> {reg.Tags.Count} tags: {reg.Tags}";
                }
                else
                {
                    result += "-> No tags";
                }
                result += "\n";
                quantity++;
            }
            return(new OkObjectResult($"There are {quantity} registrations:\n{result}"));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);
            var     handle      = data.handle.Value;

            var connectionString = Environment.GetEnvironmentVariable("NotificationHubConnectionString", EnvironmentVariableTarget.Process);
            var hub = new NotificationHubClient(connectionString, "rfc-activity");

            CollectionQueryResult <RegistrationDescription> registrationForHandle = await hub.GetRegistrationsByChannelAsync(handle, 100);

            var enumerator = registrationForHandle.GetEnumerator();

            if (!enumerator.MoveNext())
            {
                var registration = new FcmRegistrationDescription(handle);
                await hub.CreateRegistrationAsync(registration);
            }

            return(new OkResult());
        }
예제 #8
0
        public async Task RegisterPush(PushUri pushUri)
        {
            if (String.IsNullOrWhiteSpace(pushUri.DeviceId))
            {
                return;
            }

            var hubClient = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureNotificationHub_PushUrl);
            var tagsWithHashedDeviceId = new List <string>(new string[] { string.Format("userId:{0}", pushUri.UserId),
                                                                          string.Format("platform:{0}", pushUri.PlatformType),
                                                                          string.Format("deviceId:{0}", pushUri.DeviceId.GetHashCode()) });

            if (pushUri.DepartmentId > 0)
            {
                tagsWithHashedDeviceId.Add(string.Format("departmentId:{0}", pushUri.DepartmentId));
            }

            CollectionQueryResult <RegistrationDescription> registrations = null;

            try
            {
                registrations = hubClient.GetRegistrationsByTagAsync(string.Format("deviceId:{0}", pushUri.DeviceId.GetHashCode()), 50).Result;
            }
            catch
            {
                // So this just fails, like whenever it wants. I would rather people get 2 or 3 push messages for a fire then none.
            }

            // Loop through all Azure registrations for this Hashed DeviceId and remove them
            if (registrations != null)
            {
                foreach (var registration in registrations)
                {
                    try
                    {
                        await hubClient.DeleteRegistrationAsync(registration);
                    }
                    catch (Exception ex)
                    {
                        Framework.Logging.LogException(ex);
                    }
                }
            }

            if (pushUri.PlatformType == (int)Platforms.WindowsPhone7 || pushUri.PlatformType == (int)Platforms.WindowsPhone8)
            {
                try
                {
                    var result = await hubClient.CreateMpnsNativeRegistrationAsync(pushUri.PushLocation, tagsWithHashedDeviceId.ToArray());
                }
                catch (ArgumentException ex)
                {
                    Framework.Logging.LogException(ex,
                                                   string.Format("Device Information: {0} {1} {2} {3}", tagsWithHashedDeviceId[0], tagsWithHashedDeviceId[1],
                                                                 tagsWithHashedDeviceId[2], tagsWithHashedDeviceId[3]));
                }
            }
            else if (pushUri.PlatformType == (int)Platforms.Windows8)
            {
                try
                {
                    var result = await hubClient.CreateWindowsNativeRegistrationAsync(pushUri.PushLocation, tagsWithHashedDeviceId.ToArray());
                }
                catch (ArgumentException ex)
                {
                    Framework.Logging.LogException(ex,
                                                   string.Format("Device Information: {0} {1} {2} {3}", tagsWithHashedDeviceId[0], tagsWithHashedDeviceId[1],
                                                                 tagsWithHashedDeviceId[2], tagsWithHashedDeviceId[3]));
                }
            }
            else if (pushUri.PlatformType == (int)Platforms.Android)
            {
                try
                {
                    var result = await hubClient.CreateGcmNativeRegistrationAsync(pushUri.DeviceId, tagsWithHashedDeviceId.ToArray());
                }
                catch (ArgumentException ex)
                {
                    Framework.Logging.LogException(ex,
                                                   string.Format("Device Information: {0} {1} {2} {3}", tagsWithHashedDeviceId[0], tagsWithHashedDeviceId[1],
                                                                 tagsWithHashedDeviceId[2], tagsWithHashedDeviceId[3]));
                }
            }
            else if (pushUri.PlatformType == (int)Platforms.iPad || pushUri.PlatformType == (int)Platforms.iPhone)
            {
                try
                {
                    var result = await hubClient.CreateAppleNativeRegistrationAsync(pushUri.DeviceId, tagsWithHashedDeviceId.ToArray());
                }
                catch (ArgumentException ex)
                {
                    Framework.Logging.LogException(ex,
                                                   string.Format("Device Information: {0} {1} {2} {3}", tagsWithHashedDeviceId[0], tagsWithHashedDeviceId[1],
                                                                 tagsWithHashedDeviceId[2], tagsWithHashedDeviceId[3]));
                }
            }
        }
예제 #9
0
        public async Task RegisterPush(PushUri pushUri)
        {
            if (String.IsNullOrWhiteSpace(pushUri.DeviceId))
            {
                return;
            }

            if (pushUri.UnitId.HasValue)
            {
                var hubClient = NotificationHubClient.CreateClientFromConnectionString(Config.ServiceBusConfig.AzureUnitNotificationHub_FullConnectionString, Config.ServiceBusConfig.AzureUnitNotificationHub_PushUrl);
                var unitTags  = new string[]
                {
                    string.Format("pushUriId:{0}", pushUri.PushUriId),
                    string.Format("deviceId:{0}", pushUri.DeviceId.GetHashCode()),                     // Device Id is the registration token
                    string.Format("unitId:{0}", pushUri.UnitId),
                    string.Format("uuid:{0}", pushUri.PushLocation),
                    string.Format("did:{0}", pushUri.DepartmentId)
                };

                CollectionQueryResult <RegistrationDescription> registrations = null;
                try
                {
                    registrations = await hubClient.GetRegistrationsByTagAsync(string.Format("deviceId:{0}", pushUri.DeviceId.GetHashCode()), 50);
                }
                catch
                {
                    // So this just fails, like whenever it wants. I would rather people get 2 or 3 push messages for a fire then none.
                }

                // Loop through all Azure registrations for this Hashed DeviceId and remove them
                if (registrations != null)
                {
                    foreach (var registration in registrations)
                    {
                        try
                        {
                            await hubClient.DeleteRegistrationAsync(registration);
                        }
                        catch (Exception ex)
                        {
                            Framework.Logging.LogException(ex);
                        }
                    }
                }

                if (pushUri.PlatformType == (int)Platforms.UnitWin)
                {
                    try
                    {
                        var result = await hubClient.CreateMpnsNativeRegistrationAsync(pushUri.PushLocation, unitTags);
                    }
                    catch (ArgumentException ex)
                    {
                    }
                }
                else if (pushUri.PlatformType == (int)Platforms.UnitAndroid)
                {
                    try
                    {
                        var result = await hubClient.CreateFcmNativeRegistrationAsync(pushUri.DeviceId, unitTags);
                    }
                    catch (ArgumentException ex)
                    {
                    }
                }
                else if (pushUri.PlatformType == (int)Platforms.UnitIOS)
                {
                    try
                    {
                        var result = await hubClient.CreateAppleNativeRegistrationAsync(pushUri.DeviceId, unitTags);
                    }
                    catch (ArgumentException ex)
                    {
                    }
                }
            }
        }