示例#1
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());
        }
        // 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));
        }
示例#3
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."));
            }
        }
示例#4
0
        public async Task <IDataResult <RegistrationIdDto> > CreateSubscription(CreateSubscriptionCommand command)
        {
            try
            {
                var registrationId = await this.GetRegistrationId(command.Handle);

                var registrationDescriptionResult = _registrationDescriptionFactory.Build(
                    registrationId,
                    command.Platform,
                    command.Handle,
                    command.Tags);

                if (!registrationDescriptionResult.Success)
                {
                    return(new FailedDataResult <RegistrationIdDto>(registrationDescriptionResult.Errors));
                }
                await _hubClient.CreateOrUpdateRegistrationAsync(registrationDescriptionResult.Value);

                return(new SuccessfulDataResult <RegistrationIdDto>(new RegistrationIdDto(registrationId)));
            }
            catch (Exception exception)
            {
                _logger.LogError($"{nameof(CreateSubscription)}: {exception}");
                return(new FailedDataResult <RegistrationIdDto>());
            }
        }
示例#5
0
        public async Task <IHttpActionResult> UpdateRegistration(DeviceRegistrationUpdate deviceRegistrationUpdate)
        {
            var uniqueUserId          = User?.Identity?.Name ?? Guid.NewGuid().ToString("d"); //User.Identity.Name; //Guid.NewGuid().ToString("d");
            var tagValidationResponse =
                await _tagSubscriptionService.ValidateTags(deviceRegistrationUpdate.Tags, uniqueUserId);

            if (!tagValidationResponse.IsSuccess)
            {
                return(this.BuildHttpActionResult(tagValidationResponse));
            }

            var registrationDescription =
                deviceRegistrationUpdate.Platform.Value.GetRegistrationDescription(deviceRegistrationUpdate.Handle);

            registrationDescription.RegistrationId = deviceRegistrationUpdate.Id;
            registrationDescription.Tags           = _tagSubscriptionService.GetDefaultTags(uniqueUserId);

            try
            {
                var result = await _notificationHubClient.CreateOrUpdateRegistrationAsync(registrationDescription);

                return(Ok());
            }
            catch (MessagingException e)
            {
                if (HasRegistrationIdGone(e))
                {
                    throw new HttpRequestException(HttpStatusCode.Gone.ToString());
                }

                throw;
            }
        }
示例#6
0
        public async Task <HttpResponseMessage> 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":
            //    var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
            //        "<wp:Notification xmlns:wp=\"WPNotification\">" +
            //           "<wp:Toast>" +
            //                "<wp:Text1>$(message)</wp:Text1>" +
            //           "</wp:Toast> " +
            //        "</wp:Notification>";
            //    registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            //    break;
            //case "wns":
            //    toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
            //    registration = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
            //    break;
            case "apns":
                var alertTemplate = "{\"aps\":{\"alert\":\"$(message)\"}}";
                registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                break;

            case "gcm":
                var messageTemplate = "{\"data\":{\"msg\":\"$(message)\"}}";
                registration = new FcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                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);
            if (!registration.Tags.Contains("all"))
            {
                registration.Tags.Add("all");
            }
            registration.Tags.Add("username:" + username);

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

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        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 <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);
            }
        }
示例#9
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);
        }
示例#10
0
        public async Task CreateOrUpdateRegistrationAsync_UpsertAppleNativeRegistration_GetUpsertedRegistrationBack()
        {
            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.CreateOrUpdateRegistrationAsync(createdRegistration);

            Assert.Contains("tag1", updatedRegistration.Tags);
            RecordTestResults();
        }
示例#11
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));
        }
示例#12
0
        async public Task <string> Register(DeviceRegistration registration)
        {
            if (string.IsNullOrWhiteSpace(registration.Handle))
            {
                return(null);
            }

            const string templateBodyAPNS = @"{ ""aps"" : { ""content-available"" : 1, ""alert"" : { ""title"" : ""$(title)"", ""body"" : ""$(message)"", ""badge"":""#(badge)"" } }, ""payload"" : ""$(payload)"" }";
            const string templateBodyFCM  = @"{""data"":{""title"":""$(title)"",""message"":""$(message)"",""payload"":""$(payload)""}}";

            string newRegistrationId = null;
            // make sure there are no existing registrations for this push handle (used for iOS and Android)
            var registrations = await _hub.GetRegistrationsByChannelAsync(registration.Handle, 100);

            foreach (var reg in registrations)
            {
                if (newRegistrationId == null)
                {
                    newRegistrationId = reg.RegistrationId;
                }
                else
                {
                    await _hub.DeleteRegistrationAsync(reg);
                }
            }

            if (newRegistrationId == null)
            {
                newRegistrationId = await _hub.CreateRegistrationIdAsync();
            }

            RegistrationDescription description;

            switch (registration.Platform)
            {
            case "iOS":
                registration.Handle = registration.Handle.Replace("<", "").Replace(">", "").Replace(" ", "").ToUpper();
                description         = new AppleTemplateRegistrationDescription(registration.Handle, templateBodyAPNS, registration.Tags);
                break;

            case "Android":
                description = new GcmTemplateRegistrationDescription(registration.Handle, templateBodyFCM, registration.Tags);
                break;

            default:
                return(null);
            }

            description.RegistrationId = newRegistrationId;
            var result = await _hub.CreateOrUpdateRegistrationAsync(description);

            return(result?.RegistrationId);
        }
示例#13
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 <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());
        }
示例#15
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":
                var toastTemplate = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                    "<wp:Notification xmlns:wp=\"WPNotification\">" +
                                    "<wp:Toast>" +
                                    "<wp:Text1>$(message)</wp:Text1>" +
                                    "</wp:Toast> " +
                                    "</wp:Notification>";
                registration = new MpnsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
                break;

            case "wns":
                toastTemplate = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>";
                registration  = new WindowsTemplateRegistrationDescription(deviceUpdate.Handle, toastTemplate);
                break;

            case "apns":
                var alertTemplate = "{\"aps\":{\"alert\":\"$(nameandmsg)\",\"badge\":1}}";
                registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                break;

            case "gcm":
                var messageTemplate = "{\"data\":{\"msg\":\"$(message)\",\"senderid\":\"$(userid)\",\"sender\":\"$(username)\",\"icon\":\"$(usericon)\"}}";
                registration = new GcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                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);
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
        /// <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);
        }
示例#17
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));
        }
示例#18
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());
        }
示例#19
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));
        }
示例#20
0
        public async Task <string> RegisterWithHub(DeviceRegistration deviceUpdate)
        {
            string newRegistrationId = null;

            try
            {
                //    // make sure there are no existing registrations for this push handle (used for iOS and Android)
                //    if (deviceUpdate.Handle != null)
                //    {
                //        //Azure likes to uppercase the iOS device handles for some reason - no worries tho, I only spent 2 hours tracking this down
                //        if (deviceUpdate.Platform == "iOS")
                //            deviceUpdate.Handle = deviceUpdate.Handle.ToUpper();

                //        var registrations = await _hub.GetRegistrationsByChannelAsync(deviceUpdate.Handle, 100);

                //        foreach (var reg in registrations)
                //        {
                //            if (newRegistrationId == null)
                //            {
                //                newRegistrationId = reg.RegistrationId;
                //            }
                //            else
                //            {
                //                await _hub.DeleteRegistrationAsync(reg);
                //            }
                //        }
                //    }

                if (newRegistrationId == null)
                {
                    newRegistrationId = await _hub.CreateRegistrationIdAsync();
                }

                GcmRegistrationDescription registration = new GcmRegistrationDescription(deviceUpdate.Handle, deviceUpdate.Tags);
                registration.RegistrationId = newRegistrationId;
                await _hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(newRegistrationId);
        }
示例#21
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));
        }
        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);
        }
示例#24
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));
        }
示例#25
0
        // POST: api/Register
        public async Task <IHttpActionResult> Get(string loginId, string type, string handle = null)
        {
            try
            {
                var registrations = await hub.GetRegistrationsByChannelAsync(handle, 100);

                try
                {
                    //Identify User
                    //Insert tag in DB and update notification information
                    using (var commom = new Common())
                    {
                        switch (type.ToLower())
                        {
                        case "a":
                            commom.AddUpdateAgent(loginId);
                            break;

                        case "r":
                            commom.AddUpdateRetailer(loginId);
                            break;
                        }
                    }

                    foreach (RegistrationDescription registration in registrations)
                    {
                        registration.Tags = new HashSet <string>(new string[] { loginId });
                        await hub.CreateOrUpdateRegistrationAsync(registration);
                    }
                    return(Ok("Push Notification Registration Successful"));
                }
                catch (MessagingException e)
                {
                    Common.ReturnGoneIfHubResponseIsGone(e);
                    return(Ok("Push Notification Registration Failed"));
                }
            }
            catch (Exception ex)
            {
                return(Ok("Push Notification Registration Failed. " + ex.Message));
            }
        }
示例#26
0
文件: Ntfy.cs 项目: 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);
        }
示例#27
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));
        }
示例#28
0
        public async Task <IActionResult> Put([FromRoute] string id, [FromBody] DevicecRegistration 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:
                return(BadRequest(deviceUpdate));
            }

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

            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);
            }catch (MessagingException e)
            {
                return(ReturnGoneIfHubResponseIsGone(e));
            }
            return(Ok(id));
        }
        public async Task CreateOrUpdateRegistration(string id, DeviceRegistration deviceRegistration)
        {
            RegistrationDescription registration;

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

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

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

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

            default:
                throw new ArgumentException("Platform not supported.");
            }

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

            try
            {
                await _hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (MessagingException e)
            {
                ReturnGoneIfHubResponseIsGone(e);
            }
        }
示例#30
0
        public async Task <IHttpActionResult> Register([FromBody] DeviceRegistration device)
        {
            RegistrationDescription registration = new GcmRegistrationDescription(device.Handle);

            var registrationId = await CreateRegistrationId(device.Handle);

            registration.RegistrationId = registrationId;
            registration.Tags           = new HashSet <string>()
            {
                device.Tag
            };

            try
            {
                await hub.CreateOrUpdateRegistrationAsync(registration);

                return(Ok());
            }
            catch (MessagingException ex)
            {
                return(InternalServerError(ex));
            }
        }