Debugger always Break when invoke GetFileAsync in windows 8 store apps (metro style) - windows

This problem confuse me several days, when the code run to
await ApplicationData.Current.LocalFolder.GetFileAsync(udFileName);
The app was always jump to
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
The Exception e is:
{Windows.UI.Xaml.UnhandledExceptionEventArgs}
Exception {"Object reference not set to an instance of an object."}
System.Exception {System.NullReferenceException}
Message "System.NullReferenceException.......
Following is the function I invoked:
public async void RestoreUserDefaults()
{
string udFileName = "userdefaults.udef";
bool bExist = true;
{
try
{
await ApplicationData.Current.LocalFolder.GetFileAsync(udFileName);
}
catch (FileNotFoundException)
{
bExist = false;
}
}
}
I had add the file type to the package.appxmanifest.
anyone can help me, so many thanks.....

Related

Xamarin.Forms Calling Dialog from Xamarin.Android Project Throws an Exception

I've been trying to call a Dialog Alert from my xamarin.forms app using IoC container so far I haven't been able to display an alert in my app using this code:
Code at my viewModel:
await _dialogService.DisplayMessageAsync("ERROR", "There are errors on your form!", "Cancel", null);
at my shared project I have this DialogService which is the one I call from my viewModel:
public class DialogService : IDialogService
{
readonly IDialogService _dialogService;
public DialogService()
{
_dialogService = DependencyService.Get<IDialogService>();
}
public void CloseAllDialogs()
{
_dialogService.CloseAllDialogs();
}
public async Task DisplayMessageAsync(string title, string message, string buttonCancelName, Action callback)
{
await _dialogService.DisplayMessageAsync(title, message, buttonCancelName, callback);
}
public async Task DisplayMessageConfirmAsync(string title, string message, string buttonOkName, string buttonCancelName, Action<bool> callback)
{
await _dialogService.DisplayMessageConfirmAsync(title, message, buttonOkName, buttonCancelName, callback);
}
}
so at my Xamarin.Android.XXXXX I have the implementation of my DialogService which is call from my DialogService at my Shared Project this is the code:
public class DialogService : IDialogService
{
List<AlertDialog> _openDialogs = new List<AlertDialog>();
public void CloseAllDialogs()
{
foreach (var dialog in _openDialogs)
{
dialog.Dismiss();
}
_openDialogs.Clear();
}
public async Task DisplayMessageAsync(string title, string message, string okButton, Action callback)
{
await Task.Run(() => Alert(title, message, okButton, callback));
}
public async Task DisplayMessageConfirmAsync(string title, string message, string okButton, string cancelButton, Action<bool> callback)
{
await Task.Run(() => AlertConfirm(title, message, okButton, cancelButton, callback));
}
bool Alert(string title, string content, string okButton, Action callback)
{
var activity = (Activity)Forms.Context;
//var activity = (Activity)Android.App.Application.Context;
var alert = new AlertDialog.Builder(Android.App.Application.Context);
//var alert = new AlertDialog.Builder(activity);
alert.SetTitle(title);
alert.SetMessage(content);
alert.SetNegativeButton(okButton, (sender, e) =>
{
if (!Equals(callback, null))
{
callback();
}
_openDialogs.Remove((AlertDialog)sender);
});
Device.BeginInvokeOnMainThread(() =>
{
AlertDialog dialog = alert.Show();
_openDialogs.Add(dialog);
dialog.SetCanceledOnTouchOutside(false);
dialog.SetCancelable(false);
});
return true;
}
bool AlertConfirm(string title, string content, string okButton, string cancelButton, Action<bool> callback)
{
var alert = new AlertDialog.Builder(Android.App.Application.Context);
alert.SetTitle(title);
alert.SetMessage(content);
alert.SetNegativeButton(cancelButton, (sender, e) =>
{
callback(false);
_openDialogs.Remove((AlertDialog)sender);
});
alert.SetPositiveButton(okButton, (sender, e) =>
{
callback(true);
_openDialogs.Remove((AlertDialog)sender);
});
Device.BeginInvokeOnMainThread(() =>
{
var dialog = alert.Show();
_openDialogs.Add(dialog);
dialog.SetCanceledOnTouchOutside(false);
dialog.SetCancelable(false);
});
return true;
}
}
so whenever the private method alert is called it throws an Exception like this:
Unhandled Exception:
Android.Views.WindowManagerBadTokenException: Unable to add window --
token null is not valid; is your activity running?
it can be corrected if I switch this line of code:
var alert = new AlertDialog.Builder(Android.App.Application.Context);
for this line of code:
var activity = (Activity)Forms.Context;
var alert = new AlertDialog.Builder(activity);
the problem of using this I get a Xamarin.Forms warning like this:
'Forms.Context' is obsolete: 'Context is obsolete as of version 2.5.
Please use a local context instead.'
and i'm a bit obsesive I dont like to have warning and try to maintain my code as updated as possible so, can somebody help me make this code work without needing to use obsolete code. because I found answers that just replacing (Activity)Forms.Context for Android.App.Application.Context would work, but in this case it isn't working at all.
hopefully someone can point me in the right direction because i haven't been able to find any documentation about this case specifically.
Problem is that Android.App.Application.Context is not always an Activity Context.
Xamarin removed this and added a new constructor for the Renderers which include the context. The problem comes in cases like this where you are working on something that is not a CustomRenderer.
For these cases, I use James' Plugin CurrentActivityPlugin which will keep track of the current activity for you. Find it here
Hope this helps.-

Plugin.Geolocator exits method (deadlock?)

I'm building a Xamarin app and for the geolocation, I'm using the GeolocatorPlugin
The problem is that once the code wants to get the position, the code exists without warning.
My class fields:
private Position position;
private IGeolocator locator = CrossGeolocator.Current;
My page constructor:
public MainPage()
{
InitializeComponent();
locator.PositionChanged += Locator_PositionChanged;
locator.PositionError += Locator_PositionError;
}
OnAppearing event is calling the getLocationPermission:
private async Task GetLocationPermission()
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationWhenInUse);
if (status != PermissionStatus.Granted)
{
//Not granted, request permission
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.LocationWhenInUse))
{
// This is not the actual permission request
await DisplayAlert("Need your permission", "We need to access your location", "Ok");
}
// This is the actual permission request
var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.LocationWhenInUse);
if (results.ContainsKey(Permission.LocationWhenInUse))
status = results[Permission.LocationWhenInUse];
}
//Already granted, go on
if (status == PermissionStatus.Granted)
{
//Granted, get the location
GetLocation();
await GetVenues();
await locator.StartListeningAsync(TimeSpan.FromMinutes(30), 500);
}
else
{
await DisplayAlert("Access to location denied", "We don't have access to your location.", "OK");
}
}
The permission is granted and gets to the GetLocation() method:
private async void GetLocation()
{
//var locator = CrossGeolocator.Current;
try
{
var myPosition = await locator.GetPositionAsync();
position = new Position(myPosition.Latitude, myPosition.Longitude);
}
catch (Exception ex)
{
throw;
}
if (position == null)
{
//Handle exception
}
}
Once the line is reached with locator.GetPositionAsync(), it stops. No exception is thrown, also the PositionError isn't raised.
I have no idea why, but in the beginning it worked once, never worked after that.
The location settings in de Android Emulator are as follow:
Based on my research, you did not acheved that Location Changes like this link
I wrote a demo about Location changes. This is running screenshot.
This is my demo
https://github.com/851265601/GeolocationDemo

OData Connection in Xamarin Form

My code crashes and gives the following error on simulator. It attempts to run the try block in the GetDataFromOdataService() method and throws an error and also issue an alert. I am using Xamarin.Form
using Simple.OData.Client;
using System.Threading.Tasks;
private ODataClient mODataClient;
protected async override void OnAppearing ()
{
base.OnAppearing ();
await InitializeDataService ();
await GetDataFromOdataService();
}
public async Task <bool> InitializeDataService(){
try {
mODataClient = new ODataClient ("http://services.odata.org/Northwind/Northwind.svc/");
}
catch {
await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
System.Diagnostics.Debug.WriteLine("ERROR!");
}
return true;
}
public async Task<bool> GetDataFromOdataService (){
try {
myCustomers= await mODataClient.For("Customers").Top(10).FindEntriesAsync();
}
catch {
await DisplayAlert("Error", "Connection Error", "OK", "Cancel");
System.Diagnostics.Debug.WriteLine("ERROR!");
}
return true;
}
Couple issues:-
In the constructor it was doing var list = new ListView() which constrained it locally than setting the class level scope variable. This was therefore adjusted to list = new ListView().
The other thing, was in the GetTheData function where the items source was being assigned as list.ItemsSource = myList; where it needed changing to list.ItemsSource = Customers;.
I've repackaged the zip file up and sent to you. Let me know if this works for you? You should now be able to see all your customers in the ListView.

Fatal error when camera is initializing and back button is pressed or page navigating

I'm working on WP7/8 application with barcode scanning. And have a problem with disposing camera. Camera initialize too long, and when camera is still initializing and I press back button, I've got a fatal error:
A first chance exception of type 'System.ObjectDisposedException'
occurred in Microsoft.Devices.Camera.ni.dll WinRT information: Fatal
error. Disposing capture device.
Could anybody helps me how to avoid this error?
my code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InitializeAndGo();
base.OnNavigatedTo(e);
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
disposeCamera();
}
private void PhotoCameraOnInitialized(object sender, CameraOperationCompletedEventArgs cameraOperationCompletedEventArgs)
{
_width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
_height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
_luminance = new PhotoCameraLuminanceSource(_width, _height);
if (_photoCamera.IsFlashModeSupported(FlashMode.Auto))
{
_photoCamera.FlashMode = FlashMode.Off;
}
cameraInitialized = true;
Dispatcher.BeginInvoke(() =>
{
FlashCheckbox.IsEnabled = true;
if (_photoCamera.IsFlashModeSupported(FlashMode.Auto))
{
_photoCamera.FlashMode = FlashMode.Off;
}
});
_photoCamera.Focus();
}
private void InitializeAndGo()
{
stopScan = false;
_photoCamera = new PhotoCamera();
_photoCamera.Initialized += PhotoCameraOnInitialized;
_photoCamera.AutoFocusCompleted += PhotoCameraOnAutoFocusCompleted;
viewfinderBrush.SetSource(_photoCamera);
_previewTransform.Rotation = _photoCamera.Orientation;
_results = new ObservableCollection<Result>();
_barcodeReader = new BarcodeReader();
_barcodeReader.TryHarder = true;
_barcodeReader.AutoRotate = true;
_service = new MyMoviesDataService(ErrorDataService);
}
private void disposeCamera()
{
try
{
cameraInitialized = false;
StopScan();
_photoCamera.Initialized -= PhotoCameraOnInitialized;
_photoCamera.AutoFocusCompleted -= PhotoCameraOnAutoFocusCompleted;
_photoCamera.Dispose();
_photoCamera = null;
}
catch (Exception ex)
{
App.ShowErrorToast(ex.Message);
}
}
Don't use the camera until it's been successfully initialized (You can check this in the camera's Initialized event).
Also, wrap any usages of the camera in a
try
{
// camera code here
}
catch (ObjectDisposedException)
{
// re-initialize the camera?
}
to handle situations like suspension, which will dispose of the camera automatically.
As for the
An exception of type 'System.ObjectDisposedException' occurred in
Microsoft.Devices.Camera.ni.dll and wasn't handled before a
managed/native boundary WinRT information: Fatal error. Disposing
capture device.
This is something Microsoft needs to fix; I mean, how are you supposed to handle a native code exception if it isn't allowed to propagate to managed code?
Where is the exception coming from (which code line / block)?
I would for starter put a try...catch around InitializeAndGo() in the OnNavigatedTo event handler. And on the whole PhotoCameraOnInitialized event handler also.
Cheers,

Windows Service not starting chrome with Process.Start()

I have written a windows service that is supposed to run a chrome instance.
how ever on attaching the service to the process I am able to hit the breakpoint to Process.Start but it does not opens the chrome.
also I do not get any error.
can anyone help me here.
protected override void OnStart(string[] args)
{
var timer = new Timer(5000);
timer.Elapsed += TimerElapsed;
timer.Start();
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
try
{
var processes = Process.GetProcessesByName("Chrome");
var found = false;
foreach (var process in processes)
{
if (process.MainWindowTitle.StartsWith("title"))
{
found = true;
}
}
if (!found)
{
var process = Process.Start("Chrome", "http://localhost");
}
}
catch (Exception ex)
{
}
}
If I create a windows application for the same then it works fine.
due to session 0 isolation I guess this is not a good idea to proceed upon..
Click here to know more

Resources