I am new in reactnative mobile application development. I need to download file from webservice url in windows UWP. I checked with react-natived-fs and rn-fetch-blob its working only in android and ios. In windows UWP how can i achieve this download files.. Any one please help me.
i just write a bridge for this. now its working fine. For download i did
[ReactMethod]
public async void download(string fileName, JObject _, IPromise promise)
{
try
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFolder docFolder = KnownFolders.DocumentsLibrary;
string folderName = "DMSFolder";
StorageFile file = await localFolder.CreateFileAsync("sample1.pdf",CreationCollisionOption.ReplaceExisting);
StorageFile docfile = await docFolder.CreateFileAsync("sample1.zip",CreationCollisionOption.ReplaceExisting);
var cli = new HttpClient();
var uriBing = new Uri(#fileName);
Byte[] bytes = await cli.GetByteArrayAsync(uriBing);
IBuffer buffer = bytes.AsBuffer();
await Windows.Storage.FileIO.WriteBufferAsync(file, buffer);
await Windows.Storage.FileIO.WriteBufferAsync(docfile, buffer);
if (file != null)
{
promise.Resolve(null);
}
else
{
promise.Reject(null, "File Copied failed.");
}
}
catch (Exception e)//FieldAccessException
{
Console.WriteLine("Exception occured====>" + e);
promise.Reject(null, fileName, e);
}
}
Related
With the reference of following StackOverflow suggestion,
Convert HTML to PDF in .NET
I tried to convert the HTML file to PDF using HtmlRenderer.PdfSharp but unfortunately it shows compatible error like below,
HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)
HtmlRenderer.Core 1.5.0.5 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRenderer.Core 1.5.0.5 supports:
- net20 (.NETFramework,Version=v2.0)
- net30 (.NETFramework,Version=v3.0)
- net35-client (.NETFramework,Version=v3.5,Profile=Client)
- net40-client (.NETFramework,Version=v4.0,Profile=Client)
- net45 (.NETFramework,Version=v4.5)
HtmlRendererCore.PdfSharpCore 1.0.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0). Package HtmlRendererCore.PdfSharpCore 1.0.1 supports: netcoreapp2.0 (.NETCoreApp,Version=v2.0)
And I tried with wkhtmltopdf too but it throws similar error in android and other platform projects.
My requirement is to convert the HTML file to PDF file only (no need to view the PDF file, just to save it in local path).
Can anyone please provide suggestions?
Note : Need open source suggestion :)
Awaiting for your suggestions !!!
Support to convert the HTML to PDF in Xamarin Forms
You can read the HTML as a stream and store it into local like below,
public static class FileManager
{
public static async Task<MemoryStream> DownloadFileAsStreamAsync(string url)
{
try
{
var stream = new MemoryStream();
using (var httpClient = new HttpClient())
{
var downloadStream = await httpClient.GetStreamAsync(new Uri(url));
if (downloadStream != null)
{
await downloadStream.CopyToAsync(stream);
}
}
return stream;
}
catch (Exception exception)
{
return null;
}
}
public static async Task<bool> DownloadAndWriteIntoNewFile(string url, string fileName)
{
var stream = await DownloadFileAsStreamAsync(url);
if (stream == null || stream.Length == 0)
return false;
var filePath = GetFilePath(fileName);
if (!File.Exists(filePath))
return false;
File.Delete(filePath);
// Create file.
using (var createdFile = File.Create(filePath))
{
}
// Open and write into file.
using (var openFile = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite))
{
stream.WriteTo(openFile);
}
return true;
}
public static string GetFilePath(string fileName)
{
var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), fileName);
return filePath;
}
public static void WriteAsText(string filePath, string contents)
{
File.WriteAllText(filePath, contents);
}
public static string ReadAsText(string filePath)
{
return File.ReadAllText(filePath);
}
}
You can read a stored pdf file and displayed using webview like below,
private async void HtmlToPDF()
{
await FileManager.DownloadAndWriteIntoNewFile("https://www.google.co.in/?gws_rd=ssl", "SavePDF.pdf");
var filePath = FileManager.GetFilePath("SavePDF.pdf");
var pdfString = FileManager.ReadAsText(filePath);
var webView = new WebView
{
Source = new HtmlWebViewSource
{
Html = pdfString
}
};
this.Content = webView;
}
And the output below,
Likewise, you can save HTML as PDF and do what you want..
you can use the HtmlToPdfConverter
private void ConvertUrlToPdf()
{
try {
String serverIPAddress = serverIP.Text;
uint serverPortNumber = uint.Parse (serverPort.Text);
// create the HTML to PDF converter object
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter (serverIPAddress, serverPortNumber);
// set service password if necessary
if (serverPassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = serverPassword.Text;
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
// convert the HTML page from given URL to PDF in a buffer
byte[] pdfBytes = htmlToPdfConverter.ConvertUrl (urlToConvert.Text);
string documentsFolder = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
string outPdfFile = System.IO.Path.Combine (documentsFolder, "EvoHtmlToPdf.pdf");
// write the PDF buffer in output file
System.IO.File.WriteAllBytes (outPdfFile, pdfBytes);
// open the PDF document in the default PDF viewer
UIDocumentInteractionController pdfViewer = UIDocumentInteractionController.FromUrl (Foundation.NSUrl.FromFilename (outPdfFile));
pdfViewer.PresentOpenInMenu (this.View.Frame, this.View, true);
} catch (Exception ex) {
UIAlertView alert = new UIAlertView ();
alert.Title = "Error";
alert.AddButton ("OK");
alert.Message = ex.Message;
alert.Show ();
}
}
another
you can see thisurl
Trying to upload files from Windows 8.1 to Amazon s3 in Background. Kindly suggest how can I proceed.
I am using XAML. code Snippet of BackgroundDownloader and BackgroundUploader with Amazon S3 will be a great help.
Please find partial implementation of it below.
public async Task UploadFile(IReadOnlyList<StorageFile> files)
{
basicAwsCredentials = new BasicAWSCredentials(accesskey,secretkey);
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
for (int i = 0; i < files.Count; i++)
{
BackgroundTransferContentPart part = new BackgroundTransferContentPart("File" + i, files[i].Name);
part.SetFile(files[i]);
parts.Add(part);
}
Uri uri = new Uri(bucketurl+ExistingBucketName+"/");
BackgroundUploader uploader = new BackgroundUploader();
UploadOperation upload = await uploader.CreateUploadAsync(uri, parts);
// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);
}
private async Task HandleUploadAsync(UploadOperation upload, bool start)
{
try
{
CancellationTokenSource cts = new CancellationTokenSource();
Progress<UploadOperation> progressCallback = new Progress<UploadOperation>();
if (start)
{
// Start the upload and attach a progress handler.
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));
}
catch (TaskCanceledException)
{
// Log("Upload cancelled.");
}
catch (Exception ex)
{
//LogException("Error", ex);
}
}
I'm new to win8 app programming but has been assigned to write a windows store app to capture customers' signature and save it to SQL Server. After some research I found a great tutorial
http://www.codeproject.com/Articles/416878/Metro-Paint which shows how to draw and save the image locally. My question is how do I use the InkManager class in the tutorial to save the image to byte arrays so that I can save the image to SQLServer? Thanks!
private async void btnSaveWritingAsImage_Click(object sender, RoutedEventArgs e)
{
if (MyInkManager.GetStrokes().Count > 0)
{
try
{
Windows.Storage.Pickers.FileSavePicker SavePicker = new Windows.Storage.Pickers.FileSavePicker();
SavePicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
SavePicker.DefaultFileExtension = ".png";
SavePicker.FileTypeChoices.Add("PNG", new string[] { ".png" });
SavePicker.FileTypeChoices.Add("JPG", new string[] { ".jpg" });
StorageFile filesave = await SavePicker.PickSaveFileAsync();
IOutputStream ab = await filesave.OpenAsync(FileAccessMode.ReadWrite);
if (ab != null)
await MyInkManager.SaveAsync(ab);
}
catch (Exception)
{
var MsgDlg = new MessageDialog("Only handwriting can be saved as image.", "Error while saving");
MsgDlg.ShowAsync();
}
}
else
{
var MsgDlg = new MessageDialog("Only handwriting can be saved as image.", "Error while saving");
await MsgDlg.ShowAsync();
}
}
add: (IBuffer.ToArray() is defined in WindowsRuntimeBufferExtensions)
using System.Runtime.InteropServices.WindowsRuntime;
then just do:
var buffer = await FileIO.ReadBufferAsync(image);//replace ab instead of image
var bytes = buffer.ToArray();
I am creating Thumbnail and showing in frame by using this code
Platform -> windows 8 metro apps using c#
http://code.msdn.microsoft.com/windowsapps/File-and-folder-thumbnail-1d530e5d
in windows 8 metro apps using c#. i need to save or Store ( in device )the thumbnail image which i am creating at run time. in DisplayResult() of constants.cs class file i need to save that image in device how to achieve this . please give me some idea or example i am very new in mobile and never worked on Image and thumbnails Part . Thanks in advance .
Try this. The below code will save picked audio file's album art in TempFolder
private async void btnPickFile_Click(object sender, RoutedEventArgs e)
{
string[] Music = new string[] { ".mp3", ".wma", ".m4a", ".aac" };
FileOpenPicker openPicker = new FileOpenPicker();
foreach (string extension in Music)
{
openPicker.FileTypeFilter.Add(extension);
}
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
await SaveThumbnail("MySongThumb.png", file);
}
}
private async Task SaveThumbnail(string ThumbnailName, StorageFile file)
{
if (file != null)
{
using (StorageItemThumbnail thumbnail = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 100))
{
if (thumbnail != null && thumbnail.Type == ThumbnailType.Image)
{
var destinationFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(ThumbnailName, CreationCollisionOption.GenerateUniqueName);
Windows.Storage.Streams.Buffer MyBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(thumbnail.Size));
IBuffer iBuf = await thumbnail.ReadAsync(MyBuffer, MyBuffer.Capacity, InputStreamOptions.None);
using (var strm = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
{
await strm.WriteAsync(iBuf);
}
}
}
}
}
UPDATE 1
private async Task<StorageFile> SaveThumbnail(StorageItemThumbnail objThumbnail)
{
if (objThumbnail != null && objThumbnail.Type == ThumbnailType.Image)
{
var picker = new FileSavePicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
picker.FileTypeChoices.Add("PNG Image", new string[] { ".png" });
StorageFile destinationFile = await picker.PickSaveFileAsync();
if (destinationFile != null)
{
Windows.Storage.Streams.Buffer MyBuffer = new Windows.Storage.Streams.Buffer(Convert.ToUInt32(objThumbnail.Size));
IBuffer iBuf = await objThumbnail.ReadAsync(MyBuffer, MyBuffer.Capacity, InputStreamOptions.None);
using (var strm = await destinationFile.OpenAsync(FileAccessMode.ReadWrite))
{
await strm.WriteAsync(iBuf);
}
}
return destinationFile;
}
else
{
return null;
}
}
I am writing a unit test to validate the serialization of objects and I am able to successfully save the file without any issue. I can even browse the file and validate the contents are correct. However, when I attempt to open the file for reading I always receive an UnauthorizedAccess exception.
Here is the code used to save the item:
public static async Task SaveItem<T>(string folderName, T item)
where T : BaseBusinessItem
{
if (string.IsNullOrEmpty(folderName))
{
throw new ArgumentNullException("folderName");
}
if (item == null)
{
throw new ArgumentNullException("item");
}
try
{
var folder = await ApplicationData.Current.LocalFolder
.CreateFolderAsync(folderName, CreationCollisionOption.OpenIfExists);
var file =
await
folder.CreateFileAsync(item.UniqueID.GetHashCode().ToString(), CreationCollisionOption.ReplaceExisting);
var stream = await file.OpenAsync(FileAccessMode.ReadWrite);
using (var outStream = stream.GetOutputStreamAt(0))
{
var serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(outStream.AsStreamForWrite(), item);
await outStream.FlushAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
Here is the code used to restore the item:
public static async Task<T> RestoreItem<T>(string folderName, string hashCode)
where T : BaseBusinessItem, new()
{
if (string.IsNullOrEmpty(folderName))
{
throw new ArgumentNullException("folderName");
}
if (string.IsNullOrEmpty(hashCode))
{
throw new ArgumentNullException("hashCode");
}
var folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(folderName);
var file = await folder.GetFileAsync(hashCode);
var inStream = await file.OpenSequentialReadAsync();
var serializer = new DataContractJsonSerializer(typeof(T));
var retVal = (T)serializer.ReadObject(inStream.AsStreamForRead());
return retVal;
}
And the unit test:
[TestMethod]
public async Task TestFileSaveLoad()
{
await _ds.SaveItem("TestFolder");
Guid ID = _item.UniqueID;
_ds = await ItemDataSource.LoadItem("TestFolder", ID.GetHashCode().ToString());
}
Any ideas or troubleshooting steps I might be missing. The unit test app manifest includes the following capabilities: Document Library, Internet (Client). The following declarations are in place: File Open Picker, File Save Picker and File Type Associations.
Thanks!
This code snippet helped me accomplish my goal. Hope this is helpful for someone else:
http://codepaste.net/gtu5mq