public async Task GetRegistrationsByTagAsync_CreateTwoRegistrationsWithTheSameTag_GetCreatedRegistrationsWithRequestedTag() { LoadMockData(); await DeleteAllRegistrationsAndInstallations(); var appleRegistration1 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"], new [] { "tag1" }); var appleRegistration2 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"], new[] { "tag1" }); var fcmRegistration = new FcmRegistrationDescription(_configuration["GcmDeviceToken"]); var createdAppleRegistration1 = await _hubClient.CreateRegistrationAsync(appleRegistration1); var createdAppleRegistration2 = await _hubClient.CreateRegistrationAsync(appleRegistration2); // Create a registration with another channel to make sure that SDK passes correct tag and two registrations will be returned var createdFcmRegistration = await _hubClient.CreateRegistrationAsync(fcmRegistration); var allRegistrations = await _hubClient.GetRegistrationsByTagAsync("tag1", 100); var allRegistrationIds = allRegistrations.Select(r => r.RegistrationId).ToArray(); Assert.Equal(2, allRegistrationIds.Count()); Assert.Contains(createdAppleRegistration1.RegistrationId, allRegistrationIds); Assert.Contains(createdAppleRegistration2.RegistrationId, allRegistrationIds); RecordTestResults(); }
public async Task <IHttpActionResult> Send([FromBody] Message message) { try { var registrations = await hub.GetRegistrationsByTagAsync(message.RecipientId, 100); NotificationOutcome outcome; if (registrations.Any(r => r is GcmRegistrationDescription)) { var notif = "{ \"data\" : {\"subject\":\"Message from " + message.From + "\", \"message\":\"" + message.Body + "\"}}"; outcome = await hub.SendGcmNativeNotificationAsync(notif, message.RecipientId); return(Ok(outcome)); } if (registrations.Any(r => r is AppleRegistrationDescription)) { var notif = "{ \"aps\" : {\"alert\":\"" + message.From + ":" + message.Body + "\", \"subject\":\"Message from " + message.From + "\", \"message\":\"" + message.Body + "\"}}"; outcome = await hub.SendAppleNativeNotificationAsync(notif, message.RecipientId); return(Ok(outcome)); } return(NotFound()); } catch (Exception ex) { return(InternalServerError(ex)); } }
/// <summary> /// 以tag取得或新建一個azure regId, 並刪除舊id的內容 /// </summary> /// <param name="tag"></param> /// <returns></returns> private async Task <string> getRegIdAsync(string tag = null) { string newRegistrationId = null; if (tag != null) { var registrations = await hub.GetRegistrationsByTagAsync(tag, 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); }
public async Task <HttpResponseMessage> Register(Registration registration) { // You'd also want to verify that the user in the registration is allowed to register for that tag // Get notification hubs registrations for that "username" tag. // Usually, you should get only 1, if we get more than one (for example, during development you make mistakes), delete all others // The "100" parameter just represents how many registrations to return var registrationsForUser = await hub.GetRegistrationsByTagAsync(registration.Username, 100); bool firstRegistration = true; bool existingRegistration = false; foreach (var reg in registrationsForUser) { if (firstRegistration) { // Update the registration with the incoming channel var winReg = reg as WindowsRegistrationDescription; winReg.ChannelUri = new Uri(registration.Channel); winReg.Tags = new HashSet <string> { registration.Username }; await hub.UpdateRegistrationAsync(winReg); firstRegistration = false; existingRegistration = true; } else { // Delete other registrations for that user await hub.DeleteRegistrationAsync(reg); } } // Register with the notification hub and listen to the "username" tag, if this is a new registration if (!existingRegistration) { switch (registration.Platform) { case "WindowsStore": await hub.CreateWindowsNativeRegistrationAsync(registration.Channel, new List <string> { registration.Username }); break; default: // If the platform isn't supported, return Bad Request return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, registration.Platform + " platform is not supported.")); } } return(Request.CreateResponse(HttpStatusCode.OK)); }
public async Task SendIndividual(string message, string title, string tag) { var registerations = await _notificationHubClient.GetRegistrationsByTagAsync(tag, 100); foreach ( var platform in registerations.Select(registeration => registeration.Tags.Contains("android") ? "android" : "ios")) { await Send(platform, message, title, new List <string> { tag }); } }
public async Task <RegistrationDescription> Register(Guid userId, string installationId, string deviceToken) { if (Guid.Empty == userId) { throw new ArgumentException("userId"); } // Get registrations for the current installation ID. var regsForInstId = await hubClient.GetRegistrationsByTagAsync(installationId, 100); var updated = false; var firstRegistration = true; RegistrationDescription registration = null; // Check for existing registrations. foreach (var registrationDescription in regsForInstId) { if (firstRegistration) { // Update the tags. registrationDescription.Tags = new HashSet <string>() { installationId, userId.ToString() }; var iosReg = registrationDescription as AppleRegistrationDescription; iosReg.DeviceToken = deviceToken; registration = await hubClient.UpdateRegistrationAsync(iosReg); updated = true; firstRegistration = false; } else { await hubClient.DeleteRegistrationAsync(registrationDescription); } } if (!updated) { registration = await hubClient.CreateAppleNativeRegistrationAsync(deviceToken, new string[] { installationId, userId.ToString() }); } // Send out a welcome notification. await this.Send(userId, "Thanks for registering"); return(registration); }
public Task RegisterGoogle(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_google; 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("droid")) { await hubClient.DeleteRegistrationAsync(registration); } } List <string> tags = new List <string>(); tags.Add(accountTag); tags.Add("droid"); GcmRegistrationDescription newRegistration = await hubClient.CreateGcmNativeRegistrationAsync(deviceToken, tags); if (newRegistration != null) { this.API.Direct.Accounts.UpdatePushTokenGoogle(account.account_id, newRegistration.RegistrationId); } } catch (Exception ex) { base.IFoundation.LogError(ex); } })); }
async Task DeleteRegistrationsOnHub(NotificationHubClient hub, string tag) { try { var registrations = await hub.GetRegistrationsByTagAsync(tag, 0); foreach (RegistrationDescription registration in registrations) { await hub.DeleteRegistrationAsync(registration); } } catch (Exception e) { } }
public async Task <IHttpActionResult> ModifyTags(ModifyTagsRequest modifyTagsRequest) { var uniqueUserId = User?.Identity?.Name ?? Guid.NewGuid().ToString("d");//User.Identity.Name; // modifyTagsRequest.UserId ?? Guid.NewGuid().ToString("d"); var newTags = _tagSubscriptionService.GetDefaultTags(uniqueUserId).Union(modifyTagsRequest.Tags).ToList(); var validationResponse = await _tagSubscriptionService.ValidateTags(newTags, uniqueUserId); if (!validationResponse.IsSuccess) { return(this.BuildHttpActionResult(validationResponse)); } var userHubRegistration = (await _notificationHubClient.GetRegistrationsByTagAsync(uniqueUserId, 1)).Single(); userHubRegistration.Tags = new HashSet <string>(newTags); await _notificationHubClient.UpdateRegistrationAsync(userHubRegistration); return(Ok()); }
static async void FormatMessageAndSendNotificationsAsync(NotificationHubClient hub, string message, string tag, TraceWriter log) { string messageBody = null; NotificationOutcome outcome = null; tag = "shanuka"; log.Info("started format and send notifications async method"); var registrations = await hub.GetRegistrationsByTagAsync(tag, 100); var distinctList = registrations.GroupBy(t => t.ETag).Select(s => s.First()); log.Info(distinctList.Count().ToString()); var Tags = new List <string> { tag }; string label = null; foreach (var item in distinctList) { log.Info("started for loop"); if (typeof(GcmRegistrationDescription) == item.GetType()) { messageBody = "{ \"data\" : {\"message\":" + message + "}}"; log.Info(messageBody); label = "Gcm"; outcome = await hub.SendGcmNativeNotificationAsync(messageBody, Tags); } if (typeof(AppleRegistrationDescription) == item.GetType()) { messageBody = "{ \"aps\" : {\"alert\":" + message + "}}"; log.Info(messageBody); label = "Aps"; outcome = await hub.SendAppleNativeNotificationAsync(messageBody, Tags); } if (outcome != null) { log.Info(string.Format("{0} message is {1}", label, outcome.State.ToString())); } } }
private async Task <IEnumerable <RegistrationDescription> > GetRegistrationsForTagAsync(string tagValue) { try { const int pageSize = 100; var allRegistrationDescriptions = new List <RegistrationDescription>(); string continuationToken = string.Empty; do { var registrations = await _hub.GetRegistrationsByTagAsync(tagValue, continuationToken, pageSize); allRegistrationDescriptions.AddRange(registrations); continuationToken = registrations.ContinuationToken; } while (!string.IsNullOrWhiteSpace(continuationToken)); return(allRegistrationDescriptions); } catch (MessagingException ex) { throw new PushNotificationException("Something went wrong while retrieving device registration list", ex); } }
public async Task Register(string email, int platformId, string pushRegistrationId) { try { var registrationsCollection = await _hubClient.GetRegistrationsByTagAsync(email, 100); var registrations = registrationsCollection.ToList(); if (registrations != null && registrations.Count > 0) { foreach (var register in registrations) { await _hubClient.DeleteRegistrationAsync(register); } } switch ((EPlatform)platformId) { case EPlatform.ANDROID: await _hubClient.CreateGcmNativeRegistrationAsync(pushRegistrationId, new string[] { email }); break; case EPlatform.WP: await _hubClient.CreateWindowsNativeRegistrationAsync(pushRegistrationId, new string[] { email }); break; } } catch (Exception exception) { ElmahUtils.LogToElmah(exception); } }
public async Task <RegistrationDescription> Post([FromBody] JObject registrationCall) { // Get the registration info that we need from the request. var platform = registrationCall["platform"].ToString(); var installationId = registrationCall["instId"].ToString(); var channelUri = registrationCall["channelUri"] != null ? registrationCall["channelUri"].ToString() : null; var deviceToken = registrationCall["deviceToken"] != null ? registrationCall["deviceToken"].ToString() : null; var registrationId = registrationCall["registrationId"] != null ? registrationCall["registrationId"].ToString() : null; var userName = HttpContext.Current.User.Identity.Name; // Get registrations for the current installation ID. var regsForInstId = await _hubClient.GetRegistrationsByTagAsync(installationId, 100); bool updated = false; bool firstRegistration = true; RegistrationDescription registration = null; // Check for existing registrations. foreach (var registrationDescription in regsForInstId) { if (firstRegistration) { // Update the tags. registrationDescription.Tags = new HashSet <string> { installationId, userName }; // We need to handle each platform separately. switch (platform) { case "windows": var winReg = registrationDescription as WindowsRegistrationDescription; if (winReg != null) { if (channelUri != null) { winReg.ChannelUri = new Uri(channelUri); } registration = await _hubClient.UpdateRegistrationAsync(winReg); } break; case "android": var gcmReg = registrationDescription as GcmRegistrationDescription; if (gcmReg != null) { gcmReg.GcmRegistrationId = registrationId; registration = await _hubClient.UpdateRegistrationAsync(gcmReg); } break; case "ios": var iosReg = registrationDescription as AppleRegistrationDescription; if (iosReg != null) { iosReg.DeviceToken = deviceToken; registration = await _hubClient.UpdateRegistrationAsync(iosReg); } break; } updated = true; firstRegistration = false; } else { // We shouldn't have any extra registrations; delete if we do. await _hubClient.DeleteRegistrationAsync(registrationDescription); } } // Create a new registration. if (!updated) { string template; switch (platform) { case "windows": template = @"<toast><visual><binding template=""ToastText01""><text id=""1"">$(message)</text></binding></visual></toast>"; await _hubClient.CreateWindowsTemplateRegistrationAsync(channelUri, template, new string[] { installationId, userName }); break; case "android": template = "{\"data\":{\"message\":\"$(message)\"}}"; registration = await _hubClient.CreateGcmTemplateRegistrationAsync(registrationId, template, new[] { installationId, userName }); break; case "ios": template = "{\"aps\":{\"alert\":\"$(message)\"}, \"inAppMessage\":\"$(message)\"}"; await _hubClient.CreateAppleTemplateRegistrationAsync(deviceToken, template, new string[] { installationId, userName }); break; } } // Send out a test notification. SendNotification(string.Format("Test notification for {0}", userName), userName); return(registration); }
/// <summary> /// Checks if the Azure Notification Hub is available. /// </summary> /// <remarks> /// This simply gets registrations by some arbitrary tag. /// </remarks> public async Task TestServiceAsync() => await _hubClient.GetRegistrationsByTagAsync("anytag", 0);
public static async Task <IEnumerable <RegistrationDescription> > GetRegistrationsByTagExpressionAsync(this NotificationHubClient client, string tagExpression) { // タグ式を分解して、元々のオブジェクトに戻す var andExpressions = tagExpression.Split(new[] { "&&" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray(); var tags = (from expression in andExpressions let body = expression.Trim('!', '(', ')') let orExpressions = body.Split(new[] { "||" }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToArray() let key = orExpressions[0].Split(':')[0] select new TagModel { Key = key, Values = orExpressions.Select(p => p.Substring(key.Length + 1)).ToArray(), Exclude = expression.StartsWith("!") }).ToArray(); IEnumerable <RegistrationDescription> results; // 否定が入っている場合には全件取得する必要がある if (tags.Any(p => p.Exclude)) { results = await client.GetAllRegistrationsAsync(0); } else { // フィルタリングに最低限必要なタグのみ取得する results = (await Task.WhenAll(tags.SelectMany(p => p.Values.Select(q => client.GetRegistrationsByTagAsync(p.Key + ":" + q, 0))))).SelectMany(p => p).Distinct(new RegistrationDescriptionComparer()); } // フィルタリングした結果を返す return(results.Where(p => tags.All(q => { if (q.Exclude) { return !q.Values.Any(r => p.Tags.Contains(q.Key + ":" + r)); } return q.Values.Any(r => p.Tags.Contains(q.Key + ":" + r)); }))); }