StartAsync() raises error System.IO.FileNotFoundException for downloading - c#

I am trying a Background Downloader for Windows 8.1. This is the HandleDownloadAsync() which I got from the Background Downloader sample.
It started getting a FileNotFound Exception at
await download.StartAsync().AsTask(cts.Token, progressCallback);
It was working a few days back and I haven't changed the code. All the variables are assigned the correct values too.
What is wrong?
async void HandleDownloadAsync(DownloadOperation download, bool start)
{
activeDownloads.Add(download);
try
{
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(ProgressCallback);
if (start)
{
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
await download.AttachAsync().AsTask(cts.Token, progressCallback);
}
}
catch (Exception ex)
{
}
finally
{
activeDownloads.Remove(download);
}
}

Related

Task is canceled randomly on Linux Server

I ran into the following problem: I start a task to process responses from a bot in a telegram for a long execution
Task.Factory.StartNew(() => _.RunAsync(), TaskCreationOptions.LongRunning)
_ - is an instance of my service
method code below:
/// <inheritdoc />
public async Task RunAsync()
{
// запуск метода рассылки пользователям сообщений со стоимостями их портфелей
await _notifier.RunAsync(_cancellationTokenSource.Token);
var updateReceiver = _telegramClient.GetUpdateReceiver(
new[]
{
UpdateType.Message,
UpdateType.CallbackQuery,
});
try
{
Logger.Info("Revaluate portfolios service successfully launched!");
await foreach (var update in updateReceiver.WithCancellation(_cancellationTokenSource.Token))
{
var updateModel = new UpdateModel()
{
Text = update.Message?.Text ?? update.CallbackQuery?.Data,
ChatId = update.Message?.Chat.Id ?? update.CallbackQuery?.Message?.Chat.Id ?? 0,
Phone = update.Message?.Contact?.PhoneNumber ?? "",
From = update.Message?.From ?? update.CallbackQuery?.From
};
await HandleMessageAsync(updateModel);
}
}
catch (OperationCanceledException exception)
{
Logger.Error(exception, "The service was stopped by token cancellation. Reason: ");
throw;
}
catch (Exception ex)
{
Logger.Error(ex);
throw;
}
finally
{
Dispose();
}
}
I assume that the error is called from a method await HandleMessageAsync(updateModel);
where I used _cancellationTokenSource.Token.
I received next error on my server (Ubuntu 2G RAM, 2 Core, 40G SSD):
RevaluatePortfoliosService|The service was stopped by token cancellation. Reason: System.OperationCanceledException: The operation was canceled
But nothing could cause the cancellation. I don't understand why this is happening

RequestProductPurchaseAsync throws “Cannot change thread mode after it is set”

I'm using monogame as a framework for games and I'm trying to implement a in-app-purchase-functionality in an UWP-App which throws an exception when I'm calling RequestProductPurchaseAsync. It states:
Cannot change thread mode after it is set. (Exception from HRESULT:
0x80010106 (RPC_E_CHANGED_MODE)) at
Windows.ApplicationModel.Store.CurrentAppSimulator.RequestProductPurchaseAsync(String
productId) at
Crocs_World__Xbox_Edition_.App.d__7.MoveNext()
That's what I'm doing in code:
public async Task LoadInAppPurchaseProxyFileAsync()
{
StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.GetFolderAsync("data");
StorageFile proxyFile = await proxyDataFolder.GetFileAsync("in-app-purchase.xml");
licenseChangeHandler = new LicenseChangedEventHandler(InAppPurchaseRefreshScenario);
CurrentAppSimulator.LicenseInformation.LicenseChanged += licenseChangeHandler;
await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);
// setup application upsell message
try
{
ListingInformation listing = await CurrentAppSimulator.LoadListingInformationAsync();
var product1 = listing.ProductListings["product1"];
var product2 = listing.ProductListings["product2"];
}
catch (Exception e)
{
Debug.WriteLine("LoadListingInformationAsync API call failed:" + e);
}
}
private async void InAppPurchaseRefreshScenario()
{
Debug.WriteLine("InAppPurchaseRefreshScenario");
}
public async Task BuyFeature()
{
LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
if (!licenseInformation.ProductLicenses["product2"].IsActive)
{
Debug.WriteLine("Buying Product 2...");
try
{
await CurrentAppSimulator.RequestProductPurchaseAsync("product2");
if (licenseInformation.ProductLicenses["product2"].IsActive)
{
Debug.WriteLine("You bought Product 2.");
}
else
{
Debug.WriteLine("Product 2 was not purchased.");
}
}
catch (Exception e)
{
Debug.WriteLine("Unable to buy Product 2." + e);
}
}
else
{
Debug.WriteLine("You already own Product 2.");
}
}
Whenever I call BuyFeature it throws the exception. Except if I call it right in LoadInAppPurchaseProxyFileAsync. Then it seems to be in the same thread I guess.
If I replace Task with void in both methods it doesn't work either. It also doesn't matter if I call it from app.xaml.cs or the game.cs.
Does anybody have an idea what I'm doing wrong?
Thank you,
Harry
You have to call await CurrentAppSimulator.RequestProductPurchaseAsync(...) in the UI thread, because if you run it in release mode with await CurrentApp.RequestProductPurchaseAsync(...) it shows a "Buy item" content dialog on the screen which is only possible in the UI thread.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
await CurrentAppSimulator.RequestProductPurchaseAsync("product2");
};

Download txt file from google drive in windows phone 8.1

I'm doing a windows phone project, and need to download a text file from the internet and read its content.
This is what I have tried (but it didn't work)
private async Task pobierz()
{
string source = "https://drive.google.com/file/d/0BzgKBwKyU4oORkxxSlVITGswb1E/view?usp=sharing";
string LocalName = "hej.txt";
var srce = new Uri(source, UriKind.Absolute);
// var destinationFile =await KnownFolders.PicturesLibrary.CreateFileAsync()
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri(#"ms-appx:///Assets/hej.txt"));
var downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(srce,file);
}
Please see https://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj152726.aspx?f=255&MSPPError=-2147217396 for detailed description of how to use the BackgroundDownloader.
You need to implement and call the following method:
private async void HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
// Store the download so we can pause/resume.
activeDownloads.Add(download);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
if (start)
{
// Start the download and attach a progress handler.
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
// The download was already running when the application started, re-attach the progress handler.
await download.AttachAsync().AsTask(cts.Token, progressCallback);
}
ResponseInformation response = download.GetResponseInformation();
Log(String.Format("Completed: {0}, Status Code: {1}", download.Guid, response.StatusCode));
}
catch (TaskCanceledException)
{
Log("Download cancelled.");
}
catch (Exception ex)
{
LogException("Error", ex);
}
finally
{
activeDownloads.Remove(download);
}
}

Better way to show error messages in async methods

The fact that we can't use the await keyword in catch blocks makes it quite awkward to show error messages from async methods in WinRT, since the MessageDialog API is asynchronous. Ideally I would like be able to write this:
private async Task DoSomethingAsync()
{
try
{
// Some code that can throw an exception
...
}
catch (Exception ex)
{
var dialog = new MessageDialog("Something went wrong!");
await dialog.ShowAsync();
}
}
But instead I have to write it like this:
private async Task DoSomethingAsync()
{
bool error = false;
try
{
// Some code that can throw an exception
...
}
catch (Exception ex)
{
error = true;
}
if (error)
{
var dialog = new MessageDialog("Something went wrong!");
await dialog.ShowAsync();
}
}
All methods that need to do this have to follow a similar pattern, which I really don't like, because it reduces the code readability.
Is there a better way to handle this?
EDIT: I came up with this (which is similar to what svick suggested in his comments):
static class Async
{
public static async Task Try(Func<Task> asyncAction)
{
await asyncAction();
}
public static async Task Catch<TException>(this Task task, Func<TException, Task> handleExceptionAsync, bool rethrow = false)
where TException : Exception
{
TException exception = null;
try
{
await task;
}
catch (TException ex)
{
exception = ex;
}
if (exception != null)
{
await handleExceptionAsync(exception);
if (rethrow)
ExceptionDispatchInfo.Capture(exception).Throw();
}
}
}
Usage:
private async Task DoSomethingAsync()
{
await Async.Try(async () =>
{
// Some code that can throw an exception
...
})
.Catch<Exception>(async ex =>
{
var dialog = new MessageDialog("Something went wrong!");
await dialog.ShowAsync();
});
}
.Catch<...> calls can be chained to mimick multiple catch blocks.
But I'm not really happy with this solution; the syntax is even more awkward than before...
you already have that functionality in TPL
await Task.Run(async () =>
{
// Some code that can throw an exception
...
}).ContinueWith(async (a) =>
{
if (a.IsFaulted)
{
var dialog = new MessageDialog("Something went wrong!\nError: "
+ a.Exception.Message);
await dialog.ShowAsync();
}
else
{
var dialog2 = new MessageDialog("Everything is OK: " + a.Result);
await dialog2.ShowAsync();
}
}).Unwrap();
In this machine I don't have Windows 8 so I tested in Windows 7 but I think is the same.
*Edit
as stated in the comments its needed .Unwrap(); in the end for the await to work
C# 6 now supports await in catch and finally, so the code can be written the way I wanted it; a workaround is no longer needed.

async/await - Getting error "Cannot implicitly convert type 'void' to 'Windows.Foundation.IAsyncAction'"

I'm currently trying to understand how the new keywords in c#5 is working with an example. I want send through a socket connection a message and catch the answar with a listener. Where i'm realy stuck is the point that i can't await a method, here is an example:
private async void SubmitMessage(string strMessage)
{
try
{
using (StreamSocket objSocket = new StreamSocket())
{
IAsyncAction objAction = await objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
objAction.Completed = delegate(IAsyncAction asyncAction, AsyncStatus asyncStatus)
{
BindListener(objSocket.Information.LocalPort, objSocket, strMessage);
};
}
}
catch (Exception objException)
{
Debug.WriteLine(objException.Message);
throw;
}
}
Do anyone have an idea how to get this awaited? If i remove 'await' the syntax is correct. Thanks for any help.
When you use await, you don't have to muck around with IAsyncAction at all, so something like this should work:
private async Task SubmitMessage(string strMessage)
{
try
{
using (StreamSocket objSocket = new StreamSocket())
{
await objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
BindListener(objSocket.Information.LocalPort, objSocket, strMessage);
}
}
catch (Exception objException)
{
Debug.WriteLine(objException.Message);
throw;
}
}
Don't know much about this but would this do?
IAsyncAction objAction =
objSocket.ConnectAsync(new HostName(TargetHostname), TargetPortservice);
await objAction;
//...

Categories