コード例 #1
0
        private static async Task CreateAndDeleteRegistrationAsync(NotificationHubClient nhClient)
        {
            var registrationId = await nhClient.CreateRegistrationIdAsync();

            //var registrationDescr = await nhClient.CreateFcmNativeRegistrationAsync(registrationId);
            var registrationDescr = await nhClient.CreateAppleNativeRegistrationAsync(registrationId);

            //Console.WriteLine($"Created APNS registration {registrationDescr.FcmRegistrationId}");
            Console.WriteLine($"Create APNS registration {registrationDescr.RegistrationId}");

            var allRegistrations = await nhClient.GetAllRegistrationsAsync(1000);

            foreach (var regFromServer in allRegistrations)
            {
                if (regFromServer.RegistrationId == registrationDescr.RegistrationId)
                {
                    //Console.WriteLine($"Found FCM registration {registrationDescr.FcmRegistrationId}");
                    Console.WriteLine($"Found APNS registration {registrationDescr.RegistrationId}");
                    break;
                }
            }

            //commented out by code creator (next 2 lines)
            //registrationDescr = await nhClient.GetRegistrationAsync<FcmRegistrationDescription>(registrationId);
            //Console.WriteLine($"Retrieved FCM registration {registrationDescr.FcmRegistrationId}");

            await nhClient.DeleteRegistrationAsync(registrationDescr);

            //Console.WriteLine($"Deleted FCM registration {registrationDescr.FcmRegistrationId}");
            Console.WriteLine($"Deleted APNS registration {registrationDescr.RegistrationId}");
        }
コード例 #2
0
        // POST api/register
        // Cria um id de registro
        public async Task <string> Post(string handle = null)
        {
            string newRegistrationId = null;

            // ter certeza que não existe registros para esse push handle (usado para iOS e Android)
            if (handle != null)
            {
                var registrations = await hub.GetRegistrationsByChannelAsync(handle, 100);

                foreach (RegistrationDescription registration in registrations)
                {
                    if (newRegistrationId == null)
                    {
                        newRegistrationId = registration.RegistrationId;
                    }
                    else
                    {
                        await hub.DeleteRegistrationAsync(registration);
                    }
                }
            }

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

            return(newRegistrationId);
        }
コード例 #3
0
        private async Task CreateRegistrationIdAsync_CallMethod_GetRegistrationId()
        {
            LoadMockData();
            var registrationId = await _hubClient.CreateRegistrationIdAsync();

            Assert.NotNull(registrationId);
            RecordTestResults();
        }
コード例 #4
0
        public async Task <User> PostUser(User user)
        {
            var newRegistrationId = await notifications.CreateRegistrationIdAsync();

            user.PrivateKey = newRegistrationId;
            userContext.Users.Add(user);
            userContext.SaveChanges();
            return(user);
        }
コード例 #5
0
        public async Task <IHttpActionResult> Register(RegistrationRequestData registrationRequest)
        {
            var registrationId = await _notificationHubClient.CreateRegistrationIdAsync().ConfigureAwait(false);

            return(Ok(new RegistrationIdResponse()
            {
                RegistrationId = registrationId
            }));
        }
コード例 #6
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);
        }
コード例 #7
0
        private async Task <string> GetRegistrationId(string handle)
        {
            const int singleResult  = 1;
            var       registrations = await _hubClient.GetRegistrationsByChannelAsync(handle, singleResult);

            if (registrations.Any())
            {
                return(registrations.FirstOrDefault().RegistrationId);
            }

            return(await _hubClient.CreateRegistrationIdAsync());
        }
        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());
        }
コード例 #9
0
        // POST api/register
        public async Task <string> Post(string handle = null)
        {
            string newRegistrationId = null;

            if (handle == null)
            {
                return(await _hub.CreateRegistrationIdAsync());
            }
            var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100);

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

            return(newRegistrationId ?? (await _hub.CreateRegistrationIdAsync()));
        }
コード例 #10
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);
        }
コード例 #11
0
        public async Task <DeviceRegistrationReturn> Post([FromBody] DeviceRegistration input)
        {
            DeviceRegistrationReturn ret = new DeviceRegistrationReturn();

            ret.success        = true;
            ret.actionRes      = "";
            ret.RegistrationId = null;
            // string newRegistrationId = null;

            // make sure there are no existing registrations for this push handle (used for iOS and Android)
            if (input != null)
            {
                var registrations = await hub.GetRegistrationsByChannelAsync(input.channelURI, 100);


                foreach (RegistrationDescription registration in registrations)
                {
                    if (ret.RegistrationId == null)
                    {
                        ret.RegistrationId = registration.RegistrationId;
                    }
                    else
                    {
                        await hub.DeleteRegistrationAsync(registration);
                    }
                }
            }

            if (ret.RegistrationId == null)
            {
                ret.RegistrationId = await hub.CreateRegistrationIdAsync();
            }

            if (ret.RegistrationId == "" || ret.RegistrationId == null)
            {
                ret.success        = false;
                ret.actionRes      = "Something went wrong";
                ret.RegistrationId = "";
            }

            return(ret);
        }
コード例 #12
0
        public async Task <string> Upsert(PushRegistration deviceUpdate)
        {
            RegistrationDescription desc = null;

            switch (deviceUpdate.Platform)
            {
            case Platform.Windows:
                desc = new WindowsRegistrationDescription(deviceUpdate.DeviceToken);
                break;

            case Platform.iOS:
                desc = new AppleRegistrationDescription(deviceUpdate.DeviceToken);
                break;

            case Platform.Android:
                desc = new GcmRegistrationDescription(deviceUpdate.DeviceToken);
                break;

            default:
                throw new ArgumentException("Wrong PushChannel");
            }

            string registrationId = deviceUpdate.RegistrationId;

            if (string.IsNullOrEmpty(registrationId))
            {
                registrationId = await _hub.CreateRegistrationIdAsync();
            }
            desc.RegistrationId = registrationId;

            desc.Tags = new HashSet <string>(deviceUpdate.Tags);

            var registration = await _hub.CreateOrUpdateRegistrationAsync(desc);

            return(registrationId);
        }
コード例 #13
0
        /// <summary>
        /// CSV 形式でアップロードされたファイルを元に登録情報の追加、更新を行います
        /// </summary>
        public async Task <HttpResponseMessage> Post()
        {
            // マルチパート以外の場合には拒否
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // マルチパートデータを読み込む
            var provider = await Request.Content.ReadAsMultipartAsync();

            var content = provider.Contents.FirstOrDefault(p => p.Headers.ContentDisposition.Name == "\"csv\"");

            // ファイルが見つからない場合にはエラー
            if (content == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            RegistrationModel[] records;

            try
            {
                // CSV としてファイルを解析する
                var csvData = await content.ReadAsStringAsync();

                var reader = new StringReader(csvData);

                var csvReader = new CsvReader(reader);

                csvReader.Configuration.RegisterClassMap <RegistrationModelMap>();

                records = csvReader.GetRecords <RegistrationModel>().ToArray();
            }
            catch (Exception ex)
            {
                return(Failure(ex.Message));
            }

            // 予め登録済みのデータがあるかを非同期で一括取得する
            var registrations = (await Task.WhenAll(records.Where(p => !string.IsNullOrEmpty(p.RegistrationId)).Select(p => _client.GetRegistrationAsync <RegistrationDescription>(p.RegistrationId)))).Where(p => p != null).ToArray();

            long insert = 0, update = 0;

            var targets = new List <RegistrationDescription>();

            // 1 レコードごとに追加なのか、更新なのか RegistrationId の有無で処理を行う
            foreach (var record in records)
            {
                var registration = registrations.FirstOrDefault(p => p.RegistrationId == record.RegistrationId);

                if (registration == null)
                {
                    switch (record.Platform)
                    {
                    case Platforms.Windows:
                        registration = new WindowsRegistrationDescription(record.Handle);
                        break;

                    case Platforms.WindowsPhone:
                        registration = new MpnsRegistrationDescription(record.Handle);
                        break;

                    case Platforms.Apple:
                        registration = new AppleRegistrationDescription(record.Handle);
                        break;

                    case Platforms.Android:
                        registration = new GcmRegistrationDescription(record.Handle);
                        break;

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

                    registration.RegistrationId = await _client.CreateRegistrationIdAsync();

                    insert += 1;
                }
                else
                {
                    switch (record.Platform)
                    {
                    case Platforms.Windows:
                        ((WindowsRegistrationDescription)registration).ChannelUri = new Uri(record.Handle);
                        break;

                    case Platforms.WindowsPhone:
                        ((MpnsRegistrationDescription)registration).ChannelUri = new Uri(record.Handle);
                        break;

                    case Platforms.Apple:
                        ((AppleRegistrationDescription)registration).DeviceToken = record.Handle;
                        break;

                    case Platforms.Android:
                        ((GcmRegistrationDescription)registration).GcmRegistrationId = record.Handle;
                        break;

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

                    update += 1;
                }

                registration.Tags = record.Tags;

                targets.Add(registration);
            }

            try
            {
                // 処理対象を非同期で一括処理する
                await Task.WhenAll(targets.Select(p => _client.CreateOrUpdateRegistrationAsync(p)));
            }
            catch (Exception ex)
            {
                return(Failure(ex.Message));
            }

            // 処理結果を返却
            return(Success(string.Format("Imported from CSV : Insert {0}, Update {1}, Total {2}", insert, update, insert + update)));
        }
コード例 #14
0
        public async Task <IActionResult> RegisterDevice([FromBody] DeviceRegistrationModel deviceRegistration)
        {
            try
            {
                RegistrationDescription registerDescription = null;
                DeviceMobileModel       deviceModel         = null;

                switch (deviceRegistration.Platform)
                {
                case "apns":
                    registerDescription = deviceRegistration.Tags != null ?
                                          new AppleRegistrationDescription(deviceRegistration.Identifier, deviceRegistration.Tags) :
                                          new AppleRegistrationDescription(deviceRegistration.Identifier);
                    break;

                case "gcm":
                    registerDescription = deviceRegistration.Tags != null ?
                                          new GcmRegistrationDescription(deviceRegistration.Identifier, deviceRegistration.Tags) :
                                          new GcmRegistrationDescription(deviceRegistration.Identifier);
                    break;

                default:
                    throw new ArgumentException("RegisterDevice: Unsupported platform registration");
                }
                try
                {
                    string newRegistrationId = null;

                    if (deviceRegistration.Identifier != null)
                    {
                        var registrations = await _hubClient.GetRegistrationsByChannelAsync(deviceRegistration.Identifier, 100);

                        foreach (RegistrationDescription registration in registrations)
                        {
                            if (newRegistrationId == null)
                            {
                                newRegistrationId = registration.RegistrationId;
                            }
                            else
                            {
                                await _hubClient.DeleteRegistrationAsync(registration);
                            }
                        }
                    }

                    if (newRegistrationId == null)
                    {
                        newRegistrationId = await _hubClient.CreateRegistrationIdAsync();
                    }
                    registerDescription.RegistrationId = newRegistrationId;
                    RegistrationDescription output = await _hubClient.CreateOrUpdateRegistrationAsync <RegistrationDescription>(registerDescription);

                    if (output != null)
                    {
                        deviceModel = await _devicesDataManager.CreateOrUpdateDevice(
                            new DeviceMobileModel()
                        {
                            DeviceType     = "Mobile",
                            Name           = string.Concat("mobile_", deviceRegistration.Platform, "_", Guid.NewGuid()),
                            Email          = deviceRegistration.UserEmail,
                            MobileId       = deviceRegistration.Identifier,
                            Platform       = deviceRegistration.Platform,
                            RegistrationId = output.RegistrationId
                        });
                    }
                    else
                    {
                        throw new Exception(string.Format("Registration creation or update failed. MobileId: {0}", deviceRegistration.Identifier));
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                return(Ok(deviceModel));
            }
            catch (Exception e)
            {
                return(StatusCode(StatusCodes.Status502BadGateway, e.Message));
            }
        }
コード例 #15
0
 // POST api/register
 // This creates a registration id
 public async Task <string> Post()
 {
     return(await hub.CreateRegistrationIdAsync());
 }
コード例 #16
0
        public async Task <HttpResponseMessage> Post([FromBody] ProfileRequest request)
        {
            HttpResponseMessage response;

            try
            {
                var profileResponse = new ProfileResponse();

                using (DbModel.TechReadyDbContext ctx = new   DbModel.TechReadyDbContext())
                {
                    var appUser = (from c in ctx.AppUsers
                                   where
                                   c.AuthProviderName == request.AuthProvider &&
                                   c.AuthProviderUserId == request.AuthProviderUserId
                                   select c).FirstOrDefault();

                    if (appUser == null)
                    {
                        appUser = new   DbModel.AppUser();
                        ctx.AppUsers.Add(appUser);
                        appUser.RegistrationDateTime = DateTime.Now;
                    }

                    appUser.CityName = request.City.CityName;
                    appUser.Town     = request.Town;
                    if (request.Location != null)
                    {
                        appUser.Location = ConvertGeoCode(request.Location);
                    }
                    appUser.AudienceOrgID      = request.SelectedAudienceOrgType.AudienceOrgId;
                    appUser.AuthProviderName   = request.AuthProvider;
                    appUser.AuthProviderUserId = request.AuthProviderUserId;
                    appUser.Email    = request.Email;
                    appUser.FullName = request.FullName;



                    if (appUser.TechnologyTags == null)
                    {
                        appUser.TechnologyTags = new List <DbModel.PrimaryTechnology>();
                    }

                    foreach (var tech in request.SecondaryTechnologies)
                    {
                        var c = (from t in ctx.PrimaryTechnologies
                                 where t.PrimaryTechnologyID == tech.PrimaryTechnologyId
                                 select t).FirstOrDefault();
                        if (c != null)
                        {
                            if (tech.IsSelected)
                            {
                                appUser.TechnologyTags.Add(c);
                            }
                            else
                            {
                                if (
                                    appUser.TechnologyTags.FirstOrDefault(
                                        x => x.PrimaryTechnologyID == c.PrimaryTechnologyID) != null)
                                {
                                    appUser.TechnologyTags.Remove(c);
                                }
                            }
                        }
                    }
                    ctx.SaveChanges();
                    if (request.PushEnabled && !string.IsNullOrEmpty(request.PushId))
                    {
                        //Create/Update if the Platform Changes or Notifications are Enabled
                        if ((appUser.DevicePlatform != request.DevicePlatform) ||
                            (appUser.PushEnabled != request.PushEnabled) ||
                            string.IsNullOrEmpty(appUser.DeviceId) ||
                            appUser.PushId != request.PushId
                            )
                        {
                            appUser.DeviceId = await hub.CreateRegistrationIdAsync();

                            RegistrationDescription registration = null;
                            switch (request.DevicePlatform)
                            {
                            case "mpns":
                                registration = new MpnsRegistrationDescription(request.PushId);
                                break;

                            case "wns":
                                registration = new WindowsRegistrationDescription(request.PushId);
                                break;

                            case "apns":
                                registration = new AppleRegistrationDescription(request.PushId);
                                break;

                            case "gcm":
                                registration = new GcmRegistrationDescription(request.PushId);
                                break;

                            default:
                                throw new HttpResponseException(HttpStatusCode.BadRequest);
                            }
                            registration.RegistrationId = appUser.DeviceId;

                            registration.Tags =
                                new HashSet <string>(appUser.TechnologyTags.Select(x => x.PrimaryTech).ToList().Select(x => x.Replace(" ", "_")).ToList());
                            registration.Tags.Add(request.SelectedAudienceType.AudienceTypeName.Replace(" ", "_"));
                            registration.Tags.Add("userId:" + appUser.AppUserID);

                            if (appUser.FollowedEvents != null)
                            {
                                foreach (var followedEvent in appUser.FollowedEvents)
                                {
                                    registration.Tags.Add("eventId:" + followedEvent.EventID.ToString());
                                }
                            }
                            if (appUser.FollowedSpeakers != null)
                            {
                                foreach (var followedSpeaker in appUser.FollowedSpeakers)
                                {
                                    registration.Tags.Add("speakerId:" + followedSpeaker.SpeakerID.ToString());
                                }
                            }


                            await hub.CreateOrUpdateRegistrationAsync(registration);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(appUser.DeviceId))
                        {
                            await hub.DeleteRegistrationAsync(appUser.DeviceId);

                            appUser.DeviceId = null;
                        }
                    }

                    appUser.DevicePlatform = request.DevicePlatform;
                    appUser.LastAccessTime = DateTime.Now;
                    appUser.PushEnabled    = request.PushEnabled;
                    appUser.PushId         = request.PushId;

                    ctx.SaveChanges();

                    profileResponse.UserId =
                        appUser.AppUserID;
                }
                response = this.Request.CreateResponse(HttpStatusCode.OK, profileResponse);
                response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
            }
            catch (Exception ex)
            {
                HttpError myCustomError = new HttpError(ex.Message)
                {
                    { "IsSuccess", false }
                };
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, myCustomError));
            }
            return(response);
        }
コード例 #17
0
 public async Task <string> CreateRegistrationId()
 {
     return(await client.CreateRegistrationIdAsync());
 }
コード例 #18
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();
                }

                RegistrationDescription registration = null;

                switch (deviceUpdate.Platform)
                {
                case "iOS":
                    var alertTemplate = "{\"aps\":{\"alert\":\"$(message)\",\"badge\":\"#(badge)\",\"payload\":\"$(payload)\"}}";
                    registration = new AppleTemplateRegistrationDescription(deviceUpdate.Handle, alertTemplate);
                    break;

                case "Android":
                    var messageTemplate = "{\"data\":{\"title\":\"Sport\",\"message\":\"$(message)\",\"payload\":\"$(payload)\"}}";
                    registration = new GcmTemplateRegistrationDescription(deviceUpdate.Handle, messageTemplate);
                    break;

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

                registration.RegistrationId = newRegistrationId;
                registration.Tags           = new HashSet <string>(deviceUpdate.Tags);
                await _hub.CreateOrUpdateRegistrationAsync(registration);
            }
            catch (Exception ex)
            {
                throw ex.GetBaseException().Message.ToException(Request);
            }

            return(newRegistrationId);
        }
コード例 #19
0
 public async Task <string> GetRegistrationId()
 {
     return(await _hub.CreateRegistrationIdAsync());
 }