private void RemoveDevice(DeviceInstallation installation) { this._deviceService.SaveDevices(this.Devices); this._deviceService.RemoveDevice(installation.DeviceName, installation.Key); this._devices = null; base.RaisePropertyChanged <List <DeviceInstallation> >(System.Linq.Expressions.Expression.Lambda <Func <List <DeviceInstallation> > >(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(SettingsViewModel)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SettingsViewModel).GetMethod("get_Devices").MethodHandle)), new ParameterExpression[0])); }
public DeviceInstallation GetDeviceRegistration(params string[] tags) { var installationId = this.GetInstallationId(); if (FirebaseInstanceId.Instance.Token == null) { return(null); } var installation = new DeviceInstallation { InstallationId = installationId, Platform = "gcm", PushChannel = FirebaseInstanceId.Instance.Token }; // Set up tags to request installation.Tags.AddRange(tags); // Set up templates to request PushTemplate genericTemplate = new PushTemplate { Body = @"{""data"":{""message"":""$(messageParam)""}}" }; PushTemplate silentTemplate = new PushTemplate { Body = @"{""data"":{""message"":""$(silentMessageParam)"", ""action"":""$(actionParam)"", ""silent"":""true""}}" }; installation.Templates.Add("genericTemplate", genericTemplate); installation.Templates.Add("silentTemplate", silentTemplate); return(installation); }
public async Task RegisterForPushNotifications(MobileServiceClient client) { if (AppDelegate.PushDeviceToken != null) { try { var installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "apns", PushChannel = AppDelegate.PushDeviceToken.ToString() }; // Set up tags to request installation.Tags.Add("topic:Sports"); // Set up templates to request PushTemplate genericTemplate = new PushTemplate { Body = "{\"aps\":{\"alert\":\"$(messageParam)\"}}" }; // Register with NH var response = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); } catch (Exception ex) { System.Diagnostics.Debug.Fail($"[iOSPlatformProvider]: Could not register with NH: {ex.Message}"); } } }
public DeviceInstallation GetDeviceRegistration(params string[] tags) { if (!_playServicesAvailable()) { throw new Exception(_getPlayServicesError()); } var installationId = GetDeviceId(); var token = _getFirebaseToken(); if (token == null) { return(null); } var installation = new DeviceInstallation { InstallationId = installationId, Platform = "fcm", PushChannel = token }; installation.Tags.AddRange(tags); return(installation); }
public DeviceInstallation GetDeviceRegistration(params string[] tags) { if (AppDelegate.PushDeviceToken == null) { return null; } // Format our app install information for NH var registrationId = AppDelegate.PushDeviceToken.Description .Trim('<', '>').Replace(" ", string.Empty).ToUpperInvariant(); var installation = new DeviceInstallation { InstallationId = UIDevice.CurrentDevice.IdentifierForVendor.ToString(), Platform = "apns", PushChannel = registrationId }; // Set up tags to request installation.Tags.AddRange(tags); // Set up templates to request PushTemplate genericTemplate = new PushTemplate { Body = "{\"aps\":{\"alert\":\"$(messageParam)\"}}" }; PushTemplate silentTemplate = new PushTemplate { Body = "{\"aps\":{\"content-available\":\"$(silentMessageParam)\", \"sound\":\"\"},\"action\": \"$(actionParam)\"}" }; installation.Templates.Add("genericTemplate", genericTemplate); installation.Templates.Add("silentTemplate", silentTemplate); return installation; }
private static async Task <HttpStatusCode> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, string hubName, string listenConnectionString, CancellationToken cancellationToken) { if (deviceInstallation.installationId == null) { return(HttpStatusCode.BadRequest); } ConnectionStringUtility connectionSaSUtil = new ConnectionStringUtility(listenConnectionString); string hubResource = "installations/" + deviceInstallation.installationId + "?"; string apiVersion = "api-version=2016-07"; string uri = connectionSaSUtil.Endpoint + hubName + "/" + hubResource + apiVersion; string SasToken = connectionSaSUtil.getSaSToken(uri, 60); using (var httpClient = new HttpClient()) { string json = JsonConvert.SerializeObject(deviceInstallation); httpClient.DefaultRequestHeaders.Add("Authorization", SasToken); var response = await httpClient.PutAsync(uri, new StringContent(json, System.Text.Encoding.UTF8, "application/json")); return(response.StatusCode); // return HttpStatusCode.OK; } }
public async Task <IActionResult> UpdateInstallation([Required] DeviceInstallation deviceInstallation) { var username = string.Empty; if (HttpContext.User.Identity is ClaimsIdentity identity) { username = identity.FindFirst(ClaimTypes.Name).Value; } List <string> tags = new List <string>(); tags.Add($"username:{username}"); // find groups associated var groupsForUser = _db.SurveyGroups.Where(group => group.ApplicationUsers.Where(user => user.UserName == username).FirstOrDefault() != null).ToList(); foreach (var group in groupsForUser) { tags.Add("group:" + group.GroupName.Replace(' ', '-')); } deviceInstallation.Tags = tags; var success = await _notificationService.CreateOrUpdateInstallationAsync(deviceInstallation, HttpContext.RequestAborted); if (!success) { return(new UnprocessableEntityResult()); } return(new OkResult()); }
private async Task LoginAsync() { try { await _authenticationService.LoginAsync(); var deviceService = DependencyService.Resolve <IDeviceService>(); var deviceId = deviceService.GetDeviceId(); var handle = await deviceService.GetHandleAsync(); var thisDevice = new DeviceInstallation { Id = deviceId, Platfrom = "fcm", PnsHandle = handle, }; await App.NotificationsRestClient.RegisterDeviceAsync(thisDevice); await Shell.Current.GoToAsync(@"//main"); } catch (Exception ex) { var alerter = DependencyService.Resolve <IAlerter>(); alerter.Alert($"Login failed. {ex.Message}"); } }
public DeviceInstallation GetDeviceRegistration(params string[] tags) { if (!_notificationsSupported()) { throw new Exception(_getNotificationSupportError()); } var installationId = GetDeviceId(); var token = _getDeviceToken(); if (token == null) { return(null); } var pushChannel = NSDataToHex(token); var installation = new DeviceInstallation { InstallationId = installationId, Platform = "apns", PushChannel = pushChannel }; installation.Tags.AddRange(tags); return(installation); }
public static async Task RegisterDevice(DeviceInstallation deviceUpdate) { Installation installation = new Installation(); installation.InstallationId = deviceUpdate.InstallationId; installation.PushChannel = deviceUpdate.PushChannel; switch (deviceUpdate.Platform) { case "apns": installation.Platform = NotificationPlatform.Apns; break; case "gcm": installation.Platform = NotificationPlatform.Gcm; break; default: throw new Exception("Invalid Channel"); } installation.Tags = new List <string>(); //installation.Tags.Add($"requestid:{requestId}"); //Dictionary<string, InstallationTemplate> templates = new Dictionary<string, InstallationTemplate>(); //templates.Add("template", new InstallationTemplate { Body = deviceUpdate.Template }); await Client.NotificationClient.Instance.Hub.CreateOrUpdateInstallationAsync(installation); }
public async Task RegisterForPushNotifications(MobileServiceClient client) { var registrationId = GcmClient.GetRegistrationId(RootView); var azurePush = client.GetPush(); var installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "gcm", PushChannel = registrationId }; installation.Tags.Add("silent-push"); var silentTemplate = new PushTemplate { Body = @"{""data"":{""op"":""$(op)"",""table"":""$(table)"",""id"":""$(id)""}}" }; installation.Templates.Add("silent", silentTemplate); var response = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new System.Collections.Generic.Dictionary <string, string>()); }
private async Task<DeviceInstallation> GenerateInstallation(string groupName = null) { App.Channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); App.Channel.PushNotificationReceived += (s, e) => { NotificationReceived?.Invoke(s, e); }; string installationId = null; if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("nhInstallationID")) { installationId = Guid.NewGuid().ToString(); ApplicationData.Current.LocalSettings.Values.Add("nhInstallationID", installationId); } else installationId = (string)ApplicationData.Current.LocalSettings.Values["nhInstallationID"]; string userTag = $"{App.User.SID}"; string deviceTag = $"{installationId}"; //string userTag = "testtag"; var deviceInstallation = new DeviceInstallation { InstallationId = installationId, Platform = "wns", PushChannel = App.Channel.Uri, Tags = groupName == null ? new string[] { userTag, deviceTag } : new string[] { userTag, deviceTag, groupName } }; App.DeviceInstallation = deviceInstallation; return deviceInstallation; }
private void AddDevice(string deviceName) { this._deviceService.SaveDevices(this.Devices); DeviceInstallation deviceInstallation = this._deviceService.AddDevice(deviceName); this._devices = null; base.RaisePropertyChanged <List <DeviceInstallation> >(System.Linq.Expressions.Expression.Lambda <Func <List <DeviceInstallation> > >(System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression.Constant(this, typeof(SettingsViewModel)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SettingsViewModel).GetMethod("get_Devices").MethodHandle)), new ParameterExpression[0])); this.SelectedDevice = deviceInstallation; }
public DeviceInstallation AddDevice(string deviceName) { DeviceInstallation deviceInstallation = new DeviceInstallation(deviceName); List <DeviceInstallation> installedDevices = this.GetInstalledDevices(); installedDevices.Add(deviceInstallation); LocalSettings.AdditionalDevices = JsonHelper.Serialize <List <DeviceInstallation> >(installedDevices); return(deviceInstallation); }
//Part: 7 Push Notification //private async Task InitNotificationsAsync() //{ // PushNotificationChannel channel = await Windows.Networking.PushNotifications.PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); // //messageParam: is defined in edit favorite script from azure // const string templateBodyWNS = "{\"message\":\"$(messageParam)\"}"; // //const string templateBodyWNS = "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(messageParam)</text></binding></visual></toast>"; // Push push = FavoritesManager.DefaultManager.CurrentClient.GetPush(); // JObject headers = new JObject(); // headers["X-WNS-Type"] = "wns/raw"; // JObject templates = new JObject(); // templates["genericMessage"] = new JObject // { // {"body", templateBodyWNS}, // {"headers", headers} // }; // await push.RegisterAsync(channel.Uri, templates); // channel.PushNotificationReceived += OnNotificationReceived; //} //Part: 7 Push Notification //private void OnNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args) //{ // //args.NotificationType // //args.RawNotification // //responding to the notification: show to device // Helpers.ToastHelper.ProcessNotification(args); //} //Part 9: Adding Tagging Support: Pre-provisioned public async Task RegisterForPushNotificationsAsync(MobileServiceClient client) { PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync(); if (channel != null) { try { string registrationId = channel.Uri.ToString(); DeviceInstallation installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "wns", PushChannel = registrationId }; //Template: Specify exact format for receive notification //$(messageParam): define a variable which server would fill this WindowsPushTemplate genericTemplate = new WindowsPushTemplate { Body = "{\"message\":\"$(messageParam)\"}" }; genericTemplate.Headers.Add("X-WNS-Type", "wns/raw"); installation.Templates.Add("genericTemplate", genericTemplate); WindowsPushTemplate discussionTemplate = new WindowsPushTemplate { Body = "{\"message\":\"$(content)\"}" }; discussionTemplate.Headers.Add("X-WNS-Type", "wns/raw"); installation.Templates.Add("discussionTemplate", discussionTemplate); //List<string> extraTags = new List<string>(); //Tag: specific device received this notification //extraTags.Add("Windows"); //installation.Tags = extraTags; DeviceInstallation recordedInstallation = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>($"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); //dynamicTags: what the user want such as social news as notification List <string> dynamicTags = new List <string>(); dynamicTags.Add(XamarinMastering.Helpers.RegistrationHelper.CurrentPlatformId); await XamarinMastering.Helpers.RegistrationHelper.UpdateInstallationTagsAsync(client.InstallationId, dynamicTags); channel.PushNotificationReceived += OnNotificationReceived; } catch (Exception ex) { } return; } }
public async Task <HttpResponseMessage> Put([FromBody] DeviceInstallation deviceUpdate) { System.Diagnostics.Debug.WriteLine("Mobile App Registering"); if (deviceUpdate == null) { return(this.Request.CreateResponse(HttpStatusCode.BadRequest)); } Dictionary <string, InstallationTemplate> templates = new Dictionary <string, InstallationTemplate>(); foreach (var t in deviceUpdate.Templates) { templates.Add(t.Key, new InstallationTemplate { Body = t.Value.Body }); } Installation installation = new Installation() { InstallationId = deviceUpdate.InstallationId, PushChannel = deviceUpdate.PushChannel, Tags = deviceUpdate.Tags, Templates = templates }; switch (deviceUpdate.Platform) { case "apns": installation.Platform = NotificationPlatform.Apns; break; case "gcm": installation.Platform = NotificationPlatform.Gcm; break; default: throw new HttpResponseException(HttpStatusCode.BadRequest); } // In the backend we can control if a user is allowed to add tags installation.Tags = new List <string>(deviceUpdate.Tags); try { await this.Hub.CreateOrUpdateInstallationAsync(installation); return(this.Request.CreateResponse(true)); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"[PNS Error]: Issue registering device {ex.Message}"); return(this.Request.CreateResponse(false)); } }
public async Task <IActionResult> UpdateInstallation([Required] DeviceInstallation deviceInstallation) { var success = await _notificationService .CreateOrUpdateInstallationAsync(deviceInstallation, HttpContext.RequestAborted); if (!success) { return(new UnprocessableEntityResult()); } return(new OkResult()); }
//Part 9: Adding Tagging Support: Pre-provisioned public async void RegisterForPushNotifications(Context context, MobileServiceClient client) { if (GcmClient.IsRegistered(context)) { try { string registrationId = GcmClient.GetRegistrationId(context); DeviceInstallation installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "gcm", PushChannel = registrationId }; //Template: Specify exact format for receive notification //$(messageParam): define a variable which server would fill this PushTemplate genericTemplate = new PushTemplate { Body = "{\"data\":{\"message\":\"$(messageParam)\"}}" }; installation.Templates.Add("genericTemplate", genericTemplate); PushTemplate discussionTemplate = new PushTemplate { Body = "{\"data\":{\"message\":\"$(content)\"}}" }; installation.Templates.Add("discussionTemplate", discussionTemplate); //List<string> extraTags = new List<string>(); //Tag: specific device received this notification //extraTags.Add("Android"); //installation.Tags = extraTags; DeviceInstallation response = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>($"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); //dynamicTags: what the user want such as social news as notification List <string> dynamicTags = new List <string>(); dynamicTags.Add(XamarinMastering.Helpers.RegistrationHelper.CurrentPlatformId); await XamarinMastering.Helpers.RegistrationHelper.UpdateInstallationTagsAsync(client.InstallationId, dynamicTags); } catch (Exception ex) { } } else { } }
//Part 9: Adding Tagging Support: Pre-provisioned public async Task RegisterForPushNotifications(MobileServiceClient client) { if (AppDelegate.PushDeviceToken != null) { try { string registrationId = AppDelegate.PushDeviceToken .Description .Trim('<', '>') .Replace(" ", string.Empty) .ToUpperInvariant(); DeviceInstallation installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "apns", PushChannel = registrationId }; //Template: Specify exact format for receive notification //$(messageParam): define a variable which server would fill this PushTemplate genericTemplate = new PushTemplate { Body = "{\"aps\":{\"alert\":\"$(messageParam)\"}}" }; //Tag: specific device received this notification //installation.Tags.Add("iOS"); //installation.Tags.Add("Texas"); installation.Templates.Add("genericTemplate", genericTemplate); PushTemplate discussionTemplate = new PushTemplate { Body = "{\"aps\":{\"alert\":\"$(content)\"}}" }; installation.Templates.Add("discussionTemplate", discussionTemplate); DeviceInstallation response = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>($"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); //dynamicTags: what the user want such as social news as notification List <string> dynamicTags = new List <string>(); dynamicTags.Add(XamarinMastering.Helpers.RegistrationHelper.CurrentPlatformId); await XamarinMastering.Helpers.RegistrationHelper.UpdateInstallationTagsAsync(client.InstallationId, dynamicTags); } catch (Exception ex) { } } }
public async void RegisterAsync(Microsoft.WindowsAzure.MobileServices.Push push, IEnumerable <string> tags) { try { var installation = new DeviceInstallation { InstallationId = Client.InstallationId, Platform = "gcm", PushChannel = RegistrationID }; using (var scope = App.Container?.BeginLifetimeScope()) { (await scope?.Resolve <GrupoOfertaService>()?.CarregarGrupoDeOfertasUsuarioLogadoAsync()).Select(x => { installation.Tags.Add(x.Id); return(x); }).ToArray(); (await scope?.Resolve <ListaCompraService>()?.CarregarListasDeComprasUsuarioLogadoAsync()).Select(x => { installation.Tags.Add(x.Id); return(x); }).ToArray(); installation.Tags.Add("user:"******"{""data"":{""key"":""$(keyParam)"",""message"":""$(messageParam)""}}" }; PushTemplate ofertaTemplate = new PushTemplate { Body = @"{""data"":{""key"":""$(keyParam)"",""ofertaTitle"":""$(ofertaTitleParam)"",""ofertaDescription"":""$(ofertaDescriptionParam)"",""idOFerta"":""$(ofertaIdParam)""}}" }; installation.Templates.Add("genericTemplate", genericTemplate); installation.Templates.Add("ofertaTemplate", ofertaTemplate); // Register with NH await Client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{Client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); await Client.InvokeApiAsync <string[], object>("refreshPushRegistration", installation.Tags.ToArray()); //await push. RegisterAsync(RegistrationID, templates); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); Debugger.Break(); } }
public async Task RegisterForPushNotifications(MobileServiceClient client) { if (AppDelegate.PushDeviceToken != null) { try { var registrationId = AppDelegate.PushDeviceToken.Description .Trim('<', '>').Replace(" ", string.Empty).ToUpperInvariant(); var installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "apns", PushChannel = registrationId }; // Set up tags to request installation.Tags.Add("topic:Sports"); // Set up templates to request PushTemplate genericTemplate = new PushTemplate { Body = @"{""aps"":{""alert"":""$(message)"",""picture"":""$(picture)""}}" }; installation.Templates.Add("genericTemplate", genericTemplate); PushTemplate pushToSyncTemplate = new PushTemplate { Body = @"{""aps"":{""op"":""$(op)"",""table"":""$(table)"",""id"":""$(id)""},""content-available"":1}" } installation.Templates.Add("pushToSync", pushToSyncTemplate); // Register with NH var recordedInstallation = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); System.Diagnostics.Debug.WriteLine("Completed NH Push Installation"); } catch (Exception ex) { System.Diagnostics.Debug.Fail($"[iOSPlatformProvider]: Could not register with NH: {ex.Message}"); } } else { System.Diagnostics.Debug.WriteLine($"[iOSPlatformProvider]: Are you running in a simulator? Push Notifications are not available"); } }
public async Task RegisterForPushNotifications(MobileServiceClient client) { if (GcmClient.IsRegistered(RootView)) { try { var registrationId = GcmClient.GetRegistrationId(RootView); //var push = client.GetPush(); //await push.RegisterAsync(registrationId); var installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "gcm", PushChannel = registrationId }; // Set up tags to request installation.Tags.Add("topic:Sports"); // Set up templates to request var genericTemplate = new PushTemplate { Body = @"{""data"":{""message"":""$(message)"",""picture"":""$(picture)""}}" }; installation.Templates.Add("genericTemplate", genericTemplate); var pushToSyncTemplate = new PushTemplate { Body = @"{""data"":{""op"":""$(op)"",""table"":""$(table)"",""id"":""$(id)""}}" }; installation.Templates.Add("pushToSync", pushToSyncTemplate); // Register with NH var response = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); } catch (Exception ex) { Log.Error("DroidPlatformProvider", $"Could not register with NH: {ex.Message}"); } } else { Log.Error("DroidPlatformProvider", $"Not registered with GCM"); } }
public DeviceInstallation GetDeviceInstallation() { if (!NotificationsSupported) { throw new Exception(GetPlayServicesError()); } var installation = new DeviceInstallation { InstallationId = GetDeviceId(), Platform = "fcm", PushChannel = Token }; return(installation); }
public void RemoveDevice(string deviceName, string key) { List <DeviceInstallation> installedDevices = this.GetInstalledDevices(); DeviceInstallation deviceInstallation = installedDevices.FirstOrDefault <DeviceInstallation>((DeviceInstallation x) => { if (x.DeviceName != deviceName) { return(false); } return(x.Key == key); }); if (deviceInstallation != null) { installedDevices.Remove(deviceInstallation); } LocalSettings.AdditionalDevices = JsonHelper.Serialize <List <DeviceInstallation> >(installedDevices); }
public async Task RegisterForPushNotifications(MobileServiceClient client) { if (UWPPlatformProvider.Channel != null) { try { var registrationId = UWPPlatformProvider.Channel.Uri.ToString(); var installation = new DeviceInstallation { InstallationId = client.InstallationId, Platform = "wns", PushChannel = registrationId }; // Set up tags to request installation.Tags.Add("topic:Events"); // Set up templates to request var genericTemplate = new WindowsPushTemplate { Body = @"<toast> <visual> <binding template=""ToastText01""> <text id=""1"">Microsoft House</text> <text id=""1"">$(message)</text> </binding> </visual> </toast>" }; genericTemplate.Headers.Add("X-WNS-Type", "wns/toast"); installation.Templates.Add("ToastText01", genericTemplate); // Register with NH var recordedInstallation = await client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); System.Diagnostics.Debug.WriteLine("Completed NH Push Installation"); } catch (Exception ex) { System.Diagnostics.Debug.Fail($"[UWPPlatformProvider]: Could not register with NH: {ex.Message}"); } } }
public async Task <bool> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken token) { if (string.IsNullOrWhiteSpace(deviceInstallation?.InstallationId) || string.IsNullOrWhiteSpace(deviceInstallation?.Platform) || string.IsNullOrWhiteSpace(deviceInstallation?.PushChannel)) { return(false); } var templates = deviceInstallation.Templates .ToDictionary( i => i.Key, i => new InstallationTemplate { Body = i.Value.Body }); var installation = new Installation() { InstallationId = deviceInstallation.InstallationId, PushChannel = deviceInstallation.PushChannel, Tags = deviceInstallation.Tags, Templates = templates }; if (_installationPlatform.TryGetValue(deviceInstallation.Platform, out var platform)) { installation.Platform = platform; } else { return(false); } try { await _hub.CreateOrUpdateInstallationAsync(installation, token); } catch { return(false); } return(true); }
async Task RegisterForAzurePushNotifications(NSData deviceToken) { if (deviceToken == null) { return; } var registrationId = deviceToken.Description .Trim('<', '>').Replace(" ", string.Empty).ToUpperInvariant(); var push = _client.GetPush(); var installation = new DeviceInstallation { InstallationId = _client.InstallationId, Platform = "apns", PushChannel = registrationId }; // Set up tags to request installation.Tags.Add("topic:Sports"); // Set up templates to request var genericTemplate = new PushTemplate { Body = "{\"aps\":{\"alert\":\"$(messageParam)\"}}" }; installation.Templates.Add("genericTemplate", genericTemplate); try { // Register with NH var response = await _client.InvokeApiAsync <DeviceInstallation, DeviceInstallation>( $"/push/installations/{_client.InstallationId}", installation, HttpMethod.Put, new Dictionary <string, string>()); } catch (Exception ex) { System.Diagnostics.Debug.Fail($"[iOSPlatformProvider]: Could not register with NH: {ex.Message}"); } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log) { log.Info("C# HTTP trigger function processed a request."); try { var content = await req.Content.ReadAsStringAsync(); DeviceInstallation deviceUpdate = await req.Content.ReadAsAsync <DeviceInstallation>(); await NotificationManager.RegisterDevice(deviceUpdate); await NotificationManager.SendBroadcastNotification("Notificación en el webinar"); } catch (Exception ex) { log.Error(ex.Message); } return(req.CreateResponse(HttpStatusCode.OK)); }
public async Task <bool> CreateOrUpdateInstallationAsync(DeviceInstallation deviceInstallation, CancellationToken token) { if (string.IsNullOrWhiteSpace(deviceInstallation?.InstallationId) || string.IsNullOrWhiteSpace(deviceInstallation?.Platform) || string.IsNullOrWhiteSpace(deviceInstallation?.PushChannel) || string.IsNullOrWhiteSpace(deviceInstallation?.UserId)) { return(false); } var installation = new Installation() { InstallationId = deviceInstallation.InstallationId, PushChannel = deviceInstallation.PushChannel, Tags = deviceInstallation.Tags, UserId = deviceInstallation.UserId }; if (_installationPlatform.TryGetValue(deviceInstallation.Platform, out var platform)) { installation.Platform = platform; } else { return(false); } try { await _hub.CreateOrUpdateInstallationAsync(installation, token); _logger.LogInformation($"Device Id {installation.InstallationId} User Id {installation.UserId} registered"); } catch (Exception e) { _logger.LogError(e, "Unexpected error device installation"); return(false); } return(true); }
public async Task <HttpResponseMessage> CreateOrUpdateInstallation([FromBody] DeviceInstallation deviceUpdate) { //await CleanupInstallations(); var installation = new Installation { InstallationId = deviceUpdate.InstallationId, PushChannel = deviceUpdate.PushChannel, Tags = deviceUpdate.Tags, }; switch (deviceUpdate.Platform) { case "Mpns": installation.Platform = NotificationPlatform.Mpns; break; case "Wns": installation.Platform = NotificationPlatform.Wns; break; case "Apns": installation.Platform = NotificationPlatform.Apns; break; case "Fcm": installation.Platform = NotificationPlatform.Fcm; break; default: throw new Exception("Invalid platform request"); } // In the backend we can control if a user is allowed to add tags //installation.Tags = new List<string>(deviceUpdate.Tags); //installation.Tags.Add("username:" + username); await _hub.CreateOrUpdateInstallationAsync(installation); return(new HttpResponseMessage(HttpStatusCode.OK)); }