Ejemplo n.º 1
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pushRegistration"></param>
        /// <returns></returns>
        public async Task<string> CreateOrUpdateRegistrationAsync(PushRegistration pushRegistration)
        {
            UserRegistrationResult userRegistrationResult = await RegisterUserAsync(pushRegistration);
            if (userRegistrationResult == null)
            {
                return pushRegistration.RegistrationId;
            }

            RegistrationDescription registration = null;
            switch (pushRegistration.Platform)
            {
                case PushPlatform.APNS:
                    registration = new AppleRegistrationDescription(pushRegistration.Handle);
                    break;
                case PushPlatform.GCM:
                    registration = new GcmRegistrationDescription(pushRegistration.Handle);
                    break;
                case PushPlatform.WNS:
                    registration = new WindowsRegistrationDescription(pushRegistration.Handle);
                    break;
                default:
                    //throw new HttpResponseException(HttpStatusCode.BadRequest);
                    throw new Exception();
            }

            registration.RegistrationId = userRegistrationResult.RegistrationId;
            if (pushRegistration.Tags?.Any() ?? false)
            {
                registration.Tags = new HashSet<string>(pushRegistration.Tags);
            }

            await notificationHub.CreateOrUpdateRegistrationAsync(registration);

            return registration.RegistrationId;
        }
        // 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 "apns":
                registration = new AppleRegistrationDescription(deviceUpdate.Handle);
                break;

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

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

            registration.RegistrationId = id;

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
    // PUT api/register/5
    // This creates or updates a registration (with provided PNS handle) at the specified id
    public async void Put(string id, DeviceRegistration deviceUpdate)
    {
      // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags

      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 GcmRegistrationDescription(deviceUpdate.Handle);
          break;
        default:
          throw new HttpResponseException(HttpStatusCode.BadRequest);
      }

      registration.RegistrationId = id;
      registration.Tags = new HashSet<string>(deviceUpdate.Tags);

      try
      {
        await hub.CreateOrUpdateRegistrationAsync(registration);
      }
      catch (MessagingException e)
      {
        ReturnGoneIfHubResponseIsGone(e);
      }
    }
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<ApiResult> Put(DeviceDto 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 GcmRegistrationDescription(deviceUpdate.Handle);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = deviceUpdate.RegistrationId;
            

            // add check if user is allowed to add these tags
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);
       

           
                await _hub.CreateOrUpdateRegistrationAsync(registration);

                return SuccessApiResult(deviceUpdate.RegistrationId);
        }
Ejemplo n.º 6
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.º 7
0
        public async Task CreateRegistrationAsync_PassValidAppleNativeRegistration_GetCreatedRegistrationBack()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var registration = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);

            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.DeviceToken, createdRegistration.DeviceToken);
            RecordTestResults();
        }
Ejemplo n.º 8
0
        public async Task GetAllRegistrationsAsync_UsingTopLessThenNumberOfRegistrations_CorrectContinuationTokenIsReturnedThatAllowsToReadAllRegistrations()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var appleRegistration1 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);
            var appleRegistration2 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);
            var appleRegistration3 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);

            await _hubClient.CreateRegistrationAsync(appleRegistration1);

            await _hubClient.CreateRegistrationAsync(appleRegistration2);

            await _hubClient.CreateRegistrationAsync(appleRegistration3);

            string continuationToken  = null;
            var    allRegistrationIds = new List <string>();
            var    numberOfCalls      = 0;

            do
            {
                var registrations = await(continuationToken == null ? _hubClient.GetAllRegistrationsAsync(2) : _hubClient.GetAllRegistrationsAsync(continuationToken, 2));
                continuationToken = registrations.ContinuationToken;
                allRegistrationIds.AddRange(registrations.Select(r => r.RegistrationId));
                numberOfCalls++;
            } while (continuationToken != null);

            Assert.Equal(2, numberOfCalls);
            Assert.Equal(3, allRegistrationIds.Count);
            RecordTestResults();
        }
Ejemplo n.º 9
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();
        }
Ejemplo n.º 10
0
        public async Task <AppleRegistrationDescription> ProcessRegistration(string deviceToken)
        {
            Trace.TraceInformation("Creating Registration");
            AppleRegistrationDescription registration = await hub.CreateAppleNativeRegistrationAsync(deviceToken);

            Trace.TraceInformation("Created Registration with id '{0}'", registration.RegistrationId);
            return(registration);
        }
        public async Task <HttpStatusCode> Put(string id, DeviceRegistrationContract 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 "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

            registration.RegistrationId = id;
            registration.Tags           = new HashSet <string>(deviceUpdate.Tags);

            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);

                return(HttpStatusCode.OK);
            }
            catch (MessagingException e)
            {
                var webex = e.InnerException as WebException;

                if (webex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = (HttpWebResponse)webex.Response;

                    if (response.StatusCode == HttpStatusCode.Gone)
                    {
                        // Client will force a refresh for a new id after receiving this message.
                        return(HttpStatusCode.Gone);
                    }
                }

                return(HttpStatusCode.InternalServerError);
            }
            catch (Exception)
            {
                return(HttpStatusCode.InternalServerError);
            }
        }
        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.º 14
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.º 15
0
        // PUT api/register/5
        // This creates or updates a registration (with provided channelURI) at the specified id

        //there are two ways be registered in the notifications hub
        //1 is the device directly make the connection
        //2 the Back-end connects the device
        public async Task <HttpResponseMessage> Put(HttpRequestMessage req)
        {
            string jsonContent = await req.Content.ReadAsStringAsync();

            dynamic data = JsonConvert.DeserializeObject(jsonContent);
            RegistrationDescription registration = null;
            string platform = data.platform;
            //handle is the channel uri for the connection with the device, there are different code lines for each OS
            //Ex. var handle = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); for Windows app
            string handle = data.handle;

            switch (platform)
            {
            case "mpns":
                registration = new MpnsRegistrationDescription(handle);
                break;

            case "wns":
                registration = new WindowsRegistrationDescription(handle);
                break;

            case "apns":
                registration = new AppleRegistrationDescription(handle);
                break;

            case "gcm":
                registration = new GcmRegistrationDescription(handle);
                break;

            default:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            string id = data.id;

            registration.RegistrationId = id;
            string username = data.username;

            string[] tags = data.tags;
            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(tags);
            //username can be repeated many times due to the devices he has
            registration.Tags.Add("username:" + username);

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 16
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());
        }
Ejemplo n.º 17
0
        public async Task CreateOrUpdateRegistrationAsync_UpsertAppleNativeRegistrationWithCustomId_GetUpsertedRegistrationBack()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var registration = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);

            registration.RegistrationId = "123-234-1";

            var createdRegistration = await _hubClient.CreateOrUpdateRegistrationAsync(registration);

            Assert.Equal(registration.RegistrationId, createdRegistration.RegistrationId);
            RecordTestResults();
        }
Ejemplo n.º 18
0
        public Task RegisterApple(Guid account_id, string deviceToken)
        {
            return(Task.Run(async delegate()
            {
                try
                {
                    NotificationHubClient hubClient = this.HubClient;

                    Account account = this.API.Direct.Accounts.GetById(account_id);
                    string previousRegistrationID = account.push_ios;

                    if (!string.IsNullOrEmpty(previousRegistrationID))
                    {
                        if (await hubClient.RegistrationExistsAsync(previousRegistrationID))
                        {
                            await hubClient.DeleteRegistrationAsync(previousRegistrationID);
                        }
                    }

                    string accountTag = string.Format(PushAssumptions.TARGET_ACCOUNT_FORMAT, account_id.ToString().ToLower());

                    var registrations = await hubClient.GetRegistrationsByTagAsync(accountTag, 100);

                    foreach (RegistrationDescription registration in registrations)
                    {
                        if (registration.Tags.Contains("ios"))
                        {
                            await hubClient.DeleteRegistrationAsync(registration);
                        }
                    }

                    List <string> tags = new List <string>();
                    tags.Add(accountTag);
                    tags.Add("ios");


                    AppleRegistrationDescription newRegistration = await hubClient.CreateAppleNativeRegistrationAsync(deviceToken.Replace(" ", "").Replace("<", "").Replace(">", ""), tags);

                    if (newRegistration != null)
                    {
                        this.API.Direct.Accounts.UpdatePushTokenApple(account.account_id, newRegistration.RegistrationId);
                    }
                }
                catch (Exception ex)
                {
                    base.IFoundation.LogError(ex);
                }
            }));
        }
        public async Task <IActionResult> Post(DeviceRegistration device)
        {
            // New registration, execute cleanup
            if (device.RegistrationId == null && device.Handle != null)
            {
                var registrations = await _hub.GetRegistrationsByChannelAsync(device.Handle, 100);

                foreach (var registration in registrations)
                {
                    await _hub.DeleteRegistrationAsync(registration);
                }

                device.RegistrationId = await _hub.CreateRegistrationIdAsync();
            }

            // ready to registration
            // ...

            RegistrationDescription deviceRegistration = null;

            switch (device.Platform)
            {
            // ...
            case "apns":
                deviceRegistration = new AppleRegistrationDescription(device.Handle);
                break;
                //...
            }

            deviceRegistration.RegistrationId = device.RegistrationId;

            deviceRegistration.Tags = new HashSet <string>(device.Tags);

            // Get the user email depending on the current identity provider
            deviceRegistration.Tags.Add($"username:{GetCurrentUser()}");

            await _hub.CreateOrUpdateRegistrationAsync(deviceRegistration);

            var deviceInstallation = new Installation();

            // ... populate fields
            deviceInstallation.Templates = new Dictionary <string, InstallationTemplate>();
            deviceInstallation.Templates.Add("type:Welcome", new InstallationTemplate
            {
                Body = "{\"aps\": {\"alert\" : \"Hi ${FullName} welcome to Auctions!\" }}"
            });

            return(Ok());
        }
Ejemplo n.º 20
0
        public async Task DeleteRegistrationsByChannelAsync_DeleteAppleNativeRegistrationByChannel_RegistrationIsDeleted()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var registration = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);

            var createdRegistration = await _hubClient.CreateRegistrationAsync(registration);

            await _hubClient.DeleteRegistrationsByChannelAsync(_configuration["AppleDeviceToken"]);

            await Assert.ThrowsAsync <MessagingEntityNotFoundException>(async() => await _hubClient.GetRegistrationAsync <AppleRegistrationDescription>(createdRegistration.RegistrationId));

            RecordTestResults();
        }
        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")));
            }
        }
        /// <summary>
        /// register device as an asynchronous operation.
        /// </summary>
        /// <param name="deviceUpdate">The device update.</param>
        /// <param name="registrationId">The registration identifier.</param>
        /// <returns>The Task&lt;System.Boolean&gt;.</returns>
        private async Task <bool> RegisterDeviceAsync(DeviceInfo deviceUpdate, string registrationId)
        {
            bool?isRegistrationIdExpired = false;
            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 "gcm":
                registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

            registration.RegistrationId = registrationId;

            // the tags can be from the device or from the backEnd storage, it depends from the application requirements
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);

            try
            {
                await _notificationHubClient.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException messagingException)
            {
                isRegistrationIdExpired = IsRegistrationIdExpired(messagingException);
                if (isRegistrationIdExpired == null)
                {
                    throw;
                }
            }

            return(isRegistrationIdExpired.Value);
        }
Ejemplo n.º 23
0
        // PUT api/register/5
        // This creates or updates a registration (with provided PNS handle) at the specified id
        public async Task <IHttpActionResult> Put(string id, DeviceRegistration deviceUpdate)
        {
            // IMPORTANT: add logic to make sure that caller is allowed to register for the provided tags

            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 GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

            registration.RegistrationId = id;

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

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

            return(Ok());
        }
Ejemplo n.º 24
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;

            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 GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

            registration.RegistrationId = id;
            var username = deviceUpdate.UserId;

            registration.Tags = new HashSet <string>(deviceUpdate.Tags)
            {
                "username:" + username
            };

            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);
                await SetPnsToUser(deviceUpdate.UserId, deviceUpdate.Platform);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        public async Task RegisterDeviceTags(UserDevice deviceUpdate, string[] tags)
        {
        
            try
            {
                RegistrationDescription registration = null;
                switch (deviceUpdate.Platform)
                {
                    case "mpns":
                        registration = new MpnsRegistrationDescription(deviceUpdate.PushToken);
                        break;
                    case "wns":
                        registration = new WindowsRegistrationDescription(deviceUpdate.PushToken);
                        break;
                    case "apns":
                        registration = new AppleRegistrationDescription(deviceUpdate.PushToken);
                        break;
                    case "gcm":
                        registration = new GcmRegistrationDescription(deviceUpdate.PushToken);
                        break;
                    default:
                        throw new Exception("Unrecognized platform.");
                }

                registration.RegistrationId = deviceUpdate.RegistrationId;
                registration.Tags = new HashSet<string>(tags);
                // Add an extra tag for the platform, in case we want to send
                // to all users on that platform.
                registration.Tags.Add("Reop:" + deviceUpdate.Platform);
                try
                {
                    await Hub.CreateOrUpdateRegistrationAsync(registration);
                }
                catch (MessagingException e)
                {
                    ReturnGoneIfHubResponseIsGone(e);
                    throw e;
                }

                return;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 26
0
        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 GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

            registration.RegistrationId = id;
            var identity = (ClaimsIdentity)User.Identity;
            var email    = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email).Value;

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

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        // 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,string userid) //ADDED STRING USERID
        {
            ApiServices.Log.Info("user id in put request: " + userid + "\t Time: " + DateTime.Now);
            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 GcmRegistrationDescription(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
            ApiServices.Log.Info("username = "******"\t Time: " + DateTime.Now);
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);
            registration.Tags.Add("username:"******"in the try for creating registration\t Time: " + DateTime.Now);
                
                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ApiServices.Log.Error("in the catch\t Time: " + DateTime.Now);
               
                ReturnGoneIfHubResponseIsGone(e);
            }
 
            return Request.CreateResponse(HttpStatusCode.OK);
        }
Ejemplo n.º 28
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 = 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:
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

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

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

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

            return(Ok());
        }
        // PUT api/register/5
        // Cria ou atualiza um registron (com o channelURI fornecido) no para 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 GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

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

            // incluir validação se o usuário pode adicionar essas tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);
            registration.Tags.Add("username:" + username);

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
Ejemplo n.º 30
0
        public async Task UpdateRegistrationAsync_UpdateAppleNativeRegistration_GetUpdatedRegistrationBack()
        {
            LoadMockData();
            await DeleteAllRegistrationsAndInstallations();

            var registration = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]);

            var createdRegistration = await _hubClient.CreateRegistrationAsync(registration);

            createdRegistration.Tags = new HashSet <string>()
            {
                "tag1"
            };

            var updatedRegistration = await _hubClient.UpdateRegistrationAsync(createdRegistration);

            Assert.Contains("tag1", updatedRegistration.Tags);
            RecordTestResults();
        }
        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.º 32
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.º 33
0
Archivo: Ntfy.cs Proyecto: jimliuxyz/UW
        /// <summary>
        /// 以userId更新其裝置PNS的資訊
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="pns"></param>
        /// <param name="pnsToken"></param>
        /// <returns></returns>
        public async Task <string> updateRegId(string userId, PNS pns, string pnsToken)
        {
            string tag = getUserTag(userId);

            //取得或新建azure regId
            string regId = await getRegIdAsync(tag);

            //依pns類型建立註冊描述
            RegistrationDescription registration = null;

            switch (pns)
            {
            case PNS.apns:
                registration = new AppleRegistrationDescription(pnsToken);
                break;

            case PNS.gcm:
                registration = new GcmRegistrationDescription(pnsToken);
                break;

            default:
                break;
            }

            try
            {
                //填入內容並更新到azure notification hub
                registration.RegistrationId = regId;
                registration.Tags           = new HashSet <string>();
                registration.Tags.Add(D.NTFTAG.EVERYBODY);
                registration.Tags.Add(tag);

                await hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                Console.WriteLine(e.ToString());
                return(null);
            }

            return(registration.RegistrationId);
        }
Ejemplo n.º 34
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();
        }
Ejemplo n.º 35
0
        // PUT api/put/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 GcmRegistrationDescription(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);
            registration.Tags.Add("username:" + username);

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

            return Request.CreateResponse(HttpStatusCode.OK);
        }
Ejemplo n.º 36
0
        public async Task <ApiResult> Put(DeviceDto 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 GcmRegistrationDescription(deviceUpdate.Handle);
                break;

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

            registration.RegistrationId = deviceUpdate.RegistrationId;


            // add check if user is allowed to add these tags
            registration.Tags = new HashSet <string>(deviceUpdate.Tags);



            await _hub.CreateOrUpdateRegistrationAsync(registration);

            return(SuccessApiResult(deviceUpdate.RegistrationId));
        }
        public async Task<HttpStatusCode> Put(string id, DeviceRegistrationContract 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 "gcm":
                    registration = new GcmRegistrationDescription(deviceUpdate.Handle);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = id;
            registration.Tags = new HashSet<string>(deviceUpdate.Tags);

            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);
                return HttpStatusCode.OK;
            }
            catch (MessagingException e)
            {
                var webex = e.InnerException as WebException;

                if (webex.Status == WebExceptionStatus.ProtocolError)
                {
                    var response = (HttpWebResponse)webex.Response;

                    if (response.StatusCode == HttpStatusCode.Gone)
                    {
                        // Client will force a refresh for a new id after receiving this message.
                        return HttpStatusCode.Gone;
                    }
                }

                return HttpStatusCode.InternalServerError;
            }
            catch (Exception)
            {
                return HttpStatusCode.InternalServerError;
            }
        }
Ejemplo n.º 38
0
        public async Task<HttpResponseMessage> Put([FromBody]DeviceRegistration deviceUpdate)
        {
            RegistrationDescription registration = null;
            switch (deviceUpdate.platform.ToLower())
            {
                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 GcmRegistrationDescription(deviceUpdate.handle);
                    break;
                default:
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            registration.RegistrationId = deviceUpdate.deviceid;
            registration.Tags = new HashSet<string>(deviceUpdate.tags);
            // optionally you could supplement/override the list of client supplied tags here
            // tags will help you target specific devices or groups of devices depending on your needs

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

            return Request.CreateResponse(HttpStatusCode.OK);
        }