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();
}
}
Related
Am trying to connect to an API I built with the client version, running the client app with break points I can see that the data I pass in(signing up) gets passed down but when it get to the the PostAsync method that sends the data to the api the application breaks and I get 'system-net-webexception-failed-to-connect-to-localhost-127-0-0-1-44391' and an accompanying error that reads 'The selected debug engine does not support any code executing on the current thread (e.g. only native runtime code is executing)', there's no red highlight to indicate where the error is which makes this a real head scratcher for me.....
Some insight on the issue will be greatly appreciated.
Sub.Clicked += async (object sender, EventArgs e) =>
{
if (!Conection.IsConnected)
{
await DisplayAlert("No Connection", "Please turn on or reset your data connection", "Cancle");
}
var entirs = new string[] { Email.Text, Password.Text, FN.Text, LN.Text, Phone.Text};
var jcon = JsonConvert.SerializeObject(entirs);
var contain = new StringContent(jcon, Encoding.UTF8, "aplication/json");
message.Timeout = new TimeSpan(0, 0, 100);
var outcome = await message.PostAsync("https://localhost:5001/api/v1/identity/Register", contain);
if (outcome.StatusCode==HttpStatusCode.Created)
{
await DisplayAlert("Success", "Entries have been loaded", "X");
Application.Current.MainPage = new NavigationPage(new Selection());
}
else
{
await DisplayAlert("Failed", outcome.StatusCode.ToString(), "cancel");
};
};
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
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);
Please find the code snippet below that will error in IOS but coming nicly in android device:
aasync void Handle_Clicked(object sender, System.EventArgs e)
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await
locator.GetPositionAsync(timeoutMilliseconds: 10000);
logi.Text = position.Latitude.ToString();
lati.Text = position.Longitude.ToString();
}
It is a known issue on iOS but works perfectly on Android.
It turns out the timeout parameter you set is too short for the task completion, so it canceled every time.
Solution
await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
Refer to my post
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();