Xamarin forms operating camera gives empty exception - c#

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.

Related

Xamarin Forms Push Notifications using Azure Messaging Hub not working in release mode

I added a functionality to my Xamarin Forms App allowing it to receive Notifications from Azure.
Everything works fine in debug mode, but in release mode, the App crashes when I receive a notification.
I got a logger working with Adb to see the exception. The code I am using is the following:
public void OnPushNotificationReceived(Context context, INotificationMessage message)
{
try
{
var msgData = message.Data;
if (msgData.ContainsKey("EventType"))
{
try
{
if (AllowStoreNotification(msgData["VirtualStoreId"], msgData["EventType"]))
{
SendNotification(message.Title, message.Body);
}
}
catch (KeyNotFoundException ex)
{
new TrackEvent("Could not deliver notification. Parameter error.")
.AddParameter("exception", ex.Message.ToString())
.Send();
}
}
}
catch (Exception ex)
{
Log.Error("Notification", ex.Message);
}
void SendNotification(string title, string body)
{
var notification = new NotificationCompat.Builder(context, "PushNotifications")
.SetContentTitle(title)
.SetContentText(body)
.SetSmallIcon(Resource.Drawable.logo_pink_circle)
.SetAutoCancel(true)
.SetDefaults((int)NotificationDefaults.All)
.SetPriority((int)NotificationPriority.High)
.Build();
if (_notificationManager is null)
{
NotificationManagerCompat.From(context).Notify(0, notification);
}
else
{
_notificationManager.Notify(0, notification);
}
}
}
The _notificationManager is null for version Build.VERSION.SdkInt >= BuildVersionCodes.O.
The exception from de ADB log adb logcat Notification:E *:S:
Notification: no non-static method "Lcom/microsoft/windowsazure/messaging/notificationhubs/BasicNotificationMessage;.getData()Ljava/util/Map;"
Anyone knows how to fix this?
I figured out how to make it work using the skip linking assembly.
The issue is the certificate you uploaded to azure, it's just for development, not for production
You have a few options:
Change the certificate once you move to production
2 clouds, one for development and another for production.
Or just compile your app as production every time you want to test notifications

How to use Bluetooth in C#/.net?

I'm trying to do an UI with C# on Visual Studio (on PC[windows10]) and connect some bluetooth devices.
I'm using Windows.Devices.Radios & Windows.Devices.Bluetooth, but I have some troubles with that. After few steps I try to use the bluetooth when I press a button.
This is the code
private async void btnStart_ClickAsync(object sender, EventArgs e)
{
Repl test = new Repl();
var radio = await Radio.RequestAccessAsync();
if (access != RadioAccessStatus.Allowed)
{
return;
}
BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync();
if (null != adapter)
{
var btRadio = await adapter.GetRadioAsync();
if (bluetoothState)
{
await btRadio.SetStateAsync(RadioState.On);
}
else
{
await btRadio.SetStateAsync(RadioState.Off);
}
}
string connect = $"connect {macRight}\r\n";
//string start = "start\r\n";
await BaseCommands.repl.ParseLine(connect);
}
after the 1st request I'm always in the "return;"
I saw some people saying use x32 or x64 and x86. I already try that but I don't know why it doesn't work for me ...
I also saw some post saying change something in the Manifest, but I don't know where to find it :/
I'm a beginner with C#/.NET so if someone can help me to fix that i will appreciate =)
PS : I have another project which use bluetooth and it work perfectly so I have no ideas to fix my own project ...

AVAudioEngine Xamarin.iOS not catched exception engine required running

I'm using Xamarin.iOS for an application using AVAudioEngine.
Sometimes I get this exception :
AVFoundation_AVAudioPlayerNode_Play
Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: _engine->IsRunning()'
This point to my code:
private Dictionary<AudioTrack, AVAudioPlayerNode> _dicPlayerNodes;
private void PlayAudio()
{
try
{
NSError err;
if (Engine.StartAndReturnError(out err))
{
foreach (var audioTrack in _dicPlayerNodes)
{
AVAudioPlayerNode node = audioTrack.Value;
node.Play();
}
}
else
{
Messenger.Publish(new AudioErrorMessage(this) { Platform = "IOS", Code = Convert.ToInt32(err.Code), Message = err.LocalizedDescription ?? err.Description });
_exceptionHandlerService.PostHockeyApp(new Exception($"{err.Code} {err.Description}"));
}
}
catch (Exception ex)
{
_exceptionHandlerService.PostExceptionAsync(ex).Forget();
}
}
I don't understand how is it possible to have this exception that engine is not running, because in my code I Start it and get error if it failed to start ... Then play it.
Also I have a try catch that's not working in this case :( so my applicaton just crashed.
Any advices or idea ?
I comes to this thread but it doesn't help me to understand:
https://forums.developer.apple.com/thread/27980
versions:
IOS version : 10.3.3
Device: ipad 2
Xamarin.ios: 11.2.0.11
Thanks

Media capture initializing error

I have a problem with UWP media capture initilization. My code is below,
private async Task StartPreviewAsync()
{
try
{
//set initilize settings
Settings oneSetting = null;
using (SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), sqlpath))
{
oneSetting = (from p in conn.Table<Settings>()
where p.id == 0
select p).FirstOrDefault();
}
if (oneSetting.camera != null)
{
var settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
settings.PhotoCaptureSource = PhotoCaptureSource.VideoPreview;
var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(Windows.Devices.Enumeration.DeviceClass.VideoCapture);
foreach (var device in devices)
{
if ((device.Id).Equals(oneSetting.cameraId))
{
settings.VideoDeviceId = device.Id;
break;
}
}
_mediaCapture = new MediaCapture();
await _mediaCapture.InitializeAsync(settings);
//MediaCapture m = new MediaCapture();
//await m.InitializeAsync();
var focusSettings = new FocusSettings();
focusSettings.AutoFocusRange = AutoFocusRange.FullRange;
focusSettings.Mode = FocusMode.Auto;
focusSettings.WaitForFocus = true;
focusSettings.DisableDriverFallback = false;
_mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);
_mediaCapture.SetPreviewRotation(VideoRotation.Clockwise90Degrees);
_mediaCapture.SetRecordRotation(VideoRotation.Clockwise90Degrees);
capturePreview.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
_isPreviewing = true;
_displayRequest.RequestActive();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
}
}
catch (UnauthorizedAccessException)
{
// This will be thrown if the user denied access to the camera in privacy settings
System.Diagnostics.Debug.WriteLine("The app was denied access to the camera");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed. {0}", ex.Message);
}
}
It returns MediaCapture initialization failed. {0} error. Recently, it runs well. But since this morning it gives the error. Is there anybody who takes the same error?
The full error message is that;
The specified device interface level or feature is not supported on this system.
: Media Capture initialization failed. {0}
The thread 0x1924 has exited with code 0 (0x0).
Same issue here.
After many hours of retries and googling i realize that it was related to the windows 10 anniversary update.
I found the solution here:
https://www.macecraft.com/fix-webcam-issues-windows-10-anniversary-update/
I added the EnableFrameServerMode key in the registry and magically the webcam came back working.
But since this morning it gives the error.
Did you recently update your device OS? On which device did you meet this problem and what is the OS version?
I personally think this is more like a device problem or drive issue. You can try to restart your device and see if this helps. Or you can start the built-in camera app and check if this official app runs well.
I'm writing this answer here because there are too many details need to be confirmed, please leave a comment here to tell us the detail information about your device and your test result based on my suggestion, so can we keep look into this issue.

Connection Failure while calling a REST API in Xamarin PCL

While calling a REST API from PCL, The application gets crashed.
ERRORS
1. Error: ConnectFailure (Connection refused).
2. Skipped 1367 frames! The application may be doing too much work on its main thread.
Here is my code.
using (client = new HttpClient())
{
try
{
var response = await client.GetAsync("http://<my server ip>/Service//DataService.svc/?getVehicleInfo?vehicleId="+ id);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
JSONModel jsonVehicle = JsonConvert.DeserializeObject<JSONModel>(content);
vehicle = JsonConvert.DeserializeObject<VehicleModel>(jsonVehicle.Result);
}
}
catch (Exception ex)
{
Debug.WriteLine(#"ERROR {0}", ex.Message);
}
return vehicle;
}
I am getting this error at GetAsync().
Internet service is enabled in AndroidManifest.xml.
It has been an obstacle in proceeding further. Need help to resolve it.
Take a look at the double slash here: Service//DataService.svc . It may be the problem. Replace with /
Try updating Xamarin, I had a very similar problem with the 6th version of xamarin but with the 7th the problem disappears

Categories