Windows 8.1 BackgroundUploader with Amazon S3 c# in XAML - xaml

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);
}
}

Related

Using Google Drive Api on android studio?

i am working on app that integrates google drive api to upload/download files from the user's Google Drive account. i am using
this documentation google drive api v3, but it dont work,
i got this error ->
'java.net.MalformedURLException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference', i can login into google account and log out, but cant uplodad files
public Task<String> newFile(String filepath) {
return Tasks.call(executor, () -> {
File fmdt = new File();
fmdt.setName("contents.json");
java.io.File fp = new java.io.File(filepath);
FileContent mediaContent = new FileContent("application/json",fp);
File mf = null;
try {
mf = driveService.files().create(fmdt, mediaContent).setFields("id").execute();
} catch (Exception e) {
e.printStackTrace();
Log.d("usr","drive-> "+e.getMessage() );
}
if (mf == null) {
throw new IOException("null result");
}
return mf.getId();
});
}
this is how i solve, i guest you re actualli singin on goggle
//the class that handle upload request
public class GoogleDriveHelper {
private final Executor executor = Executors.newSingleThreadExecutor();
private final Drive driveService;
public GoogleDriveHelper(Drive mDriveService) {
this.driveService = mDriveService;
}
public Task<String> newFile(String fileName, String path, String parentId, File file) {
return Tasks.call(executor, () -> {
//use parent to save in especific folder
File fmdt = new File()
.setParents(Collections.singletonList(parentId))
.setMimeType("application/octet-stream")
.setName(nfileName);
File mf = null;
FileContent mediaContent = new FileContent("application/octet-stream", file);
try {
mf = driveService.files().create(fmdt, mediaContent).setFields("id").execute();
} catch (Exception e) {
e.printStackTrace();
}
if (mf == null) {
throw new IOException("null result");
}
return mf.getId();
});
}}
//inicialize google drive service
val credential =
GoogleAccountCredential.usingOAuth2(
ctx,
Collections.singleton(DriveScopes.DRIVE_FILE)
)
credential.selectedAccount = account!!.account
gService = Drive.Builder(
AndroidHttp.newCompatibleTransport(),
GsonFactory(),
credential
).
setApplicationName(APPLICATION_NAME).build();
gDrivehelper = GoogleDriveHelper(gService)

How to detect when client has closed stream when writing to Response.Body in asp.net core

I'm trying to write an infinite length response body and detect when a client disconnects so I can stop writing. I'm used to getting socket exceptions or similar when a client closes the connection but that doesn't seem to be happening when writing directly to Response.Body. I can close the client applications and the server side just keeps on writing. I've included the relevant code below. It's entirely possible there is a better way to do it but this came to mind. Basically I have a live video feed which should go on forever. I'm writing to ResponseBody as chunked content (No content length, flushing after each video frame). The video frames are received via an event callback from elsewhere in the program so I'm subscribing to the events in the controller method and then forcing it to stay open with the await Task.Delay loop so the Response stream isn't closed. The callback for H264PacketReceived is formatting the data as a streaming mp4 file and writing it to the Response Stream. This all seems to work fine, I can play the live stream with ffmpeg or chrome, but when I close the client application I don't get an exception or anything. It just keeps writing to the stream without any errors.
public class LiveController : ControllerBase
{
[HttpGet]
[Route("/live/{cameraId}/{stream}.mp4")]
public async Task GetLiveMP4(Guid cameraId, int stream)
{
try
{
Response.StatusCode = 200;
Response.ContentType = "video/mp4";
Response.Headers.Add("Cache-Control", "no-store");
Response.Headers.Add("Connection", "close");
ms = Response.Body;
lock (TCPVideoReceiver.CameraStreams)
{
TCPVideoReceiver.CameraStreams.TryGetValue(cameraId, out cameraStream);
}
if (this.PacketStream == null)
{
throw new KeyNotFoundException($"Stream {cameraId}_{stream} not found");
}
else
{
connected = true;
this.PacketStream.H264PacketReceived += DefaultStream_H264PacketReceived;
this.PacketStream.StreamClosed += PacketStream_StreamClosed;
}
while(connected)
{
await Task.Delay(1000);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connected = false;
this.PacketStream.H264PacketReceived -= DefaultStream_H264PacketReceived;
this.PacketStream.StreamClosed -= PacketStream_StreamClosed;
}
}
private bool connected = false;
private PacketStream PacketStream;
private Mp4File mp4File;
private Stream ms;
private async void PacketStream_StreamClosed(PacketStream source)
{
await Task.Run(() =>
{
try
{
Console.WriteLine($"Closing live stream");
connected = false;
ms.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
});
}
private async void DefaultStream_H264PacketReceived(PacketStream source, H264Packet packet)
{
try
{
if (mp4File == null && packet.IsIFrame)
{
mp4File = new Mp4File(null, packet.sps, packet.pps);
var _p = mp4File.WriteHeader(0);
await ms.WriteAsync(mp4File.buffer, 0, _p);
}
if (mp4File != null)
{
var _p = mp4File.WriteFrame(packet, 0);
var start = mp4File._moofScratchIndex - _p;
if (_p > 0)
{
await ms.WriteAsync(mp4File._moofScratch, start, _p);
await ms.FlushAsync();
}
}
return;
}
catch (Exception ex)
{
connected = false;
Console.WriteLine(ex.ToString());
}
}
Answering my own question.
When the client disconnects mvc core sets the cancellation token HttpContext.RequestAborted
By monitoring and/or using that cancellation token you can detect a disconnect and clean everything up.
That said, the entire design can be improved by creating a custom stream which encapsulates the event handling (producer/consumer). Then the controller action can be reduced to.
return File(new MyCustomStream(cameraId, stream), "video/mp4");
The File Method already monitors the cancellation token and everything works as you'd expect.

How to Dowload files in React-Native UWP application

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);
}
}

Save InkManager images to byte array

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();

Cannot Open Files in WinRT Unit Testing

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