Ejemplo n.º 1
0
        public async Task CreateRegistrationAsync_PassValidGcmNativeRegistration_GetCreatedRegistrationBack()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var registration = new FcmRegistrationDescription(_configuration["GcmDeviceToken"]);

            registration.PushVariables = new Dictionary <string, string>()
            {
                { "var1", "value1" }
            };
            registration.Tags = new HashSet <string>()
            {
                "tag1"
            };

            var createdRegistration = await _hubClient.CreateRegistrationAsync(registration);

            Assert.NotNull(createdRegistration.RegistrationId);
            Assert.NotNull(createdRegistration.ETag);
            Assert.NotNull(createdRegistration.ExpirationTime);
            Assert.Contains(new KeyValuePair <string, string>("var1", "value1"), createdRegistration.PushVariables);
            Assert.Contains("tag1", createdRegistration.Tags);
            Assert.Equal(registration.FcmRegistrationId, createdRegistration.FcmRegistrationId);
            RecordTestResults();
        }
Ejemplo n.º 2
0
        public async Task Register(MobilePlatform platform, string handle, string registrationId, IEnumerable <string> tags)
        {
            var hub = _factory.NotificationHubClient;
            RegistrationDescription registration = null;

            switch (platform)
            {
            case MobilePlatform.Windows:
                registration = new WindowsRegistrationDescription(handle);
                break;

            case MobilePlatform.Apple:
                registration = new AppleRegistrationDescription(handle);
                break;

            case MobilePlatform.Android:
                registration = new FcmRegistrationDescription(handle);
                break;
            }

            registration.RegistrationId = registrationId;
            registration.Tags           = new HashSet <string>(tags ?? Enumerable.Empty <string>());

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException exception)
            {
                _logger.LogError(exception, "Unhandled exception was thrown during registration in Azure Notification Hub");
                throw;
            }
        }
Ejemplo n.º 3
0
        public async Task <IHttpActionResult> GetUpdateRegistration(string id, string platform, string token)
        {
            RegistrationDescription registration = null;

            switch (platform)
            {
            case "fcm":
                registration = new FcmRegistrationDescription(token);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;

            try
            {
                var dd = await _hubClient.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
Ejemplo n.º 4
0
        ///
        /// <summary>
        /// Register device to receive push notifications.
        /// Registration ID ontained from Azure Notification Hub has to be provided
        /// Then basing on platform (Android, iOS or Windows) specific
        /// handle (token) obtained from Push Notification Service has to be provided
        /// </summary>
        /// <param name="id"></param>
        /// <param name="deviceUpdate"></param>
        /// <returns></returns>
        public async Task <HubResponse> RegisterForPushNotifications(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registrationDescription = null;

            switch (deviceUpdate.Platform)
            {
            case MobilePlatform.ApplePushNotificationsService:
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case MobilePlatform.GoogleCloudMessaging:
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(new HubResponse().AddErrorMessage("Please provide correct platform notification service name."));
            }

            registrationDescription.RegistrationId = id;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                await _hubClient.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(new HubResponse());
            }
            catch (MessagingException)
            {
                return(new HubResponse().AddErrorMessage("Registration failed because of HttpStatusCode.Gone. PLease register once again."));
            }
        }
Ejemplo n.º 5
0
        public async Task GetRegistrationsByTagAsync_CreateTwoRegistrationsWithTheSameTag_GetCreatedRegistrationsWithRequestedTag()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var appleRegistration1 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"], new [] { "tag1" });
            var appleRegistration2 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"], new[] { "tag1" });
            var fcmRegistration    = new FcmRegistrationDescription(_configuration["GcmDeviceToken"]);

            var createdAppleRegistration1 = await _hubClient.CreateRegistrationAsync(appleRegistration1);

            var createdAppleRegistration2 = await _hubClient.CreateRegistrationAsync(appleRegistration2);

            // Create a registration with another channel to make sure that SDK passes correct tag and two registrations will be returned
            var createdFcmRegistration = await _hubClient.CreateRegistrationAsync(fcmRegistration);

            var allRegistrations = await _hubClient.GetRegistrationsByTagAsync("tag1", 100);

            var allRegistrationIds = allRegistrations.Select(r => r.RegistrationId).ToArray();

            Assert.Equal(2, allRegistrationIds.Count());
            Assert.Contains(createdAppleRegistration1.RegistrationId, allRegistrationIds);
            Assert.Contains(createdAppleRegistration2.RegistrationId, allRegistrationIds);
            RecordTestResults();
        }
        public async Task <UpdateRegistrationResponseModel> UpdateHubRegistration(string handle, PlatFormId platform, string registrationId, string userName)
        {
            RegistrationDescription registration;

            switch (platform)
            {
            case PlatFormId.MicrosoftPushNotificationService:
                registration = new MpnsRegistrationDescription(handle);
                break;

            case PlatFormId.WindowsPushNotificationService:
                registration = new WindowsRegistrationDescription(handle);
                break;

            case PlatFormId.ApplePushNotificationService:
                registration = new AppleRegistrationDescription(handle);
                break;

            case PlatFormId.FirebaseCloudMessaging:
                registration = new FcmRegistrationDescription(handle);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(platform));
            }

            registration.RegistrationId = registrationId;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>();
            registration.Tags.Add("username:" + userName);

            try
            {
                var hub = _hubClientFactory.Primary;
                var registrationDescription = await hub.CreateOrUpdateRegistrationAsync(registration);

                return(new UpdateRegistrationResponseModel
                {
                    RegistrationId = registrationDescription.RegistrationId
                });
            }
            catch (MessagingException e)
            {
                var webex = e.InnerException as WebException;
                if (webex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = (HttpWebResponse)webex.Response;
                    if (response.StatusCode == HttpStatusCode.Gone)
                    {
                        return(null);
                    }
                }

                throw;
            }
        }
        public async Task <bool> RegisterForPushNotifications(string id, DeviceRegistration deviceUpdate, UserManager <IdentityUser> userManager, ApplicationDbContext context)
        {
            RegistrationDescription registrationDescription = null;
            int deviceType = 0;

            switch (deviceUpdate.Platform)
            {
            case "apns":
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                deviceType = DeviceType.IOS;
                break;

            case "fcm":
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                deviceType = DeviceType.ANDROID;
                break;
            }

            registrationDescription.RegistrationId = id;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                var user = await userManager.FindByNameAsync(deviceUpdate.Tags[0].Split(":")[1]);

                if (!context.UserClaims.Any(x => x.UserId == user.Id && x.ClaimType == "PushNotificationsProvider"))
                {
                    IdentityUserClaim <string> claim = new IdentityUserClaim <string>()
                    {
                        UserId     = user.Id,
                        ClaimType  = "PushNotificationsProvider",
                        ClaimValue = deviceType.ToString()
                    };
                    context.Add(claim);
                }
                else
                {
                    var existingClaim = context.UserClaims.Single(x => x.UserId == user.Id && x.ClaimType == "PushNotificationsProvider");
                    existingClaim.ClaimValue = deviceType.ToString();
                    context.Update(existingClaim);
                }

                context.SaveChanges();

                await _hub.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 8
0
        public static async Task <FcmRegistrationDescription> RegistDeviceAsync(NotificationHubClient _hub, string deviceToken, string[] tags, string regId)
        {
            var registration = new FcmRegistrationDescription(regId);

            registration.RegistrationId = deviceToken;
            registration.Tags           = new HashSet <string>(tags);
            var ret = await _hub.CreateOrUpdateRegistrationAsync(registration);

            return(ret);
        }
Ejemplo n.º 9
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task <IActionResult> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;
            var username = HttpContext.User.Identity.Name;
            var nickname = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "nickname")?.Value;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("username:"******"nickname:" + nickname);

            try
            {
                var hub = _hubClientFactory.Primary;
                var registrationDescription = await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                var webex = e.InnerException as WebException;
                if (webex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = (HttpWebResponse)webex.Response;
                    if (response.StatusCode == HttpStatusCode.Gone)
                    {
                        return(StatusCode((int)HttpStatusCode.Gone));
                    }
                }
            }

            return(Ok());
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Put(string id, [FromBody] DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;

            var username = User.GetEmail();
            var userId   = User.GetUserId();

            if (string.IsNullOrEmpty(username))
            {
                return(Unauthorized());
            }

            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            // registration.Tags.Add("email:" + username.ToUpper());
            // registration.Tags.Add("userid:" + userId);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok());
        }
        public async Task <ApiResponse> RegisterForPushNotifications(string registrationId, DeviceRegistration deviceUpdate)
        {
            var hub = _notificationHubFactory.NotificationHubClient;
            RegistrationDescription registrationDescription = null;

            switch (deviceUpdate.Platform)
            {
            case MobilePlatform.wns:
                registrationDescription = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case MobilePlatform.apns:
                registrationDescription = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case MobilePlatform.fcm:
                registrationDescription = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(new ApiResponse()
                       .SetAsFailureResponse(new Core.Exceptions.Error("Cannot register for push notifications",
                                                                       "Please provide correct platform notification service name")));
            }

            registrationDescription.RegistrationId = registrationId;
            if (deviceUpdate.Tags != null)
            {
                registrationDescription.Tags = new HashSet <string>(deviceUpdate.Tags);
            }

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(new ApiResponse());
            }
            catch (MessagingException exception)
            {
                Log.Error("Unhandled exception was thrown during registration in the Azure Notification Hub:");
                Log.Error(exception.Message);
                Log.Error(exception.StackTrace);

                return(new ApiResponse()
                       .SetAsFailureResponse(new Core.Exceptions.Error("Cannot register for push notifications",
                                                                       "Registration failed because of HttpStatusCode.Gone. Please register once again")));
            }
        }
Ejemplo n.º 12
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id
        public async Task <HttpResponseMessage> Put(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "gcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            var username = HttpContext.Current.User.Identity.Name;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags)
            {
                "username:" + username
            };

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 13
0
        public async Task registerForTagsAsync(List <string> tags, string token)
        {
            try {
                var channel = new NotificationChannel(Constants.NotificationHubName, "FCM Notifications", NotificationImportance.Default);

                var notificationManager = (NotificationManager)GetSystemService(Android.Content.Context.NotificationService);
                notificationManager.CreateNotificationChannel(channel);
            }catch (Exception eeer) {
                Console.WriteLine(eeer);
            }


            return;

            NotificationHubClient hubub;

            try {
                hubub = NotificationHubClient.CreateClientFromConnectionString(Constants.ListenConnectionString, Constants.NotificationHubName, true);
            }catch (Exception err) {
                Console.WriteLine(err);
                return;
            }
            //
            string regID = "";

            try {
                regID = await hubub.CreateRegistrationIdAsync();
            }
            catch (Exception err) {
                Console.WriteLine(err);
                return;
            }
            FcmRegistrationDescription desc = new FcmRegistrationDescription(regID);

            Console.WriteLine(desc.Tags);
            desc.Tags.Add("Alert");
            try {
                await hubub.UpdateRegistrationAsync(desc);
            }catch (Exception err) {
                Console.WriteLine(err);
            }

            // var pushChannel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
            //SendRegistrationToServer(token);
        }
        public async Task <EbNFRegisterResponse> Register(string id, DeviceRegistration device)
        {
            EbNFRegisterResponse nFResponse = new EbNFRegisterResponse();

            try
            {
                RegistrationDescription registrationDescription;

                switch (device.Platform)
                {
                case PNSPlatforms.WNS:
                    registrationDescription = new WindowsRegistrationDescription(device.Handle);
                    break;

                case PNSPlatforms.APNS:
                    registrationDescription = new AppleRegistrationDescription(device.Handle);
                    break;

                case PNSPlatforms.GCM:
                    registrationDescription = new FcmRegistrationDescription(device.Handle);
                    break;

                default:
                    nFResponse.Message = "Please provide correct platform notification service name.";
                    return(nFResponse);
                }

                registrationDescription.RegistrationId = id;
                registrationDescription.Tags           = new HashSet <string>(device.Tags);

                await client.CreateOrUpdateRegistrationAsync(registrationDescription);

                nFResponse.Status  = true;
                nFResponse.Message = "Success";
            }
            catch (MessagingException)
            {
                nFResponse.Status  = false;
                nFResponse.Message = "Registration failed because of HttpStatusCode.Gone. PLease register once again.";
            }

            return(nFResponse);
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> RegisterDevice(string id, DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;

            switch (deviceUpdate.Platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(deviceUpdate.Handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

            case "fcm":
                registration = new FcmRegistrationDescription(deviceUpdate.Handle);
                break;

            default:
                return(BadRequest());
            }

            registration.RegistrationId = id;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("rider:" + deviceUpdate.riderName);

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Ok(registration));
        }
Ejemplo n.º 16
0
        public async Task GetAllRegistrationsAsync_CreateTwoRegistrations_GetAllCreatedRegistrations()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var appleRegistration = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);
            var fcmRegistration   = new FcmRegistrationDescription(_configuration["GcmDeviceToken"]);

            var createdAppleRegistration = await _hubClient.CreateRegistrationAsync(appleRegistration);

            var createdFcmRegistration = await _hubClient.CreateRegistrationAsync(fcmRegistration);

            var allRegistrations = await _hubClient.GetAllRegistrationsAsync(100);

            var allRegistrationIds = allRegistrations.Select(r => r.RegistrationId).ToArray();

            Assert.Equal(2, allRegistrationIds.Count());
            Assert.Contains(createdAppleRegistration.RegistrationId, allRegistrationIds);
            Assert.Contains(createdFcmRegistration.RegistrationId, allRegistrationIds);
            RecordTestResults();
        }
        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());
        }