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

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();

Related

Issue with FCM Push Notification Android

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);

Push Notification using Amazon SNS – Device id

Developing the mobile app using the Xamarin Forms. For push notification we are using Amazon Simple Notification Service(SNS).
Xamarin.Andriod :
1. While installing the app we have used the below code snippet to register the device id into the Amazon SNS in OnCreate method of MainActivity. It works fine
using (Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER"))
{
string senders = AmazonUtils.GoogleConsoleProjectId;
intent.SetPackage("com.google.android.gsf");
intent.PutExtra("app", PendingIntent.GetBroadcast(this, 0, new Intent(), 0));
intent.PutExtra("sender", senders);
this.StartService(intent);
}
Every time when app opens checking the corresponding device id is registered in the Amazon SNS. Due to this app takes additional 4 secs to check this process and after that page is loading.
Do we need to check the device is register or not for every time when the app opens ?. Is this standard for the push notification ?.
Regards,
Cheran
Install Xam.Plugins.Settings.
It will add a helper class called Settings
In this class you should add:
private const string IsRegisteredKey = "registered_key";
private static readonly bool IsRegisteredDefault = false;
//Then adding this property
public static bool IsRegistered
{
get
{
return AppSettings.GetValueOrDefault(IsRegisteredKey, IsRegisteredDefault);
}
set
{
AppSettings.AddOrUpdateValue(IsRegisteredKey, value);
}
}
Then in your code call this property, like this:
using YourProjectNameSpace.Droid.Helper
....
if(!Settings.IsRegistered)
{
using (Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER"))
{
string senders = AmazonUtils.GoogleConsoleProjectId;
intent.SetPackage("com.google.android.gsf");
intent.PutExtra("app", PendingIntent.GetBroadcast(this, 0, new Intent(), 0));
intent.PutExtra("sender", senders);
this.StartService(intent);
}
Settings.IsRegistered = true;
}

Xamarin.Forms App return data to calling App

So, either I am asking incorrectly, or it isn't possible, let's see which...
If my app (Xamarin.Forms) is launched from another app, in order to get a url from my app, how do I return that data to the calling app? I wrongly assumed SetResult and Finish, I also wrongly assumed StartActivityForResult, but there has to be a way to do this. I know how to get data INTO my app from another app, but not the same in return.
POSSIBLE PARTIAL SOLUTION -- UPDATE, FAILS
So I have to setup an interface in my PCL, and call the method from the listview item selected handler, in the Android app I can then do this:
Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_url"));
setResult(Activity.RESULT_OK, result);
finish();
(source: https://developer.android.com/training/basics/intents/filters.html)
Is this looking right, and how would I implement the same thing on iOS?
END
I deleted my previous question because I couldn't explain the problem clearly, so here goes.
I have a Xamarin Forms app, I want to use a section of this app as a gallery. Currently I have images displayed in a list, and I have an Intent filter set that launches this page when you select the app as the source for an image (such as upload image on Facebook).
My issue is that I don't know how to return the data (the selected image) back to the app / webpage that made the request. In android I understand that you would use StartActivityForResult and OnActivityResult to handle this, but I am using Xamarin Forms (Android, iOS, UWP) and can't really find a solution that could be used cross-platform.
Just a link to documentation that covers this would be great, but if you have an example then even better.
Thanks
EDIT
Here is the code used to launch the app, I am interested in getting data back from the Intent.ActionPick after the user has selected an image from a ListView, which is in a ContentPage in the PCL.
[Activity(Label = "", Icon = "#drawable/icon", Theme = "#style/DefaultTheme", MainLauncher = true, LaunchMode = LaunchMode.SingleTop,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[IntentFilter(new[] { Intent.ActionSend }, Categories = new[] { Intent.CategoryDefault }, DataMimeType = #"*/*")]
[IntentFilter(new[] { Intent.ActionView, Intent.ActionPick, Intent.ActionGetContent }, Categories = new[] { Intent.CategoryDefault, Intent.CategoryOpenable }, DataMimeType = #"*/*")]
public class MainActivity : FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
try
{
base.OnCreate(bundle);
CurrentPlatform.Init();
Xamarin.Forms.Forms.Init(this, bundle);
App _app = new App();
LoadApplication(_app);
if (Intent.Action == Intent.ActionSend)
{
var image = Intent.ClipData.GetItemAt(0);
var imageStream = ContentResolver.OpenInputStream(image.Uri);
var memOfImage = new System.IO.MemoryStream();
imageStream.CopyTo(memOfImage);
_app.UploadManager(memOfImage.ToArray()); //This allows me to upload images to my app
}
else if (Intent.Action == Intent.ActionPick)
{
_app.SelectManager(); //here is where I need help
}
else
{
_app.AuthManager(); //this is the default route
}
}
catch (Exception e)
{
}
}
It seems you cannot use remote URI to provide to calling app. Some posts I checked suggest to store the file locally and provide it's path to calling app. To avoid memory leak with many files stored I suggest to use the same file name then you will have only one file at any moment.
One more note. I tested this solution in facebook. Skype doesn't seem to accept that and, again, the posts I checked saying that Skype doesn't handle Intent properly (not sure what that means).
Now to solution. In main activity for example in OnCreate method add the follow.
ReturnImagePage is the name of my page class where I select an image
Xamarin.Forms.MessagingCenter.Subscribe<ReturnImagePage, string>(this, "imageUri", (sender, requestedUri) => {
Intent share = new Intent();
string uri = "file://" + requestedUri;
share.SetData(Android.Net.Uri.Parse(uri));
// OR
//Android.Net.Uri uri = Android.Net.Uri.Parse(requestedUri);
//Intent share = new Intent(Intent.ActionSend);
//share.PutExtra(Intent.ExtraStream, uri);
//share.SetType("image/*");
//share.AddFlags(ActivityFlags.GrantReadUriPermission);
SetResult(Result.Ok, share);
Finish();
});
Above will listen for the message when the image is selected.
Then in XFroms code when image is selected dowload it, store it, get path and send to Activity using it's path. Below is my test path
MessagingCenter.Send<ReturnImagePage, string>(this, "imageUri", "/storage/emulated/0/Android/data/ButtonRendererDemo.Droid/files/Pictures/temp/IMG_20170207_174559_21.jpg");
You can use static public class to save and access results like:
public static class StaticClass
{
public static int Result;
}

How to add an Attachment to Outlook Mail from UWP App programmatically?

I am developing an UWP Application , i want to add a Attachment to outlook from UWP app programmatically
Request you to please me know if any alternatives are there.
Looking forward for your response.
You can use the share contract to send some data to the compliant applications (including outlook). It allows you to share some text and data with any compliant apps.
To activate the sharing, you just need to register to the DataRequested event and show the share UI:
DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
DataTransferManager.ShowShareUI();
Then, in the event handler:
private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
try
{
args.Request.Data.Properties.Title = "Share Title"
args.Request.Data.Properties.Description = "Share some data/file";
var file = await ApplicationData.Current.TemporaryFolder.GetFileAsync("myFileToShare.xxx");
args.Request.Data.SetStorageItems(new IStorageItem[] { logFile });
}
catch
{
args.Request.FailWithDisplayText("Unable to share data");
}
finally
{
deferral.Complete();
sender.DataRequested -= OnDataRequested;
}
}
Once done, the system will show the share UI where the user will be able to select the app he want. This app will receive the sent data.
While #Vincent's answer is perfect when you want to use Share Contract, if you want to use Just Email and attach the File, Below is a simple Method that i use in one of my App.
internal async void ShowEmail(string body, string subject, StorageFile attachment)
{
EmailMessage email = new EmailMessage();
email.Subject = subject;
email.Body = body;
var stream = RandomAccessStreamReference.CreateFromFile(attachment);
email.SetBodyStream(EmailMessageBodyKind.Html, stream);
await EmailManager.ShowComposeNewEmailAsync(email);
}
Above method is a strip down of the example from Here

Launch Cordova Windows App with Parameters

Am finding hard to launch Cordova Windows App, from another native Windows App.
Using Protocol invocation, I am passing few parameters to Cordova Windows App, to see if the Cordova app identifies those parameters from the Windows Native App.
Is there anyway to pass Parameters from native Windows App to Cordova App, so that Cordova App identifies the parameters as arguments?
In native windows 8 store app I am using app protocol association to send parameters one app to another app. like
in sender app:
mainpage.xaml.cs on button click
var url = "apptest:?" + name;
Uri uri = new Uri(url);
await Launcher.LaunchUriAsync(uri);
in received app
Package.appxmanifest:
Declarations --> available declarations add --> protocol --> name = apptest
app.xaml.cs
protected override void OnActivated(IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;
var rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), protocolArgs);
Window.Current.Content = rootFrame;
}
Window.Current.Activate();
}
mainpage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ProtocolActivatedEventArgs pa = e.Parameter as ProtocolActivatedEventArgs;
if(pa != null)enter code here
{
string qS = pa.Uri.Query;
if (!string.IsNullOrEmpty(qS))
{
Txt_name.Text = qS;
}
}
}
in this way i will take the data from sender app.
Same like is there any way to receive data from windows 10 native app to cordova app. it is very hard to find the solution. not able to find the exact piece of code.

Resources