Issue with FCM Push Notification Android - xamarin

I was able to receive push notifications some months ago, a day ago i started to work again on the app now the issue is it's not able to receive push notification. It does provide FCM token but onMessageReceived never gets called also if i try with Postman it gives an error of Mismatchsender ID, but the scenario here is a bit confusing. If i change the package name (after creating new project on console and added new goole-service.json file) it doesn't let me register for FCM token. i've stuck in this situation from last day. can anybody please help? what i'm doing wrong.
Here is implementaion of FCMToken
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseIIDService : FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "Refreshed token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token)
{
// Add custom implementation, as needed.
}
}
Here it gives me error if i change my package name to any other,
Error: Java.Lang.IllegalStateException: Default FirebaseApp is not
initialized in this process
try
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
// PushNotificationManager.Initialize(this, false);
} catch(Exception ee)
{
}

I've solved my issue with with customization of FirebaseInitialize after creating new project on Firebase here is my code. But one bad thing is here that when new token gets initialized it never gets called on FirebaseInstanceIdReceiver.
var options = new FirebaseOptions.Builder()
.SetApplicationId("<AppID>")
.SetApiKey("<ApiKey>")
.SetDatabaseUrl("<DBURl>")
.SetStorageBucket("<StorageBucket>")
.SetGcmSenderId("<SenderID>").Build();
var fapp = FirebaseApp.InitializeApp(this, options);

Related

URI start of MAUI Windows app creates a new instance. I need to have only one instance of app

I am able to start my Windows MAUI app using an URI, and I can get the URI itself. But, it appears that a NEW instance of the app is being created. This is not ideal for me -- if my app is already running, I want to use that instance.
I have done something like this for a Xamarin.Forms app. I override OnActivated in Application class.
Re: my MAUI app, I'm not even clear on whether the issue is how I've done the "protocol" in package.appxmanifest, or if it is how I respond to lifecycle events.
The default behaviour is to run multiple instances of your app. You can make the app single-instanced by defining a customized class with a Main method as suggested in this blog post:
[STAThread]
static async Task Main(string[] args)
{
WinRT.ComWrappersSupport.InitializeComWrappers();
bool isRedirect = await DecideRedirection();
if (!isRedirect)
{
Microsoft.UI.Xaml.Application.Start((p) =>
{
var context = new DispatcherQueueSynchronizationContext(
DispatcherQueue.GetForCurrentThread());
SynchronizationContext.SetSynchronizationContext(context);
new App();
});
}
return 0;
}
private static async Task DecideRedirection()
{
bool isRedirect = false;
AppActivationArguments args = AppInstance.GetCurrent().GetActivatedEventArgs();
ExtendedActivationKind kind = args.Kind;
AppInstance keyInstance = AppInstance.FindOrRegisterForKey("randomKey");
if (keyInstance.IsCurrent)
{
keyInstance.Activated += OnActivated;
}
else
{
isRedirect = true;
await keyInstance.RedirectActivationToAsync(args);
}
return isRedirect;
}
There is an open suggestion to simplify this process available on GitHub.

Graph API - BadRequest on sending channel messages with #mention

We had some code that has been working for the past 10 months (since it was developed) and just stopped working this afternoon. It's a WebAPI code to send a channel message mentioning the bot and a user, which now is returning "Bad Request. Invalid request body was sent."
If the "Mentions" property is not provided, the call works, and the message is sent without the #mentions. So, I wonder if there was a breaking change in this API that's now expecting a different format for the "Mentions" property.
It's quite simple to reproduce by following the example code found in the Microsoft Graph documentation.
I'm posting here in the hope some fellow dev spots something obvious or is aware of an alternative way of using the API that it might stop complaining, as Microsoft takes forever to reply.
Here's the code we have that can lead me to discover the issue:
private async Task SendMentionToTheBotAsync(GraphServiceClient onBehalfOfClient, string userName, string teamId, string channelId)
{
var supportAgentUser = await onBehalfOfClient.Me.Request().GetAsync();
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = $"<at id=\"0\">{Configuration["BotName"]}</at>: This is the start of the conversation between {userName} and <at id=\"1\">{supportAgentUser.DisplayName}</at>."
},
Mentions = new List<ChatMessageMention>
{
new ChatMessageMention
{
Id = 0,
MentionText = Configuration["BotName"],
Mentioned = new IdentitySet
{
Application = new Identity
{
DisplayName = Configuration["BotName"],
Id = Configuration["BotAppId"],
AdditionalData = new Dictionary<string,object>
{
{
"applicationIdentityType", "bot"
}
}
}
}
},
new ChatMessageMention
{
Id = 1,
MentionText = supportAgentUser.DisplayName,
Mentioned = new IdentitySet
{
User = new Identity
{
DisplayName = supportAgentUser.DisplayName,
Id = supportAgentUser.Id,
AdditionalData = new Dictionary<string,object>
{
{
"userIdentityType", "aadUser"
}
}
}
}
}
}
};
await onBehalfOfClient.Teams[teamId].Channels[channelId].Messages
.Request()
.AddAsync(chatMessage);
}
Microsoft Support responded with :
"Thank you for contacting Microsoft Support.
I understand the issue is related to the post messages to Teams. Based on the screenshot, it seems you are using mention to a channel. It's possible that you are using key "conversationIdentityType#odata.type" in your request.
Could you please try to remove "conversationIdentityType#odata.type" key from the request body and try again. It should work. It is because deployment is on the way in the Asia region. Once it's 100% rolled out, this key WILL NOT be entertained in the request."
Removed the key and it worked for me.
Paulo,
Unfortunately i am not a programmer. I am using Graph calls in a Microsoft 365 Power Automate workflow. I have an app that i use to get the Authorisation Bearer token and then post to Teams messages using a graph HTTP action.
Here is the syntax of the HTTP ( purple items are variables if u r not familiar with Flow )
click to view image of Power Automate workflow HTTP action

How to Register a device through Azure Notification Hub App Service SDK or manually for a Xamarin Forms App?

So i'm using Azure Notification Hub, and in that i followed their tutorial where they had mentioned to use FCM for Android , configure it and use their API key, and creating a certificate for iOS, which is working flawless
But the problem is i'm working on Xamarin forms, and i'd like to know if i could do the registration manually through API, and i've already written a method to do that in my API Service
public async Task<string> RegisterDevice([FromBody] string handle = null)
{
string newRegistrationId = null;
//newRegistrationId = await hub.CreateRegistrationIdAsync();
//// 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 (newRegistrationId == null)
// {
// newRegistrationId = registration.RegistrationId;
// }
// else
// {
// await hub.DeleteRegistrationAsync(registration);
// }
// }
//}
newRegistrationId = await hub.CreateRegistrationIdAsync();
return newRegistrationId;
}
But i'm not able to understand how the device would be linked to this registration ID and/or what is a pns handle, i know the abbreviation but i dont know how to use it in this case or if at all is it necessary?
Any help would be deeply appreciated
While registering Azure Notification Hub, If you want to ask for Push permissions after login, you have to call RegisterForRemoteNotifications(); (iOS) & CreateNotificationChannel(); (Android) after Login.
What you're asking would require a few steps-
You would have to created a DependencyService like this, which would require creating an Interface like IPushRegistrationService with a RegisterForPush() function that would basically be called after login:
var pushService = DependencyService.Get<IPushRegistrationService>();
pushService.RegisterForPush();

Connecting to localhost with Restsharp on Android

I created a Web API and would like to access it in my Android XAMARIN App. It's a XAMARIN Forms App, which references a .NET Standard 2.0 library with the newest RestSharp nuget package installed.
Unfortunately I get the error:
Error: ConnectFailure (No route to host)
whenever I do the following:
public async Task<List<ETFPortfolio>> GetPortfolios()
{
var client = new RestClient("http://10.0.2.2:51262/api/");
var request = new RestRequest("portfolio", Method.GET);
request.AddHeader("Accept", "application/json");
var response = client.Execute(request); // Result with the error stated above
throw new Exception();
}
My WebAPI controller is set up like this:
[Route("api/[controller]")]
public class PortfolioController : Controller
{
// GET api/portfolio
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
var handler = new MyHandler();
var portfolioList = await handler.Handle();
return Ok(portfolioList);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
I found a similar question, unfortunately there were no answers yet.
Error: ConnectFailure (No route to host)
Is there anything I'm missing here or could check out to make this work?
Since you are using a real device, your API url should not be a localhost but an IP address of the computer on which you have the API running.
localhost will work only on the emulator running on the same machine with your API.
P.S.: I wrote a blogpost on this topic, you might be interested in checking it as well.

Facebook sdk for Unity: error

As facebook just released it's new sdk for Unity. I m trying to use FB.API method and getting a lot of troubles with it. Like this is code I have written in UnityScript in my Unity project.
function LoginCallback() {
Debug.Log("User id is"+ FB.UserId);
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, LogCallback, null);
FBUtil.Log(FB.UserId); // Use this to sync progress, etc.
}
function LogCallback(response:String) {
// Debug.Log(response);
var profile = FBUtil.DeserializeJSONProfile(response);
var friends = FBUtil.DeserializeJSONFriends(response);
}
I am getting this error in Unity Log
BCE0005: Unknown identifier: 'FBUtil'.
And if I comment out the FBUtil part and just try to print the json string by writing this
function LoginCallback() {
Debug.Log("User id is"+ FB.UserId);
FB.API("/me?fields=id,first_name,friends.limit(100).fields(first_name,id)", Facebook.HttpMethod.GET, LogCallback, null);
}
function LogCallback(response:String) {
Debug.Log(response);
}
I am able to get Fb.UserId but I am not getting the response with the following details like first_name, friends. The error in DDMS Log is this
"09-04 21:35:04.534: E/Unity(23893): (Filename: ./Runtime/ExportGenerated/AndroidManaged/UnityEngineDebug.cpp Line: 54)
"
Someone help me out.

Resources