public async Task GetRegistrationsByChannelAsync_CreateTwoRegistrationsWithTheSameChannel_GetCreatedRegistrationsWithRequestedChannel() { LoadMockData(); await DeleteAllRegistrationsAndInstallations(); var appleRegistration1 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]); var appleRegistration2 = new AppleRegistrationDescription(_configuration["AppleDeviceToken"]); 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 channel and two registrations will be returned var createdFcmRegistration = await _hubClient.CreateRegistrationAsync(fcmRegistration); var allRegistrations = await _hubClient.GetRegistrationsByChannelAsync(_configuration["AppleDeviceToken"], 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(); }
// POST api/register // This creates a registration id public async Task <string> Post(string handle = null) { string newRegistrationId = null; // This is requied - to make uniform handle format, otherwise could have some issue. handle = handle.ToUpper(); // make sure there are no existing registrations for this push handle (used for iOS and 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); }
public async Task <RegistrationResponse> CreateRegistration(string handle) { RegistrationResponse response = new RegistrationResponse(); string newRegistrationId = null; // make sure there are no existing registrations for this push handle (used for iOS and 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(); } response.RegistrationId = newRegistrationId; response.IsSuccess = true; return(response); }
public async Task <string> Post([FromUri] string handle) { string notificationRegistrationId = null; // Make sure there are no existing registrations for this push handle (used for iOS and Android) if (handle != null) { var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100); foreach (var registration in registrations) { if (notificationRegistrationId == null) { notificationRegistrationId = registration.RegistrationId; } else { await _hub.DeleteRegistrationAsync(registration); } } } if (notificationRegistrationId == null) { notificationRegistrationId = await _hub.CreateRegistrationIdAsync(); } return(notificationRegistrationId); }
// 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); }
public async Task <IActionResult> RegisterDevice(string handle) { string newRegistrationId = null; 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(Ok(newRegistrationId)); }
public async Task <IHttpActionResult> GetRegistrationId(string pns_FCM_Token = null) { string newRegistrationId = null; if (pns_FCM_Token != null) { var registrations = await _hubClient.GetRegistrationsByChannelAsync(pns_FCM_Token, 10); foreach (RegistrationDescription registration in registrations) { if (newRegistrationId == null) { newRegistrationId = registration.RegistrationId; } else { await _hubClient.DeleteRegistrationAsync(registration); } } } if (newRegistrationId == null) { newRegistrationId = await _hubClient.CreateRegistrationIdAsync(); } return(Ok(newRegistrationId)); }
public static async Task <string> GetRegistrationIdAsync(NotificationHubClient _hub, string deviceToken = null) { string newRegistrationId = null; if (deviceToken != null) { var registrations = await _hub.GetRegistrationsByChannelAsync(deviceToken, 50); 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); }
//POST api/register //this creates a registration id public async Task <string> Post(string handle = null) { string newRegistrationId = null; if (handle != null) { var registrations = await hub.GetRegistrationsByChannelAsync(handle, 100); foreach (var registration in registrations) { if (newRegistrationId == null) { newRegistrationId = registration.RegistrationId; } else { await hub.DeleteRegistrationAsync(registration); } } } if (newRegistrationId == null) { newRegistrationId = await hub.CreateRegistrationIdAsync(); } return(newRegistrationId); }
private async Task <Response <string> > GetRegistrationIdForDeviceAsync(string handle) { Response <string> response = new Response <string>(); try { if (!string.IsNullOrEmpty(handle)) { var registrations = await hub.GetRegistrationsByChannelAsync(handle, 100); foreach (RegistrationDescription registration in registrations) { if (response.Value == null) { response.Value = registration.RegistrationId; } else { await hub.DeleteRegistrationAsync(registration); } } } if (response.Value == null) { response.Value = await hub.CreateRegistrationIdAsync(); } } catch (Exception ex) { response.IsSuccess = false; response.Message = Constants.GENERIC_ERROR_MESSAGE + ex.Message; } return(response); }
public async Task <string> Post(string handle = null) { string newRegistrationId = null; // make sure there are no existing registrations for this push handle (used for iOS and 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); }
// POST api/register // This creates a registration id public async Task <string> Post() { string value = await Request.Content.ReadAsStringAsync(); var entidad = System.Web.Helpers.Json.Decode(value); string handle = entidad.key; string newRegistrationId = null; // make sure there are no existing registrations for this push handle (used for iOS and 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); }
public async Task <ApiResult> Register(RegisterPushDto registerPushDto) { string newRegistrationId = null; if (registerPushDto == null) { return(ErrorApiResult(300, "Какая то херня пришла от тебя братиш")); } var handle = registerPushDto.Handle; // make sure there are no existing registrations for this push handle (used for iOS and Android) if (handle != null) { var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100); foreach (RegistrationDescription registration in registrations) { await _hub.DeleteRegistrationAsync(registration); } } newRegistrationId = await _hub.CreateRegistrationIdAsync(); return(SuccessApiResult(newRegistrationId)); }
public static async Task <bool> SendNotificationAsync(string message, string idNotificacao, bool broadcast = false) { string[] userTag = new string[1]; // Obs importantíssima: O username tá na primeira parte do id da // notificação antes do ":"(dois pontos). Para mandar broadcast é só //enviar o username em branco userTag[0] = string.Empty; string defaultFullSharedAccessSignature = util.configTools.getConfig("hubnotificacao"); string hubName = util.configTools.getConfig("hubname"); string handle = idNotificacao;//hubName; NotificationHubClient _hub = NotificationHubClient.CreateClientFromConnectionString(defaultFullSharedAccessSignature, hubName); //await _hub.DeleteRegistrationAsync(idNotificacao); //Excluindo registros var registrations = await _hub.GetRegistrationsByChannelAsync(handle, 100); foreach (RegistrationDescription xregistration in registrations) { try { await _hub.DeleteRegistrationAsync(xregistration); } catch (Exception ex) { string sm = ex.Message; } } if (!broadcast) { string to_tag = idNotificacao.Split(':')[0]; userTag[0] = "username:"******"{ \"data\" : {\"message\":\"" + message + "\"}}"; outcome = await _hub.SendGcmNativeNotificationAsync(notif, userTag); if (outcome != null) { if (!((outcome.State == NotificationOutcomeState.Abandoned) || (outcome.State == NotificationOutcomeState.Unknown))) { return(true); } } return(false); }
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); }
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()); }
// 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)); } }
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); }
public async Task Register(Registration registration) { if (registration.Handle == null) { throw new ArgumentNullException("Registration handle is null"); } try { var registrations = await Hub.GetRegistrationsByChannelAsync(registration.Handle, 0); foreach (var regDescription in registrations) { await Hub.DeleteRegistrationAsync(regDescription); } foreach (var key in registration.Keys) { await Unregister(key); } await RemoveOld(registration.Handle); RegistrationDescription reg = await Hub.CreateFcmNativeRegistrationAsync(registration.Handle, registration.Keys); lock (devicesLock) { Debug.WriteLine("registered " + registration.Keys); registeredDevices.Add(new UserDevice { Registration = registration, RegistrationID = reg.RegistrationId }); } } catch (Exception e) { Debug.WriteLine("REGISTER " + e.Message); throw e; } }
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); }
private async Task<bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient) { IPrincipal user = this.User; int expectedTagsCount = 1; if (user.Identity != null && user.Identity.IsAuthenticated) { expectedTagsCount = 2; } string continuationToken = null; do { CollectionQueryResult<RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100); continuationToken = regsForChannel.ContinuationToken; foreach (RegistrationDescription reg in regsForChannel) { RegistrationDescription registration = await nhClient.GetRegistrationAsync<RegistrationDescription>(reg.RegistrationId); if (registration.Tags == null || registration.Tags.Count() != expectedTagsCount) { return false; } if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}")) { return false; } ClaimsIdentity identity = user.Identity as ClaimsIdentity; Claim userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); string userId = (userIdClaim != null) ? userIdClaim.Value : string.Empty; if (expectedTagsCount > 1 && !registration.Tags.Contains("_UserId:" + userId)) { return false; } } } while (continuationToken != null); return true; }
private async Task <bool> VerifyTags(string channelUri, string installationId, NotificationHubClient nhClient) { IPrincipal user = this.User; int expectedTagsCount = 1; if (user.Identity != null && user.Identity.IsAuthenticated) { expectedTagsCount = 2; } string continuationToken = null; do { CollectionQueryResult <RegistrationDescription> regsForChannel = await nhClient.GetRegistrationsByChannelAsync(channelUri, continuationToken, 100); continuationToken = regsForChannel.ContinuationToken; foreach (RegistrationDescription reg in regsForChannel) { RegistrationDescription registration = await nhClient.GetRegistrationAsync <RegistrationDescription>(reg.RegistrationId); if (registration.Tags == null || registration.Tags.Count() != expectedTagsCount) { return(false); } if (!registration.Tags.Contains("$InstallationId:{" + installationId + "}")) { return(false); } ClaimsIdentity identity = user.Identity as ClaimsIdentity; Claim userIdClaim = identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); string userId = (userIdClaim != null) ? userIdClaim.Value : string.Empty; if (expectedTagsCount > 1 && !registration.Tags.Contains("_UserId:" + userId)) { return(false); } } } while (continuationToken != null); return(true); }
public static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log) { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); var handle = data.handle.Value; var connectionString = Environment.GetEnvironmentVariable("NotificationHubConnectionString", EnvironmentVariableTarget.Process); var hub = new NotificationHubClient(connectionString, "rfc-activity"); CollectionQueryResult <RegistrationDescription> registrationForHandle = await hub.GetRegistrationsByChannelAsync(handle, 100); var enumerator = registrationForHandle.GetEnumerator(); if (!enumerator.MoveNext()) { var registration = new FcmRegistrationDescription(handle); await hub.CreateRegistrationAsync(registration); } return(new OkResult()); }
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)); } }