private static async Task<TileSet> LoadTileSetAsync(IInputStream stream) { using (var reader = new StreamReader(stream.AsStreamForRead())) { return JsonConvert.DeserializeObject<TileSet>(await reader.ReadToEndAsync()); } }
//Loads the cart information on startup if exists public static async Task LoadLocalWatchlistInformation() { try { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { DataContractSerializer serializer = new DataContractSerializer(typeof(ObservableCollection <C4H_Webservice.CharityProfile>)); var data = (ObservableCollection <C4H_Webservice.CharityProfile>)serializer.ReadObject(inStream.AsStreamForRead()); if (data != null) { FollowedCharitiesList = data; } } } catch { } }
public IAsyncAction UploadFromStreamAsync(IInputStream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { CommonUtils.AssertNotNull("source", source); this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient); operationContext = operationContext ?? new OperationContext(); Stream sourceAsStream = source.AsStreamForRead(); if (!sourceAsStream.CanSeek) { throw new InvalidOperationException(); } long size = sourceAsStream.Length - sourceAsStream.Position; if ((size % Constants.PageSize) != 0) { throw new ArgumentException(SR.InvalidPageSize, "source"); } return AsyncInfo.Run(async (token) => { 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; } await Task.Run(async () => { IOutputStream writeStream = await this.OpenWriteAsync(size, accessCondition, options, operationContext); // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our // stream copier only writes 64K buffers at a time anyway, so no buffering is needed. using (Stream blobStream = writeStream.AsStreamForWrite(0)) { await sourceAsStream.WriteToAsync(blobStream, null /* maxLength */, false, new OperationContext(), null /* streamCopyState */, streamCopyToken); } }); }); }
public IAsyncAction UploadFromStreamAsync(IInputStream source, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { CommonUtils.AssertNotNull("source", source); this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.BlockBlob, this.ServiceClient); operationContext = operationContext ?? new OperationContext(); Stream sourceAsStream = source.AsStreamForRead(); return AsyncInfo.Run(async (token) => { 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; } if ((this.ServiceClient.ParallelOperationThreadCount == 1) && sourceAsStream.CanSeek && ((sourceAsStream.Length - sourceAsStream.Position) <= this.ServiceClient.SingleBlobUploadThresholdInBytes)) { string contentMD5 = null; if (modifiedOptions.StoreBlobContentMD5.Value) { OperationContext tempOperationContext = new OperationContext(); StreamDescriptor streamCopyState = new StreamDescriptor(); long startPosition = sourceAsStream.Position; await sourceAsStream.WriteToAsync(Stream.Null, null /* maxLength */, true, tempOperationContext, streamCopyState, streamCopyToken); sourceAsStream.Position = startPosition; contentMD5 = streamCopyState.Md5; } if (modifiedOptions.MaximumExecutionTime.HasValue) { modifiedOptions.MaximumExecutionTime -= DateTime.Now.Subtract(streamCopyStartTime); } await Executor.ExecuteAsyncNullReturn( this.PutBlobImpl(sourceAsStream, contentMD5, accessCondition, modifiedOptions), modifiedOptions.RetryPolicy, operationContext, token); } else { await Task.Run(async () => { IOutputStream writeStream = await this.OpenWriteAsync(accessCondition, options, operationContext); // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our // stream copier only writes 64K buffers at a time anyway, so no buffering is needed. using (Stream blobStream = writeStream.AsStreamForWrite(0)) { await sourceAsStream.WriteToAsync(blobStream, null /* maxLength */, false, new OperationContext(), null /* streamCopyState */, streamCopyToken); } }); } }); }
public static StorageExtendedErrorInformation ReadFromStream(IInputStream inputStream) { return ReadFromStream(inputStream.AsStreamForRead()); }
public IAsyncAction WriteRangeAsync(IInputStream rangeData, long startOffset, string contentMD5, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext) #endif { CommonUtility.AssertNotNull("rangeData", rangeData); FileRequestOptions modifiedOptions = FileRequestOptions.ApplyDefaults(options, this.ServiceClient); bool requiresContentMD5 = (contentMD5 == null) && modifiedOptions.UseTransactionalMD5.Value; operationContext = operationContext ?? new OperationContext(); ExecutionState<NullType> tempExecutionState = CommonUtility.CreateTemporaryExecutionState(modifiedOptions); #if ASPNET_K return Task.Run(async () => #else return AsyncInfo.Run(async (cancellationToken) => #endif { DateTime streamCopyStartTime = DateTime.Now; Stream rangeDataAsStream = rangeData.AsStreamForRead(); Stream seekableStream = rangeDataAsStream; if (!rangeDataAsStream.CanSeek || requiresContentMD5) { Stream writeToStream; if (rangeDataAsStream.CanSeek) { writeToStream = Stream.Null; } else { seekableStream = new MultiBufferMemoryStream(this.ServiceClient.BufferManager); writeToStream = seekableStream; } StreamDescriptor streamCopyState = new StreamDescriptor(); long startPosition = seekableStream.Position; await rangeDataAsStream.WriteToAsync(writeToStream, null /* copyLength */, Constants.MaxBlockSize, requiresContentMD5, tempExecutionState, streamCopyState, cancellationToken); seekableStream.Position = startPosition; if (requiresContentMD5) { contentMD5 = streamCopyState.Md5; } if (modifiedOptions.MaximumExecutionTime.HasValue) { modifiedOptions.MaximumExecutionTime -= DateTime.Now.Subtract(streamCopyStartTime); } } await Executor.ExecuteAsyncNullReturn( this.PutRangeImpl(seekableStream, startOffset, contentMD5, accessCondition, modifiedOptions), modifiedOptions.RetryPolicy, operationContext, cancellationToken); #if ASPNET_K }, cancellationToken); #else });
public IAsyncAction PutBlockAsync(string blockId, IInputStream blockData, string contentMD5, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.BlockBlob, this.ServiceClient); bool requiresContentMD5 = (contentMD5 == null) && modifiedOptions.UseTransactionalMD5.Value; operationContext = operationContext ?? new OperationContext(); ExecutionState<NullType> tempExecutionState = CommonUtility.CreateTemporaryExecutionState(modifiedOptions); return AsyncInfo.Run(async (token) => { Stream blockDataAsStream = blockData.AsStreamForRead(); Stream seekableStream = blockDataAsStream; if (!blockDataAsStream.CanSeek || requiresContentMD5) { Stream writeToStream; if (blockDataAsStream.CanSeek) { writeToStream = Stream.Null; } else { seekableStream = new MultiBufferMemoryStream(this.ServiceClient.BufferManager); writeToStream = seekableStream; } StreamDescriptor streamCopyState = new StreamDescriptor(); long startPosition = seekableStream.Position; await blockDataAsStream.WriteToAsync(writeToStream, null /* copyLength */, Constants.MaxBlockSize, requiresContentMD5, tempExecutionState, streamCopyState, token); seekableStream.Position = startPosition; if (requiresContentMD5) { contentMD5 = streamCopyState.Md5; } } await Executor.ExecuteAsyncNullReturn( this.PutBlockImpl(seekableStream, blockId, contentMD5, accessCondition, modifiedOptions), modifiedOptions.RetryPolicy, operationContext, token); }); }
internal IAsyncAction UploadFromStreamAsyncHelper(IInputStream source, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { CommonUtility.AssertNotNull("source", source); Stream sourceAsStream = source.AsStreamForRead(); if (!sourceAsStream.CanSeek) { throw new InvalidOperationException(); } if (length.HasValue) { CommonUtility.AssertInBounds("length", length.Value, 1, sourceAsStream.Length - sourceAsStream.Position); } else { length = sourceAsStream.Length - sourceAsStream.Position; } this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.PageBlob, this.ServiceClient); operationContext = operationContext ?? new OperationContext(); ExecutionState<NullType> tempExecutionState = CommonUtility.CreateTemporaryExecutionState(modifiedOptions); if ((length % Constants.PageSize) != 0) { throw new ArgumentException(SR.InvalidPageSize, "source"); } return AsyncInfo.Run(async (token) => { using (ICloudBlobStream blobStream = await this.OpenWriteAsync(length, accessCondition, options, operationContext).AsTask(token)) { // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our // stream copier only writes 64K buffers at a time anyway, so no buffering is needed. await sourceAsStream.WriteToAsync(blobStream.AsStreamForWrite(0), length, null /* maxLength */, false, tempExecutionState, null /* streamCopyState */, token); await blobStream.CommitAsync().AsTask(token); } }); }
/// <summary> /// Returns a range of elements from the source, if the elements are not local it will fetch them from the interwebs /// This can take multiple web calls to get the list, so this can be slow. If there aren't enough elements remaining /// we will return as many as we can get. /// THIS IS NOT THREAD SAFE /// </summary> /// <param name="bottom">The bottom range, inclusive</param> /// <param name="top">The top of the range, exclusive</param> /// <returns></returns> public async Task <List <Element <T> > > FetchElements(int bottom, int top) { if (top <= bottom) { throw new Exception("top can't be larger than bottom!"); } int sanityCheckCount = 0; while (true) { // See if we now have what they asked for, OR the list has elements but we don't have an after. // (this is the case when we have hit the end of the list) // #bug!?!? At some point I changed the children count in the after check to sanityCheckCount == 0, but I can't remember why // and it breaks lists that have ends. There is some bug where something doesn't try to refresh or something... if (m_currentElementList.Children.Count >= top || (m_currentElementList.Children.Count != 0 && m_currentElementList.After == null) || (sanityCheckCount > 25)) { // Return what they asked for capped at the list size int length = top - bottom; int listLength = m_currentElementList.Children.Count - bottom; length = Math.Min(length, listLength); // Set what the top was we returned. m_lastTopGet = bottom + length; return(m_currentElementList.Children.GetRange(bottom, length)); } // Figure out how many we need still. int numberNeeded = top - m_currentElementList.Children.Count; // Make the request. IHttpContent webResult = await MakeRequest(numberNeeded, m_currentElementList.After); // This will hold the root RootElement <T> root = null; // Get the input stream and json reader. // NOTE!! We are really careful not to use a string here so we don't have to allocate a huge string. IInputStream inputStream = await webResult.ReadAsInputStreamAsync(); using (StreamReader reader = new StreamReader(inputStream.AsStreamForRead())) using (JsonReader jsonReader = new JsonTextReader(reader)) { // Check if we have an array root or a object root if (m_isArrayRoot) { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); List <RootElement <T> > arrayRoot = await Task.Run(() => serializer.Deserialize <List <RootElement <T> > >(jsonReader)); // Use which ever list element we want. if (m_takeFirstArrayRoot) { root = arrayRoot[0]; } else { root = arrayRoot[1]; } } else { // Parse the Json as an object JsonSerializer serializer = new JsonSerializer(); root = await Task.Run(() => serializer.Deserialize <RootElement <T> >(jsonReader)); } } // Copy the new contents into the current cache m_currentElementList.Children.AddRange(root.Data.Children); // Update the before and after m_currentElementList.After = root.Data.After; m_currentElementList.Before = root.Data.Before; sanityCheckCount++; } }
public static StorageExtendedErrorInformation ReadFromStream(IInputStream inputStream) { return(ReadFromStream(inputStream.AsStreamForRead())); }
/// <summary> /// Stellt den zuvor gespeicherten <see cref="SessionState"/> wieder her. Für alle <see cref="Frame"/>-Instanzen, /// die bei <see cref="RegisterFrame"/> registriert wurden, wird ebenfalls der vorherige /// Navigationszustand wiederhergestellt, wodurch deren aktive <see cref="Page"/> eine Gelegenheit zum Wiederherstellen /// des Zustands erhält. /// </summary> /// <param name="sessionBaseKey">Ein optionaler Schlüssel zum Identifizieren des Typs der Sitzung. /// Damit können verschiedene Szenarien für den Anwendungsstart unterschieden werden.</param> /// <returns>Eine asynchrone Aufgabe, die das Lesen des Sitzungszustands wiedergibt. Auf den /// Inhalt von <see cref="SessionState"/> sollte erst zurückgegriffen werden, wenn diese Aufgabe /// abgeschlossen ist.</returns> public static async Task RestoreAsync(String sessionBaseKey = null) { _sessionState = new Dictionary <String, Object>(); try { // Eingabedatenstrom für die SessionState-Datei abrufen StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // Sitzungszustand deserialisieren DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes); _sessionState = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // Alle registrierten Rahmen auf den gespeicherten Zustand wiederherstellen foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } }
public static MAST CreateFromMast(IInputStream stream) { return CreateFromMast(stream.AsStreamForRead()); }
public static async Task RestoreAsync() { _sessionState = new Dictionary <String, Object>(); try { StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(SessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { var serializer = new DataContractJsonSerializer(typeof(Dictionary <string, object>), _knownTypes); _sessionState = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } } // ReSharper disable EmptyGeneralCatchClause catch // ReSharper restore EmptyGeneralCatchClause { } }
public static Task <StorageExtendedErrorInformation> ReadFromStreamAsync(IInputStream inputStream) { return(ReadFromStreamAsync(inputStream.AsStreamForRead())); }
/// <summary> /// 以前保存された <see cref="SessionState"/> を復元します。 /// <see cref="RegisterFrame"/> で登録された <see cref="Frame"/> インスタンスは、前のナビゲーション状態も復元します。 /// これは、アクティブな <see cref="Page"/> に状態を復元する機会を順番に提供します。 /// ます。 /// </summary> /// <returns>セッション状態が読み取られたときに反映される非同期タスクです。 /// このタスクが完了するまで、<see cref="SessionState"/> のコンテンツには /// 完了します。</returns> public static async Task RestoreAsync() { _sessionState = new Dictionary <String, Object>(); try { // SessionState ファイルの入力ストリームを取得します StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // セッション状態を逆シリアル化します DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes); _sessionState = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // 登録されているフレームを保存された状態に復元します foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } }
public SocketStream(IInputStream inputStream, IOutputStream outputStream) { this.inputStream = inputStream.AsStreamForRead(); this.outputStream = outputStream.AsStreamForWrite(); }
/// <summary> /// Восстанавливает ранее сохраненный объект <see cref="SessionState"/>. Любые экземпляры <see cref="Frame"/>, /// зарегистрированные с помощью <see cref="RegisterFrame"/>, также восстановят свое предыдущее /// состояние навигации, которое, в свою очередь, предоставляет их активной <see cref="Page"/> возможность восстановления /// состояния. /// </summary> /// <returns>Асинхронная задача, отражающая чтение состояния сеанса. Содержимое /// <see cref="SessionState"/> не должно считаться достоверным, пока эта задача не будет /// завершена.</returns> public static async Task RestoreAsync() { _sessionState = new Dictionary <String, Object>(); try { // Получение входного потока для файла SessionState StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // Десериализация состояния сеанса DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes); _sessionState = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // Восстановление всех зарегистрированных фреймов к сохраненному состоянию foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } }
internal IAsyncAction UploadFromStreamAsyncHelper(IInputStream source, long? length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext) { CommonUtility.AssertNotNull("source", source); Stream sourceAsStream = source.AsStreamForRead(); if (length.HasValue) { CommonUtility.AssertInBounds("length", length.Value, 1); if (sourceAsStream.CanSeek && length > sourceAsStream.Length - sourceAsStream.Position) { throw new ArgumentOutOfRangeException("length", SR.StreamLengthShortError); } } this.attributes.AssertNoSnapshot(); BlobRequestOptions modifiedOptions = BlobRequestOptions.ApplyDefaults(options, BlobType.BlockBlob, this.ServiceClient); operationContext = operationContext ?? new OperationContext(); ExecutionState<NullType> tempExecutionState = CommonUtility.CreateTemporaryExecutionState(modifiedOptions); return AsyncInfo.Run(async (token) => { bool lessThanSingleBlobThreshold = sourceAsStream.CanSeek && (length ?? sourceAsStream.Length - sourceAsStream.Position) <= this.ServiceClient.SingleBlobUploadThresholdInBytes; if (this.ServiceClient.ParallelOperationThreadCount == 1 && lessThanSingleBlobThreshold) { string contentMD5 = null; if (modifiedOptions.StoreBlobContentMD5.Value) { StreamDescriptor streamCopyState = new StreamDescriptor(); long startPosition = sourceAsStream.Position; await sourceAsStream.WriteToAsync(Stream.Null, length, null /* maxLength */, true, tempExecutionState, streamCopyState, token); sourceAsStream.Position = startPosition; contentMD5 = streamCopyState.Md5; } else { if (modifiedOptions.UseTransactionalMD5.Value) { throw new ArgumentException(SR.PutBlobNeedsStoreBlobContentMD5, "options"); } } await Executor.ExecuteAsyncNullReturn( this.PutBlobImpl(sourceAsStream, length, contentMD5, accessCondition, modifiedOptions), modifiedOptions.RetryPolicy, operationContext, token); } else { using (ICloudBlobStream blobStream = await this.OpenWriteAsync(accessCondition, options, operationContext).AsTask(token)) { // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our // stream copier only writes 64K buffers at a time anyway, so no buffering is needed. await sourceAsStream.WriteToAsync(blobStream.AsStreamForWrite(0), length, null /* maxLength */, false, tempExecutionState, null /* streamCopyState */, token); await blobStream.CommitAsync().AsTask(token); } } }); }
/// <summary> /// 이전에 저장된 <see cref="SessionState"/>를 복원합니다. <see cref="RegisterFrame"/>으로 등록된 모든 /// <see cref="Frame"/> 인스턴스도 이전의 탐색 상태를 복원합니다. /// 따라서 활성 <see cref="Page"/>에 해당 상태를 복원할 수 있는 기회를 /// 제공합니다. /// </summary> /// <returns>세션 상태를 읽은 시기를 반영하는 비동기 작업입니다. /// <see cref="SessionState"/>의 내용은 이 작업이 완료될 때까지 신뢰해서는 /// 안 됩니다.</returns> public static async Task RestoreAsync() { _sessionState = new Dictionary <String, Object> (); try { // SessionState 파일에 대한 입력 스트림을 가져옵니다. StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // 세션 상태를 deserialize합니다. DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes); _sessionState = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // 등록된 모든 프레임을 저장된 상태로 복원합니다. foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame)) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } }
public IAsyncOperation<Blob> UploadBlob(BlobInfo blobInfo, IInputStream source) { if (source == null) { throw new ArgumentNullException("source"); } blobInfo.ValidateRequired("blobInfo"); return AsyncInfo.Run( async cancelToken => { Stream stream = source.AsStreamForRead(); Uri blobUri = await Client.RecordMethods.UploadBlobStreamAsync( m_recordRef, stream, blobInfo.ContentType, cancelToken); return new Blob(blobInfo, (int) stream.Length, blobUri.AbsoluteUri); } ); }
/// <summary> /// Restores previously saved <see cref="SessionState"/>. Any <see cref="Frame"/> instances /// registered with <see cref="RegisterFrame"/> will also restore their prior navigation /// state, which in turn gives their active <see cref="Page"/> an opportunity restore its /// state. /// </summary> /// <param name="sessionBaseKey">An optional key that identifies the type of session. /// This can be used to distinguish between multiple application launch scenarios.</param> /// <returns>An asynchronous task that reflects when session state has been read. The /// content of <see cref="SessionState"/> should not be relied upon until this task /// completes.</returns> public static async Task RestoreAsync(String sessionBaseKey = null) { _sessionState = new Dictionary <String, Object>(); try { // Get the input stream for the SessionState file StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); using (IInputStream inStream = await file.OpenSequentialReadAsync()) { // Deserialize the Session State DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary <string, object>), _knownTypes); _sessionState = (Dictionary <string, object>)serializer.ReadObject(inStream.AsStreamForRead()); } // Restore any registered frames to their saved state foreach (var weakFrameReference in _registeredFrames) { Frame frame; if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey) { frame.ClearValue(FrameSessionStateProperty); RestoreFrameNavigationState(frame); } } } catch (Exception e) { throw new SuspensionManagerException(e); } }
internal IAsyncAction UploadFromStreamAsyncHelper(IInputStream source, long? length, AccessCondition accessCondition, FileRequestOptions options, OperationContext operationContext) #endif { CommonUtility.AssertNotNull("source", source); Stream sourceAsStream = source.AsStreamForRead(); if (!sourceAsStream.CanSeek) { throw new InvalidOperationException(); } if (length.HasValue) { CommonUtility.AssertInBounds("length", length.Value, 1, sourceAsStream.Length - sourceAsStream.Position); } else { length = sourceAsStream.Length - sourceAsStream.Position; } FileRequestOptions modifiedOptions = FileRequestOptions.ApplyDefaults(options, this.ServiceClient); operationContext = operationContext ?? new OperationContext(); ExecutionState<NullType> tempExecutionState = CommonUtility.CreateTemporaryExecutionState(modifiedOptions); #if ASPNET_K return Task.Run(async () => { using (CloudFileStream fileStream = await this.OpenWriteAsync(length, accessCondition, options, operationContext, cancellationToken)) { // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our // stream copier only writes 64K buffers at a time anyway, so no buffering is needed. await sourceAsStream.WriteToAsync(fileStream, length, null /* maxLength */, false, tempExecutionState, null /* streamCopyState */, cancellationToken); await fileStream.CommitAsync(); } }, cancellationToken); #else return AsyncInfo.Run(async (token) => { using (ICloudFileStream fileStream = await this.OpenWriteAsync(length, accessCondition, options, operationContext).AsTask(token)) { // We should always call AsStreamForWrite with bufferSize=0 to prevent buffering. Our // stream copier only writes 64K buffers at a time anyway, so no buffering is needed. await sourceAsStream.WriteToAsync(fileStream.AsStreamForWrite(0), length, null /* maxLength */, false, tempExecutionState, null /* streamCopyState */, token); await fileStream.CommitAsync().AsTask(token); } }); #endif }
/// <summary> /// Loads the specified XML key file. /// </summary> /// <param name="input">The keyfile stream.</param> /// <returns>The binary data buffer, or <c>null</c> if not a valid XML keyfile.</returns> private static IBuffer LoadXmlKeyFile(IInputStream input) { try { var doc = XDocument.Load(input.AsStreamForRead()); // Root var root = doc.Root; if (root == null || root.Name != "KeyFile") return null; // Key var key = root.Element("Key"); if (key == null) return null; // Data var data = key.Element("Data"); if (data == null) return null; try { return CryptographicBuffer .DecodeFromBase64String(data.Value); } catch (Exception) { return null; } } catch (XmlException) { return null; } }
public static IAsyncOperation<AdDocumentPayload> CreateFromVast(IInputStream stream, int? maxRedirectDepth, bool allowMultipleAds) { return AsyncInfo.Run(c => CreateFromVast(stream.AsStreamForRead(), maxRedirectDepth, allowMultipleAds)); }
private async Task ParseFileContent(IInputStream inputStream) { using (var reader = new StreamReader(inputStream.AsStreamForRead())) { var encodedBytes = Convert.FromBase64String(reader.ReadToEnd()); var cardString = Encoding.UTF8.GetString(encodedBytes, 0, encodedBytes.Length); var cards = JsonConvert.DeserializeObject<ObservableCollection<Card>>(cardString); Messenger.Default.Send(new NotificationMessage(cards, "RestoreCards")); ProgressText = string.Empty; ProgressVisibility = Visibility.Collapsed; } }
public static Vmap CreateFromMVmap(IInputStream stream) { return CreateFromVmap(stream.AsStreamForRead()); }
public static FWAdResponse CreateFromSmartXml(IInputStream stream) { return CreateFromSmartXml(stream.AsStreamForRead()); }
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 static Vmap CreateFromMVmap(IInputStream stream) { return(CreateFromVmap(stream.AsStreamForRead())); }