WriteAsync() 공개 메소드

public WriteAsync ( Byte buffer, int offset, int count, CancellationToken cancellationToken ) : Task
buffer Byte
offset int
count int
cancellationToken CancellationToken
리턴 Task
예제 #1
0
        private async Task WriteSection(int offsetPointer, int sizePointer, uint offset, uint size, byte[] section)
        {
            byte[] data    = this.SafeGetBuffer();
            uint   oldSize = size;

            using (var ms = new IO.MemoryStream())
                using (var bw = new IO.BinaryWriter(ms))
                {
                    // Write up to offset pointer
                    await ms.WriteAsync(data, 0, offsetPointer);

                    // Write new section coordinates
                    bw.Write(offset);
                    bw.Write((uint)section.Length);

                    // Write up to beginning of section
                    await ms.WriteAsync(data, sizePointer + SizeOfPointer, (int)(offset - (sizePointer + SizeOfPointer)));

                    // Write new section
                    await ms.WriteAsync(section, 0, section.Length);

                    // Write stuff after old section
                    await ms.WriteAsync(data, (int)(offset + oldSize), (int)(data.Length - (offset + oldSize)));

                    this.buffer = ms.ToArray();
                }
        }
예제 #2
0
        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);
        }
예제 #3
0
 public async Task<byte[]> ReceieveMessageAsync()
 {
     if (IsDisposed) throw new ObjectDisposedException(nameof(Connection));
     if (!ConnectionStream.CanRead) throw new AccessViolationException(nameof(ConnectionStream));
     int size;
     using (var stream = new MemoryStream())
     {
         var message = new byte[4];
         while (stream.Length < 4 && ConnectionStream.CanRead)
         {
             int receieved = await ConnectionStream.ReadAsync(message, 0, 4 - Convert.ToInt32(stream.Length));
             await stream.WriteAsync(message, 0, receieved);
         }
         size = BitConverter.ToInt32(stream.ToArray(), 0);
     }
     if (!ConnectionStream.CanRead)
         throw new AccessViolationException(nameof(ConnectionStream));
     if (size > MaxSize)
         return null;
     using (var stream = new MemoryStream())
     {
         var buffer = new byte[512];
         while (stream.Length < size)
         {
             if (!ConnectionStream.CanRead) throw new AccessViolationException(nameof(ConnectionStream));
             var receieved = await ConnectionStream.ReadAsync(buffer, 0, size - Convert.ToInt32(stream.Length));
             await stream.WriteAsync(buffer, 0, receieved);
         }
         return stream.ToArray();
     }
 }
예제 #4
0
        public async Task<string> LoadFirstLinesFromDiskAsync(string fileName, int lineCount, SecureString passphrase)
        {
            using (var inputStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))
            {
                using (var outputStream = new MemoryStream())
                {
                    var password = SecureStringCredentialStore.SecureStringToString(passphrase);
                    using (var cryptoStream = CipherStream.Open(inputStream, password))
                    {
                        while (cryptoStream.CanRead)
                        {
                            var buffer = new byte[4096];
                            await cryptoStream.ReadAsync(buffer, 0, 4096);
                            await outputStream.WriteAsync(buffer, 0, 4096);
                            char[] chunk = Encoding.UTF8.GetChars(buffer);
                            var occurances = chunk.Count(c => c == '\n');
                            if (occurances >= lineCount) break;
                        }
                    }

                    outputStream.Position = 0;
                    using (var reader = new StreamReader(outputStream))
                    {
                        return await reader.ReadToEndAsync();
                    }
                }
            }
        }
		public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
		{
			var tableResult = await _table.ExecuteAsync(TableOperation.Retrieve<DynamicTableEntity>(grainReference.ToKeyString(), grainType));
			if (tableResult.Result == null)
			{
				return;
			}
			var entity = tableResult.Result as DynamicTableEntity;

			var serializer = new JsonSerializer();
			using (var memoryStream = new MemoryStream())
			{
				foreach (var propertyName in entity.Properties.Keys.Where(p => p.StartsWith("d")).OrderBy(p => p))
				{
					var dataPart = entity.Properties[propertyName];
					await memoryStream.WriteAsync(dataPart.BinaryValue, 0, dataPart.BinaryValue.Length);
				}

				memoryStream.Position = 0;
				using (var bsonReader = new BsonReader(memoryStream))
				{
					var data = serializer.Deserialize<Dictionary<string, object>>(bsonReader);
					grainState.SetAll(data);
				}
			}
		}
예제 #6
0
        private async static Task<byte[]> AliceSendsData(string message)
        {
            Console.WriteLine("Alice send message {0}", message);
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using(var aliceAlgo = new ECDiffieHellmanCng(aliceKey))
            {
                using(CngKey bobPubKey = CngKey.Import(bobPubKeyBlob, CngKeyBlobFormat.GenericPublicBlob))
                {
                    byte[] symmKey = aliceAlgo.DeriveKeyMaterial(bobPubKey);
                    Console.WriteLine("Alice create this symm key with Bobs public key information : {0}", Convert.ToBase64String(symmKey));
                    using(var aes = new AesCryptoServiceProvider())
                    {
                        aes.Key = symmKey;
                        aes.GenerateIV();
                        using(ICryptoTransform encryptor = aes.CreateEncryptor())
                        {
                            using(MemoryStream ms = new MemoryStream())
                            {
                                var cs = new CryptoStream(ms, encryptor,CryptoStreamMode.Write);
                                await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
                                cs.Write(rawData, 0, rawData.Length);
                                cs.Close();
                                encryptedData = ms.ToArray();
                            }
                        }
                        aes.Clear();
                    }
                }
            }
            Console.WriteLine("Alice message is encrypted : {0}", Convert.ToBase64String(encryptedData));
            return encryptedData;
        }
예제 #7
0
		public async Task<byte[]> PackAsync(ICollection<ClientFile> files)
		{
			if (files == null) throw new ArgumentNullException("files");
			if (files.Count == 0) throw new ArgumentOutOfRangeException("files");

			var header = new StringBuilder();

			var totalBuffer = new byte[files.Select(f => f.Data.Length).Sum()];

			using (var output = new MemoryStream(totalBuffer))
			{
				foreach (var f in files)
				{
					var data = f.Data;
					await output.WriteAsync(data, 0, data.Length);

					if (header.Length > 0)
					{
						header.Append(FileSeparator);
					}
					header.Append(f.Name);
					header.Append(SizeSeparator);
					header.Append(data.Length);
				}

				var headerData = Encoding.Unicode.GetBytes(header.ToString());
				var headerSize = BitConverter.GetBytes(headerData.Length);

				return Utilities.Concat(headerSize, headerData, totalBuffer);
			}
		}
예제 #8
0
        public async Task<HttpResponseMessage> Get(string key)
        {
            var cachedItem = MemoryCache.Default.Get(key) as byte[];

            if(cachedItem == null)
            {
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }


            Stream stream = null;

            if (cachedItem != null)
            {
                stream = new MemoryStream();
                await stream.WriteAsync(cachedItem, 0, cachedItem.Length);
                stream.Position = 0;
            }

            //var content = new PushStreamContent(async (stream, httpContent, transportContext) =>
            //{
            //    await stream.WriteAsync(cachedItem, 0, cachedItem.Length);
            //    stream.Close();
            //});

            var content = new StreamContent(stream);
            return new HttpResponseMessage() { Content = content };
        }
예제 #9
0
		/// <summary>
		/// Read a thumbnail in metadata from byte array.
		/// </summary>
		/// <param name="bytes">Byte array</param>
		/// <returns>BitmapImage of thumbnail</returns>
		internal static async Task<BitmapImage> ReadThumbnailAsync(byte[] bytes)
		{
			if ((bytes == null) || !bytes.Any())
				throw new ArgumentNullException("bytes");

			try
			{
				using (var ms = new MemoryStream())
				{
					await ms.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);

					// If continued by ContinueWith, an exception will not be caught by try-catch block in debug mode.
					return ReadThumbnailFromExifByImaging(ms);
				}
			}
			catch (Exception ex)
			{
				Debug.WriteLine("Failed to read a thumbnail. {0}", ex);

				if (IsImageNotSupported(ex))
					throw new ImageNotSupportedException();

				throw;
			}
		}
예제 #10
0
        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;
        }
예제 #11
0
 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;
 }
예제 #12
0
 public static async Task UploadTextAsync(ICloudBlob blob, string text, Encoding encoding, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
 {
     byte[] textAsBytes = encoding.GetBytes(text);
     using (MemoryStream stream = new MemoryStream())
     {
         await stream.WriteAsync(textAsBytes, 0, textAsBytes.Length);
         if (blob.BlobType == BlobType.PageBlob)
         {
             int lastPageSize = (int)(stream.Length % 512);
             if (lastPageSize != 0)
             {
                 byte[] padding = new byte[512 - lastPageSize];
                 await stream.WriteAsync(padding, 0, padding.Length);
             }
         }
         stream.Seek(0, SeekOrigin.Begin);
         await blob.UploadFromStreamAsync(stream.AsInputStream(), accessCondition, options, operationContext);
     }
 }
예제 #13
0
 private async Task<DataHeader> GetDataHeader(byte[] btarrHeader) {
    BinaryFormatter objFormatter = new BinaryFormatter();
    DataHeader objHeader;
    using(MemoryStream objStream = new MemoryStream()) {
       await objStream.WriteAsync(btarrHeader, 0, btarrHeader.Length);
       objStream.Position = 0;
       objHeader = (DataHeader)objFormatter.Deserialize(objStream);
    }
    return objHeader;
 }
예제 #14
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="stream"></param>
 /// <returns></returns>
 public static async Task<byte[]> ReadToEndAsByteAsync(this Stream stream) {
     var buffer = new byte[16 * 1024];
     using (var ms = new MemoryStream()) {
         int read;
         while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) {
             await ms.WriteAsync(buffer, 0, read);
         }
         return ms.ToArray();
     }
 }
예제 #15
0
      private async Task ProcessingStreets(byte[] btarrResponse) {
         BinaryFormatter objFormatter = new BinaryFormatter();
         using(MemoryStream objStream = new MemoryStream()) {
            await objStream.WriteAsync(btarrResponse, 0, btarrResponse.Length);
            objStream.Position = 0;

            List<Street> objStreets = (List<Street>)objFormatter.Deserialize(objStream);
            ShowStreets(objStreets);
         }
      }
예제 #16
0
 private async Task ProcessingImage(byte[] btarrResponse) {
    Bitmap objBitMap;
    BinaryFormatter objFormatter = new BinaryFormatter();
    using(MemoryStream objStream = new MemoryStream()) {
       await objStream.WriteAsync(btarrResponse, 0, btarrResponse.Length);
       objStream.Position = 0;
       objBitMap = (Bitmap)objFormatter.Deserialize(objStream);
       objBitMap.Save(@"D:\screenshot.jpg");
    }
 }
예제 #17
0
    public static async Task<Stream> CreateTempCopyStream(String path)
    {
        var bytes = File.ReadAllBytes(path);

        var ms = new MemoryStream();
        await ms.WriteAsync(bytes, 0, bytes.Length);
        ms.Position = 0;

        return ms;
    }
예제 #18
0
        private async Task <byte[]> GetSection(uint offset, uint size)
        {
            byte[] data = this.SafeGetBuffer();

            using (var ms = new IO.MemoryStream())
            {
                await ms.WriteAsync(data, (int)offset, (int)size);

                return(ms.ToArray());
            }
        }
 public static async Task<Stream> ReadStream(this IStorageFile file)
 {
     using (var stream = await file.OpenStreamForReadAsync())
     {
         var bytes = new byte[stream.Length];
         await stream.ReadAsync(bytes, 0, (int)stream.Length);
         var memoryStream = new MemoryStream();
         await memoryStream.WriteAsync(bytes, 0, bytes.Length);
         return memoryStream;
     }
 }
예제 #20
0
 public async Task<Stream> GetStream(string key)
 {
     var file = await GetStorageFile(key);
     using (var stream = await file.OpenStreamForReadAsync())
     {
         var bytes = new byte[stream.Length];
         await stream.ReadAsync(bytes, 0, (int)stream.Length);
         var memoryStream = new MemoryStream();
         await memoryStream.WriteAsync(bytes, 0, bytes.Length);
         return memoryStream;
     }
 }
예제 #21
0
 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.WriteAsync(buffer, 0, read);
         }
         return ms.ToArray();
     }
 }
 private static async Task<byte[]> ReadAllBytes(Stream input)
 {
     byte[] buffer = new byte[16 * 1024];
     using (MemoryStream ms = new MemoryStream())
     {
         int read;
         while ((read = await input.ReadAsync(buffer, 0, buffer.Length)) > 0)
         {
             await ms.WriteAsync(buffer, 0, read);
         }
         return ms.ToArray();
     }
 }
예제 #23
0
        internal System.IO.MemoryStream Save <T>(T data)
        {
            string json = JsonConvert.SerializeObject(data);

            return(Task.Run <System.IO.MemoryStream>(() =>
            {
                System.IO.MemoryStream stream = new System.IO.MemoryStream();

                byte[] d = Serialization.WriteString(json);
                stream.WriteAsync(d, 0, d.Length);
                return stream;
            }).Result);
        }
        public async Task<IHttpActionResult> S3UploadTest()
        {
            IS3Provider<S3ApiModel> amazon = new S3Client();

            Stream testStream = new MemoryStream();

            byte[] data = File.ReadAllBytes(HttpContext.Current.Server.MapPath("~/test.pdf"));

            await testStream.WriteAsync(data, 0, data.Count());

            var obj = await amazon.CreateRequest(testStream, ".pdf").SaveObject();

            return this.Ok(new ApiResponse(200, obj));
        }
예제 #25
0
        public static async Task UploadTextAsync(CloudBlob blob, string text, Encoding encoding, AccessCondition accessCondition = null, BlobRequestOptions options = null, OperationContext operationContext = null)
        {
            byte[] textAsBytes = encoding.GetBytes(text);
            using (MemoryStream stream = new MemoryStream())
            {
                await stream.WriteAsync(textAsBytes, 0, textAsBytes.Length);
                if (blob.BlobType == BlobType.PageBlob)
                {
                    int lastPageSize = (int)(stream.Length % 512);
                    if (lastPageSize != 0)
                    {
                        byte[] padding = new byte[512 - lastPageSize];
                        await stream.WriteAsync(padding, 0, padding.Length);
                    }
                }

                stream.Seek(0, SeekOrigin.Begin);
                blob.ServiceClient.DefaultRequestOptions.ParallelOperationThreadCount = 2;

                if (blob.BlobType == BlobType.AppendBlob)
                {
                    CloudAppendBlob blob1 = blob as CloudAppendBlob;
                    await blob1.CreateOrReplaceAsync();
                    await blob1.AppendBlockAsync(stream, null);
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    CloudPageBlob pageBlob = blob as CloudPageBlob;
                    await pageBlob.UploadFromStreamAsync(stream, accessCondition, options, operationContext);
                }
                else
                {
                    CloudBlockBlob blockBlob = blob as CloudBlockBlob;
                    await blockBlob.UploadFromStreamAsync(stream, accessCondition, options, operationContext);
                }
            }
        }
        public async Task<byte[]> SendReceiveAsync(byte[] payload)
        {
            byte[] receiveBytes = new byte[10240];

            // Send request operation
            await this.clientWebSocket.SendAsync(new ArraySegment<byte>(payload), WebSocketMessageType.Binary, true, CancellationToken.None);

            WebSocketReceiveResult receiveResult =
                await this.clientWebSocket.ReceiveAsync(new ArraySegment<byte>(receiveBytes), CancellationToken.None);

            using (MemoryStream ms = new MemoryStream())
            {
                await ms.WriteAsync(receiveBytes, 0, receiveResult.Count);
                return ms.ToArray();
            }
        }
예제 #27
0
        public async Task<byte[]> Run(int port)
        {
            var listener = new TcpListener(IPAddress.Any, port);
            listener.Start();
            var client = await listener.AcceptTcpClientAsync();


            var ms = new MemoryStream();

            using (var stream = client.GetStream())
            {
                var data = new byte[4096];
                var x = await stream.ReadAsync(data, 0, data.Length);
                await ms.WriteAsync(data, 0, x);
            }
            return ms.ToArray();
        }
예제 #28
0
        public static async Task<byte[]> ReadToEndAsync(this Stream stream)
        {
            var buffer = new byte[1024 * 1024];

            using (var memoryStream = new MemoryStream())
            {
                while (true)
                {
                    var read = await stream.ReadAsync(buffer, 0, buffer.Length);

                    if (read <= 0) break;

                    await memoryStream.WriteAsync(buffer, 0, read);
                }

                return memoryStream.ToArray();
            }
        }
예제 #29
0
 public static async Task<MemoryStream> UnEncode(MemoryStream encodedContent, string transferEncoding)
 {
     var unEncodedContent = new MemoryStream();
     try
     {
         switch (transferEncoding.ToLower())
         {
             case "7bit":
             case "8bit":
             case "binary":
                 unEncodedContent = encodedContent;
                 break;
             case "quoted-printable":
                 unEncodedContent = MailMethods.FromQuotedPrintable(encodedContent);
                 break;
             case "base64":
                 var base64String = Encoding.ASCII.GetString(encodedContent.ToArray());
                 var bytes = Convert.FromBase64String(base64String);
                 await unEncodedContent.WriteAsync(bytes, 0, bytes.Length);
                 break;
             default:
                 using (var writer = new StreamWriter(unEncodedContent, Encoding.ASCII))
                 {
                     writer.WriteLine("Unknown 'Content-transfer-encoding' encounterd: {0}", transferEncoding);
                     writer.WriteLine("------Encoded Content-------");
                     await writer.FlushAsync();
                     await encodedContent.CopyToAsync(unEncodedContent);
                 }
                 break;
         }
         return unEncodedContent;
     }
     catch (Exception ex)
     {
         using (var writer = new StreamWriter(unEncodedContent, Encoding.ASCII))
         {
             writer.WriteLine(ex.Message);
             writer.WriteLine("------Encoded Content-------");
             await writer.FlushAsync();
             await encodedContent.CopyToAsync(unEncodedContent);
             return unEncodedContent;
         }
     }
 }
예제 #30
0
 public async Task LoadAlbumsFromMediaLibraryAsync(PictureAlbum album, CancellationToken token)
 {
     ObservableCollection<CollectionControlModel> newItems = new ObservableCollection<CollectionControlModel>();
     foreach (var photo in album.Pictures)
     {
         Log(photo.Name);
        // await Task.Delay(new TimeSpan(0,0,0,0,10));
         token.ThrowIfCancellationRequested();
         Log(photo.Name + "50");
         newItems.Add(new CollectionControlModel()
         {
             FileName = Path.GetFileNameWithoutExtension(photo.Name),
             Data = photo
         });
         Log(photo.Name);
         token.ThrowIfCancellationRequested();
         using (Stream str = photo.GetThumbnail())
         {
            
             Log(photo.Name + "60");
             byte[] buffer = new byte[str.Length];
             await str.ReadAsync(buffer, 0, buffer.Length);
             Log(photo.Name + "63");
             token.ThrowIfCancellationRequested();
             using (MemoryStream ms = new MemoryStream())
             {
                 Log(photo.Name + "67");
                 await ms.WriteAsync(buffer, 0, buffer.Length);
                 token.ThrowIfCancellationRequested();
                 newItems.Last().Thumbnail = new BitmapImage();
                 newItems.Last().Thumbnail.SetSource(ms);
                 Log(photo.Name + "72");
             }
             //await Task.Delay(new TimeSpan(0, 0, 0, 0, 10));
             //Thread.Sleep(1000);
         }
     }
     foreach (var item in newItems)
     {
         Items.Add(item);
     }
 }
예제 #31
0
        public void SetImage(BiometricType bio)
        {
            if (bio == null)
                return;
            byte[] photo = bio.data;
            if (photo == null || photo.Length == 0)
            {
                return;
            }

            var memStream = new MemoryStream();
            Task t = memStream.WriteAsync(photo, 0, photo.Length);

            t.ContinueWith(result =>
            {
                memStream.Position = 0;
                this.photo.Image = Image.FromStream(memStream, true, true);
                this.photo.SizeMode = PictureBoxSizeMode.StretchImage;
            });
        }
        private async Task<BandImage> CreateMeTileAsync(CancellationToken cancel)
        {
            byte[] imgData = Convert.FromBase64String(base64ImageString);
            byte[] rgb565 = null;

            // convert image data to bgr 565 format...
            // first write data to a memory stream..
            using (var ms = new MemoryStream())
            {
                await ms.WriteAsync(imgData, 0, imgData.Length, cancel);
                ms.Position = 0;
                rgb565 = ms.GetPixelArrayBgr565();
            }

            var ti = typeof(BandImage).GetTypeInfo();
            var ctor = ti.DeclaredConstructors.First();
            var bi = (BandImage)ctor.Invoke(new object[] { 310, 102, rgb565 });

            return bi;
        }
예제 #33
0
 private void InitSamples()
 {
     samples = new List<MemoryStream>();
     for(int i = 0; i < KeyCount; i++)
     {
         string address = "Assets/Piano Keys/Piano" + i.ToString();
         using (FileStream fStream = new FileStream(address, FileMode.Open))
         {
             using (MemoryStream ms = new MemoryStream())
             {
                 byte[] buffer = new byte[fStream.Length];
                 fStream.ReadAsync(buffer,0, buffer.Length);
                 ms.WriteAsync(buffer,0,buffer.Length);
                 ms.Seek(0, SeekOrigin.Begin);
                 ms.Close();
                 samples.Add(ms);
             }
             fStream.Close();
         }
     }
 }
        private async Task<byte[]> AliceSendsDataAsync(string message)
        {
            WriteLine($"Alice sends message: {message}");
            byte[] rawData = Encoding.UTF8.GetBytes(message);
            byte[] encryptedData = null;

            using (var aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey))
            using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob,
                  CngKeyBlobFormat.EccPublicBlob))
            {
                byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey);
                WriteLine("Alice creates this symmetric key with " +
                      $"Bobs public key information: { Convert.ToBase64String(symmKey)}");

                using (var aes = new AesCryptoServiceProvider())
                {
                    aes.Key = symmKey;
                    aes.GenerateIV();
                    using (ICryptoTransform encryptor = aes.CreateEncryptor())
                    using (var ms = new MemoryStream())
                    {
                        // create CryptoStream and encrypt data to send
                        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                        {

                            // write initialization vector not encrypted
                            await ms.WriteAsync(aes.IV, 0, aes.IV.Length);
                            await cs.WriteAsync(rawData, 0, rawData.Length);
                        }
                        encryptedData = ms.ToArray();
                    }
                    aes.Clear();
                }
            }
            WriteLine($"Alice: message is encrypted: {Convert.ToBase64String(encryptedData)}"); ;
            WriteLine();
            return encryptedData;
        }
예제 #35
0
        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);
        }
예제 #36
0
        static private async Task <Stream> GetFileStream(string authHeader, string destinationFileName, FileContextInfo fileContextInfo)
        {
            var filePath = new Uri(destinationFileName).AbsolutePath;
            var stream   = new System.IO.MemoryStream();

            try
            {
                using (var client = new WebClient())
                {
                    client.Headers.Add(HttpRequestHeader.Authorization, authHeader);
                    var fileUri      = new Uri(destinationFileName);
                    var downloadData = await client.DownloadDataTaskAsync($"{fileContextInfo.WebUrl}/_api/web/getfilebyserverrelativeurl('{filePath}')/$value");

                    await stream.WriteAsync(downloadData, 0, downloadData.Length);

                    return(stream);
                }
            }
            catch (Exception ex)
            {
                stream.Dispose();
                throw ex;
            }
        }
예제 #37
0
 async private void WriteMemoryStream(System.IO.MemoryStream stream, byte[] data)
 {
     await stream.WriteAsync(data, 0, data.Length);
 }