I have a webrequest to get a xml.That works great but when i press F12(lock screen) while the the server is requested by my app...I got a WebException.
I use a taskCompeltionSource object...Here is my code
public async Task<String> Query(DataRequestParam dataRequestParam)
{
_dataRequestParam = dataRequestParam;
try
{
Result = "";
Result = await myDownloadString(dataRequestParam);
}
catch (WebException we)//ERROR IS CAUGHT HERE
{
throw new WebException(we.Message);
}
catch (Exception ex)
{
throw new MyException(ex.Message);
}
return Result;
}
public static Task<string> myDownloadString(DataRequestParam dataRequestParam)
{
var tcs = new TaskCompletionSource<string>();
var web = new WebClient();
if (!string.IsNullOrEmpty(dataRequestParam.AuthentificationLogin))
{
System.Net.NetworkCredential account = new NetworkCredential(dataRequestParam.AuthentificationLogin, dataRequestParam.AuthentificationPassword);
web.Credentials = account;
}
web.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
web.DownloadStringAsync(dataRequestParam.TargetUri);
return tcs.Task;
}
If you haven't disabled ApplisationIdleDetection, your process is stopped while entering Lock screen - thus you probably get the exception - like I've said in comment. Disabling will solve this issue, but you must be aware of few things:
you will still get the exception when hitting Start Button (or other case putting your app to dormant state). In this case your app is stopped and there is no way to prevent this behaviour.
you must fulfill certification requirements when disabling App Idle Detection - point 6.3
if you want to download files in the Background (lock screen, after closing/leaving app) then you can think of Background Transfers
Related
I develop an Universal App that uses MVVM-Light. I call WebServices from the ViewModels, and I throw the exceptions encountered by the calls at the WebServices to the ViewModels: TimeOut, Wrong URL, Server Exception, ...
I have created a class "ExceptionsMsgHelper.cs" which centralizes the messages displayed for each of these exceptions through MessageDialog.
My HomePage is based on a Pivot that containing several datas: some WebServices are called asynchronously. I so meet a crash if I show an Exception in a MessageDialog through the class "ExceptionsMsgHelper.cs", whereas a previous Exception is also showed in another MessageDialog.
Here is a part of my original class:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
await msgbox.ShowAsync();
}
}
=> If I call twice the "msgbox.ShowAsync()", I get the "System.UnauthorizedAccessException" Exception: with message "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
I've so looked for solutions in order to fix it:
use a "Dispatcter", like it is recommended here (WinRT - MessageDialog.ShowAsync will throw UnauthorizedAccessException in my custom class)
The code is:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await msgbox.ShowAsync();
});
}
}
=> But I always meet the same exception.
use a "IAsyncOperation" command to close the previous MessageDialog, like recommended here (MessageDialog ShowAsync throws accessdenied exception on second dialog)
With this code:
public class ExceptionsMsgHelper
{
private static IAsyncOperation<IUICommand> messageDialogCommand = null;
public async static Task<bool> ShowDialog(MessageDialog dlg)
{
// Close the previous one out
if (messageDialogCommand != null)
{
messageDialogCommand.Cancel();
messageDialogCommand = null;
}
messageDialogCommand = dlg.ShowAsync();
await messageDialogCommand;
return true;
}
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await ShowDialog(msgbox);
});
}
}
=> But in this case too, I always get the same exception.
use an extension to queue up messagedialogs, like describing here (Multiple MessageDialog app crash)
The code is now:
public class ExceptionsMsgHelper
{
public async static void MsgboxWebserviceErrors(WebServiceErrorsException wseE, string errors)
{
Windows.UI.Popups.MessageDialog msgbox =
new Windows.UI.Popups.MessageDialog("The Websercice '" + wseE.WebService + "' has returned errors : \n" + errors,
"Unexpected data");
await MessageDialogExtensions.ShowAsyncQueue(msgbox);
}
}
public static class MessageDialogExtensions
{
private static TaskCompletionSource<MessageDialog> _currentDialogShowRequest;
public static async Task<IUICommand> ShowAsyncQueue(this MessageDialog dialog)
{
if (!Window.Current.Dispatcher.HasThreadAccess)
{
throw new InvalidOperationException("This method can only be invoked from UI thread.");
}
while (_currentDialogShowRequest != null)
{
await _currentDialogShowRequest.Task;
}
var request = _currentDialogShowRequest = new TaskCompletionSource<MessageDialog>();
var result = await dialog.ShowAsync();
_currentDialogShowRequest = null;
request.SetResult(dialog);
return result;
}
private static IAsyncOperation<IUICommand> messageDialogCommand = null;
public async static Task<bool> ShowDialog(this MessageDialog dlg)
{
// Close the previous one out
if (messageDialogCommand != null)
{
messageDialogCommand.Cancel();
messageDialogCommand = null;
}
messageDialogCommand = dlg.ShowAsync();
await messageDialogCommand;
return true;
}
#endregion
}
=> And this works for me.
But like says it's author, it's probably not the best solution:
Close existing dialog when you need to open a new one. This is the simplest option and possibly the best, although you risk cancelling a dialog that might be somehow important depending on what your dialogs are about.
Queue up dialogs so the old ones don't get dismissed, but the new ones show up after the old ones were dismissed. This one will make sure all dialogs are closed by the user, but that could be a problem if your app can somehow start showing hundreds of dialogs.
Only open a new one if there isn't one already displayed. Now this risks that a newer message is not shown, which sounds more problematic than the first option.
=> I would like to understand why I can't apply one the 2 first solutions that seems to be more adapted
Ofcourse you can't show 2 or more message dialog at the same time (windows phone limits). Moreover MesssageDialog on Windows Phone 8.1 has probably bug and can't be closed.
If closing previous dialog will be solution for you, try to use ContentDialog instead MessageDialog. Check my answer in this topic: Closing MessageDialog programatically in WP 8.1 RT
I think it solve your problem.
I have IntentService that I use to upload data to server. When this upload goes wrong (sometimes when the user does not have reception or Internet connection) then I use exponential backoff to try and upload the information again and again. I do this inside the onHandleIntent method, which to my understanding runs in separate thread:
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
WebPostsRest posts = new WebPostsRest(HTTPVerb.POST, Uri.parse(CONSTS_WEB.URI_POST_NEW_POST), extras, this);
double backoffMillis = 0;
int backoffexp = 0;
int iTries = CONSTS_APP_GENERAL.NO_OF_POST_TRIES;
while (iTries > 0) {
mIsSuccess = posts.runRestNoReturnData();
if (mIsSuccess) {
iTries = 0;
} else {
if (backoffexp < 11) {
backoffMillis = Math.pow(2, backoffexp) * 1000;
backoffexp++;
}
try {
Thread.sleep((int) backoffMillis);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
iTries--;
}
}
}
}
For some reason I get ANRs, which I assume come from this Thread.sleep part. Any idea why it happens and how to solve things? thank you.
I had the same problem and in my case it was causing by queue for the IntentService. Make sure you are not calling this intent service multiple times. It seems if first call of IntentService fail and use Thread.sleep() and at the same time more request are in waiting mode to use this IntentService then it throws ANR.
I have a valid URL for a remote JPEG which I'm trying to load in the background. But I find I never get control back after invoking the BitmapImage() constructor. My question is, should this approach work, or should I pitch it all, load up BcpAsync project from NuGet and start working with WebClient asynch methods?
A sample URL for which it fails is
http://image.weather.com/images/maps/current/garden_june_720x486.jpg
It is valid. .UpdateAsync() references it from AppViewModel.Instance, it's not explicitly referenced here.
Here's the background agent:
protected override async void OnInvoke(ScheduledTask task)
{
AppViewModel.LoadData();
await AppViewModel.Instance.RemoteImageProxy.UpdateAsync();
AppViewModel.Instance.ImageUrl = AppViewModel.Instance.RemoteImageProxy.LocalFileUri;
AppViewModel.Instance.UpdateCount++;
PinnedTile.Update();
}
AppViewModel.SaveData();
#if DEBUG
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(AppViewModel.Instance.BgAgentInterval));
#endif
NotifyComplete();
}
Here's the invoked method:
public Task<double> UpdateAsync() {
LastCheckedTime = DateTime.UtcNow;
CompletionTask = new TaskCompletionSource<double>();
// Not usually called on UI thread, not worth optimizing for that case here.
Deployment.Current.Dispatcher.BeginInvoke(() => { //todo determine whether System.Windows.Deployment.Dispatcher can be called from main app, or just bgAgent.
HelperImageControl = new Image();
HelperImageControl.Loaded += im_Loaded;
HelperImageControl.ImageFailed += im_ImageFailed;
HelperImageControl.ImageOpened += im_ImageOpened;
// breakpoint here
HelperImageControl.Source = new BitmapImage(SourceUri);
// stepping over the function, control does not return here. Nor are any of the above events fired.
});
return CompletionTask.Task; // this will be completed in one of the subsequent control events...
}
You need to call CompletionTask.SetResult(); to return control back to the caller method.
This works (I'm returning 100 in case of successful download because you set the task to return double).
TaskCompletionSource<double> CompletionTask;
public Task<double> UpdateAsync()
{
CompletionTask = new TaskCompletionSource<double>();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var HelperImageControl = new Image();
var bmp = new BitmapImage();
bmp.ImageOpened += bmp_ImageOpened;
bmp.ImageFailed += bmp_ImageFailed;
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = new Uri("http://image.weather.com/images/maps/current/garden_june_720x486.jpg", UriKind.Absolute);
HelperImageControl.Source = bmp;
});
return CompletionTask.Task;
}
void bmp_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
CompletionTask.SetException(e.ErrorException);
}
void bmp_ImageOpened(object sender, RoutedEventArgs e)
{
CompletionTask.SetResult(100);
}
I'm developing my first Windows Store App, using MvvmCross framework and I have a problem with images management. In particular I have the following simple ViewModel in my PCL project, and a Store project with a button bound with AddPictureCommand.
public class FirstViewModel : MvxViewModel
{
IMvxPictureChooserTask _pictureChooserTask;
IMvxFileStore _fileStore;
public FirstViewModel(IMvxPictureChooserTask pictureChooserTask, IMvxFileStore fileStore)
{
_pictureChooserTask = pictureChooserTask;
_fileStore = fileStore;
}
private byte[] _pictureBytes;
public byte[] PictureBytes
{
get { return _pictureBytes; }
set
{
if (_pictureBytes == value) return;
_pictureBytes = value;
RaisePropertyChanged(() => PictureBytes);
}
}
public ICommand AddPictureCommand
{
get { return new MvxCommand(() =>
{
_pictureChooserTask.ChoosePictureFromLibrary(400, 95, pictureAvailable, () => { });
}); }
}
private void pictureAvailable(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
PictureBytes = memoryStream.ToArray();
GenerateImagePath();
}
private string GenerateImagePath()
{
if (PictureBytes == null) return null;
var RandomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";
_fileStore.EnsureFolderExists("Images");
var path = _fileStore.PathCombine("Images", RandomFileName);
_fileStore.WriteFile(path, PictureBytes);
return path;
}
}
The problem is that the method _fileStore.EnsureFolderExists("Images");
gives me the an "NotImplementedException" with message: "Need to implement this - doesn't seem obvious from the StorageFolder API".
Has anyone already seen it before?
Thank you
This not implemented exception is documented in the wiki - see https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#File
It should be fairly straightforward to implement these missing methods if they are required. Indeed I know of at least 2 users that have implemented these - but sadly they've not contributed them back.
to implement them, just
fork (copy) the code from https://github.com/MvvmCross/MvvmCross/blob/v3/Plugins/Cirrious/File/Cirrious.MvvmCross.Plugins.File.WindowsStore/MvxWindowsStoreBlockingFileStore.cs
implement the missing methods using the winrt StorageFolder apis
in your Store UI project, don't load the File plugin - so comment out or remove the File bootstrap class.
during setup, register your implementation with ioc using Mvx.RegisterType - e.g.:
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Cirrious.CrossCore.Mvx.RegisterType<IMvxFileStore, MyFileStore>();
}
For more on using ioc, see https://github.com/MvvmCross/MvvmCross/wiki/Service-Location-and-Inversion-of-Control
For more on customising the setup sequence, see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup
Following Stuart's suggestions I've implemented the following methods for Windows 8 Store App:
public bool FolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
return false;
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in FolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
return true;
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
public void EnsureFolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
var localFolder = ToFullPath(string.Empty);
var storageFolder = StorageFolder.GetFolderFromPathAsync(localFolder).Await();
storageFolder.CreateFolderAsync(folderPath).Await();
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in EnsureFolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - doesn't seem obvious from the StorageFolder API");
//var folder = StorageFolder.GetFolderFromPathAsync(ToFullPath(folderPath)).Await();
}
The third method we need to implement is DeleteFolder(string folderPath, bool recursive). Unfortunately StorageFolder method "DeleteFolder" doesn't have a "recursive" parameter. So I should implement DeleteFolder ignoring it:
public void DeleteFolder(string folderPath, bool recursive)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
storageFolder.DeleteAsync().Await();
}
catch (FileNotFoundException)
{
//Folder doesn't exist. Nothing to do
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in DeleteFolder - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
or I should check if the folder is empty before to delete it if "recursive" equals false.
Better implementations are welcomed.
I am trying to implement jsr-179 APi into Nokia Symbian phone for periodic location update using setLocationListener through J2me. In emulator it is working fine. While I installed Midlet on the device nokia 5230, it is given NullPointerException and the application is automatically terminating. What might be possible causes?
Below is my class, I am instantiating object for this class on a form in netbeans
class MovementTracker implements LocationListener {
LocationProvider provider;
Location lastValidLocation;
UpdateHandler handler;
boolean done;
public MovementTracker() throws LocationException
{
done = false;
handler = new UpdateHandler();
new Thread(handler).start();
//Defining Criteria for Location Provider
/*
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
*/
//you can place cr inside getInstance
provider = LocationProvider.getInstance(null);
//listener,interval,timeout,int maxAge
//Passing -1 selects default interval
// provider.setLocationListener(MovementTracker.this, -1, -1, -1);
provider.setLocationListener(MovementTracker.this, -1, 30000, 30000);
}
public void locationUpdated(LocationProvider provider, Location location)
{
handler.handleUpdate(location);
batteryLevel = System.getProperty("com.nokia.mid.batterylevel");
sn = System.getProperty("com.nokia.mid.networksignal");
localTime = System.currentTimeMillis();
Send_Location();
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
class UpdateHandler implements Runnable
{
private Location updatedLocation = null;
// The run method performs the actual processing of the location
public void run()
{
Location locationToBeHandled = null;
while (!done)
{
synchronized(this)
{
if (updatedLocation == null)
{
try
{
wait();
}
catch (Exception e)
{
// Handle interruption
}
}
locationToBeHandled = updatedLocation;
updatedLocation = null;
}
// The benefit of the MessageListener is here.
// This thread could via similar triggers be
// handling other kind of events as well in
// addition to just receiving the location updates.
if (locationToBeHandled != null)
processUpdate(locationToBeHandled);
}
try
{
Thread.sleep(10000); //Sleeps for 10 sec & then sends the data
}
catch (InterruptedException ex)
{
}
}
public synchronized void handleUpdate(Location update)
{
updatedLocation = update;
notify();
}
private void processUpdate(Location update)
{
latitude = update.getQualifiedCoordinates().getLatitude();
longitude = update.getQualifiedCoordinates().getLongitude();
altitude = update.getQualifiedCoordinates().getAltitude();
}
}
}
public MovementTracker() throws LocationException
...
I have not written any code for handling LocationException.
No code is very dangerous practice, just search the web for something like "java swallow exceptions".
It is quite possible that because of implementation specifics Nokia throws LocationException where emulator does not throw it. Since you don't handle exception this may indeed crash you midlet at Nokia - and you wouldn't know the reason for that because, again, you have written no code to handle it.
How can I catch that exception?
The simplest thing you can do is to display an Alert with exception message and exit the midlet after user reads and dismisses alert