FingerPrint Authentication in Xamarin form - c#

I am having a login form and implementing fingerprint authentication.
I have the following code but the app crashes suddenly.
Button in xml file:
<Button Text="Scan Fingerprint" Clicked="FingerPrint_clicked"/>
Code behind this:
public async void FingerPrint_clicked(object sender, EventArgs e)
{
var cancellationToken = new System.Threading.CancellationToken();
var scanResult = await CrossFingerprint.Current.AuthenticateAsync("Show your fingerprint", cancellationToken);
if(scanResult.Authenticated)
{
await DisplayAlert(null, "done", "ok");
}
else
{
await DisplayAlert(null, "failed", "ok");
}
}
MainActivity.cs
CrossFingerprint.SetCurrentActivityResolver(()=> CrossCurrentActivity.Current.Activity);
Added fingerprint in android.manifest file
and set fingerprint in emulator too
Upon clicking the button for fingerprint test, the app crashes suddenly.

Resolved by adding this line to MainActivity.cs file:
CrossCurrentActivity.Current.Init(this, savedInstanceState);

Related

xamarin access protected firebase realtime database with nuget package FirebaseAuthentication.net

im beginner in firebase and im using two nuget packages FirebaseAuthentication.net and FirebaseDatabase.net .
im trying to write to a protected firebase realtime database that has a rule that look like this
{
"rules": {
".read": "auth.uid != null",
".write": "auth.uid != null"
}
}
i randomly tryed SignInWithOAuthAsync method however it throws an Exception [ mail auth type connot be used like this. use method specifc to email & password authentication]
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApiKey));
var savedfirebaseauth = JsonConvert.DeserializeObject<FirebaseAuth>(Preferences.Get("MyFirebaseRefreshToken", ""));
await authProvider.SignInWithOAuthAsync(FirebaseAuthType.EmailAndPassword, savedfirebaseauth.FirebaseToken);
//inserting info into the database
await firebaseClient.Child("users").Child("some uid1").PutAsync(new userinfo
{
firstName = "noor",
secondName = "mohammed"
});
//clear the entry
recordData.Text = "";
}catch(Exception ex)
{
await App.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK");
}
}
pleace let me know if my question needs more Clarificatio thanks in advance.

How to check if the device has biometrics

I am new to Xamarin forms and coding in general, I want to check if the device has biometrics as soon as the app is launched. I came across this video that shows how to do it using a button, I wanted to use it as soon as I open the app. can you help?
btnFPLogin.Clicked += FingerPrint;
private async void FingerPrint(object sender, EventArgs e)
{
var result = await CrossFingerprint.Current.IsAvailableAsync(true);
Plugin.Fingerprint.Abstractions.FingerprintAuthenticationResult auth;
if (result)
{
try
{
var res = await App.Current.MainPage.DisplayAlert("Success", "Your data are saved", "Ok", "Cancel");
auth = await CrossFingerprint.Current.AuthenticateAsync("Authenticate access");
if (auth.Authenticated)
{
await App.Current.MainPage.DisplayAlert("Results are here", "Valid fingerprint found", "Ok");
}
else
{
await App.Current.MainPage.DisplayAlert("Results are here", "Invalid fingerprint", "Ok");
}
}
catch
{
await App.Current.MainPage.DisplayAlert("permission to use FaceID", "We need permission to use FaceID", "Ok");
}
}
}
you've answered your own question. To check if a device supports biometric login, use the CrossFingerprint plugin
var result = await CrossFingerprint.Current.IsAvailableAsync(true);
if you want to check this on app launch, put it in the OnStart method of the App class

Xamarin forms operating camera gives empty exception

I'm working on a mobile Android app using Xamarin Forms and Visual Studio.
I'm using the CrossMedia Plugin to be able to take or select photo's in my mobile app. At first I had problems with the initialize and that issue appeared to be caused by the wrong Android SDK I was targeting. After I updated the SDK and updated all the packages I was able to get the 'select a photo' option working, but using the camera still doesn't work, and I can't figure out what is causing this.
I've got the following method;
private async void TakeAPhoto(object sender, EventArgs e)
{
try
{
await CrossMedia.Current.Initialize();
}
catch (Exception exception)
{
await DisplayAlert("ERROR", "Error initializing camera!", "Ok");
}
var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (cameraStatus != PermissionStatus.Granted || storageStatus != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera, Permission.Storage });
cameraStatus = results[Permission.Camera];
storageStatus = results[Permission.Storage];
}
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No camera", "No camera available", "Ok");
return;
}
if (cameraStatus == PermissionStatus.Granted && storageStatus == PermissionStatus.Granted)
{
MediaFile file;
try
{
//Exception occurs in this code.
file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
//Specify Store to Album OR Directory, not both
Directory = "App_Images",
Name = "Test.jpg"
});
}
catch (Exception exception)
{
//I've got a break point here which is being hit, but the exception is (null)
throw;
}
if (file == null)
return;
//TODO: Store image to azure.
}
else
{
await DisplayAlert("Permissions Denied", "Unable to take photos.", "OK");
//On iOS you may want to send your user to the settings screen.
//CrossPermissions.Current.OpenAppSettings();
}
}
However, when I'm running the code I'm getting an empty exception, it just says '(null)';
The debug window of Visual Studio gives me a lot of information, but the only real exception I see here is an 'InvocationException';
InspectorDebugSession(0): HandleTargetEvent: TargetHitBreakpoint
InspectorDebugSession(0): StateChange: EntryPointBreakpointRegistered -> EntryPointBreakpointHit
InspectorDebugSession(0): AgentBridge.InjectAssembly: /mnt/shell/emulated/0/Android/data/MyFirstAppPackage.MyFirstAppPackage/files/.__override__/inspector-temp/Xamarin.Interactive.dll
InspectorDebugSession(0): AgentBridge.InjectAssembly: Mono.Debugger.Soft.InvocationException: Exception of type 'Mono.Debugger.Soft.InvocationException' was thrown.
at Mono.Debugger.Soft.InvocationsAPI.EndInvokeMethodInternalWithResultImpl(IAsyncResult asyncResult)
at Xamarin.Interactive.IdeSupport.AgentBridge.InjectAssembly(String agentAssemblyPath) in C:\d\lanes\4699\fec6f88f\source\xamarinvs\External\inspector-ide-integration\Xamarin.Interactive.IdeSupport\AgentBridge.cs:line 55
at Xamarin.Interactive.IdeSupport.InspectorDebuggerSession.<HandleTargetEvent>b__26_0(Object <p0>) in C:\d\lanes\4699\fec6f88f\source\xamarinvs\External\inspector-ide-integration\Xamarin.Interactive.IdeSupport\InspectorDebuggerSession.cs:line 242
InspectorDebugSession(0): StateChange: EntryPointBreakpointHit -> Error
InspectorDebugSession(0): Disposed
I've been busy for quite some time to try and figure this out, but I'm completely stuck on this at the moment. I've also tried remote debugging by attaching a Samsung Galaxy S4 Mini to my computer, but it gives me the same error. What am I doing wrong here?
I got this issue resolved by simply selecting the proper Android version to compile on. The plugin documentation says the compile version of android needs to be set to Android 6.0, I had it set to 7.0 because I thought this was possible. But it's not.
Also the target android version was set to a higher version. Setting these both to Android 6.0 fixed the issue.
For more information see the documentation here.

UWP share feature not working in Windows 10 Mobile

I have created a very simple UWP application with a single button. Clicking it should show the built-in share popup to share a PDF file.
The fact is that I have it working for Windows 10 (Desktop) but it doesn't work for mobile (the popup doesn't appear on the screen).
The PDF file comes as a byte array (because it will come from a remote service).
This is the code in MainPage.xaml.cs
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
// This should come from a service
PdfBytes = await Microsoft.Toolkit.Uwp.StorageFileHelper.ReadBytesFromPackagedFileAsync("Document.pdf");
}
public byte[] PdfBytes { get; set; }
private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
var si = await StorageFile.CreateStreamedFileAsync("Document.pdf", stream =>
{
var writeStream = stream.AsStreamForWrite();
writeStream.Write(PdfBytes, 0, PdfBytes.Length);
stream.Dispose();
}, null);
args.Request.Data.Properties.Title = "PDF Document";
args.Request.Data.Properties.Description = "Some description";
args.Request.Data.SetStorageItems(new IStorageItem[] { si });
deferral.Complete();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
DataTransferManager.ShowShareUI();
}
}
Is it correct? If it's not, how should I share the PDF (from its bytes)?
Thank you for your feedback. It seems that CreateStreamedFileAsync method does not work properly with Share contract in Mobile. We've logged this issue internally and I will update here once there is any progress.
For now, as a workaround, you can store the file in TemporaryFolder first and then share it like the following:
private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("Document.pdf", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(tempFile, PdfBytes);
args.Request.Data.Properties.Title = "PDF Document";
args.Request.Data.Properties.Description = "Some description";
args.Request.Data.SetStorageItems(new IStorageItem[] { tempFile });
deferral.Complete();
}
Temporary app data store is the right place for data that you don’t want persisted after the current app session. The system can delete data stored at this location as needed to free up space. You can use it for any intermediate or temporary files. If you are writing large amounts of data to Temp, it is a good idea to clear it when your app is initialized to avoid the system or the user having to take action to free up storage. And you can do this by calling:
await ApplicationData.ClearAsync(ApplicationDataLocality.Temporary);
You have similar issue I had I believe
Have you tried changing
private async void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
var si = await StorageFile.CreateStreamedFileAsync("Document.pdf", stream =>
{
var writeStream = stream.AsStreamForWrite();
writeStream.Write(PdfBytes, 0, PdfBytes.Length);
stream.Dispose();
args.Request.Data.Properties.Title = "PDF Document";
args.Request.Data.Properties.Description = "Some description";
args.Request.Data.SetStorageItems(new IStorageItem[] { si });
deferral.Complete();
}, null);
}
I havent checked this code, so it probably wont compile but I have found that I had issue that looks similar to yours, if threads are involved. Take look at my issue here UWP DataTransferManager ShowShareUI() Opens Sharing Dialog with "This app can't share right now" and Closes it Immediately After
I faced the same issue, My share worked good in desktop application but not in mobile. After big struggle I found that the deferral is not working in windows 10 mobile.
So better remove these lines and try. Its working
var deferral = args.Request.GetDeferral();
deferral.Complete();

MediaElement current state close Unreason

My app has been working fine for a lot of months, but now its not working. When I handle the exception, I get: MediaElement.currentState is Closed. And get result:"Media Player not avaliable". This my code:
if (mediaElement.CurrentState.Equals(MediaElementState.Playing)) {
mediaElement.Stop();
}
else {
try {
SpeechSynthesisStream stream = await sin.SynthesizeTextToStreamAsync(texto);
// Send the stream to the media object.
mediaElement.AutoPlay = true;
mediaElement.SetSource(stream, stream.ContentType);
mediaElement.Play();
}
catch (System.IO.FileNotFoundException) {
var messageDialog = new Windows.UI.Popups.MessageDialog("Media Player not avaliable");
await messageDialog.ShowAsync();
}
}
I have tested your code on my side and I cannot reproduce your issue. Since your code is not completed, I added the remain code by myself and it can run successfully now. Please compare the code snippet to find if something is wrong with your code. You can also run the following simple demo on your machine which can work well on my machine to see if it is a machine environment issue. My test environment is windows 10 build 14393.
XAML Code
<MediaElement x:Name="mediaElement"
CurrentStateChanged="MediaElement_CurrentStateChanged" Height="200" Width="300" AutoPlay="False"/>
<Button x:Name="btntest" Click="btntest_Click" Content=" media close test"></Button>
Code behind
private async void btntest_Click(object sender, RoutedEventArgs e)
{
if (mediaElement.CurrentState.Equals(MediaElementState.Playing))
{
mediaElement.Stop();
}
else
{
try
{
var sin = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
string texto = "hello world";
SpeechSynthesisStream stream= await sin.SynthesizeTextToStreamAsync(texto);
// Send the stream to the media object.
mediaElement.AutoPlay = true;
mediaElement.SetSource(stream, stream.ContentType);
mediaElement.Play();
}
catch (System.IO.FileNotFoundException)
{
var messageDialog = new Windows.UI.Popups.MessageDialog("Media Player not avaliable");
await messageDialog.ShowAsync();
}
}

Categories