BackgroundDownloader The system cannot find the file specified - c#

I'm using C# and Windows Phone 8.1 as Universal.
I Have an issue with BackgroundDownloader. when I start a downloader, it gave me an exception:
Downloading http://localhost/MySong.mp3 to MySong.mp3 with Default priority, a95c00db-738d-4e22-a456-dc30d49b0a3b
A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Exception: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
here is my code:
private void downladButton_Tapped(object sender, TappedRoutedEventArgs e)
{
PumpUrl(txtUrl.Text);
}
async void PumpUrl(string url)
{
if (!string.IsNullOrEmpty(url) && CheckUrl(url))
StartDownloadMethod(url);
else
await new MessageDialog("Looks like URL is invalid.\r\nPlease check your URL and try again"").ShowAsync();
}
public bool CheckUrl(string URL)
{
Uri source;
if (Uri.TryCreate(URL, UriKind.RelativeOrAbsolute, out source))
return true;
else
return false;
}
public void StartDownloadMethod(string url, string fileName = null)
{
StartDownload(url, BackgroundTransferPriority.Default, false, fileName);
}
private async void StartDownload(string url, BackgroundTransferPriority priority, bool requestUnconstrainedDownload, string fileName = null)
{
Uri source;
if (!Uri.TryCreate(url.Trim(), UriKind.RelativeOrAbsolute, out source))
{
Debug.WriteLine("Invalid URI.");
return;
}
string destination = null;
if (string.IsNullOrEmpty(fileName))
try
{
destination = System.IO.Path.GetFileName(Uri.UnescapeDataString(url)).Trim();
}
catch { }
else
destination = Uri.UnescapeDataString(fileName).Trim();
if (string.IsNullOrWhiteSpace(destination))
{
Debug.WriteLine("A local file name is required.");
return;
}
StorageFile destinationFile = null;
try
{
if (vars.localType == LocalType.SDCard)
destinationFile = await KnownFolders.RemovableDevices.CreateFileAsync(
"Downloads\\Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
else
destinationFile = await KnownFolders.MusicLibrary.CreateFileAsync(
"Test App\\" + destination, CreationCollisionOption.GenerateUniqueName);
}
catch (FileNotFoundException ex)
{
Debug.WriteLine("Error while creating file: " + ex.Message);
return;
}
catch (Exception ex) { Debug.WriteLine("Error while creating file: " + ex.Message); }
if (destinationFile == null)
return;
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Downloading {0} to {1} with {2} priority, {3}",
source.AbsoluteUri, destinationFile.Name, priority, download.Guid));
download.Priority = priority;
Add(url, destination, download);
if (!requestUnconstrainedDownload)
{
// Attach progress and completion handlers.
await HandleDownloadAsync(download, true);
return;
}
List<DownloadOperation> requestOperations = new List<DownloadOperation>();
requestOperations.Add(download);
UnconstrainedTransferRequestResult result;
try
{
result = await BackgroundDownloader.RequestUnconstrainedDownloadsAsync(requestOperations);
}
catch (NotImplementedException)
{
Debug.WriteLine(
"BackgroundDownloader.RequestUnconstrainedDownloadsAsync is not supported in Windows Phone.");
return;
}
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Request for unconstrained downloads has been {0}",
(result.IsUnconstrained ? "granted" : "denied")));
await HandleDownloadAsync(download, true);
}
private async Task HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
Debug.WriteLine("Running: " + download.Guid);
bool bb = false;
foreach (DownloadOperation item in DownloadDB.activeDownloads)
{
if (item != null && item.Guid == download.Guid)
{
bb = true;
break;
}
}
if (!bb)
DownloadDB.activeDownloads.Add(download);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
CancellationTokenSource cts = new CancellationTokenSource();
AppendCancellationTokenSource(download, cts);
if (start)
await download.StartAsync().AsTask(cts.Token, progressCallback);
else
await download.AttachAsync().AsTask(cts.Token, progressCallback);
ResponseInformation response = download.GetResponseInformation();
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
DownloadDB.SaveDB();
Debug.WriteLine(String.Format(CultureInfo.CurrentCulture, "Completed: {0}, Status Code: {1}",
download.Guid, response.StatusCode));
}
catch (TaskCanceledException taskCanceled)
{
Debug.WriteLine("TaskCanceledException: " + download.Guid + "\t" + taskCanceled.Message);
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
}
finally
{
DownloadDB.RemoveChildByGuid(download.Guid.ToString());
DownloadDB.activeDownloads.Remove(download);
}
}
I used my code in other application 3 month ago and it works fine but in this application dosent work. Where I wrong?
Thanks

Related

Unable to evaluate the expression

I'm unable to debug the the SaveFileToDisk method. Please me help me out how to resolve the issue. Thanks in advance.
private void Download_TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
try
{
PortalTeacherDairyAttachmentList attachment = ((TappedEventArgs)e).Parameter as PortalTeacherDairyAttachmentList;
byte[] attachmentbyte = attachment.Attachment;
DependencyService.Get<IDownloadManager>().SaveFileToDisk(attachment.FileName,attachmentbyte);
}
catch (Exception ex)
{
}
}
SaveFileToDiskCode:
{
Toast.MakeText(Android.App.Application.Context, "Downloading started...", ToastLength.Long).Show();
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var absolutepath = dir.AbsolutePath;
string name = filename;
string filePath = System.IO.Path.Combine(absolutepath, name);
try
{
System.IO.File.WriteAllBytes(filePath, data);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
OpenFile(filePath, filename);
Toast.MakeText(Android.App.Application.Context, "File downloaded at" + filePath, ToastLength.Long).Show();
CreateNotificationChannel(name);
}
catch (System.Exception e)
{
System.Console.WriteLine(e.ToString());
Toast.MakeText(Android.App.Application.Context, "Error occured", ToastLength.Long).Show();
}
}

c# UWP ReadTextAsync fails at 2 time

So i'm trying to import 2 configs from the localfolder with Windows.Storage. But at the second time it fails with no exception.
This is my Code:
public async Task<string> ImportLines(string filename)
{
try
{
Windows.Storage.StorageFile importFile = await StorageFolder.GetFileAsync(filename);
string savedString = await Windows.Storage.FileIO.ReadTextAsync(importFile);
return savedString;
}
catch (Exception)
{
//log
}
}
I call this methode with:
public async void LoadConfig()
{
if (File.Exists(_textDataHandler.StorageFolder.Path + #"\" + PluginsFilename))
{
string tmp = await _textDataHandler.ImportLines(PluginsFilename);
Plugins = JsonConvert.DeserializeObject<PluginConfiguration>(tmp);
}
else
{
CreateDefaultPluginsConfiguration();
//log
_textDataHandler.CreateFile(_pluginsFilename);
string export = JsonConvert.SerializeObject(Plugins, Formatting.Indented);
_textDataHandler.ExportText(_pluginsFilename, export);
//log
}
if (File.Exists(_textDataHandler.StorageFolder.Path + #"\" + _settingsFilename))
{
string tmp = await _textDataHandler.ImportLines(Settingsfilename);
Config = JsonConvert.DeserializeObject<Configuration>(tmp);
_textDataHandler.CreateFile(Config.DatabaseFilename);
}
else
{
CreateDefaultSettingsConfiguration();
//log
_textDataHandler.CreateFile(_settingsFilename);
string export = JsonConvert.SerializeObject(Config, Formatting.Indented);
_textDataHandler.ExportText(_settingsFilename, export);
//Log
}
}
If one config does not exist its fine but if both exist it fails at the second time
If you have created async method. please avoid synchronous invoke with GetResult. You could add await key word in front of calling line.
private async void Button_Click(object sender, RoutedEventArgs e)
{
string tmp = await ImportLines(Filename);
}
Update
Please try use dataReader to read file content.
public async Task<string> ImportLines(string filename)
{
try
{
StorageFile importFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
var buffer = await FileIO.ReadBufferAsync(importFile);
using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
{
return dataReader.ReadString(buffer.Length);
}
}
catch (Exception ex)
{
return ex.Message;
}
}

signalr .net client reconnect error

I'm writing a program that makes remote desktop connection with signalr. I keep sending screenshots (in the .net client) for it. But when I reconnect to the server after a while, I get error: Connection started reconnecting before invocation result was received.
public void ImageMain()
{
var querstring = new Dictionary<string, string>();
querstring.Add("userid", "sessionlocal");
var hubConnectionMouse = new HubConnection("http://localhost:8089/", querstring);
Program p = new Program();
IHubProxy myHubProxyMouse = hubConnectionMouse.CreateHubProxy("MyHub");
string a = "";
try
{
hubConnectionMouse.Start().Wait();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
byte[] ekran;
while (true)
{
ekran = null;
ekran = EkranGoruntusu();
if (ekran.Length < 80000)
{
try
{
myHubProxy.Invoke("addMessage", "sessionlocal", ekran).ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("!!! image gönderilirken hata olıştu:{0} \n",
task.Exception.GetBaseException() + "tekrar bağlanılıyor....");
}
else
{
Console.WriteLine("Add messgae" + " gonderilecek ekran boyutu " + ekran.Length);
Console.WriteLine("hub durumu" + hubConnection.State);
}
}).Wait();
}
catch (Exception exception)
{
Console.WriteLine("bağlantı hatas tekrar bağlanılıyor" + exception.Message);
Console.ReadKey();
}
}
else
{
Console.WriteLine("gonderilcek goruntü cok büyük");
}
}
Console.ReadLine();
}

Android error: Nested signal detected - original signal being reported

This is killing me. I'm new to android/Xamarin. I can't find anything on the web that explains what is going on here.
I'm using xamarin forms for my application. I have a page that synchronizes the device with a web service.
The method simply retrieves 100 records at a time from the web service and updates a sqlite table on the device. I randomly get this error. I'm running 5000 records for my test sample.
Here is the button click:
public async void OnSyncCachedData_Clicked(object sender, EventArgs e)
{
activityIndicatorAll.IsRunning = true;
try
{
actIndSyncItems.IsRunning = true;
SyncAllFinished += SynchAllFinishedProcessing;
await Task.Run(async () => await App.ItemsRepo.LoadCacheDataFromCacheAsync(DbPath).ConfigureAwait(false));
}
catch (BAL.Exceptions.NetworkException nex)
{
await DisplayAlert(Messages.TitleError, nex.Message, Messages.MsgOk);
}
catch (Exception ex)
{
await DisplayAlert(Messages.TitleError, string.Format(Messages.MsgAreYouConnectedParm1, ex.Message), Messages.MsgOk);
}
finally
{
EventHandler handler = SyncAllFinished;
if (handler != null)
{
handler(this, new EventArgs());
}
SyncAllFinished -= SynchAllFinishedProcessing;
}
}
the main worker method:
public async Task<bool> LoadCacheDataFromCacheAsync(string dbPath)
{
WebSvcManagers.ItemsManager itemsWebServiceManager = new WebSvcManagers.ItemsManager();
List<Models.WebServiceItems> consumedRecords = new List<Models.WebServiceItems>() { };
int bufferSize = 100;
Log.Debug(TAG, "LoadCacheDataFromCacheAsync starting");
try
{
{
int lastID = 0;
IEnumerable<Models.WebServiceItems> remoteRecords = await BAL.DataAccessHelper.GetItemsFromGPCacheAsync(App.Login, lastID, bufferSize, itemsWebServiceManager).ConfigureAwait(false);
while (remoteRecords.Count() != 0)
{
foreach (Models.WebServiceItems remoteItem in remoteRecords)
{
// DbActionTypes dbAction = (DbActionTypes)remoteItem.DbAction;
Models.Items itemRecord = new Models.Items() { ItemNumber = remoteItem.ItemNumber.ToUpper().Trim(), Description = remoteItem.Description.Trim() };
Log.Debug(TAG, "Processing {0}", remoteItem.ItemNumber.Trim());
bool success = await AddRecordAsync(itemRecord).ConfigureAwait(false);
if (success)
consumedRecords.Add(remoteItem);
}
lastID = remoteRecords.Max(r => r.RecordID) + 1;
remoteRecords = await BAL.DataAccessHelper.GetItemsFromGPCacheAsync(App.Login, lastID, bufferSize, itemsWebServiceManager).ConfigureAwait(false);
}
}
// await UpdateConsumedRecords(consumedRecords).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
this.StatusMessage = ex.Message;
Log.Debug(TAG, "Error Catch: {0}", StatusMessage);
return false;
}
finally
{
itemsWebServiceManager = null;
HandleSyncFinished(this, new EventArgs());
SyncAllFinished -= HandleSyncFinished;
}
}
My simple webservice manager:
public static async Task<IEnumerable<Models.WebServiceItems>> GetItemsFromGPCacheAsync(Models.Login login, int offset, int bufferCount, WebSvcManagers.ItemsManager manager)
{
try
{
return await manager.GetCacheRecordsAsync(login, offset, bufferCount).ConfigureAwait(false);
}
catch (Exception)
{
throw;
}
}
And the code for the interaction with the web service:
const int bufferSize = 100;
public async Task<IEnumerable<Models.WebServiceItems>> GetCacheRecordsAsync(Models.Login login, int offSet, int bufferCount)
{
string deviceID = App.ConfigSettings.DeviceID.ToString("D");
try
{
///* Testing start */
//return await DataStore(bufferCount, offSet).ConfigureAwait(false);
///* Testing end */
if (!App.IsConnected)
throw new BAL.Exceptions.NetworkException(Messages.ExceptionNetworkConnection);
string user = login.UserName;
string password = login.Password;
HttpClient client = HttpClientExtensions.CreateHttpClient(user, password);
try
{
List<Models.WebServiceItems> items = new List<Models.WebServiceItems>() { };
int lastID = offSet;
int i = 0;
string uri = string.Format("{0}", string.Format(Messages.WebRequestItemsCacheParms3, deviceID, lastID, Math.Min(bufferCount, bufferSize)));
Log.Debug(TAG, string.Format("Webservice {0}", uri));
string response = await client.GetStringAsync(uri).ConfigureAwait(false);
while (i < bufferCount && response != null && response != "[]")
{
while (response != null && response != "[]")
{
dynamic array = JsonConvert.DeserializeObject(response);
foreach (var item in array)
{
i++;
items.Add(new Models.WebServiceItems()
{
ItemNumber = item["ITEMNMBR"].Value.Trim(),
Description = item["ITEMDESC"].Value.Trim(),
DbAction = (int)(item["DbAction"].Value),
RecordID = (int)(item["DEX_ROW_ID"].Value),
});
lastID = (int)(item["DEX_ROW_ID"].Value);
Log.Debug(TAG, string.Format("Webservice {0}", item["ITEMNMBR"].Value.Trim()));
}
if (i < Math.Min(bufferCount, bufferSize))
{
uri = string.Format("{0}", string.Format(Messages.WebRequestItemsCacheParms3, deviceID, lastID + 1, Math.Min(bufferCount, bufferSize)));
Log.Debug(TAG, string.Format("Webservice {0}", uri));
response = await client.GetStringAsync(uri).ConfigureAwait(false);
}
else
break;
}
}
Log.Debug(TAG, string.Format("Webservice return {0} items", items.Count()));
return items;
}
catch (Exception ex)
{
Log.Debug(TAG, "Error Catch: {0}", ex.Message);
throw ex;
}
}
catch (System.Net.Http.HttpRequestException nex)
{
throw new Exception(string.Format(Messages.ExceptionWebServiceLoginParm1, nex.Message));
}
catch (Exception)
{
throw;
}
}
I've had assistance from a Xamarin instructor and we thought we got it, (because this is random), but it clearly is not swatted. I've been hitting my head up against a wall for over 3 weeks on this. It smells like a memory leak, but I have no idea how to find it with such a generic error message that doesn't appear on web searches.
Somebody out there with some major brains, Please help!
Error:
08-03 12:41:11.281 D/X:ItemsRepositiory(16980): UpdateRecordAsync 65702-40710
08-03 12:41:11.306 D/X:ItemsManager(16980): Webservice DeleteCacheRecordAsync 20497
08-03 12:41:11.406 D/X:ItemsManager(16980): Webservice api/InventoryItems?DeviceID=7c5bb45d-2ea0-45b9-ae50-92f2e25a2983&OffSet=20498&Ma‌​x=100&cached=true
Thread finished: <Thread Pool> #7 08-03 12:41:11.521 E/art (16980): Nested signal detected - original signal being reported The thread 'Unknown' (0x7) has exited with code 0 (0x0).
This might be a problem with the VS Android Emulator. As we have shown in tests, this is not reproducible on the Google Android Emulators, nor on Xamarin Android Player, nor on a physical Android device.

The process cannot access the file because it is being used by another process

I am running a program where a file gets uploaded to a folder in IIS,and then is processed to extract some values from it. I use a WCF service to perform the process, and BackgroundUploader to upload the file to IIS. However, after the upload process is complete, I get the error "The process cannot access the file x because it is being used by another process." Based on similar questions asked here, I gathered that the file concerned needs to be in a using statement. I tried to modify my code to the following, but it didn't work, and I am not sure if it is even right.
namespace App17
{
public sealed partial class MainPage : Page, IDisposable
{
private CancellationTokenSource cts;
public void Dispose()
{
if (cts != null)
{
cts.Dispose();
cts = null;
}
GC.SuppressFinalize(this);
}
public MainPage()
{
this.InitializeComponent();
cts = new CancellationTokenSource();
}
public async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Uri uri = new Uri(serverAddressField.Text.Trim());
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
GlobalClass.filecontent = file.Name;
GlobalClass.filepath = file.Path;
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);
await HandleUploadAsync(upload, true);
stream.Dispose();
}
}
catch (Exception ex)
{
string message = ex.ToString();
var dialog = new MessageDialog(message);
await dialog.ShowAsync();
Log(message);
}
}
private void CancelAll(object sender, RoutedEventArgs e)
{
Log("Canceling all active uploads");
cts.Cancel();
cts.Dispose();
cts = new CancellationTokenSource();
}
private async Task HandleUploadAsync(UploadOperation upload, bool start)
{
try
{
Progress<UploadOperation> progressCallback = new Progress<UploadOperation>(UploadProgress);
if (start)
{
await upload.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
// The upload was already running when the application started, re-attach the progress handler.
await upload.AttachAsync().AsTask(cts.Token, progressCallback);
}
ResponseInformation response = upload.GetResponseInformation();
Log(String.Format("Completed: {0}, Status Code: {1}", upload.Guid, response.StatusCode));
cts.Dispose();
}
catch (TaskCanceledException)
{
Log("Upload cancelled.");
}
catch (Exception ex)
{
string message = ex.ToString();
var dialog = new MessageDialog(message);
await dialog.ShowAsync();
Log(message);
}
}
private void Log(string message)
{
outputField.Text += message + "\r\n";
}
private async void LogStatus(string message)
{
var dialog = new MessageDialog(message);
await dialog.ShowAsync();
Log(message);
}
private void UploadProgress(UploadOperation upload)
{
BackgroundUploadProgress currentProgress = upload.Progress;
MarshalLog(String.Format(CultureInfo.CurrentCulture, "Progress: {0}, Status: {1}", upload.Guid,
currentProgress.Status));
double percentSent = 100;
if (currentProgress.TotalBytesToSend > 0)
{
percentSent = currentProgress.BytesSent * 100 / currentProgress.TotalBytesToSend;
}
MarshalLog(String.Format(CultureInfo.CurrentCulture,
" - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", currentProgress.BytesSent,
currentProgress.TotalBytesToSend, percentSent, currentProgress.BytesReceived, currentProgress.TotalBytesToReceive));
if (currentProgress.HasRestarted)
{
MarshalLog(" - Upload restarted");
}
if (currentProgress.HasResponseChanged)
{
MarshalLog(" - Response updated; Header count: " + upload.GetResponseInformation().Headers.Count);
}
}
private void MarshalLog(string value)
{
var ignore = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
Log(value);
});
}
}
}
After this is done, the file name is sent to a WCF service which will access and process the uploaded file to extract certain values. It is at this point I receive the error. I would truly appreciate some help.
public async void Extract_Button_Click(object sender, RoutedEventArgs e)
{
ServiceReference1.Service1Client MyService = new ServiceReference1.Service1Client();
string filename = GlobalClass.filecontent;
string filepath = #"C:\Users\R\Documents\Visual Studio 2015\Projects\WCF\WCF\Uploads\"+ filename;
bool x = await MyService.ReadECGAsync(filename, filepath);
}
EDIT: Code before I added the using block
try
{
Uri uri = new Uri(serverAddressField.Text.Trim());
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();
GlobalClass.filecontent = file.Name;
GlobalClass.filepath = file.Path;
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);
await HandleUploadAsync(upload, true);
}
When you work with stream writers you actually create a process, which you can close it from task manager. And after stream.Dispose() put stream.Close().
This should solve your problem.
You should also close the stream that writes the file to disk (look at your implementation of CreateUpload).
i got such error in DotNet Core 2 using this code:
await file.CopyToAsync(new FileStream(fullFileName, FileMode.Create));
counter++;
and this is how I managed to get rid of message (The process cannot access the file x because it is being used by another process):
using (FileStream DestinationStream = new FileStream(fullFileName, FileMode.Create))
{
await file.CopyToAsync(DestinationStream);
counter++;
}

Categories