/// <summary> /// Resizes the image using a high quality. /// From http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp /// </summary> /// <param name="imageStream"></param> /// <returns></returns> internal static MemoryStream ProcessImage(MemoryStream imageStream) { var height = 100; var width = 100; Image original = Image.FromStream(imageStream); var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(original.HorizontalResolution, original.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(original, destRect, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, wrapMode); } } MemoryStream ret = new MemoryStream(); destImage.Save(ret, original.RawFormat); ret.FlushAsync().Wait(); ret.Position = 0; return ret; }
public static async Task<byte[]> ToByteArrayAsync(this ArraySegment<byte> source) { byte[] data = null; using (MemoryStream ms = new MemoryStream()) { await ms.WriteAsync(source.Array, source.Offset, source.Count); await ms.FlushAsync(); data = ms.ToArray(); } return data; }
public static async Task<byte[]> CompressAsync(this byte[] data, CancellationToken cancellationToken = default(CancellationToken)) { byte[] compressesData; using (var outputStream = new MemoryStream()) { using (var zip = new GZipStream(outputStream, CompressionMode.Compress, true)) { await zip.WriteAsync(data, 0, data.Length, cancellationToken); } await outputStream.FlushAsync(cancellationToken); compressesData = outputStream.ToArray(); } return compressesData; }
public static async Task<string> DownloadToString(this CloudBlockBlob blob) { using (var strm = new MemoryStream()) { await Task.Factory.FromAsync((cb, state) => blob.BeginDownloadToStream(strm, cb, state), ar => blob.EndDownloadToStream(ar), state: null); await strm.FlushAsync(); strm.Seek(0, SeekOrigin.Begin); return await new StreamReader(strm).ReadToEndAsync(); } }
/// <summary> /// Transport the given <paramref name="serialisedMessage"/>. /// </summary> /// <param name="serialisedMessage">The content of the message to send.</param> /// <returns>An awaitable object for the Send operation.</returns> public async Task SendMessageAsync(string serialisedMessage) { using (var outputStream = this._ftpClient.PutFile(string.Concat("/", DateTime.Now.ToFileTimeUtc(), ".msg"))) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(serialisedMessage))) { await stream.CopyToAsync(outputStream); await stream.FlushAsync(); await outputStream.FlushAsync(); } } }
/// <summary> /// Place a raw message onto the FTP Server. /// </summary> /// <param name="messageLocation">The relative location where the message should be placed.</param> /// <param name="serialisedMessage">The raw message content.</param> /// <returns>An awaitable object for the Put operation.</returns> public async Task PutMessage(Uri messageLocation, string serialisedMessage) { using (var outputStream = this._ftpClient.PutFile(messageLocation.ToString())) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(serialisedMessage))) { await stream.CopyToAsync(outputStream); await stream.FlushAsync(); await outputStream.FlushAsync(); } } }
public async Task <byte[]> ToCsvAsync() { using var memoryStream = new System.IO.MemoryStream(); using var writer = new System.IO.StreamWriter(memoryStream); using var csv = new CsvHelper.CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)); await csv .WriteRecordsAsync(await _schoolService.GetForExportAsync()); await csv.FlushAsync(); await writer.FlushAsync(); await memoryStream.FlushAsync(); return(memoryStream.ToArray()); }
public async Task UploadAsync(string url, IDictionary<string, string> headers, string method, string file) { byte[] data = null; // Get the local folder. var localStorage = IsolatedStorageFile.GetUserStoreForApplication(); using (var fileStream = new IsolatedStorageFileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, localStorage)) { using (var memStream = new MemoryStream()) { await fileStream.CopyToAsync(memStream); await fileStream.FlushAsync(); await memStream.FlushAsync(); data = memStream.ToArray(); } } await UploadAsync(url, headers, method, data); }
public async static Task<String> ToBase64String(this Bitmap iBitmap) { using (MemoryStream pMSmOutput = new MemoryStream()) { using (EncoderParameters pEPsParams = new EncoderParameters(1)) { EncoderParameter pEPrParam = new EncoderParameter(Encoder.Quality, 100L); pEPsParams.Param[0] = pEPrParam; using (Bitmap pBmpCopy = new Bitmap(iBitmap)) { pBmpCopy.Save(pMSmOutput, GetEncoder(ImageFormat.Jpeg), pEPsParams); } await pMSmOutput.FlushAsync(); String pStrBase64 = Convert.ToBase64String(pMSmOutput.ToArray()); return (pStrBase64); } } }
public async Task<Tuple<Stream,string>> AddUrlResourceAsync(string url,bool needBig) { string contentType; var hash = ComputeMD5(url); CloudBlockBlob blobRef = Container.GetBlockBlobReference(hash); if (blobRef.Exists()) { MemoryStream ms2=new MemoryStream(); if(needBig) { await blobRef.DownloadToStreamAsync(ms2); } else { await quantizedManager.DownloadToStream(ms2, hash); } ms2.Seek(0, SeekOrigin.Begin); contentType = blobRef.Properties.ContentType; return new Tuple<Stream, string>(ms2, contentType); } WebClient wc = new WebClient(); Stream stream = wc.OpenRead(url); contentType=blobRef.Properties.ContentType = wc.ResponseHeaders["Content-Type"]; if (!whiteMIMEList.Contains(contentType.ToLower())) return null;//これ以外で実行形式などがアップロードされないようにホワイトリスト await blobRef.UploadFromStreamAsync(stream); MemoryStream ms=new MemoryStream(); await blobRef.DownloadToStreamAsync(ms); await ms.FlushAsync(); ms.Seek(0, SeekOrigin.Begin); Bitmap sourceBitmap = new Bitmap(ms); var size = ClampSize(sourceBitmap); Bitmap resizedBitmap = ResizeImage(sourceBitmap, size.Item1, size.Item2); MemoryStream ms3=new MemoryStream(); resizedBitmap.Save(ms3,ImageFormat.Jpeg); ms3.Seek(0, SeekOrigin.Begin); await quantizedManager.UploadResizedBlob(ms3,hash); ms3.Seek(0, SeekOrigin.Begin); return new Tuple<Stream, string>(ms3,"image/jpeg"); }
public async Task<byte[]> DownloadAsync(string url, IDictionary<string, string> headers, string method) { var client = new WebClient(); if (headers != null) { foreach (var header in headers) client.Headers[header.Key] = header.Value; } var downloadStream = await client.OpenReadTaskAsync(url); byte[] buffer = new byte[1024]; using (MemoryStream stream = new MemoryStream()) { while (downloadStream.Read(buffer, 0, buffer.Length) > 0) { stream.Write(buffer, 0, buffer.Length); } await stream.FlushAsync(); return stream.ToArray(); } }
internal override async Task Compress(Func<IDictionary<string, object>, Task> next, OwinContext context, ICompressor compressor, Stream httpOutputStream) { using (var uncompressedStream = new MemoryStream()) { context.Response.Body = uncompressedStream; await next.Invoke(context.Environment); await uncompressedStream.FlushAsync(); if (uncompressedStream.Length > 0) { uncompressedStream.Position = 0; if (ShouldCompress(context.Response.ContentType)) { await CompressToHttpOutputStream(context, compressor, httpOutputStream, uncompressedStream); } else { await uncompressedStream.CopyToAsync(httpOutputStream, BufferSize); } } } }
public async Task RaiseOutputMessageEvent() { // Arrange const string message = "Hello node.js!"; string formattedMessage = string.Format("Content-Length: {0}{1}{1}{2}", Encoding.UTF8.GetByteCount(message), Environment.NewLine, message); byte[] rawMessage = Encoding.UTF8.GetBytes(formattedMessage); var memoryStream = new MemoryStream(); await memoryStream.WriteAsync(rawMessage, 0, rawMessage.Length); await memoryStream.FlushAsync(); memoryStream.Seek(0, SeekOrigin.Begin); var tcpClientMock = new Mock<INetworkClient>(); tcpClientMock.Setup(p => p.GetStream()).Returns(() => memoryStream); tcpClientMock.SetupGet(p => p.Connected).Returns(() => true); var tcpClientFactoryMock = new Mock<INetworkClientFactory>(); tcpClientFactoryMock.Setup(p => p.CreateNetworkClient(It.IsAny<Uri>())).Returns(() => tcpClientMock.Object); var debuggerConnection = new DebuggerConnection(tcpClientFactoryMock.Object); object sender = null; MessageEventArgs args = null; bool inital = debuggerConnection.Connected; // Act debuggerConnection.OutputMessage += (s, a) => { sender = s; args = a; }; debuggerConnection.Connect(new Uri("tcp://localhost:5858")); bool afterConnection = debuggerConnection.Connected; await Task.Delay(TimeSpan.FromMilliseconds(100)); memoryStream.Close(); // Assert Assert.IsNotNull(sender); Assert.AreEqual(debuggerConnection, sender); Assert.IsNotNull(args); Assert.AreEqual(message, args.Message); Assert.IsFalse(inital); Assert.IsTrue(afterConnection); }
public async Task RetrieveNodeVersion() { // Arrange const string version = "0.10.25"; string message = string.Format("Embedding-Host: node v{0}\r\n\r\n", version); byte[] rawMessage = Encoding.UTF8.GetBytes(message); var memoryStream = new MemoryStream(); await memoryStream.WriteAsync(rawMessage, 0, rawMessage.Length); await memoryStream.FlushAsync(); memoryStream.Seek(0, SeekOrigin.Begin); var tcpClientMock = new Mock<INetworkClient>(); tcpClientMock.Setup(p => p.GetStream()).Returns(() => memoryStream); tcpClientMock.SetupGet(p => p.Connected).Returns(() => true); var tcpClientFactoryMock = new Mock<INetworkClientFactory>(); tcpClientFactoryMock.Setup(p => p.CreateNetworkClient(It.IsAny<Uri>())).Returns(() => tcpClientMock.Object); var debuggerConnection = new DebuggerConnection(tcpClientFactoryMock.Object); // Act debuggerConnection.Connect(new Uri("tcp://localhost:5858")); for (int i = 0; i < 10 && debuggerConnection.NodeVersion == null; ++i) { await Task.Delay(TimeSpan.FromMilliseconds(100)); } memoryStream.Close(); // Assert Assert.IsNotNull(debuggerConnection.NodeVersion); Assert.AreEqual(version, debuggerConnection.NodeVersion.ToString()); }
public async Task CreateCopyToDestroyBlob() { using (MemoryStream ms = new MemoryStream()) using (BinaryWriter writer = new BinaryWriter(ms)) { // write ~7MB of data for (int i = 0; i < 1000000; ++i) { writer.Write((long)i); } writer.Flush(); await ms.FlushAsync(); ms.Position = 0; IRBlobInfo blob = null; using (RBlobStream blobStream = await RBlobStream.CreateAsync(_session)) { await ms.CopyToAsync(blobStream); blob = blobStream.GetBlobInfo(); } using (RBlobStream blobStream = await RBlobStream.OpenAsync(blob, _session)) using (MemoryStream ms2 = new MemoryStream()) { await blobStream.CopyToAsync(ms2, 1024 * 1024); await ms2.FlushAsync(); ms.ToArray().Should().Equal(ms2.ToArray()); } } }
private async Task<Stream> ReadStreamFromResponse( WebResponse result ) { if( result == null ) { return null; } MemoryStream ms = new MemoryStream(); using( Stream stream = result.GetResponseStream() ) { await stream.CopyToAsync( ms ); await ms.FlushAsync(); } return ms; }
public static async Task<byte[]> ResizeImageAndroid (byte[] imageData, float width, float height) { // Load the bitmap Bitmap originalImage = BitmapFactory.DecodeByteArray (imageData, 0, imageData.Length); Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)width, (int)height, false); byte[] imagearray = null; using (MemoryStream ms = new MemoryStream()) { resizedImage.Compress (Bitmap.CompressFormat.Jpeg, 100, ms); imagearray = ms.ToArray (); ms.Close (); ms.Dispose (); await ms.FlushAsync (); } return imagearray; }
private async Task WriteRemoteManifestFile(PlayServicesManager playServicesManager) { using(Stream stream = new MemoryStream()) { PlayServicesManifest manifest = new PlayServicesManifest(); await manifest.Write(stream).ConfigureAwait(false); await stream.FlushAsync().ConfigureAwait(false); stream.Position = 0; await playServicesManager.SaveFileToDriveAppFolderAsync(PlayServicesManifest.FileTitle, PlayServicesManifest.ContentType, stream).ConfigureAwait(false); } }
private async Task ReadObjectParallel(FileProperties properties, Stream stream, CancellationToken ct, string key, int partSize) { var requests = new List<GetObjectRequest>(); long partCount = properties.Size/partSize; if (properties.Size%partSize > 0) partCount++; for (int i = 0; i < partCount; i++) { long startIncl = i*partSize; long endExcl = Math.Min(startIncl + partSize, properties.Size); requests.Add(new GetObjectRequest { BucketName = _bucket, Key = key, ByteRangeLong = new Amazon.S3.Model.Tuple<long, long>(startIncl, endExcl - 1) }); } var fileLock = new CloudSync.AsyncLock(); await CloudSync.ForEachPooled(requests, MaxParallelStreams, ct, async (r, t) => { using (var buffer = new MemoryStream()) using (GetObjectResponse response = await _s3.GetObjectAsync(r).ConfigureAwait(false)) { await response.ResponseStream.CopyToAsync(buffer).ConfigureAwait(false); await buffer.FlushAsync().ConfigureAwait(false); // truncate buffer to be safe buffer.Position = 0; buffer.SetLength(r.ByteRangeLong.Second - r.ByteRangeLong.First + 1); using (await fileLock.LockAsync().ConfigureAwait(false)) { stream.Position = r.ByteRangeLong.First; buffer.CopyToAsync(stream, 64*1024, ct).Wait(); stream.FlushAsync().Wait(); } } }).ConfigureAwait(false); }
/// <summary> /// Helper function to download package from given url, and place package (only 'content' folder from package) to given folder /// </summary> /// <param name="identity">Package identity</param> /// <param name="destinationFolder">Folder where we copy the package content (content folder only) to</param> /// <param name="pathToLocalCopyOfNudpk">File path where we copy the nudpk to</param> /// <returns></returns> public static async Task DownloadPackageToFolder(this SourceRepository srcRepo, PackageIdentity identity, string destinationFolder, string pathToLocalCopyOfNudpk = null) { var downloadResource = await srcRepo.GetResourceAsync<DownloadResource>(); using (Stream sourceStream = await downloadResource.GetStream(identity, CancellationToken.None)) { Stream packageStream = sourceStream; try { if (!sourceStream.CanSeek) { // V3 DownloadResource.GetStream does not support seek operations. // https://github.com/NuGet/NuGet.Protocol/issues/15 MemoryStream memStream = new MemoryStream(); try { byte[] buffer = new byte[2048]; int bytesRead = 0; do { bytesRead = sourceStream.Read(buffer, 0, buffer.Length); memStream.Write(buffer, 0, bytesRead); } while (bytesRead != 0); await memStream.FlushAsync(); memStream.Position = 0; packageStream = memStream; } catch { memStream.Dispose(); throw; } } if (!string.IsNullOrWhiteSpace(pathToLocalCopyOfNudpk)) { string packageFolderPath = Path.GetDirectoryName(pathToLocalCopyOfNudpk); FileSystemHelpers.CreateDirectory(packageFolderPath); using (Stream writeStream = FileSystemHelpers.OpenWrite(pathToLocalCopyOfNudpk)) { OperationManager.Attempt(() => packageStream.CopyTo(writeStream)); } // set position back to the head of stream packageStream.Position = 0; } using (ZipFile zipFile = ZipFile.Read(packageStream)) { // we only care about stuff under "content" folder int substringStartIndex = @"content/".Length; IEnumerable<ZipEntry> contentEntries = zipFile.Entries.Where(e => e.FileName.StartsWith(@"content/", StringComparison.InvariantCultureIgnoreCase)); foreach (var entry in contentEntries) { string fullPath = Path.Combine(destinationFolder, entry.FileName.Substring(substringStartIndex)); FileSystemHelpers.CreateDirectory(Path.GetDirectoryName(fullPath)); using (Stream writeStream = FileSystemHelpers.OpenWrite(fullPath)) { // let the thread go with itself, so that once file finsihed writing, doesn`t need to request thread context from main thread await entry.OpenReader().CopyToAsync(writeStream).ConfigureAwait(false); } } } } finally { if (packageStream != null && !sourceStream.CanSeek) { // in this case, we created a copy of the source stream in memoery, need to manually dispose packageStream.Dispose(); } } } }
static async Task<BitmapImage> ByteArrayToImageAsync(byte[] imageBytes) { using (var stream = new MemoryStream()) { BitmapImage image = new BitmapImage(); await stream.WriteAsync(imageBytes, 0, imageBytes.Length); await stream.FlushAsync(); stream.Seek(0, SeekOrigin.Begin); image.SetSource(stream); return image; } }
private static async Task<byte[]> AssembleFile(string filePath) { byte[] buffer; using (var resultStream = new MemoryStream()) { var content = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", Guid.NewGuid(), Path.GetFileName(filePath), Environment.NewLine); buffer = Encoding.UTF8.GetBytes(content); await resultStream.WriteAsync(buffer, 0, buffer.Length); content = "Content-Type: application/octet-stream" + Environment.NewLine + Environment.NewLine; buffer = Encoding.UTF8.GetBytes(content); await resultStream.WriteAsync(buffer, 0, buffer.Length); buffer = IOFile.ReadAllBytes(filePath); await resultStream.WriteAsync(buffer, 0, buffer.Length); buffer = Encoding.UTF8.GetBytes(Environment.NewLine); await resultStream.WriteAsync(buffer, 0, buffer.Length); await resultStream.FlushAsync(); buffer = resultStream.ToArray(); } return buffer; }
private async Task<IEnumerable<byte[]>> AssembleFilesBlock(ICollection<string> filePaths, byte[] additionalData) { const int assembleFileExtraBytes = 134; var result = new List<byte[]>(); var formattedBoundary = GetFormattedBoundary(false); var needSize = (from f in filePaths select new FileInfo(f).Length).Sum() + (from f in filePaths select Encoding.UTF8.GetByteCount(Path.GetFileName(f))).Sum() + (formattedBoundary.Length + assembleFileExtraBytes) * filePaths.Count + additionalData.Length; var memoryStream = new MemoryStream((int) Math.Min(needSize, int.MaxValue)); var streamWillExceedCapacity = new Func<MemoryStream, byte[], bool>((stream, file) => stream.Length + formattedBoundary.Length + file.Length + additionalData.Length > stream.Capacity); // Todo: get rid of this when API will be fixed var numberOfFilesCanBeUploadedPerSingleRequest = 20; var getStreamData = new Func<MemoryStream, byte[]>(stream => stream.Length == stream.Capacity ? stream.GetBuffer() : stream.ToArray()); // <------------------------------------------------------------ foreach (var t in filePaths) { var file = await AssembleFile(t); if (streamWillExceedCapacity(memoryStream, file) || numberOfFilesCanBeUploadedPerSingleRequest < 1) { await memoryStream.WriteAsync(additionalData, 0, additionalData.Length); await memoryStream.FlushAsync(); result.Add(getStreamData(memoryStream)); memoryStream.Dispose(); memoryStream = new MemoryStream((int) Math.Min(needSize, int.MaxValue)); numberOfFilesCanBeUploadedPerSingleRequest = 20; } await memoryStream.WriteAsync(formattedBoundary, 0, formattedBoundary.Length); await memoryStream.WriteAsync(file, 0, file.Length); needSize -= formattedBoundary.Length + file.Length; --numberOfFilesCanBeUploadedPerSingleRequest; } await memoryStream.WriteAsync(additionalData, 0, additionalData.Length); await memoryStream.FlushAsync(); result.Add(getStreamData(memoryStream)); memoryStream.Dispose(); return result; }
private async Task SaveNonDbPropertiesAsync() { //for (int i = 0; i < 100000000; i++) //wait a few seconds, for testing //{ // String aaa = i.ToString(); //} try { using (MemoryStream memoryStream = new MemoryStream()) { var file = await Directory .CreateFileAsync(FILENAME, CreationCollisionOption.ReplaceExisting) .AsTask().ConfigureAwait(false); var sessionDataSerializer = new DataContractSerializer(typeof(Binder)); sessionDataSerializer.WriteObject(memoryStream, this); using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false); await memoryStream.FlushAsync().ConfigureAwait(false); await fileStream.FlushAsync().ConfigureAwait(false); } } Debug.WriteLine("ended method Binder.SaveAsync()"); } catch (Exception ex) { Logger.Add_TPL(ex.ToString(), Logger.FileErrorLogFilename); } }
public static async Task<byte[]> DownloadToByteArrayAsync(Uri uri, Encoding encoding = null) { var response = await DownloadToStreamAsync(uri); using (var stream = response.GetResponseStream()) { if (stream == null) return new byte[0]; using (var destinationStream = new MemoryStream()) { await stream.CopyToAsync(destinationStream); await destinationStream.FlushAsync(); var bytes = destinationStream.ToArray(); return bytes; } } }
private async Task<bool> SaveAsync() { try { using (var memoryStream = new MemoryStream()) { var serializer = new DataContractSerializer(typeof(MetaBriefcaseRubbishBin)); serializer.WriteObject(memoryStream, this); string currentInstance = string.Empty; memoryStream.Seek(0, SeekOrigin.Begin); using (StreamReader streamReader = new StreamReader(memoryStream)) { currentInstance = streamReader.ReadToEnd(); var file = await MetaBriefcase.GetDirectory() .CreateFileAsync(FILENAME, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false); using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false); await memoryStream.FlushAsync().ConfigureAwait(false); await fileStream.FlushAsync().ConfigureAwait(false); } } } return true; } catch (Exception ex) { Logger.Add_TPL(ex.ToString(), Logger.FileErrorLogFilename); } return false; }
private async Task<bool> Save2Async(StorageFile file = null) { //for (int i = 0; i < 100000000; i++) //wait a few seconds, for testing //{ // String aaa = i.ToString(); //} await Logger.AddAsync("MetaBriefcase about to save", Logger.FileErrorLogFilename, Logger.Severity.Info).ConfigureAwait(false); bool result = false; // save xml properties try { _localDataSemaphore.WaitOne(); if (file == null) { file = await GetDirectory() .TryGetItemAsync(FILENAME).AsTask().ConfigureAwait(false) as StorageFile; } string savedData = string.Empty; if (file != null) { using (var localFileContent = await file.OpenStreamForReadAsync().ConfigureAwait(false)) { using (StreamReader streamReader = new StreamReader(localFileContent)) { savedData = streamReader.ReadToEnd(); } } } using (var memoryStream = new MemoryStream()) { var serializer = new DataContractSerializer(typeof(MetaBriefcase)); serializer.WriteObject(memoryStream, this); string currentMetaBriefcase = string.Empty; memoryStream.Seek(0, SeekOrigin.Begin); using (StreamReader streamReader = new StreamReader(memoryStream)) { currentMetaBriefcase = streamReader.ReadToEnd(); if (!currentMetaBriefcase.Trim().Equals(savedData.Trim())) { if (file == null) { file = await GetDirectory() .CreateFileAsync(FILENAME, CreationCollisionOption.ReplaceExisting).AsTask().ConfigureAwait(false); } using (var fileStream = await file.OpenStreamForWriteAsync().ConfigureAwait(false)) { fileStream.SetLength(0); // avoid leaving crap at the end if overwriting a file that was longer memoryStream.Seek(0, SeekOrigin.Begin); await memoryStream.CopyToAsync(fileStream).ConfigureAwait(false); await memoryStream.FlushAsync().ConfigureAwait(false); await fileStream.FlushAsync().ConfigureAwait(false); } } } } Debug.WriteLine("ended method MetaBriefcase.SaveAsync()"); result = true; } catch (Exception ex) { Logger.Add_TPL(ex.ToString(), Logger.FileErrorLogFilename); } finally { // save non-xml properties result = result & RegistryAccess.TrySetValue(ConstantData.REG_MBC_IS_ELEVATED, IsElevated.ToString()); SemaphoreExtensions.TryRelease(_localDataSemaphore); } return result; }
public async Task<Stream> OpenFile(string path, CancellationToken cancellationToken) { using (var isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (var inputStream = isf.OpenFile(path, FileMode.Open, FileAccess.Read)) { var outputStream = new MemoryStream(); await inputStream.CopyToAsync(outputStream, 4096, cancellationToken); await outputStream.FlushAsync(cancellationToken); outputStream.Seek(0, SeekOrigin.Begin); return outputStream; } } }
public async Task UploadPhotoAsync(Photo photo, HttpPostedFileBase fileToUpload) { var container = getCloudBlobContainer(); var fileName = string.Format("Photo-{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(fileToUpload.FileName)); var blockBlob = container.GetBlockBlobReference(string.Format("{0}/{1}", photo.AlbumID, fileName)); blockBlob.Properties.ContentType = fileToUpload.ContentType; await blockBlob.UploadFromStreamAsync(fileToUpload.InputStream); blockBlob.StorageUri.ToString(); var uriBuilder = new UriBuilder(blockBlob.Uri) { Scheme = "http" }; photo.FileName = fileName; photo.PhotoPath = uriBuilder.ToString(); //Now upload the created thumbnail. var bitMap = Image.FromStream(fileToUpload.InputStream); var thumbNail = bitMap.GetThumbnailImage(160, 160, null, IntPtr.Zero); var thumbNailFileName = string.Format("{0}/{1}/{2}", photo.AlbumID, "thumbs", fileName); var memory = new MemoryStream(); thumbNail.Save(memory, ImageFormat.Jpeg); var byteArray = new byte[memory.Length]; memory.Position = 0; await memory.ReadAsync(byteArray, 0, (int)memory.Length); blockBlob = container.GetBlockBlobReference(thumbNailFileName); blockBlob.Properties.ContentType = fileToUpload.ContentType; await blockBlob.UploadFromByteArrayAsync(byteArray, 0, byteArray.Length); uriBuilder = new UriBuilder(blockBlob.Uri) { Scheme = "http" }; await memory.FlushAsync(); photo.ThumbnailPath = uriBuilder.ToString(); }
/// <summary> /// Shares the reference to a message payload with the specified recipient. /// </summary> /// <param name="messageReference">The payload reference to share.</param> /// <param name="recipient">The recipient that should be notified of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task representing the asynchronous operation.</returns> protected virtual async Task PostPayloadReferenceAsync(PayloadReference messageReference, Endpoint recipient, CancellationToken cancellationToken) { Requires.NotNull(recipient, "recipient"); Requires.NotNull(messageReference, "messageReference"); cancellationToken.ThrowIfCancellationRequested(); // Prepare the payload. var plainTextPayloadStream = new MemoryStream(); var plainTextPayloadWriter = new BinaryWriter(plainTextPayloadStream); // Include the intended recipient's signing certificate so the recipient knows that // the message author intended the recipient to receive it (defeats fowarding and re-encrypting // a message notification with the intent to deceive a victim that a message was intended for them when it was not.) plainTextPayloadWriter.WriteSizeAndBuffer(recipient.SigningKeyPublicMaterial); plainTextPayloadWriter.Write(DateTime.UtcNow.ToBinary()); // Write out the author of this notification (which may be different from the author of the // message itself in the case of a "forward"). plainTextPayloadWriter.SerializeDataContract(this.Endpoint.PublicEndpoint); plainTextPayloadWriter.SerializeDataContract(messageReference); plainTextPayloadWriter.Flush(); this.Log("Message invite plaintext", plainTextPayloadStream.ToArray()); byte[] notificationSignature = this.CryptoServices.Sign(plainTextPayloadStream.ToArray(), this.Endpoint.SigningKeyPrivateMaterial); var signedPlainTextPayloadStream = new MemoryStream((int)plainTextPayloadStream.Length + notificationSignature.Length + 4); await signedPlainTextPayloadStream.WriteSizeAndBufferAsync(notificationSignature, cancellationToken); plainTextPayloadStream.Position = 0; await plainTextPayloadStream.CopyToAsync(signedPlainTextPayloadStream, 4096, cancellationToken); var encryptedPayload = this.CryptoServices.Encrypt(signedPlainTextPayloadStream.ToArray()); this.Log("Message invite ciphertext", encryptedPayload.Ciphertext); this.Log("Message invite key", encryptedPayload.Key); this.Log("Message invite IV", encryptedPayload.IV); var builder = new UriBuilder(recipient.MessageReceivingEndpoint); var lifetimeInMinutes = (int)(messageReference.ExpiresUtc - DateTime.UtcNow).TotalMinutes; builder.Query += "&lifetime=" + lifetimeInMinutes.ToString(CultureInfo.InvariantCulture); var postContent = new MemoryStream(); var encryptedKey = this.CryptoServices.Encrypt(recipient.EncryptionKeyPublicMaterial, encryptedPayload.Key); this.Log("Message invite encrypted key", encryptedKey); await postContent.WriteSizeAndBufferAsync(encryptedKey, cancellationToken); await postContent.WriteSizeAndBufferAsync(encryptedPayload.IV, cancellationToken); await postContent.WriteSizeAndBufferAsync(encryptedPayload.Ciphertext, cancellationToken); await postContent.FlushAsync(); postContent.Position = 0; using (var response = await this.HttpClient.PostAsync(builder.Uri, new StreamContent(postContent), cancellationToken)) { response.EnsureSuccessStatusCode(); } }
/// <summary> /// Shares the reference to a message payload with the specified recipient. /// </summary> /// <param name="messageReference">The payload reference to share.</param> /// <param name="recipient">The recipient that should be notified of the message.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task representing the asynchronous operation.</returns> protected virtual async Task<NotificationPostedReceipt> PostPayloadReferenceAsync(PayloadReference messageReference, Endpoint recipient, CancellationToken cancellationToken) { Requires.NotNull(recipient, "recipient"); Requires.NotNull(messageReference, "messageReference"); cancellationToken.ThrowIfCancellationRequested(); // Prepare the payload. var plainTextPayloadStream = new MemoryStream(); var plainTextPayloadWriter = new BinaryWriter(plainTextPayloadStream); // Include the intended recipient's signing certificate so the recipient knows that // the message author intended the recipient to receive it (defeats fowarding and re-encrypting // a message notification with the intent to deceive a victim that a message was intended for them when it was not.) plainTextPayloadWriter.WriteSizeAndBuffer(recipient.SigningKeyPublicMaterial); plainTextPayloadWriter.Write(DateTime.UtcNow.ToBinary()); // Write out the author of this notification (which may be different from the author of the // message itself in the case of a "forward"). plainTextPayloadWriter.SerializeDataContract(this.Endpoint.PublicEndpoint); plainTextPayloadWriter.SerializeDataContract(messageReference); plainTextPayloadWriter.Flush(); this.Log("Message invite plaintext", plainTextPayloadStream.ToArray()); byte[] notificationSignature = WinRTCrypto.CryptographicEngine.Sign(this.Endpoint.SigningKey, plainTextPayloadStream.ToArray()); var signedPlainTextPayloadStream = new MemoryStream((int)plainTextPayloadStream.Length + notificationSignature.Length + 4); ////await signedPlainTextPayloadStream.WriteSizeAndBufferAsync(Encoding.UTF8.GetBytes(this.CryptoServices.HashAlgorithmName), cancellationToken); await signedPlainTextPayloadStream.WriteSizeAndBufferAsync(notificationSignature, cancellationToken).ConfigureAwait(false); plainTextPayloadStream.Position = 0; await plainTextPayloadStream.CopyToAsync(signedPlainTextPayloadStream, 4096, cancellationToken).ConfigureAwait(false); signedPlainTextPayloadStream.Position = 0; var cipherTextStream = new MemoryStream(); var encryptedVariables = await this.CryptoServices.EncryptAsync(signedPlainTextPayloadStream, cipherTextStream, cancellationToken: cancellationToken).ConfigureAwait(false); this.Log("Message invite ciphertext", cipherTextStream.ToArray()); this.Log("Message invite key", encryptedVariables.Key); this.Log("Message invite IV", encryptedVariables.IV); var builder = new UriBuilder(recipient.MessageReceivingEndpoint); var lifetimeInMinutes = (int)(messageReference.ExpiresUtc - DateTime.UtcNow).TotalMinutes; builder.Query += "&lifetime=" + lifetimeInMinutes.ToString(CultureInfo.InvariantCulture); var postContent = new MemoryStream(); var encryptionKey = CryptoSettings.EncryptionAlgorithm.ImportPublicKey( recipient.EncryptionKeyPublicMaterial, CryptoSettings.PublicKeyFormat); var encryptedKey = WinRTCrypto.CryptographicEngine.Encrypt(encryptionKey, encryptedVariables.Key); this.Log("Message invite encrypted key", encryptedKey); await postContent.WriteSizeAndBufferAsync(encryptedKey, cancellationToken).ConfigureAwait(false); await postContent.WriteSizeAndBufferAsync(encryptedVariables.IV, cancellationToken).ConfigureAwait(false); cipherTextStream.Position = 0; await postContent.WriteSizeAndStreamAsync(cipherTextStream, cancellationToken).ConfigureAwait(false); await postContent.FlushAsync().ConfigureAwait(false); postContent.Position = 0; using (var response = await this.HttpClient.PostAsync(builder.Uri, new StreamContent(postContent), cancellationToken).ConfigureAwait(false)) { if (response.Content != null) { // Just to help in debugging. string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false); } response.EnsureSuccessStatusCode(); var receipt = new NotificationPostedReceipt(recipient, response.Headers.Date); return receipt; } }