Azure / Azure/azure-notificationhubs-android

[BUG] Hub.Register() Errors in Release, works fine in Debug

Open
#171 4 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
33
Forks
65
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
In a Xamarin Forms project implementing the Azure Notification Hub throws an exception in release mode that it does not exhibit during debugging that causes remote PNS registrations to fail.

***Exception or Stack Trace***

```
{
"JniPeerMembers": {
"ManagedPeerType": "WindowsAzure.Messaging.NotificationHubException, Xamarin.Azure.NotificationHubs.Android, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"JniPeerTypeName": "com/microsoft/windowsazure/messaging/NotificationHubException",
"JniPeerType": {
"PeerReference": {
"Handle": {
"value": 15194
},
"Type": 2,
"IsValid": true
},
"Name": "com/microsoft/windowsazure/messaging/NotificationHubException"
},
"InstanceMethods": {},
"InstanceFields": {},
"StaticMethods": {},
"StaticFields": {}
},
"StatusCode": 400,
"StackTrace": "
at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance,
Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <3f19c9fc57a34ac9a473579164f8755e>:0 \n
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualObjectMethod (System.String encodedMember,
Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <3f19c9fc57a34ac9a473579164f8755e>:0 \n
at WindowsAzure.Messaging.NotificationHub.Register (System.String pnsHandle, System.String[] tags) [0x00043] in <15ee46979411457bb0abfed951cc2b1e>:0 \n
at NorthNorfolk.Mobile.Client.Droid.Notifications.FirebaseService.SendRegistrationToServer (System.String token) [0x00078] in :0 \n
--- End of managed WindowsAzure.Messaging.NotificationHubException stack trace

---\ncom.microsoft.windowsazure.messaging.NotificationHubException\n\tat
com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:254)\n\tat
com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:170)\n\tat
com.microsoft.windowsazure.messaging.Connection.executeRequest(Connection.java:130)\n\tat
com.microsoft.windowsazure.messaging.NotificationHub.upsertRegistrationInternal(NotificationHub.java:446)\n\tat
com.microsoft.windowsazure.messaging.NotificationHub.registerInternal(NotificationHub.java:410)\n\tat
com.microsoft.windowsazure.messaging.NotificationHub.register(NotificationHub.java:148)\n\tat
com.MYAPPNAME.mobile.FirebaseService.n_onNewToken(Native Method)\n\tat
com.MYAPPNAME.mobile.FirebaseService.onNewToken(FirebaseService.java:38)\n\tat
com.google.firebase.messaging.FirebaseMessagingService.zzd(Unknown Source:86)\n\tat
com.google.firebase.iid.zzg.run(Unknown Source:4)\n\tat
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)\n\tat
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)\n\tat
com.google.android.gms.common.util.concurrent.zza.run(Unknown Source:6)\n\tat
java.lang.Thread.run(Thread.java:919)\n",
"JniIdentityHashCode": 19017287,
"PeerReference": {
"Handle": {
"value": 19298
},
"Type": 2,
"IsValid": true
},
"Handle": {
"value": 19298
},
"Message": null,
"Data": {},
"InnerException": null,
"Source": "mscorlib",
"HResult": -2146233088
}
```

**To Reproduce**

Simply run the example project for Xamarin Forms focusing on the android platform, switch to release mode and look out for the errors in the logcat.

***Code Snippet***

FireBaseService in the Android Native project:

```
using Android.App;
using Android.Content;
using Android.Util;
using AndroidX.Core.App;
using Firebase.Messaging;
using Newtonsoft.Json;
using Mobile.Client.Configuration;
using System;
using System.Linq;
using WindowsAzure.Messaging;
using Xamarin.Forms;

namespace Mobile.Client.Droid.Notifications
{
[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class FirebaseService : FirebaseMessagingService
{
const string TAG = "FirebaseService";

public override void OnMessageReceived(RemoteMessage message)
{
Log.Debug(TAG, "From: " + message.From);
if (message.GetNotification() != null)
{
//These is how most messages will be received
Log.Debug(TAG, "Notification Message Body: " + message.GetNotification().Body);
SendNotification(message.GetNotification().Body);
}
else
{
//Only used for debugging payloads sent from the Azure portal
SendNotification(message.Data.Values.First());
}
}

public override async void OnNewToken(string token)
{
Log.Info(TAG, $"Registration Token: {token}");
App.Current.Properties["NotificationToken"] = token;
await App.Current.SavePropertiesAsync();
SendRegistrationToServer(token);
}

private void SendNotification(string messageBody)
{
var intent = new Intent(this, typeof(MainActivity));
intent.AddFlags(ActivityFlags.ClearTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent);

var notificationChannelName = AppSettingsManager.Settings["NotificationChannelName"];

var notificationBuilder = new NotificationCompat.Builder(this, notificationChannelName);

notificationBuilder.SetContentTitle("Notification")
.SetSmallIcon(Resource.Drawable.nndc_logo)
.SetContentText(messageBody)
.SetAutoCancel(true)
.SetAllowSystemGeneratedContextualActions(true)
.SetShowWhen(false)
.SetContentIntent(pendingIntent);

var notificationManager = NotificationManager.FromContext(this);

notificationManager.Notify(0, notificationBuilder.Build());

MessagingCenter.Send(App.Current, "NotificationRecieved");
}

private void SendRegistrationToServer(string token)
{
try
{
var notificationHubName = AppSettingsManager.Settings["NotificationHubName"];
var listenConnectionString = AppSettingsManager.Settings["ListenConnectionString"];
var subscriptionTags = AppSettingsManager.Settings["SubscriptionTags"]?.Split(",");
var fCMTemplateBody = AppSettingsManager.Settings["FCMTemplateBody"];

NotificationHub hub = new NotificationHub(notificationHubName, listenConnectionString, this);
Log.Info(TAG, $"Created hub object: {hub.NotificationHubPath}");

// register device with Azure Notification Hub using the token from FCM
Registration registration = hub.Register(token, subscriptionTags);
Log.Info(TAG, $"Registered token and tags: {registration.PNSHandle}");

// subscribe to the SubscriptionTags list with a simple template.
string pnsHandle = registration.PNSHandle;
Log.Info(TAG, $"PNS Handle: {pnsHandle}");

TemplateRegistration templateReg = hub.RegisterTemplate(pnsHandle, "defaultTemplate", fCMTemplateBody, subscriptionTags);

Log.Info(TAG, $"Registered template: {templateReg.NotificationHubPath}");
}
catch (Exception e)
{
Log.Info(TAG, $"PNS REGISTRATION EXCEPTION: {JsonConvert.SerializeObject(e)}");
//Log.Error("DEBUG", $"Error registering device: {e.Message}");
}
}
}
}
```

Android Manifest:

```



























```

**Expected behavior**

I would expect this to register the device with the notification hub and be visible as a registration in Service Bus Explorer.

**Setup (please complete the following information):**
- OS: Ran against Android OS 10 (SDK 29) primarily.
- IDE : Visual Studio : Version 16.8.1
- Version of the Library used:
Xamarin.Azure.NotificationHubs.Android
Version: 1.1.3

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with the Android example's FirebaseService.SendRegistrationToServer method and the NotificationHub.Register call, then reproduce the failure in Release mode using the provided Android setup. Compare the Release and Debug behavior and inspect the HTTP 400 exception; done means device and template registration succeed in Release mode.

Written by the indexing model from the issue text.

Assessment

Tech stack
android, azure, csharp, firebase, java
Domain
backend-api-design, mobile-dev
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.