public PushAttachmentData(String contentType, IInputStream data, ulong dataSize, byte[] key) { this.contentType = contentType; this.data = data; this.dataSize = dataSize; this.key = key; }
public bool ReadStringFromInputStream(IInputStream inputStream, List<string> messages, out string s) { var bytesCollection = new List<byte[]>(); var bytes = new byte[Environment.SystemPageSize]; while (true) { var bytesRead = inputStream.Read(bytes, _timeout); if (bytesRead <= 0) break; var bytesCopy = new byte[bytesRead]; Buffer.BlockCopy(bytes, 0, bytesCopy, 0, bytesRead); bytesCollection.Add(bytesCopy); } var bytesCount = bytesCollection.Sum(bytesChunk => bytesChunk.Length); bytes = new byte[bytesCount]; var offset = 0; foreach (var bytesChunk in bytesCollection) { Buffer.BlockCopy(bytesChunk, 0, bytes, offset, bytesChunk.Length); offset += bytesChunk.Length; } try { s = _encoding.GetString(bytes); } catch (Exception e) { messages.Add(e.ToString()); s = null; return false; } return true; }
/// <exception cref="System.IO.IOException"></exception> public NetworkSocketBase(Sharpen.Net.Socket socket, string hostName) { _socket = socket; _hostName = hostName; _in = _socket.GetInputStream(); _out = _socket.GetOutputStream(); }
private static async Task<TileSet> LoadTileSetAsync(IInputStream stream) { using (var reader = new StreamReader(stream.AsStreamForRead())) { return JsonConvert.DeserializeObject<TileSet>(await reader.ReadToEndAsync()); } }
public InputStreamReader(IInputStream stream, uint bufferSize) { _reader = new DataReader(stream); _reader.InputStreamOptions = InputStreamOptions.Partial; _bufferSize = bufferSize; }
internal Reader( IInputStream stream, files.File file ) { this.parser = new FileParser(stream, file); }
public DataReader (IInputStream inputStream) { if (inputStream == null) throw new ArgumentNullException ("inputStream"); throw new NotImplementedException(); }
/// <summary> /// Encrypt an input stream and output to another stream /// </summary> /// <param name="inStream"></param> /// <param name="outStream"></param> /// <param name="userDescriptor"></param> /// <returns></returns> public static async Task ProtectStreamToStream(IInputStream inStream, IOutputStream outStream, string userDescriptor) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor); await Provider.ProtectStreamAsync(inStream, outStream); }
public XBeeDevice(SerialDevice serialDevice) { _serialDevice = serialDevice; _serialDevice.ErrorReceived += _serialDevice_ErrorReceived; _input = _serialDevice.InputStream; _output = _serialDevice.OutputStream; Task.Run(() => ReadLoop(_cts.Token)); }
public LengthMarkedBufferedInputStream(IInputStream input) { this.input = input; buf = new byte[InitialBufferSize]; count = 0; markedLength = -1; markedIndex = -1; }
internal AfmParser( IInputStream fontData ) { FontData = fontData; Load(); }
public SerialConnection(SerialDevice serialDevice) { _serialDevice = serialDevice; _input = _serialDevice.InputStream; _output = _serialDevice.OutputStream; _serialDevice.ErrorReceived += _serialDevice_ErrorReceived; _buffer = new byte[1024]; }
void photoChooser_Completed(object sender, PhotoResult e) { if (e.ChosenPhoto == null) { return; } stream= e.ChosenPhoto.AsInputStream(); }
internal FileParser( IInputStream stream, files.File file ) : base(stream) { this.file = file; }
/// <summary> /// Decrypt an input stream and output to another stream /// </summary> /// <param name="readStream"></param> /// <param name="outStream"></param> /// <returns></returns> public static async Task DecryptStream(IInputStream readStream, IOutputStream outStream, string userDescriptor) { // Create a DataProtectionProvider object for the specified descriptor. DataProtectionProvider Provider = new DataProtectionProvider(userDescriptor); await Provider.UnprotectStreamAsync(readStream, outStream); // decrypt and output return; }
public void Open(IInputStream input, IOutputStream output) { m_DataReader = new DataReader(input); m_DataReader.ByteOrder = ByteOrder.LittleEndian; m_Reader.Reader = m_DataReader; m_DataWriter = new DataWriter(output); m_DataWriter.ByteOrder = ByteOrder.LittleEndian; m_Writer.Writer = m_DataWriter; }
public HashedInputStream(IInputStream stream) { if (stream == null) throw new ArgumentNullException("stream"); _stream = stream; _sha = HashAlgorithmProvider .OpenAlgorithm(HashAlgorithmNames.Sha256) .CreateHash(); }
protected void writeStream(IInputStream input)// throws IOException { /*byte[] buffer = new byte[4096]; int read; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); } input.close();*/ throw new NotImplementedException(); }
internal async Task<HttpRequest> ParseRequestStream(IInputStream requestStream) { var httpStream = new HttpRequestStream(requestStream); var request = new HttpRequest(); try { var stream = await httpStream.ReadAsync(BUFFER_SIZE, InputStreamOptions.Partial); byte[] streamData = stream.Data; var requestPipeline = GetPipeline(); using (var pipeLineEnumerator = requestPipeline.GetEnumerator()) { pipeLineEnumerator.MoveNext(); bool requestComplete = false; while (!requestComplete) { pipeLineEnumerator.Current.HandleRequestPart(streamData, request); streamData = pipeLineEnumerator.Current.UnparsedData; if (pipeLineEnumerator.Current.IsFinished) { if (!pipeLineEnumerator.Current.IsSucceeded || !pipeLineEnumerator.MoveNext()) { break; } } else { var newStreamdata = await httpStream.ReadAsync(BUFFER_SIZE, InputStreamOptions.Partial); if (!newStreamdata.ReadSuccessful) { break; } streamData = streamData.ConcatArray(newStreamdata.Data); } } } request.IsComplete = requestPipeline.All(p => p.IsSucceeded); } catch (Exception ex) { Debug.WriteLine(ex.Message); } return request; }
/// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> public TailoredUploadOperation( LiveConnectClient client, Uri url, string fileName, IInputStream inputStream, OverwriteOption option, IProgress<LiveOperationProgress> progress, SynchronizationContextWrapper syncContext) : this(client, url, fileName, option, progress, syncContext) { Debug.Assert(inputStream != null, "inputStream is null."); this.InputStream = inputStream; }
/// <summary> /// This class implements the upload operation on Windows 8 using the background uploader. /// </summary> /// <remarks>This constructor is used when uploading a stream created by the application.</remarks> public CreateBackgroundUploadOperation( LiveConnectClient client, Uri url, string fileName, IInputStream inputStream, OverwriteOption option) : base(client, url, ApiMethod.Upload, null, null) { Debug.Assert(inputStream != null, "inputStream is null."); this.InputStream = inputStream; this.FileName = fileName; this.OverwriteOption = option; }
public StreamWatcher( IInputStream stream ) { if ( stream == null ) throw new ArgumentNullException( "stream" ); ReadSize = 256; _reader = new DataReader( stream ) { ByteOrder = ByteOrder.LittleEndian, InputStreamOptions = InputStreamOptions.Partial }; Task.Factory.StartNew( CheckForData, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default ); }
/// <exception cref="System.IO.IOException"></exception> protected virtual void Copy(IInputStream rawin, Socket4Adapter sock, bool update) { BufferedInputStream @in = new BufferedInputStream(rawin); byte[] buffer = new byte[BlobImpl.CopybufferLength]; int bytesread = -1; while ((bytesread = rawin.Read(buffer)) >= 0) { sock.Write(buffer, 0, bytesread); if (update) { _currentByte += bytesread; } } @in.Close(); }
internal static async Task <AnimatedVisualFactory?> LoadAsync( ImageAssetHandler?imageLoader, IInputStream inputStream, LottieVisualOptions options) { if (inputStream is null) { return(null); } var loader = new InputStreamLoader(imageLoader, inputStream); return(await Loader.LoadAsync( loader.GetJsonStreamAsync, loader, options)); }
public async Task BlobOpenWriteSeekReadTestAsync() { byte[] buffer = GetRandomBuffer(2 * 1024); CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); CloudPageBlob blob = container.GetPageBlobReference("blob1"); MemoryStream memoryStream = new MemoryStream(buffer); IOutputStream iBlobStream = await blob.OpenWriteAsync(2048); using (Stream blobStream = iBlobStream.AsStreamForWrite()) { await blobStream.WriteAsync(buffer, 0, 2048); Assert.AreEqual(blobStream.Position, 2048); blobStream.Seek(1024, 0); memoryStream.Seek(1024, 0); Assert.AreEqual(blobStream.Position, 1024); byte[] testBuffer = GetRandomBuffer(1024);; await memoryStream.WriteAsync(testBuffer, 0, 1024); await blobStream.WriteAsync(testBuffer, 0, 1024); Assert.AreEqual(blobStream.Position, memoryStream.Position); await blobStream.FlushAsync(); } IInputStream iDstStream = await blob.OpenReadAsync(); using (Stream dstStream = iDstStream.AsStreamForRead()) { dstStream.Seek(2048, 0); TestHelper.AssertStreamsAreEqual(memoryStream, dstStream); } } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
/// <summary> /// Write the contents of stream to filename in the cache location. If a null stream is provided, the file is created with no contents. /// </summary> /// <param name="stream">Content to be written to file</param> /// <param name="filename">Name of the file to be written in cache location</param> private static async Task WriteFileAsync(Stream stream, string filename) { // Prepare output file stream StorageFolder parent = GetCacheFolder(); StorageFile file = null; try { file = await parent.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); } catch (Exception) { } if (file != null && stream != null) { // Prepare input image stream IInputStream inStream = stream.AsInputStream(); DataReader reader = new DataReader(inStream); IRandomAccessStream fileStream = null; try { fileStream = await file.OpenAsync(FileAccessMode.ReadWrite); // Buffered write to file await reader.LoadAsync(1024); while (reader.UnconsumedBufferLength > 0) { await fileStream.WriteAsync(reader.ReadBuffer(reader.UnconsumedBufferLength)); await reader.LoadAsync(1024); } } catch (Exception) { } finally { if (fileStream != null) { await fileStream.FlushAsync(); } } inStream.Dispose(); } }
/// <summary> /// Converts received stream to a parsed message and passes it to the WebSocketMessageReceived handler. /// </summary> /// <param name="sender">The <see cref="MessageWebSocket" /> that sent the message.</param> /// <param name="args">The message from the web socket.</param> private async void MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { if (this.IsListeningForMessages) { using (IInputStream inputStream = args.GetDataStream()) { Stream stream = new MemoryStream(); await inputStream.AsStreamForRead().CopyToAsync(stream); // Ensure we return with the stream pointed at the origin. stream.Position = 0; this.ConvertStreamToMessage(stream); } } }
public async Task GetInputStream(Uri targetUri) { try { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, targetUri); HttpResponseMessage response = await hc.SendRequestAsync(request); IInputStream stream = await response.Content.ReadAsInputStreamAsync(); return(stream); } catch (Exception ex) { Debug.WriteLine("Exception {0}", ex); return(null); } }
public override InputStream openForRead() { ensureGotStorageFile(); try { IInputStream inputStream = storageFile.OpenSequentialReadAsync().DoSynchronously(); // TODO: Need to close the inputStream itself; add a closedListener to InputStream, i think // Use the default 16K buffer for AsStreamForRead() return(new DotNetStreamInputStream(inputStream.AsStreamForRead())); } catch (System.IO.IOException e) { throw DotNetIOUtils.jSimpleExceptionFromDotNetIOException(e); } }
// Moved it to the end while using Dev10 VS because it does not understand async and everything that follows looses intellisense. // Should move this code into the Reading regios once using Dev11 VS becomes the norm. private async Task <Int32> ReadAsyncInternal(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer.Length - offset >= count); Debug.Assert(_canRead); IInputStream wrtStr = EnsureNotDisposed <IInputStream>(); #if DEBUG AssertValidStream(wrtStr); #endif // DEBUG try { IBuffer userBuffer = buffer.AsBuffer(offset, count); IAsyncOperationWithProgress <IBuffer, UInt32> asyncReadOperation = wrtStr.ReadAsync(userBuffer, unchecked ((UInt32)count), InputStreamOptions.Partial); IBuffer resultBuffer = await asyncReadOperation.AsTask(cancellationToken).ConfigureAwait(continueOnCapturedContext: false); // If cancellationToken was cancelled until now, then we are currently propagating the corresponding cancellation exception. // (It will be correctly rethrown by the catch block below and overall we will return a cancelled task.) // But if the underlying operation managed to complete before it was cancelled, we want // the entire task to complete as well. This is ok as the continuation is very lightweight: if (resultBuffer == null) { return(0); } WinRtIOHelper.EnsureResultsInUserBuffer(userBuffer, resultBuffer); Debug.Assert(resultBuffer.Length <= unchecked ((UInt32)Int32.MaxValue)); return((Int32)resultBuffer.Length); } catch (Exception ex) { // If the interop layer gave us an Exception, we assume that it hit a general/unknown case and wrap it into // an IOException as this is what Stream users expect. WinRtIOHelper.NativeExceptionToIOExceptionInfo(ex).Throw(); return(0); } }
public static Index Parse(IInputStream stream) { byte[][] data = new byte[stream.ReadUnsignedShort()][]; { int[] offsets = new int[data.Length + 1]; int offSize = stream.ReadByte(); for (int index = 0, count = offsets.Length; index < count; index++) { offsets[index] = stream.ReadInt(offSize); } for (int index = 0, count = data.Length; index < count; index++) { stream.Read(data[index] = new byte[offsets[index + 1] - offsets[index]]); } } return(new Index(data)); }
private bool SetCacheImage(string id, string imageUrl, IInputStream stream) { try { id = $"$/{id}"; var file = _fileStorage.Upload(id, imageUrl, stream.AsStreamForRead()); _fileStorage.SetMetadata(id, new BsonDocument(new Dictionary <string, BsonValue>() { { "updateAt", DateTime.Now } })); return(true); } catch { return(false); } }
/// <summary> /// Stores stream content as file on OneDrive. This method is NOT thread safe. It assumes that the contents of the stream will not change during the upload process. /// </summary> /// <param name="file"></param> The stream to upload to OneDrive. /// <param name="destinationPath"></param> The path to the destination on Onedrive. Passing in an empty string will place the file in the root of Onedrive. Other folder paths should be passed in with a leading '/' character, such as "/Documents" or "/Pictures/Random" /// <returns>The response message given by the server for the request</returns> public async Task <HttpResponseMessage> UploadFileAsync(IInputStream stream, string path, string fileName) { string uploadUri = String.Format(UploadUrlFormat, CorrectOneDrivePath(path), fileName); using (HttpStreamContent streamContent = new HttpStreamContent(stream)) { using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Put, new Uri(uploadUri))) { requestMessage.Content = streamContent; using (HttpResponseMessage response = await httpClient.SendRequestAsync(requestMessage)) { return(response); } } } }
protected override IDisposable?LoadAndObserveAnimationData( IInputStream sourceJson, string sourceCacheKey, UpdatedAnimation updateCallback) { var cts = new CancellationTokenSource(); _updateCallback = updateCallback; var t = LoadAndUpdate(cts.Token, sourceCacheKey, sourceJson); return(Disposable.Create(() => { cts.Cancel(); cts.Dispose(); })); }
/// <summary> /// Starts the playback and returns immediately /// The main use case is real-time feeds. /// </summary> public void Start() { foreach (IInputStream i in _inputs) { i.StartTime = StartTime; i.EndTime = EndTime; if (KnownTypes == null) { continue; } foreach (Type t in KnownTypes) { i.AddKnownType(t); } } if (_inputs.Count == 0) { throw new Exception("No input sequences were added to the Playback"); } if (_inputs.Count > 1) { IEnumerator <Timestamped <object> >[] queues = (from i in _inputs select i.Output).ToArray(); _mergesort = new PullMergeSort <Timestamped <object> >(e => e.Timestamp.DateTime, queues); _timeSource.Connect(); _pumpStart = new ManualResetEvent(false); _pump = new OutputPump <Timestamped <object> >(_mergesort, _subject, _pumpStart); _pumpStart.Set(); _stopwatch.Start(); foreach (IInputStream i in _inputs) { i.Start(); } } else { _timeSource.Connect(); IInputStream singleInput = _inputs[0]; _stopwatch.Start(); singleInput.Start(_subject); } }
private async void ListenerConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { StreamSocket socket = args.Socket; StringBuilder requestStrBuilder = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); requestStrBuilder.Append(Encoding.UTF8.GetString(data, 0, (int)buffer.Length)); dataRead = buffer.Length; } } string requestStr = requestStrBuilder.ToString(); if (String.IsNullOrEmpty(requestStr)) { return; } FlexRequest request = FlexRequest.TryParse(requestStr); if (request == null) { return; } FlexResponse response = await ProcessRequest(request); using (IOutputStream output = socket.OutputStream) { using (Stream responseStream = output.AsStreamForWrite()) { await response.WriteToStream(responseStream); await responseStream.FlushAsync(); } } }
private async Task<StringBuilder> ReadInputStream(IInputStream InputStream) { StringBuilder requestbuilder = new StringBuilder(); using (IInputStream input = InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); requestbuilder.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } return requestbuilder; }
private void MainPage_Unloaded(object sender, RoutedEventArgs e) { if (this.mediaElement != null) { this.mediaElement.Source = null; } if (this.flvMediaStreamSource != null) { this.flvMediaStreamSource.Dispose(); this.flvMediaStreamSource = null; } if (this.videoStream != null) { this.videoStream.Dispose(); this.videoStream = null; } }
private async Task LoadDatas <T>(string containerName, string fileName) { var storageFolder = ApplicationData.Current.LocalFolder; var file = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.OpenIfExists); if (file == null) { return; } IInputStream stream = await file.OpenReadAsync(); var serializer = new DataContractSerializer(typeof(T)); this.persistedObject = serializer.ReadObject(stream.AsStreamForRead()); }
public async Task FileOpenWriteSeekReadTestAsync() { byte[] buffer = GetRandomBuffer(2 * 1024); CloudFileShare share = GetRandomShareReference(); try { await share.CreateAsync(); CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1"); MemoryStream memoryStream = new MemoryStream(buffer); using (ICloudFileStream fileStream = await file.OpenWriteAsync(2048)) { Stream fileStreamForWrite = fileStream.AsStreamForWrite(); await fileStreamForWrite.WriteAsync(buffer, 0, 2048); Assert.AreEqual(fileStreamForWrite.Position, 2048); fileStreamForWrite.Seek(1024, 0); memoryStream.Seek(1024, 0); Assert.AreEqual(fileStreamForWrite.Position, 1024); byte[] testBuffer = GetRandomBuffer(1024); await memoryStream.WriteAsync(testBuffer, 0, 1024); await fileStreamForWrite.WriteAsync(testBuffer, 0, 1024); Assert.AreEqual(fileStreamForWrite.Position, memoryStream.Position); await fileStreamForWrite.FlushAsync(); } using (IInputStream dstStream = await file.OpenReadAsync()) { Stream dstStreamForRead = dstStream.AsStreamForRead(); TestHelper.AssertStreamsAreEqual(memoryStream, dstStreamForRead); } } finally { share.DeleteIfExistsAsync().AsTask().Wait(); } }
/** * <summary>Retrieves the starting position of the last xref-table section [PDF:1.6:3.4.4].</summary> */ public long RetrieveXRefOffset() { // [FIX:69] 'startxref' keyword not found (file was corrupted by alien data in the tail). IInputStream stream = Stream; long streamLength = stream.Length; long position = streamLength; int chunkSize = (int)Math.Min(streamLength, EOFMarkerChunkSize); int index = -1; while (index < 0 && position > 0) { /* * NOTE: This condition prevents the keyword from being split by the chunk boundary. */ if (position < streamLength) { position += Keyword.StartXRef.Length; } position -= chunkSize; if (position < 0) { position = 0; } stream.Seek(position); // Get 'startxref' keyword position! index = stream.ReadString(chunkSize).LastIndexOf(Keyword.StartXRef, StringComparison.Ordinal); } if (index < 0) { throw new PostScriptParseException("'" + Keyword.StartXRef + "' keyword not found.", this); } // Go past the 'startxref' keyword! stream.Seek(position + index); MoveNext(); // Get the xref offset! MoveNext(); if (TokenType != TokenTypeEnum.Integer) { throw new PostScriptParseException("'" + Keyword.StartXRef + "' value invalid.", this); } return((int)Token); }
public override bool MoveNext( ) { bool moved = base.MoveNext(); if (moved) { switch (TokenType) { case TokenTypeEnum.Integer: { /* * NOTE: We need to verify whether indirect reference pattern is applicable: * ref := { int int 'R' } */ IInputStream stream = Stream; long baseOffset = stream.Position; // Backs up the recovery position. // 1. Object number. int objectNumber = (int)Token; // 2. Generation number. base.MoveNext(); if (TokenType == TokenTypeEnum.Integer) { int generationNumber = (int)Token; // 3. Reference keyword. base.MoveNext(); if (TokenType == TokenTypeEnum.Keyword && Token.Equals(Keyword.Reference)) { Token = new Reference(objectNumber, generationNumber); } } if (!(Token is Reference)) { // Rollback! stream.Seek(baseOffset); Token = objectNumber; TokenType = TokenTypeEnum.Integer; } } break; } } return(moved); }
private async void ReadPlaylist() { try { StorageFile fileAsync = await ApplicationData.Current.LocalFolder.GetFileAsync(this.playlistname); StorageFile storageFile = fileAsync; IInputStream inputStream = await storageFile.OpenSequentialReadAsync(); try { DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(PlayList)); PlayList playList = dataContractSerializer.ReadObject(inputStream.AsStreamForRead()) as PlayList; this.internal_playlist = playList; } finally { if (inputStream != null) { inputStream.Dispose(); } } StorageFile fileAsync1 = await ApplicationData.Current.LocalFolder.GetFileAsync(this.shuffleplaylistname); storageFile = fileAsync1; IInputStream inputStream1 = await storageFile.OpenSequentialReadAsync(); try { DataContractSerializer dataContractSerializer1 = new DataContractSerializer(typeof(PlayList)); PlayList playList1 = dataContractSerializer1.ReadObject(inputStream1.AsStreamForRead()) as PlayList; this.shuffle_internal_playlist = playList1; } finally { if (inputStream1 != null) { inputStream1.Dispose(); } } } catch (Exception exception) { } }
private async Task SendRequestAsync() { Debug.Assert(_inputStream == null); HttpRequestMessage request = GetRequest(Position); Debug.WriteLine(request); HttpResponseMessage response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); Debug.WriteLine(response); if (response.Content?.Headers?.ContentLength != null) { Size = (ulong)response.Content.Headers.ContentLength.Value; } if (response.StatusCode != HttpStatusCode.PartialContent && Position != 0) { throw new Exception("HTTP server did not reply with a '206 Partial Content' status."); } if (!response.Headers.Contains("Accept-Ranges")) { throw new Exception("HTTP server does not support range requests"); } if (string.IsNullOrEmpty(_etagHeader) && response.Headers.Contains("ETag")) { _etagHeader = Join(response.Headers.GetValues("ETag")); } if (string.IsNullOrEmpty(_lastModifiedHeader) && response.Content.Headers.Contains("Last-Modified")) { _lastModifiedHeader = Join(response.Content.Headers.GetValues("Last-Modified")); } if (response.Content.Headers.Contains("Content-Type")) { ContentType = Join(response.Content.Headers.GetValues("Content-Type")); } _inputStream = (await response.Content.ReadAsStreamAsync().ConfigureAwait(false)).AsInputStream(); string Join(IEnumerable <string> enumerable) => string.Join(" ", enumerable); }
public async Task <byte[]> Encrypt(byte[] data) { var provider = new DataProtectionProvider(UseForAllUsers ? _localMachineDescriptor : _localUserDescriptor); var contentBuffer = CryptographicBuffer.CreateFromByteArray(data); var contentInputStream = new InMemoryRandomAccessStream(); var protectedContentStream = new InMemoryRandomAccessStream(); //storing data in the stream IOutputStream outputStream = contentInputStream.GetOutputStreamAt(0); var dataWriter = new DataWriter(outputStream); dataWriter.WriteBuffer(contentBuffer); await dataWriter.StoreAsync(); await dataWriter.FlushAsync(); //reopening in input mode IInputStream encodingInputStream = contentInputStream.GetInputStreamAt(0); IOutputStream protectedOutputStream = protectedContentStream.GetOutputStreamAt(0); await provider.ProtectStreamAsync(encodingInputStream, protectedOutputStream); await protectedOutputStream.FlushAsync(); //verify that encryption happened var inputReader = new DataReader(contentInputStream.GetInputStreamAt(0)); var protectedReader = new DataReader(protectedContentStream.GetInputStreamAt(0)); await inputReader.LoadAsync((uint)contentInputStream.Size); await protectedReader.LoadAsync((uint)protectedContentStream.Size); var inputBuffer = inputReader.ReadBuffer((uint)contentInputStream.Size); var protectedBuffer = protectedReader.ReadBuffer((uint)protectedContentStream.Size); if (!CryptographicBuffer.Compare(inputBuffer, protectedBuffer)) { return(protectedBuffer.ToArray()); } else { return(null); } }
private async Task <String> SampleDataUnprotectStream( IBuffer buffProtected, BinaryStringEncoding encoding) { // Create a DataProtectionProvider object. DataProtectionProvider Provider = new DataProtectionProvider(); // Create a random access stream to contain the encrypted message. InMemoryRandomAccessStream inputData = new InMemoryRandomAccessStream(); // Create a random access stream to contain the decrypted data. InMemoryRandomAccessStream unprotectedData = new InMemoryRandomAccessStream(); // Retrieve an IOutputStream object and fill it with the input (encrypted) data. IOutputStream outputStream = inputData.GetOutputStreamAt(0); DataWriter writer = new DataWriter(outputStream); writer.WriteBuffer(buffProtected); await writer.StoreAsync(); await outputStream.FlushAsync(); // Retrieve an IInputStream object from which you can read the input (encrypted) data. IInputStream source = inputData.GetInputStreamAt(0); // Retrieve an IOutputStream object and fill it with decrypted data. IOutputStream dest = unprotectedData.GetOutputStreamAt(0); await Provider.UnprotectStreamAsync(source, dest); await dest.FlushAsync(); // Write the decrypted data to an IBuffer object. DataReader reader2 = new DataReader(unprotectedData.GetInputStreamAt(0)); await reader2.LoadAsync((uint)unprotectedData.Size); IBuffer buffUnprotectedData = reader2.ReadBuffer((uint)unprotectedData.Size); // Convert the IBuffer object to a string using the same encoding that was // used previously to conver the plaintext string (before encryption) to an // IBuffer object. String strUnprotected = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotectedData); // Return the decrypted data. return(strUnprotected); }
private static async Task <string> ToString(IInputStream input) { StringBuilder request = new StringBuilder(); byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } return(request.ToString()); }
public static async Task <InMemoryRandomAccessStream> CreateMemoryRandom(this Stream stream) { IBuffer buffer = null; IInputStream inputstream = stream.AsInputStream(); using (var dataReader = new DataReader(inputstream)) { await dataReader.LoadAsync((uint)stream.Length); buffer = dataReader.DetachBuffer(); } var randomAccessStream = new InMemoryRandomAccessStream(); await randomAccessStream.WriteAsync(buffer); return(randomAccessStream); }
public OfcParser([CanBeNull] IInputStream <OfcToken> input, [CanBeNull] IParserHook <string> hook, int bufferSize) { if (bufferSize < 64) { throw new ArgumentOutOfRangeException(nameof(bufferSize)); } /** set base members */ _buffer = new OfcToken[bufferSize]; _eos = input == null; _length = 0; _position = 0; _size = bufferSize; _source = input; /** set parser members */ _hook = hook ?? EmptyHook <string> .Instance; }
// 发送文件 POST 请求 private static async Task <JObject> POST_FILE(string api, string key, StorageFile file) { // 读取文件流 IInputStream stream = await file.OpenSequentialReadAsync(); var streamContent = new HttpStreamContent(stream); // 上传文件 var form = new HttpMultipartFormDataContent(); form.Add(streamContent, key, file.Name); HttpClient client = new HttpClient(); var response = await client.PostAsync(new Uri(SERVER + api), form); string resStr = await response.Content.ReadAsStringAsync(); return((JObject)JsonConvert.DeserializeObject(resStr)); }
public async void Open(InkCanvas display) { try { FileOpenPicker picker = new FileOpenPicker(); picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary; picker.FileTypeFilter.Add(".drw"); StorageFile file = await picker.PickSingleFileAsync(); using (IInputStream stream = await file.OpenSequentialReadAsync()) { await display.InkPresenter.StrokeContainer.LoadAsync(stream); } } catch { } }
public IAsyncAction UploadAsync(IRecord record, string contentType, IInputStream stream) { if (record == null) { throw new ArgumentNullException("record"); } return(AsyncInfo.Run(cancelToken => Task.Run(async() => { if (string.IsNullOrEmpty(contentType)) { contentType = HttpStreamer.OctetStreamMimeType; } var blobInfo = new BlobInfo(contentType); await record.PutBlobInItem(Item, blobInfo, stream).AsTask(cancelToken); }))); }
public static async Task loadAppState() { var file = await ApplicationData.Current.LocalFolder.GetFileAsync("backup.xml"); if (file == null) { return; } using (IInputStream stream = await file.OpenSequentialReadAsync()) { var serializer = new DataContractSerializer(typeof(Dictionary <string, object>), new List <Type>() { typeof(CurrencyData), typeof(CurrencyHistoryView) }); appState = (Dictionary <string, object>)serializer.ReadObject(stream.AsStreamForRead()); } }
public static async Task<string> ComputeMd5(IInputStream stream, BinaryStringEncoding encoding = BinaryStringEncoding.Utf8) { var hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5); var hash = hashAlgorithmProvider.CreateHash(); uint size = 1024*64; var buffer = new Buffer(size); while (true) { var x = await stream.ReadAsync(buffer, size, InputStreamOptions.Partial); if (x.Length < 1) { break; } hash.Append(x); } var result = hash.GetValueAndReset(); var hex = CryptographicBuffer.EncodeToHexString(result); return hex; }
public async static Task<MutableHttpServerRequest> Parse(IInputStream requestStream) { return await HttpRequestParser.Default.ParseRequestStream(requestStream); }
public HttpRequestStream(IInputStream requestStream) { _requestStream = requestStream; }
public StreamBufferedReader(IInputStream stream, int bufferSize) { buffer = new ArrayBuffer(bufferSize); args = new BufferFilledEventArgs(buffer); this.stream = stream; }
public IAsyncAction WritePagesAsync(IInputStream pageData, long startOffset, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient); bool requiresContentMD5 = (contentMD5 == null) && modifiedOptions.UseTransactionalMD5.Value; operationContext = operationContext ?? new OperationContext(); return AsyncInfo.Run(async (token) => { Stream pageDataAsStream = pageData.AsStreamForRead(); Stream seekableStream = pageDataAsStream; if (!pageDataAsStream.CanSeek || requiresContentMD5) { DateTime streamCopyStartTime = DateTime.Now; CancellationToken streamCopyToken = token; if (modifiedOptions.MaximumExecutionTime.HasValue) { // Setup token CancellationTokenSource cts = new CancellationTokenSource(modifiedOptions.MaximumExecutionTime.Value); CancellationToken tokenWithTimeout = cts.Token; // Hookup users token token.Register(() => cts.Cancel()); streamCopyToken = tokenWithTimeout; } Stream writeToStream; if (pageDataAsStream.CanSeek) { writeToStream = Stream.Null; } else { seekableStream = new MemoryStream(); writeToStream = seekableStream; } OperationContext tempOperationContext = new OperationContext(); StreamDescriptor streamCopyState = new StreamDescriptor(); long startPosition = seekableStream.Position; await pageDataAsStream.WriteToAsync(writeToStream, Constants.MaxBlockSize, requiresContentMD5, tempOperationContext, streamCopyState, streamCopyToken); seekableStream.Position = startPosition; if (requiresContentMD5) { contentMD5 = streamCopyState.Md5; } if (modifiedOptions.MaximumExecutionTime.HasValue) { modifiedOptions.MaximumExecutionTime -= DateTime.Now.Subtract(streamCopyStartTime); } } await Executor.ExecuteAsyncNullReturn( this.PutPageImpl(seekableStream, startOffset, contentMD5, accessCondition, modifiedOptions), modifiedOptions.RetryPolicy, operationContext, token); }); }
public IAsyncAction WritePagesAsync(IInputStream pageData, long startOffset, string contentMD5) { return this.WritePagesAsync(pageData, startOffset, contentMD5, null /* accessCondition */, null /* options */, null /* operationContext */); }