System.Reflection.TargetInvocationException with Windows phone 8 when tracking location - c#

I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps, and I'm using the code bellow:
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
The problem is: I got a System.Reflection.TargetInvocationException
Do you have any solutuon for that kind of problem ?

try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}

Most likely this error is causes by the location not being marked as on in your application manifest file

As #Stuart mentioned make sure that you've ticked the ID_CAP_LOCATION from your AppManifest file. If you don’t do this your app will throw an exception and when you try deploy it during development and will cause your app to fail.
How to continuously track the phone's location for Windows Phone 8

Related

LayoutSerializationCallback not be called

I'm using AvalonDock and I would serialize and deserialize my layout. But the callback (where I use the ContentId for create an instance of correct object) is not always called. For this reason the loaded not work correctly. I have tried to add one "try-catch", but not thrown exception.
This is my code:
` var layoutSerializer = new XmlLayoutSerializer(manager);
layoutSerializer.LayoutSerializationCallback += (s, e) =>
{
MyClass item;
if (items.TryGetValue(e.Model.ContentId, out item))
{
e.Content = item;
var tool = item as IMyClassToolApp;
var anchorable = e.Model as LayoutAnchorable;
var document = item as IMyClassDocumentApp;
var layoutDocument = e.Model as LayoutDocument;
if (tool != null && anchorable != null)
{
addToolCallback(tool);
tool.IsVisible = anchorable.IsVisible;
tool.IsSelected = e.Model.IsSelected;
return;
}
if (document != null && layoutDocument != null)
{
addDocumentCallback(document);
// Nasty hack to get around issue that occurs if documents are loaded from state,
// and more documents are opened programmatically.
layoutDocument.GetType().GetProperty("IsLastFocusedDocument").SetValue(layoutDocument, false, null);
document.IsVisible = true;
document.IsSelected = layoutDocument.IsSelected;
return;
}
}
e.Cancel = true;
};
try
{
layoutSerializer.Deserialize(stream);
}
catch
{
return false;
}`
Thank you for your help!
Are you sure your stream is O.K? If for example configuration file does not exist LayoutSerializationCallback method will not be called.
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "MainWindow_Loaded");
string filePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Jofta\Analyzer\configs\AvalonDock.config");
if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
{
XmlLayoutSerializer serializer = new XmlLayoutSerializer(this.dockingManager);
serializer.LayoutSerializationCallback += this.Serializer_LayoutSerializationCallback;
serializer.Deserialize(filePath);
}
MainWindow.logger.Debug("Exiting: {0}", "MainWindow_Loaded");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "MainWindow_Loaded");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}
private void Serializer_LayoutSerializationCallback(object sender, LayoutSerializationCallbackEventArgs e)
{
try
{
MainWindow.logger.Debug("Entering: {0}", "serializer_LayoutSerializationCallback");
if (e.Model.ContentId == ObjectExplorerViewModel.AnchorableContentId)
{
e.Content = Workspace.Instance.ObjectExplorer;
return;
}
// ...
// ...
MainWindow.logger.Debug("Exiting: {0}", "serializer_LayoutSerializationCallback");
}
catch (Exception ex)
{
MainWindow.logger.Error("Exception in: {0}", "serializer_LayoutSerializationCallback");
MainWindow.logger.Error("Message: {0}", ex.Message);
}
}

Tracking location continuously windows phone 8

I'm developing an app based in GPS services and i must track the location of the user continuously, like HERE Maps.
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 20; //Doesn't matter the value I put here, it won't work
geolocator.PositionChanged += geolocator_PositionChanged;
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
Dispatcher.BeginInvoke(() =>
{
if(args.Position != null)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateData();
}
});
}
(I've tried with GeoCoordinateWatcher but i got nothing).
These functions work perfectly when i'm standing at the same place or moving very slowly, but if i enter in a car and start to drive the app crashes after few seconds, and I don't know WHY.
I've searched a lot of codes with the same finality and all of them don't work.
Do you know any other solution for that problem or have already found yourselves in the same position as mine ?
try
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Location is Disabled in Phone Settings.");
}
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
if (args.Position != null && args.Position.Coordinate.ToGeoCoordinate() != myPosition)
{
if(args.Position.Coordinate.Accuracy <= 1500)
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
UpDateMyPositionCircle(args.Position.Coordinate.Accuracy);
}
}
});
}
catch (TargetInvocationException tie)
{
if (tie.Data == null) throw;
else MessageBox.Show("TargetInvocationException while Tracking: " + tie.InnerException.ToString());
}
catch(SystemException se)
{
if (se.Data == null) throw;
else MessageBox.Show("SystemException while Tracking: " + se.InnerException.ToString());
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}

BackgroundTransferRequest connect external power error

I use BackgroundTransferRequest class to download mp3 files in my wp8 app. Some of my files are over 100mb, so because of that I set transferRequest.TransferPreferences = TransferPreferences.None;. However, transferstatus method still returns me external power message.
If you look at line 12 in code you can see that i set TransferPreferences as None
Here is my code to download mp3 file:
private void download_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
if (transferFileName != null)
{
Uri transferUri = new Uri(Uri.EscapeUriString(transferFileName), UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
Uri downloadUri = new Uri("shared/transfers/" + downloadFile, UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = downloadFile;
transferRequest.TransferPreferences = TransferPreferences.None;
try
{
BackgroundTransferService.Add(transferRequest);
}
catch (InvalidOperationException ex)
{
// TBD - update when exceptions are finalized
MessageBox.Show("Unable to add background transfer request. " + ex.Message);
}
catch (Exception e2)
{
MessageBox.Show("Unable to add background transfer request."+e2.ToString());
}
transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
}
else
MessageBox.Show("select an mp3 file to download");
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
RemoveTransferRequest(transfer.RequestId);
processresult.Text = "";
download.Visibility = Visibility.Visible;
lnk = new linkname();
URLListBox.ItemsSource = lnk.obj();
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
string filename = transfer.Tag;
if (isoStore.FileExists(filename))
{
isoStore.DeleteFile(filename);
}
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, filename);
}
}
else
{
RemoveTransferRequest(transfer.RequestId);
if (transfer.TransferError != null)
{
MessageBox.Show(transfer.TransferError.ToString());
}
}
break;
case TransferStatus.WaitingForExternalPower:
WaitingForExternalPower = true;
processresult.Text = "Waiting For External Power";
break;
case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
WaitingForExternalPowerDueToBatterySaverMode = true;
processresult.Text = "Waiting For External Power Due To Battery Saver Mode";
break;
case TransferStatus.WaitingForNonVoiceBlockingNetwork:
WaitingForNonVoiceBlockingNetwork = true;
processresult.Text = "Waiting For Non Voice Blocking Network";
break;
case TransferStatus.WaitingForWiFi:
WaitingForWiFi = true;
processresult.Text = "Waiting For WiFi";
break;
}
}
private void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
From the Documentation
If the file to be transferred is larger than 100 MB, set the TransferPreferences property of the transfer to None. If you do not, the system will automatically change the transfer settings to this value, meaning that the transfer will only proceed when the phone is connected to external power and has a Wi-Fi connection.

GetGeopositionAsync takes too long to complete

current I use this code to get GPS:
Geolocator geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.Default;
geolocator.DesiredAccuracyInMeters = 50;
try
{
Geoposition currentPosition = await geolocator.GetGeopositionAsync(TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(30));
MyCoordinate = new GeoCoordinate(currentPosition.Coordinate.Latitude, currentPosition.Coordinate.Longitude);
}
catch (Exception ex)
{
if (ex.Message.Contains("This operation returned because the timeout period expired."))
{
MessageBox.Show("GPS is taking too long too complete. Pleaes try again.");
this.SetProgressIndicator(false);
RadBusyIndicator.IsRunning = false;
return;
}
else
{
this.SetProgressIndicator(false);
RadBusyIndicator.IsRunning = false;
return;
}
};
But it always takes too long to complete, as you can see I set timeout 30s but not sure why
it doesn't show timeout exception when took more than 30s.
I'm getting stuck on this issue. Does anyone have any idea?
Make sure the wifi or cellphone device is on, this enables the fallback methods to be used when the GPS device can't find a signal.
Someone with more or less the same problem made another thread in here:
GetGeopositionAsync does not return
More information on the GeoLocator class:
http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.geolocation.geolocator#properties
I don't know why too, but TimeSpanis realy slow, but doing it with ReportInterval works fine:
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.ReportInterval = 2000;
geolocator.PositionChanged += geolocator_PositionChanged;
private void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
try
{
Dispatcher.BeginInvoke(() =>
{
myPosition = args.Position.Coordinate.ToGeoCoordinate();
});
}
catch(Exception ex)
{
if (ex.Data == null) throw;
else MessageBox.Show("Exception while Tracking: " + ex.InnerException.ToString());
}
}

Exception while tracking location in Windows Phone 8

When I try to track location it works perfectly but when i add service reference to it it throws an exception
when I try the same program without adding location only add service reference it works perfectly
My code is here below while copy from How to continuously track the phone's location for Windows Phone 8
public partial class MainPage : PhoneApplicationPage
{
Geolocator geolocator = null;
bool tracking = false;
ServiceReference2.GetPositionClient client = new ServiceReference2.GetPositionClient();
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("LocationConsent"))
{
// User has opted in or out of Location
return;
}
else
{
MessageBoxResult result =
MessageBox.Show("This app accesses your phone's location. Is that ok?",
"Location",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = true;
}
else
{
IsolatedStorageSettings.ApplicationSettings["LocationConsent"] = false;
}
IsolatedStorageSettings.ApplicationSettings.Save();
}
}
private void TrackLocation_Click(object sender, RoutedEventArgs e)
{
if ((bool)IsolatedStorageSettings.ApplicationSettings["LocationConsent"] != true)
{
// The user has opted out of Location.
return;
}
if (!tracking)
{
geolocator = new Geolocator();
geolocator.DesiredAccuracy = PositionAccuracy.High;
geolocator.MovementThreshold = 100; // The units are meters.
geolocator.StatusChanged += geolocator_StatusChanged;
geolocator.PositionChanged += geolocator_PositionChanged;
tracking = true;
TrackLocationButton.Content = "stop tracking";
}
else
{
geolocator.PositionChanged -= geolocator_PositionChanged;
geolocator.StatusChanged -= geolocator_StatusChanged;
geolocator = null;
tracking = false;
TrackLocationButton.Content = "track location";
StatusTextBlock.Text = "stopped";
}
}
void geolocator_StatusChanged(Geolocator sender, StatusChangedEventArgs args)
{
string status = "";
switch (args.Status)
{
case PositionStatus.Disabled:
// the application does not have the right capability or the location master switch is off
status = "location is disabled in phone settings";
break;
case PositionStatus.Initializing:
// the geolocator started the tracking operation
status = "initializing";
break;
case PositionStatus.NoData:
// the location service was not able to acquire the location
status = "no data";
break;
case PositionStatus.Ready:
// the location service is generating geopositions as specified by the tracking parameters
status = "ready";
break;
case PositionStatus.NotAvailable:
status = "not available";
// not used in WindowsPhone, Windows desktop uses this value to signal that there is no hardware capable to acquire location information
break;
case PositionStatus.NotInitialized:
// the initial state of the geolocator, once the tracking operation is stopped by the user the geolocator moves back to this state
break;
}
Dispatcher.BeginInvoke(() =>
{
StatusTextBlock.Text = status;
});
}
void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
client.getPosCompleted += new EventHandler<ServiceReference2.getPosCompletedEventArgs>(sendData);
client.getPosAsync(11,11);
Dispatcher.BeginInvoke(() =>
{
LatitudeTextBlock.Text = args.Position.Coordinate.Latitude.ToString("0.00");
LongitudeTextBlock.Text = args.Position.Coordinate.Longitude.ToString("0.00");
});
}
public void sendData(object sender, ServiceReference2.getPosCompletedEventArgs e)
{
dd.Text = e.Result;
}
}
you have
client.getPosCompleted += new EventHandler<ServiceReference2.getPosCompletedEventArgs>(sendData);
but you haven't given Client any values anywhere else, I assume that you are getting a null Reference exception, and that this is why.
It just resolved it , just the fault of setting of IIS because mobile and pc are on different network so the communication is not possible .i just the forward the port in router setting –

Categories