public ReadAsync ( Byte buffer, int offset, int count, CancellationToken cancellationToken ) : Task |
||
buffer | Byte | |
offset | int | |
count | int | |
cancellationToken | CancellationToken | |
return | Task |
public async Task WritesMessage() { MemoryStream outputStream = new MemoryStream(); MessageWriter messageWriter = new MessageWriter( outputStream, this.messageSerializer); // Write the message and then roll back the stream to be read // TODO: This will need to be redone! await messageWriter.WriteMessage(Message.Event("testEvent", null)); outputStream.Seek(0, SeekOrigin.Begin); string expectedHeaderString = string.Format( Constants.ContentLengthFormatString, ExpectedMessageByteCount); byte[] buffer = new byte[128]; await outputStream.ReadAsync(buffer, 0, expectedHeaderString.Length); Assert.Equal( expectedHeaderString, Encoding.ASCII.GetString(buffer, 0, expectedHeaderString.Length)); // Read the message await outputStream.ReadAsync(buffer, 0, ExpectedMessageByteCount); Assert.Equal( TestEventString, Encoding.UTF8.GetString(buffer, 0, ExpectedMessageByteCount)); outputStream.Dispose(); }
private static async Task <byte[]> GetMultipartFormDataAsync(string boundary, byte[] imageBytes) { var encoding = Encoding.UTF8; Stream formDataStream = new System.IO.MemoryStream(); var fileName = Guid.NewGuid().ToString() + ".png"; // Add just the first part of this param, since we will write the file data directly to the Stream string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"\r\nContent-Type: {3}\r\n\r\n", boundary, "source", fileName, "image/png"); await formDataStream.WriteAsync(encoding.GetBytes(header), 0, encoding.GetByteCount(header)); // Write the file data directly to the Stream, rather than serializing it to a string. await formDataStream.WriteAsync(imageBytes, 0, imageBytes.Length); // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; await formDataStream.WriteAsync(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer)); // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; await formDataStream.ReadAsync(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
async public ValueTask <int> Async(System.IO.MemoryStream stream) { var buffer = new byte[4]; await stream.ReadAsync(buffer.AsMemory()); // This overload of ReadAsync() returns a ValueTask<int> return(buffer[0] + buffer[1] + buffer[2] + buffer[3]); }
public async Task<HttpResponseMessage> Get(int width, int height, string bgColor, string fgColor) { var bg = GetColor(bgColor, Color.LightGray); var fg = GetColor(fgColor, Color.DarkGray); var result = new HttpResponseMessage(HttpStatusCode.OK); using (var ms = new MemoryStream()) using (var img = await GetImageAsync($"{width} x {height}", width, height, bg, fg)) { if (img == null) { result.StatusCode = HttpStatusCode.BadRequest; return result; } img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); var bytes = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); await ms.ReadAsync(bytes, 0, bytes.Length); result.Content = new ByteArrayContent(bytes); } result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); return result; }
// todo refactor public async Task WriteBufferToFile(byte[] buffer, string path) { using (var fileStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var memoryStream = new MemoryStream(buffer)) { byte[] bytes = new byte[memoryStream.Length]; await memoryStream.ReadAsync(bytes, 0, (int)memoryStream.Length); await fileStream.WriteAsync(bytes, 0, bytes.Length); }; }
public async Task TestDownloadFileFromDriveAsync() { var env = await TestEnvironment.CreateSimpleAsync(); var file = await env.GetFileByFullPathAsync("photos2015/info.txt"); var stream = new MemoryStream(); await env.Account.DownloadFileFromDriveAsync(file, stream, CancellationToken.None); stream.Seek(0, SeekOrigin.Begin); var buffer = new byte[stream.Length]; await stream.ReadAsync(buffer, 0, buffer.Length); var content = Encoding.ASCII.GetString(buffer); Assert.AreEqual("Hello, World!", content); }
private static async Task <byte[]> GetMultipartMixedFormDataAsync(string boundary, byte[] postQueryData = null, byte[] postData = null, bool isOctet = false) { var encoding = Encoding.UTF8; Stream formDataStream = new System.IO.MemoryStream(); if (postQueryData != null && postQueryData.Length > 0) { // adds url query to the body // https://docs.microsoft.com/en-us/linkedin/shared/api-guide/concepts/query-tunneling string queryHeader = $"--{boundary}\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n"; await formDataStream.WriteAsync(encoding.GetBytes(queryHeader), 0, encoding.GetByteCount(queryHeader)); await formDataStream.WriteAsync(postQueryData, 0, postQueryData.Length); string queryBoundary = $"\r\n--{boundary}\r\n"; await formDataStream.WriteAsync(encoding.GetBytes(queryBoundary), 0, encoding.GetByteCount(queryBoundary)); } if (postData != null && postData.Length > 0) { // adds post data to the body string postHeader = $"--{boundary}\r\nContent-Type: application/json\r\n\r\n"; if (isOctet) { // adds asset data to the body postHeader = $"--{boundary}\r\nContent-Type: application/octet-stream\r\n\r\n"; } await formDataStream.WriteAsync(encoding.GetBytes(postHeader), 0, encoding.GetByteCount(postHeader)); // Write the file data directly to the Stream, rather than serializing it to a string. await formDataStream.WriteAsync(postData, 0, postData.Length); string postBoundary = $"\r\n--{boundary}--\r\n"; await formDataStream.WriteAsync(encoding.GetBytes(postBoundary), 0, encoding.GetByteCount(postBoundary)); } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; await formDataStream.ReadAsync(formData, 0, formData.Length); formDataStream.Close(); return(formData); }
public async Task SaveAsync(Stream output, CancellationToken cancellationToken) { if (output == null) throw new ArgumentNullException(nameof(output)); var buffer = new byte[64 * 1024]; foreach (var file in Files) { using (var input = new MemoryStream(file)) { int readBytes; while ((readBytes = await input.ReadAsync(buffer, 0, buffer.Length, cancellationToken)) != 0) { await output.WriteAsync(buffer, 0, readBytes, cancellationToken); } } } }
public override async Task ProcessRequestAsync(HttpContext context) { System.Drawing.Bitmap myBitmap = null; MemoryStream objMemoryStream = null; try { var strImageFileName = context.Request.QueryString["ImageUrl"].ToString(); var height = context.Request.QueryString["height"]; var width = context.Request.QueryString["width"]; //create callback handler var myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); //creat BitMap object from image path passed in querystring myBitmap = new System.Drawing.Bitmap( context.Server.MapPath("~/Images/Users/" + strImageFileName)); //create unit object for height and width. This is to convert parameter passed in differen unit like pixel, inch into generic unit. var widthUnit = System.Web.UI.WebControls.Unit.Parse(width); var heightUnit = System.Web.UI.WebControls.Unit.Parse(height); //Resize actual image using width and height paramters passed in querystring var myThumbnail = myBitmap.GetThumbnailImage(Convert.ToInt16(widthUnit.Value), Convert.ToInt16(heightUnit.Value), myCallback, IntPtr.Zero); //Create memory stream and save resized image into memory stream objMemoryStream = new System.IO.MemoryStream(); myThumbnail.Save(objMemoryStream, System.Drawing.Imaging.ImageFormat.Png); //Declare byte array of size memory stream and read memory stream data into array var imageData = new byte[objMemoryStream.Length]; objMemoryStream.Position = 0; await objMemoryStream.ReadAsync(imageData, 0, (int)objMemoryStream.Length); //send contents of byte array as response to client (browser) context.Response.BinaryWrite(imageData); myBitmap.Dispose(); } catch { context.Response.End(); } finally { if (objMemoryStream != null) objMemoryStream.Dispose(); if (myBitmap != null) myBitmap.Dispose(); } }
/// <summary> /// Compresses the specified source stream onto the destination stream. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <returns>An async void.</returns> public virtual async Task<long> Compress(Stream source, Stream destination) { using (var mem = new MemoryStream()) { using (var gzip = this.CreateCompressionStream(mem)) { await source.CopyToAsync(gzip); } mem.Position = 0; var compressed = new byte[mem.Length]; await mem.ReadAsync(compressed, 0, compressed.Length); var outStream = new MemoryStream(compressed); await outStream.CopyToAsync(destination); return mem.Length; } }
private async Task UploadPackageAsync(ITransferHandler handler) { using (var ms = new MemoryStream(await handler.ReadAsync())) { var header = new RequestHeader().Setup(ms); var packageBytes = new byte[ms.Length - ms.Position]; await ms.ReadAsync(packageBytes, 0, packageBytes.Length); var package = new RequestPackage(header, packageBytes); _packages[(int)package.Header.ClientPlatform] = package; await this.SavePackageAsync(package.Header.ClientPlatform, package); } }
/// <summary> /// Reads incoming data, and puts it in the buffer for processing. /// </summary> public async Task ReadAsync() { var readBuffer = new MemoryStream(BUFFER_SIZE); //Set up buffers to store incoming data byte[] inputBuffer = new byte[BUFFER_SIZE]; int bytesRead = 0; //Read packet from stream bytesRead = await networkStream.ReadAsync(inputBuffer, 0, inputBuffer.Length); //Add read data to the read buffer await readBuffer.WriteAsync(inputBuffer, 0, bytesRead); //Determine if there are terminators in the buffer, because that would signify //at least 1 full record. var readBufferArray = readBuffer.ToArray(); var terminatorStrings = readBufferArray .Select((v, i) => new { Value = v, Index = i }) .Where(a => a.Index < readBufferArray.Length - 1 && a.Value == LF && readBufferArray[a.Index + 1] == CR).ToList(); //Find all full messages in the readBuffer, and process them. readBuffer.Position = 0; foreach (var termString in terminatorStrings) { var messageLength = (int)termString.Index - (int)readBuffer.Position; var messageContents = new byte[messageLength]; await readBuffer.ReadAsync(messageContents, 0, messageLength); OnRawMessageReceived(new RawMessageReceivedEventArgs(messageContents)); //Increase position by terminator string width. readBuffer.Position += 2; } //All full messages have been processed, so copy whatever is still in the buffer to the //start of a new reset buffer. var finalPosition = (int)readBuffer.Position; var bufferLength = (int)readBuffer.Length; var bytesLeft = bufferLength - finalPosition; //Create a new readBuffer that can hold the current remaining data and a full extra read. readBuffer = new MemoryStream((bytesLeft > 0) ? BUFFER_SIZE + bytesLeft : BUFFER_SIZE); if (bytesLeft > 0) { await readBuffer.WriteAsync(readBufferArray, finalPosition, bytesLeft); } }
/// <summary> /// Encrypts a file asynchron with libsodium and protobuf-net. /// </summary> /// <param name="senderPrivateKey">A 32 byte private key.</param> /// <param name="senderPublicKey">A 32 byte public key.</param> /// <param name="recipientPublicKey">A 32 byte public key.</param> /// <param name="filename">The file name.</param> /// <param name="inputStream">The input stream.</param> /// <param name="encryptionProgress">StreamCryptorTaskAsyncProgress object.</param> /// <param name="outputFolder">There the encrypted file will be stored, if this is null the input directory is used.</param> /// <param name="fileExtension">Set a custom file extenstion: .whatever</param> /// <param name="maskFileName">Replaces the filename with some random name.</param> /// <param name="cancellationToken">Token to request task cancellation.</param> /// <returns>The name of the encrypted file.</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="DirectoryNotFoundException"></exception> /// <exception cref="OperationCanceledException"></exception> public static async Task<string> EncrypMemoryStreamAsync(byte[] senderPrivateKey, byte[] senderPublicKey, byte[] recipientPublicKey, string filename, MemoryStream inputStream, string outputFolder = null, string fileExtension = DEFAULT_FILE_EXTENSION, bool maskFileName = false, IProgress<StreamCryptorTaskAsyncProgress> encryptionProgress = null, CancellationToken cancellationToken = default(CancellationToken)) { string outputFullPath; string outputFile; //validate the senderPrivateKey if (senderPrivateKey == null || senderPrivateKey.Length != ASYNC_KEY_LENGTH) { throw new ArgumentOutOfRangeException("senderPrivateKey", "invalid senderPrivateKey"); } //validate the senderPublicKey if (senderPublicKey == null || senderPublicKey.Length != ASYNC_KEY_LENGTH) { throw new ArgumentOutOfRangeException("senderPublicKey", "invalid senderPublicKey"); } //validate the recipientPublicKey if (recipientPublicKey == null || recipientPublicKey.Length != ASYNC_KEY_LENGTH) { throw new ArgumentOutOfRangeException("recipientPublicKey", "invalid recipientPublicKey"); } //validate the filename if (string.IsNullOrEmpty(filename)) { throw new ArgumentOutOfRangeException("filename", (filename == null) ? 0 : filename.Length, string.Format("filename must be greater {0} in length.", 0)); } if (filename.Length > MAX_FILENAME_LENGTH) { throw new ArgumentOutOfRangeException("filename", string.Format("filename name must be smaller {0} in length.", MAX_FILENAME_LENGTH)); } //validate the file extension if (!fileExtension[0].Equals('.')) { throw new ArgumentOutOfRangeException("fileExtension", "fileExtension must start with: ."); } //validate the outputFolder if (string.IsNullOrEmpty(outputFolder)) { throw new ArgumentNullException("outputFolder"); } if (!Directory.Exists(outputFolder)) { throw new DirectoryNotFoundException("outputFolder could not be found."); } //generate the name of the output file if (maskFileName) { //store the output file with a masked file name and the fileExtension outputFile = Utils.GetRandomFileName(MASKED_FILENAME_LENGTH, fileExtension); outputFullPath = Path.Combine(outputFolder, outputFile); } else { //store the output file, just with the fileExtension outputFile = filename + fileExtension; outputFullPath = Path.Combine(outputFolder, outputFile); } using (FileStream fileStreamEncrypted = File.OpenWrite(outputFullPath)) { //initialize our file header for encryption EncryptedFileHeader encryptedFileHeader = new EncryptedFileHeader( CURRENT_VERSION, NONCE_LENGTH, CHUNK_BASE_NONCE_LENGTH, inputStream.Length, senderPrivateKey, senderPublicKey, recipientPublicKey); //protect and set the file name to the header encryptedFileHeader.ProtectFileName(filename, MAX_FILENAME_LENGTH); //generate and set the checksum to validate our file header on decryption encryptedFileHeader.SetHeaderChecksum(HEADER_CHECKSUM_LENGTH); //write the file header to the stream Serializer.SerializeWithLengthPrefix(fileStreamEncrypted, encryptedFileHeader, PrefixStyle.Base128, 1); //we start at chunk number 0 int chunkNumber = CHUNK_COUNT_START; //used to calculate the footer checksum long overallChunkLength = 0; //used for progress reporting long overallBytesRead = 0; int bytesRead; do { //cancel the task if requested cancellationToken.ThrowIfCancellationRequested(); //start reading the unencrypted file in chunks of the given length: CHUNK_LENGTH byte[] unencryptedChunk = new byte[CHUNK_LENGTH]; bytesRead = await inputStream.ReadAsync(unencryptedChunk, 0, CHUNK_LENGTH, cancellationToken).ConfigureAwait(false); //check if there is still some work if (bytesRead != 0) { //prepare the EncryptedFileChunk EncryptedFileChunk encryptedFileChunk = new EncryptedFileChunk(); byte[] readedBytes = new byte[bytesRead]; //cut unreaded bytes Array.Copy(unencryptedChunk, readedBytes, bytesRead); //check if the file is smaller or equal the CHUNK_LENGTH if (encryptedFileHeader.UnencryptedFileLength <= CHUNK_LENGTH) { //so we have the one and only chunk encryptedFileChunk = EncryptFileChunk(readedBytes, chunkNumber, encryptedFileHeader.BaseNonce, encryptedFileHeader.UnencryptedEphemeralKey, true); } else { //let`s check if this chunk is smaller than the given CHUNK_LENGTH if (bytesRead < CHUNK_LENGTH) { //it`s the last chunk in the stream encryptedFileChunk = EncryptFileChunk(readedBytes, chunkNumber, encryptedFileHeader.BaseNonce, encryptedFileHeader.UnencryptedEphemeralKey, true); } else { //it`s a full chunk encryptedFileChunk = EncryptFileChunk(readedBytes, chunkNumber, encryptedFileHeader.BaseNonce, encryptedFileHeader.UnencryptedEphemeralKey, false); } } overallChunkLength += encryptedFileChunk.Chunk.Length; //write encryptedFileChunk to the output stream Serializer.SerializeWithLengthPrefix(fileStreamEncrypted, encryptedFileChunk, PrefixStyle.Base128, 2); //increment for the next chunk chunkNumber++; overallBytesRead += bytesRead; //report status if (encryptionProgress != null) { var args = new StreamCryptorTaskAsyncProgress(); args.ProgressPercentage = (int) (encryptedFileHeader.UnencryptedFileLength <= 0 ? 0 : (100 * overallBytesRead) / encryptedFileHeader.UnencryptedFileLength); encryptionProgress.Report(args); } } else { //Prepare the EncryptedFileFooter for encryption. EncryptedFileFooter encryptedFileFooter = new EncryptedFileFooter(); //generate the FooterChecksum encryptedFileFooter.SetFooterChecksum(BitConverter.GetBytes(chunkNumber), BitConverter.GetBytes(overallChunkLength), encryptedFileHeader.UnencryptedEphemeralKey, FOOTER_CHECKSUM_LENGTH); //put the footer to the stream Serializer.SerializeWithLengthPrefix(fileStreamEncrypted, encryptedFileFooter, PrefixStyle.Base128, 3); } } while (bytesRead != 0); } return outputFile; }
/// <summary> /// Downloads a <see cref="PayloadReference"/> that is referenced from an incoming inbox item. /// </summary> /// <param name="inboxItem">The inbox item that referenced the <see cref="PayloadReference"/>.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task representing the asynchronous operation.</returns> protected virtual async Task<PayloadReference> DownloadPayloadReferenceAsync(IncomingList.IncomingItem inboxItem, CancellationToken cancellationToken) { Requires.NotNull(inboxItem, "inboxItem"); var responseMessage = await this.HttpClient.GetAsync(inboxItem.Location, cancellationToken); if (responseMessage.StatusCode == HttpStatusCode.NotFound) { // delete inbox item and move on. await this.DeletePayloadReferenceAsync(inboxItem.Location, cancellationToken); this.Log("Missing payload reference.", null); return null; } responseMessage.EnsureSuccessStatusCode(); var responseStream = await responseMessage.Content.ReadAsStreamAsync(); var responseStreamCopy = new MemoryStream(); await responseStream.CopyToAsync(responseStreamCopy, 4096, cancellationToken); responseStreamCopy.Position = 0; var encryptedKey = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken); var key = this.CryptoServices.Decrypt(this.Endpoint.EncryptionKeyPrivateMaterial, encryptedKey); var iv = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken); var ciphertext = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken); var encryptedPayload = new SymmetricEncryptionResult(key, iv, ciphertext); var plainTextPayloadBuffer = this.CryptoServices.Decrypt(encryptedPayload); var plainTextPayloadStream = new MemoryStream(plainTextPayloadBuffer); var signature = await plainTextPayloadStream.ReadSizeAndBufferAsync(cancellationToken); long payloadStartPosition = plainTextPayloadStream.Position; var signedBytes = new byte[plainTextPayloadStream.Length - plainTextPayloadStream.Position]; await plainTextPayloadStream.ReadAsync(signedBytes, 0, signedBytes.Length); plainTextPayloadStream.Position = payloadStartPosition; var plainTextPayloadReader = new BinaryReader(plainTextPayloadStream); var recipientPublicSigningKeyBuffer = plainTextPayloadReader.ReadSizeAndBuffer(); var creationDateUtc = DateTime.FromBinary(plainTextPayloadReader.ReadInt64()); var notificationAuthor = Utilities.DeserializeDataContract<Endpoint>(plainTextPayloadReader); var messageReference = Utilities.DeserializeDataContract<PayloadReference>(plainTextPayloadReader); messageReference.ReferenceLocation = inboxItem.Location; if (!this.CryptoServices.VerifySignature(notificationAuthor.SigningKeyPublicMaterial, signedBytes, signature)) { throw new InvalidMessageException(); } if (!Utilities.AreEquivalent(recipientPublicSigningKeyBuffer, this.Endpoint.PublicEndpoint.SigningKeyPublicMaterial)) { throw new InvalidMessageException(Strings.MisdirectedMessage); } return messageReference; }
public async Task SaveFileAsync(string path, byte[] data) { if (data == null) throw new CustomArgumentException("NULL Data can't be written to Storage!"); var blob = this.GetBlobReference(path); List<string> blocks = new List<string>(); using (MemoryStream ms = new MemoryStream(data)) { byte[] buffer = new byte[MaxUploadBlobSize]; int index = 0, offset = 0, readed = 0; this.LogMessage($"begin uploading to {path} [{data.Length}]"); // reading portions from the array while ((readed = await ms.ReadAsync(buffer, 0, MaxUploadBlobSize)) > 0) { // move through array offset += readed; // generate new blockID var blockID = this.GetBlobBlockID(index); // put block with buffer into storage await blob.PutBlockAsync(blockID, new MemoryStream(buffer, 0, readed), null); // remember blockID to be saved blocks.Add(blockID); this.LogMessage($"uploaded block {index}:{blockID} [{readed}]"); // increase index to get next blockID index++; } } // write to storage await blob.PutBlockListAsync(blocks); this.LogMessage($"complete uploading to {path} [{data.Length}] with {blocks.Count} blocks"); }
public async Task<System.IO.MemoryStream> RenderLabelToStream( float imageWidth, float imageHeight, Color4 foregroundColor, Vector2 origin, TextLayout textLayout, float dpi = DEFAULT_DPI, SharpDX.DXGI.Format format = SharpDX.DXGI.Format.B8G8R8A8_UNorm, SharpDX.Direct2D1.AlphaMode alpha = AlphaMode.Premultiplied) { // Get stream var pngStream = new MemoryStream(); using (var renderTarget = RenderLabel( imageWidth, imageHeight, foregroundColor, origin, textLayout, dpi, format, alpha)) { pngStream.Position = 0; // Create a WIC outputstream using (var wicStream = new WICStream(FactoryImaging, pngStream)) { var size = renderTarget.PixelSize; // Initialize a Png encoder with this stream using (var wicBitmapEncoder = new PngBitmapEncoder(FactoryImaging, wicStream)) { // Create a Frame encoder using (var wicFrameEncoder = new BitmapFrameEncode(wicBitmapEncoder)) { wicFrameEncoder.Initialize(); // Create image encoder ImageEncoder wicImageEncoder; ImagingFactory2 factory2 = new ImagingFactory2(); wicImageEncoder = new ImageEncoder(factory2, D2DDevice); var imgParams = new ImageParameters(); imgParams.PixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.B8G8R8A8_UNorm, AlphaMode.Premultiplied); imgParams.PixelHeight = (int)size.Height; imgParams.PixelWidth = (int)size.Width; wicImageEncoder.WriteFrame(renderTarget, wicFrameEncoder, imgParams); //// Commit changes wicFrameEncoder.Commit(); wicBitmapEncoder.Commit(); byte[] buffer = new byte[pngStream.Length]; pngStream.Position = 0; await pngStream.ReadAsync(buffer, 0, (int)pngStream.Length); } } } } return pngStream; }
/// <summary> /// Downloads a <see cref="PayloadReference"/> that is referenced from an incoming inbox item. /// </summary> /// <param name="inboxItem">The inbox item that referenced the <see cref="PayloadReference"/>.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task representing the asynchronous operation.</returns> protected virtual async Task<PayloadReference> DownloadPayloadReferenceAsync(IncomingList.IncomingItem inboxItem, CancellationToken cancellationToken) { Requires.NotNull(inboxItem, "inboxItem"); var responseMessage = await this.HttpClient.GetAsync(inboxItem.Location, cancellationToken).ConfigureAwait(false); if (responseMessage.StatusCode == HttpStatusCode.NotFound) { // delete inbox item and move on. await this.DeletePayloadReferenceAsync(inboxItem.Location, cancellationToken).ConfigureAwait(false); this.Log("Missing payload reference.", null); return null; } responseMessage.EnsureSuccessStatusCode(); var responseStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); var responseStreamCopy = new MemoryStream(); await responseStream.CopyToAsync(responseStreamCopy, 4096, cancellationToken).ConfigureAwait(false); responseStreamCopy.Position = 0; var encryptedKey = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken).ConfigureAwait(false); var key = WinRTCrypto.CryptographicEngine.Decrypt(this.Endpoint.EncryptionKey, encryptedKey); var iv = await responseStreamCopy.ReadSizeAndBufferAsync(cancellationToken).ConfigureAwait(false); var ciphertextStream = await responseStreamCopy.ReadSizeAndStreamAsync(cancellationToken).ConfigureAwait(false); var encryptedVariables = new SymmetricEncryptionVariables(key, iv); var plainTextPayloadStream = new MemoryStream(); await this.CryptoServices.DecryptAsync(ciphertextStream, plainTextPayloadStream, encryptedVariables, cancellationToken).ConfigureAwait(false); plainTextPayloadStream.Position = 0; AsymmetricAlgorithm? signingHashAlgorithm = null; //// Encoding.UTF8.GetString(await plainTextPayloadStream.ReadSizeAndBufferAsync(cancellationToken)); byte[] signature = await plainTextPayloadStream.ReadSizeAndBufferAsync(cancellationToken).ConfigureAwait(false); long payloadStartPosition = plainTextPayloadStream.Position; var signedBytes = new byte[plainTextPayloadStream.Length - plainTextPayloadStream.Position]; await plainTextPayloadStream.ReadAsync(signedBytes, 0, signedBytes.Length).ConfigureAwait(false); plainTextPayloadStream.Position = payloadStartPosition; var plainTextPayloadReader = new BinaryReader(plainTextPayloadStream); var recipientPublicSigningKeyBuffer = plainTextPayloadReader.ReadSizeAndBuffer(); var creationDateUtc = DateTime.FromBinary(plainTextPayloadReader.ReadInt64()); var notificationAuthor = Utilities.DeserializeDataContract<Endpoint>(plainTextPayloadReader); var messageReference = Utilities.DeserializeDataContract<PayloadReference>(plainTextPayloadReader); messageReference.ReferenceLocation = inboxItem.Location; if (messageReference.HashAlgorithmName == null) { messageReference.HashAlgorithmName = Utilities.GuessHashAlgorithmFromLength(messageReference.Hash.Length).GetHashAlgorithmName(); } if (!CryptoProviderExtensions.VerifySignatureWithTolerantHashAlgorithm(notificationAuthor.SigningKeyPublicMaterial, signedBytes, signature, signingHashAlgorithm)) { throw new InvalidMessageException(); } if (!Utilities.AreEquivalent(recipientPublicSigningKeyBuffer, this.Endpoint.PublicEndpoint.SigningKeyPublicMaterial)) { throw new InvalidMessageException(Strings.MisdirectedMessage); } return messageReference; }
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(); }