Downloading and saving a file fails after publishing app - c#

When I finish developing app on Windows Phone 8 in Visual Studio 2013 and start testing it on my physical device - everything works perfect.
After publishing app in Windows Mobile Store, when i download app on device, it giving me error in moment i want to download and save file into IsolatedStorage. This occurs in this fragment.
I missing some permissions? Why when I debug app via VS everything is okay, but after publishing - fails?
private Task<Stream> DownloadFile(Uri url)
{
var task = new TaskCompletionSource<Stream>();
var webClient = new WebClient();
webClient.OpenReadCompleted += (s, e) =>
{
if (e.Error != null) task.TrySetException(e.Error);
else if (e.Cancelled) task.TrySetCanceled();
else task.TrySetResult(e.Result);
};
webClient.OpenReadAsync(url);
return task.Task;
}
private async Task<Problem> DownloadFileFromWeb(Uri uriToDownload, string fileName, CancellationToken cToken)
{
try
{
using (Stream stream = await DownloadFile(uriToDownload))
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (storage.FileExists(fileName)) return Problem.Other;
using (IsolatedStorageFileStream file = storage.CreateFile(fileName))
{
const int BUFFER_SIZE = 8192;
byte[] buf = new byte[BUFFER_SIZE];
int bytesread = 0;
while ((bytesread = await stream.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
cToken.ThrowIfCancellationRequested();
file.Write(buf, 0, bytesread);
}
}
}
return Problem.Ok;
}
catch (Exception exc)
{
if (exc is OperationCanceledException)
return Problem.Cancelled;
else return Problem.Other;
}
}

Related

multiple files download using httpclient

I am working on xamarin.forms application. I want to download multiple files simultaneously using HttpClient. If there is multiple files then I am getting : System.IO.IOException:Sharing violation on path . Is there anything that has to be improved ?
Here is my code for downloading files :
public async Task DownloadFileAsync(string sourceUrl, string filePathWhereToSave, CancellationTokenSource cts)
{
Exception error = null;
bool isCancelled = false;
try
{
if (!downloadingTasks.ContainsKey(sourceUrl))
downloadingTasks.Add(sourceUrl, cts);
var token = cts.Token;
var response = await _client.GetAsync(sourceUrl, HttpCompletionOption.ResponseHeadersRead, token);
response.EnsureSuccessStatusCode();
string fileName = filePathWhereToSave.Substring(filePathWhereToSave.LastIndexOf('/'));
string directory = filePathWhereToSave.Substring(0, filePathWhereToSave.LastIndexOf('/'));
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
Directory.CreateDirectory(directory);
var totalData = response.Content.Headers.ContentLength.GetValueOrDefault(-1L);
var canSendProgress = totalData != -1L;
await Task.Run(async() =>
{
using (var fileStream = OpenStream(filePathWhereToSave))
{
using (var stream = await response.Content.ReadAsStreamAsync())
{
var totalRead = 0L;
var buffer = new byte[bufferSize];
var isMoreDataToRead = true;
do
{
var read = await stream.ReadAsync(buffer, 0, buffer.Length, token);
if (read == 0)
isMoreDataToRead = false;
else
{
await fileStream.WriteAsync(buffer, 0, read);
totalRead += read;
if (canSendProgress)
{
//var progress = ((totalRead * 1d) / (totalData * 1d) * 100);
MessagingCenter.Send<DownloadFileProgressChangedMessage>(new DownloadFileProgressChangedMessage(sourceUrl, totalRead, totalData, 0), MessageNameConstants.DownloadFileProgressChangedMessage);
}
}
} while (isMoreDataToRead);
}
}
});
}
catch (OperationCanceledException ex)
{
isCancelled = true;
}
catch (Exception e)
{
error = e;
System.Diagnostics.Debug.WriteLine(e.ToString());
}
finally
{
MessagingCenter.Send<DownloadCompletedMessage>(new DownloadCompletedMessage(sourceUrl, filePathWhereToSave, error, isCancelled), MessageNameConstants.DownloadCompletedMessage);
if (downloadingTasks.ContainsKey(sourceUrl))
downloadingTasks.Remove(sourceUrl);
}
}
This may be happening because the file is being locked by the reading stream, so the writing stream can't be created and you get the exception.
To avoid it you could enable read/write access with the class FileStream .
FileStream fileStream = new FileStream(filePathWhereToSave,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.None);
Or use StreamWriter
using (var writer = new StreamWriter(filePathWhereToSave))
{
// do work here.
}
BTW , what is OpenStream ? I can't find it in any assembly, is it included in a third-party library ?
Refer to
https://stackoverflow.com/a/23779697/8187800
https://stackoverflow.com/a/11541330/8187800

Writing apk file to android

I'm trying to write an apk file from a filestream to my android storage. I'm using Unity 3D with C#.
When testing on the PC I can send requests to my server (whichis also a c# console application), and save the apk file that my server sends me. It is a complete file and can be installed on any android.
However, when I build the project for android, it won;t wriet all the data to the storage device. here is the relevant code:
string apkFilePath = Application.persistentDataPath;
apkFilePath = apkFilePath + "/new.apk";
public void Receive()
{
byte[] RecData = new byte[BufferSize];
int RecBytes;
for (; ; )
{
string Status = string.Empty;
try
{
int totalrecbytes = 0;
if(File.Exists(apkFilePath))
{
File.Delete(apkFilePath);
}
FileStream Fs = new FileStream(apkFilePath, FileMode.Create, FileAccess.Write);
while ((RecBytes = ns.Read(RecData, 0, RecData.Length)) > 0)
{
if (RecBytes >= BufferSize)
{
print(RecBytes);
Fs.Write(RecData, 0, RecBytes);
totalrecbytes += RecBytes;
Fs.Flush();
}
if(RecBytes < BufferSize && RecBytes > 0)
{
print(RecBytes);
Fs.Write(RecData, 0, RecBytes);
totalrecbytes += RecBytes;
Fs.Flush();
break;
}
}
print("OUT OF LOOP");
//Fs.Flush();
Fs.Dispose();
Fs.Close();
quit = true;
break;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
//netstream.Close();
}
}
}
Any suggestions why it works for my PC but not on Android?

Download files from web and save in Phone : Windows Phone 8.1 (SilverLight) Development

I need to download files like ".Doc , .pdf , .xls , .Jpeg, .PNG etc" from the server and store into phone memory not to Isolated. I have search a lot but can not get any things for .doc , .pdf. I got a link Downloading and saving a file Async in Windows Phone 8
but can not work. So if any one can do this please let me know.
Thanks in advance.
I have done with FileSavePicker , here is code
public void DownloadFiles(Uri url)
{
var wc = new WebClient();
wc.OpenReadCompleted +=async (s, e) =>
{
Stream st = e.Result;
buf = ReadFully(st);
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
savePicker.PickSaveFileAndContinue();
StorageFile SF = await KnownFolders.PicturesLibrary.CreateFileAsync
("Guide.pdf", CreationCollisionOption.ReplaceExisting);
var fs = await SF.OpenAsync(FileAccessMode.ReadWrite);
StorageStreamTransaction transaction = await SF.OpenTransactedWriteAsync();
DataWriter dataWriter = new DataWriter(transaction.Stream);
dataWriter.WriteBytes(buf);
transaction.Stream.Size = await dataWriter.StoreAsync(); // reset stream size to override the file
await transaction.CommitAsync();
};
wc.OpenReadAsync(url);
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private async void ContinueFileOpenPicker(FileSavePickerContinuationEventArgs args)
{
StorageFile file = args.File;
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteBytesAsync(file, buf);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
Debug.WriteLine("File " + file.Name + " was saved.");
}
else
{
Debug.WriteLine("File " + file.Name + " couldn't be saved.");
}
}
else
{
Debug.WriteLine("Operation cancelled.");
}
await Windows.System.Launcher.LaunchFileAsync(file);
}
For More information Please go with this url How to continue your Windows Phone app after calling a file picker
I don't think you'll be able to directly download and store the files into the memory card as they have restricted access for security purposes. I guess Isolated Storage could be the option.
Reference

Launch app to view pdf from the webview wp8

I'm trying to launch a pdf app viewer when the page on the webview is a pdf file, but i canĀ“t find how to make this, is it possible?
You should read following article if you are not familiar with Async:
MSDN Asynchronous Programming with Async and Await
I couldn't test my app because my WP8 Phone is currently not available and I can't install an PDF reader on the emulator.
Call following method to start the download
WebClient pdfDownloader = null;
string LastFileName = ""; //To save the filename of the last created pdf
private void StartPDFDownload(string URL)
{
pdfDownloader = new WebClient(); //prevents that the OpenReadCompleted-Event is called multiple times
pdfDownloader.OpenReadCompleted += DownloadPDF; //Create an event handler
pdfDownloader.OpenReadAsync(new Uri(URL)); //Start to read the website
}
async void DownloadPDF(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length]; //Gets the byte length of the pdf file
await e.Result.ReadAsync(buffer, 0, buffer.Length); //Waits until the rad is completed (Async doesn't block the GUI Thread)
using (IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
LastFileName = "tempPDF" + DateTime.Now.Ticks + ".pdf";
using (IsolatedStorageFileStream ISFileStream = ISFile.CreateFile(LastFileName))
{
await ISFileStream.WriteAsync(buffer, 0, buffer.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + ex.HResult,
ex.Source, MessageBoxButton.OK);
//Catch errors regarding the creation of file
}
}
OpenPDFFile();
}
private async void OpenPDFFile()
{
StorageFolder ISFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
try
{
IStorageFile ISFile = await ISFolder.GetFileAsync(LastFileName);
await Windows.System.Launcher.LaunchFileAsync(ISFile);
//http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987%28v=vs.105%29.aspx
}
catch (Exception ex)
{
//Catch unknown errors while getting the file
//or opening the app to display it
}
}
To call these methods from your WebBrowser-Control you need to catch the navigating event.
YourWebBrowserControl.Navigating += YourWebBrowserControl_Navigating;
void YourWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
if(e.Uri.AbsolutPath.EndsWith("pdf"))
{
StartPDFDownload(e.Uri.ToString());
}
}
Don't forget that you'll have to delete the files created someday.

File Upload in Silverlight

I need to update a file which is on a remote server, using Silverlight and C#.
I created the file on the current machine and after that I tried to upload it using this example. It returned no error, but it doesn't upload my file either.
Could you help me?
this is the ashx code
<%# WebHandler Language="C#" Class="receiver" %>
using System;
using System.Web;
using System.IO;
public class receiver : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string filename = context.Request.QueryString["DB.xml"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/CLientBin" + filename)))
{
SaveFile(context.Request.InputStream, fs);
}
}
private void SaveFile(Stream stream, FileStream fs)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
public bool IsReusable {
get {
return false;
}
}
}
and this is the c# code:
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "All files (*.*)|*.*|PNG Images (*.png)|*.png";
bool? retval = dlg.ShowDialog();
if (retval != null && retval == true)
{
try
{
UploadFile(dlg.File.Name, dlg.File.OpenRead());
titlu.Text = dlg.File.Name;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
titlu.Text = "No file selected...";
}
}
private void UploadFile(string fileName, Stream data)
{
UriBuilder ub = new UriBuilder("http://ganduri.elementfx.com/Handler.ashx");
ub.Query = string.Format("filename={0}", fileName);
WebClient c = new WebClient();
c.OpenWriteCompleted += (sender, e) =>
{
PushData(data, e.Result);
e.Result.Close();
data.Close();
};
c.OpenWriteAsync(ub.Uri);
}
private void PushData(Stream input, Stream output)
{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
MessageBox.Show("Writed");
}
I have also checked the permissions to the ClientBin folder and are read/write permissions
When I run this code it shows me the "Writed" messageBox, but if I look in the server, the file isn't anywhere.
I have set a breakpoint in af ashx file functions and id doesn't reach any of them.
Think you need check upload folder for existence, and write access rights

Categories

Resources