private static ResourceContext CreateContext(CoreDispatcher dispatcher) { if ((dispatcher != null)) { if (dispatcher.HasThreadAccess) { return(ResourceContext.GetForCurrentView()); } var cancellationTokenSource = new CancellationTokenSource(); try { var context = default(ResourceContext); var action = dispatcher.RunAsync(CoreDispatcherPriority.High, () => context = ResourceContext.GetForCurrentView()); var task = WindowsRuntimeSystemExtensions.AsTask(action, cancellationTokenSource.Token); // Runs into a 'timeout', when the 'main-thread' is blocked recently. // Don't wait too long as there is an alternative way to retrieve an context (for independent use). task.Wait(TimeSpan.FromSeconds(1)); cancellationTokenSource.Cancel(); if ((context != null)) { return(context); } } finally { cancellationTokenSource.Dispose(); } } return(ResourceContext.GetForViewIndependentUse()); }
internal static StorageFile GetFileForPathOrURI(string path) { IAsyncOperation <StorageFile> source = !System.Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute) ? StorageFile.GetFileFromPathAsync(path) : StorageFile.GetFileFromApplicationUriAsync(new System.Uri(path)); WindowsRuntimeSystemExtensions.AsTask <StorageFile>(source).Wait(); return(source.GetResults()); }
private static StorageFolder GetDirectoryForPath(string path) { IAsyncOperation <StorageFolder> folderFromPathAsync = StorageFolder.GetFolderFromPathAsync(path); WindowsRuntimeSystemExtensions.AsTask <StorageFolder>(folderFromPathAsync).Wait(); return(folderFromPathAsync.GetResults()); }
public static void Copy(string sourceFileName, string destFileName, bool overwrite) { try { StorageFile fileForPathOrUri = FileHelper.GetFileForPathOrURI(sourceFileName); if (overwrite) { StorageFile storageFile = (StorageFile)null; try { storageFile = FileHelper.GetFileForPathOrURI(destFileName); } catch { } if (storageFile != null) { WindowsRuntimeSystemExtensions.AsTask(fileForPathOrUri.CopyAndReplaceAsync((IStorageFile)storageFile)).Wait(); return; } } WindowsRuntimeSystemExtensions.AsTask <StorageFile>(fileForPathOrUri.CopyAsync((IStorageFolder)FileHelper.GetFolderForPathOrURI(destFileName), Path.GetFileName(destFileName))).Wait(); } catch (Exception ex) { throw File.GetRethrowException(ex); } }
public static IEnumerable <string> EnumerateFiles(string path) { if (path == null) { throw new ArgumentNullException(); } if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Path is empty"); } try { IAsyncOperation <IReadOnlyList <StorageFile> > filesAsync = Directory.GetDirectoryForPath(path).GetFilesAsync(); WindowsRuntimeSystemExtensions.AsTask <IReadOnlyList <StorageFile> >(filesAsync).Wait(); IReadOnlyList <StorageFile> results = filesAsync.GetResults(); List <string> list = new List <string>(Enumerable.Count <StorageFile>((IEnumerable <StorageFile>)results)); foreach (StorageFile storageFile in (IEnumerable <StorageFile>)results) { list.Add(storageFile.Path); } return((IEnumerable <string>)list); } catch (IOException ex) { System.Diagnostics.Debug.WriteLine("Directory.EnumerateFiles: " + ex.Message + "\n" + ex.StackTrace); throw; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Directory.EnumerateFiles: " + ex.Message + "\n" + ex.StackTrace); throw new IOException(ex.Message, ex); } }
private static StorageFile CreateOrReplaceFile(string path) { IAsyncOperation <StorageFile> fileAsync = FileHelper.GetFolderForPathOrURI(path).CreateFileAsync(Path.GetFileName(path), CreationCollisionOption.ReplaceExisting); WindowsRuntimeSystemExtensions.AsTask <StorageFile>(fileAsync).Wait(); return(fileAsync.GetResults()); }
public static IEnumerable <string> ReadLines(string path) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException(); } try { IAsyncOperation <IRandomAccessStream> source = FileHelper.GetFileForPathOrURI(path).OpenAsync(FileAccessMode.Read); WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(source).Wait(); using (FileRandomAccessStream randomAccessStream = (FileRandomAccessStream)source.GetResults()) { StreamReader streamReader = new StreamReader(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)randomAccessStream)); List <string> list = new List <string>(); while (true) { string str = streamReader.ReadLine(); if (str != null) { list.Add(str); } else { break; } } return((IEnumerable <string>)list); } } catch (Exception ex) { throw File.GetRethrowException(ex); } }
internal static string LoadString(string path) { string dataString = null; try { #if NETFX_CORE { StorageFile file = WindowsRuntimeSystemExtensions.AsTask <StorageFile>( GetStore().GetFileAsync(path), CancellationToken.None ).Result; dataString = (string)WindowsRuntimeSystemExtensions.AsTask( FileIO.ReadTextAsync(file) ).Result; Debug.WriteLine("LoadString: " + dataString); } #else { IsolatedStorageFile storage = StorageHelper.GetStore(); using (IsolatedStorageFileStream stream = storage.OpenFile(path, FileMode.Open, FileAccess.Read, FileShare.None)) { StreamReader reader = new StreamReader(stream); dataString = reader.ReadToEnd(); } } #endif } catch (Exception) { // There is a small chance the file is still being // written to by another thread. Return null in // this case. Reader will try again later. } return(dataString); }
public async Task <int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { StreamSocket socket = this._socket; if (null == socket) { throw new InvalidOperationException("The socket is not open"); } IBuffer iBuffer = WindowsRuntimeBufferExtensions.AsBuffer(buffer, offset, 0, length); IBuffer iBuffer2 = await WindowsRuntimeSystemExtensions.AsTask <IBuffer, uint>(socket.InputStream.ReadAsync(iBuffer, (uint)length, InputStreamOptions.Partial), cancellationToken).ConfigureAwait(false); int bytesRead = (int)iBuffer2.Length; int num; if (bytesRead <= 0) { num = 0; } else if (object.ReferenceEquals((object)iBuffer, (object)iBuffer2)) { num = bytesRead; } else { Debug.Assert(bytesRead <= length, "Length out-of-range"); WindowsRuntimeBufferExtensions.CopyTo(iBuffer2, 0U, buffer, offset, bytesRead); num = bytesRead; } return(num); }
public async Task <Stream> Encode() { try { Stopwatch stopwatchEncode = new Stopwatch(); stopwatchEncode.Start(); IRandomAccessStream imageStream = (IRandomAccessStream) new InMemoryRandomAccessStream(); BitmapEncoder bitmapEncoder = await GraffitiEncoder.BuildEncoder(imageStream); BitmapPixelFormat pixelFormat; byte[] imageBinaryData1 = GraffitiEncoder.GetImageBinaryData1(this._bitmap, out pixelFormat); int num1 = (int)pixelFormat; int num2 = 0; int pixelWidth = ((BitmapSource)this._bitmap).PixelWidth; int pixelHeight = ((BitmapSource)this._bitmap).PixelHeight; double dpiX = 72.0; double dpiY = 72.0; byte[] pixels = imageBinaryData1; bitmapEncoder.SetPixelData((BitmapPixelFormat)num1, (BitmapAlphaMode)num2, (uint)pixelWidth, (uint)pixelHeight, dpiX, dpiY, pixels); await WindowsRuntimeSystemExtensions.AsTask(bitmapEncoder.FlushAsync()).ConfigureAwait(false); long size = (long)imageStream.Size; stopwatchEncode.Stop(); Execute.ExecuteOnUIThread((Action)(() => {})); return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)imageStream)); } catch { return(null); } }
internal ImageSource GetActualImageSource() { if (_imageSource != null) { return(_imageSource); } if (_uriSource != null) { // hdt BitmapImage imageSource = new BitmapImage(); StorageFile.GetFileFromApplicationUriAsync(_uriSource).AsTask().ContinueWith((fr) => { if ((fr.Result != null) && !fr.IsFaulted) { Action <Task <IRandomAccessStreamWithContentType> > func = delegate(Task <IRandomAccessStreamWithContentType> r) { using (Stream stream = WindowsRuntimeStreamExtensions.AsStreamForRead(r.Result)) { // Utility.InitImageSource(imageSource, stream); //导出RptText ImageUri时图片不出问题 李雪修改 InitImageSource(stream); } }; WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStreamWithContentType>(fr.Result.OpenReadAsync()).ContinueWith(func); } }); return(imageSource); } return(null); }
public async Task ConnectAsync(Uri url, CancellationToken cancellationToken) { string host = url.Host; string serviceName = url.Port.ToString((IFormatProvider)CultureInfo.InvariantCulture); HostName hostName = new HostName(host); bool useTls = string.Equals("HTTPS", url.Scheme, StringComparison.OrdinalIgnoreCase); if (!useTls && !string.Equals("HTTP", url.Scheme, StringComparison.OrdinalIgnoreCase)) { throw new NotSupportedException("Scheme not supported: " + url.Scheme); } StreamSocket socket = new StreamSocket(); if (null != Interlocked.CompareExchange <StreamSocket>(ref this._socket, socket, (StreamSocket)null)) { socket.Dispose(); throw new InvalidOperationException("The socket is in use"); } try { socket.Control.NoDelay = true; SocketProtectionLevel protectionLevel = useTls ? SocketProtectionLevel.Ssl : SocketProtectionLevel.PlainSocket; await WindowsRuntimeSystemExtensions.AsTask(socket.ConnectAsync(hostName, serviceName, protectionLevel), cancellationToken).ConfigureAwait(false); } catch (Exception ex) { this.Close(); throw; } }
// Init the AudioGraph // despite the Aync methods - this will exec synchronously to get the InitPhase only get done when all is available private void InitAudioGraph( ) { LOG.Log("InitAudioGraph: Begin"); if (!_canPlay) { LOG.Log("InitAudioGraph: Canceled with _canPlay = false"); return; // cannot even try.. } // MUST WAIT UNTIL all items are created, else one may call Play too early... // cleanup existing items if (_deviceOutputNode != null) { _deviceOutputNode.Dispose( ); _deviceOutputNode = null; } if (_audioGraph != null) { _audioGraph.Dispose( ); _audioGraph = null; } // Create an AudioGraph AudioGraphSettings settings = new AudioGraphSettings(_renderCat) { PrimaryRenderDevice = null, // If PrimaryRenderDevice is null, the default playback device will be used. MaxPlaybackSpeedFactor = 2, // should preserve some memory }; // We await here the execution without providing an async method ... var resultAG = WindowsRuntimeSystemExtensions.AsTask(AudioGraph.CreateAsync(settings)); resultAG.Wait( ); if (resultAG.Result.Status != AudioGraphCreationStatus.Success) { LOG.LogError($"InitAudioGraph: Failed to create AudioGraph with RenderCategory: {_renderCat}"); LOG.LogError($"InitAudioGraph: AudioGraph creation: {resultAG.Result.Status}, TaskStatus: {resultAG.Status}" + $"\nExtError: {resultAG.Result.ExtendedError}"); _canPlay = false; return; } _audioGraph = resultAG.Result.Graph; LOG.Log($"InitAudioGraph: AudioGraph: [{_audioGraph.EncodingProperties}]"); // Create a device output node // The output node uses the PrimaryRenderDevice of the audio graph. // We await here the execution without providing an async method ... var resultDO = WindowsRuntimeSystemExtensions.AsTask(_audioGraph.CreateDeviceOutputNodeAsync()); resultDO.Wait( ); if (resultDO.Result.Status != AudioDeviceNodeCreationStatus.Success) { // Cannot create device output node LOG.LogError($"InitAudioGraph: DeviceOutputNode creation: {resultDO.Result.Status}, TaskStatus: {resultDO.Status}" + $"\nExtError: {resultDO.Result.ExtendedError}"); _canPlay = false; return; } _deviceOutputNode = resultDO.Result.DeviceOutputNode; LOG.Log($"InitAudioGraph: DeviceOutputNode: [{_deviceOutputNode.Device}]"); LOG.Log($"InitAudioGraph: InitAudioGraph-END"); }
// Find a valid AudioGraph RenderCategory // this should leave _renderCat with a valid one or _renderNone private void FindRenderCategory( ) { // A list of tryouts for the output rendering Queue <AudioRenderCategory> renderSequence = new Queue <AudioRenderCategory>(new [] { AudioRenderCategory.Speech, AudioRenderCategory.GameChat, AudioRenderCategory.GameEffects, AudioRenderCategory.SoundEffects, AudioRenderCategory.Media, AudioRenderCategory.Other, // Finally the Not Available Cat _renderNone, }); _renderCat = renderSequence.Dequeue( ); // Try a cat that works do { // Create an AudioGraph AudioGraphSettings settings = new AudioGraphSettings(_renderCat) { PrimaryRenderDevice = null, // If PrimaryRenderDevice is null, the default playback device will be used. }; LOG.Log($"FindRenderCategory: About to test AudioGraph with RenderCategory: {_renderCat}"); // We await here the execution without providing an async method ... var resultAG = WindowsRuntimeSystemExtensions.AsTask(AudioGraph.CreateAsync(settings)); resultAG.Wait( ); if (resultAG.Result.Status != AudioGraphCreationStatus.Success) { LOG.LogError($"FindRenderCategory: AudioGraph test error: {resultAG.Result.Status}, TaskStatus: {resultAG.Status}" + $"\nExtError: {resultAG.Result.ExtendedError}"); // try next category if there is one left if (renderSequence.Count > 0) { _renderCat = renderSequence.Dequeue( ); } else { // sanity - should never happen LOG.LogError($"FindRenderCategory: Program error - Queue overrun"); _renderCat = _renderNone; return; } } else { resultAG.Result.Graph?.Dispose( ); // not used after tryout LOG.Log($"FindRenderCategory: Success with RenderCategory: {_renderCat}"); return; // _renderCat contains a successful one } } while (_renderCat != _renderNone); LOG.LogError($"FindRenderCategory: Failed to find a working RenderCategory - cannot speak"); _canSpeak = false; return; // could not resolve - left with _renderNone }
protected override async Task DoExecuteAsync() { var result = await WindowsRuntimeSystemExtensions.AsTask(Characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(Descriptor)).ConfigureAwait(false); if (result == GattCommunicationStatus.Unreachable) { throw new DeviceUnreachableException(); } }
protected override async Task DoExecuteAsync() { var result = await WindowsRuntimeSystemExtensions.AsTask(Characteristic.WriteValueAsync(Bytes.AsBuffer(), WithoutResponse ? GattWriteOption.WriteWithoutResponse : GattWriteOption.WriteWithResponse)).ConfigureAwait(false); if (result == GattCommunicationStatus.Unreachable) { throw new DeviceUnreachableException(); } }
/// <summary> /// hdt /// </summary> /// <param name="propertyKey"></param> /// <returns></returns> static Task <string> GetRootDeviceInfoAsync(string propertyKey) { TaskAwaiter <PnpObject> awaiter; awaiter = WindowsRuntimeSystemExtensions.GetAwaiter <PnpObject>(PnpObject.CreateFromIdAsync(PnpObjectType.DeviceContainer, "{00000000-0000-0000-FFFF-FFFFFFFFFFFF}", new string[] { propertyKey })); PnpObject pnp = awaiter.GetResult(); string str = pnp.Properties[propertyKey].ToString(); return(Task.FromResult <string>(str)); }
internal static StorageFolder GetFolderForPathOrURI(string path) { if (System.Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute)) { return(FileHelper.GetFolderForURI(path)); } IAsyncOperation <StorageFolder> folderFromPathAsync = StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(path)); WindowsRuntimeSystemExtensions.AsTask <StorageFolder>(folderFromPathAsync).Wait(); return(folderFromPathAsync.GetResults()); }
internal static void CreateFolder(string path) { #if NETFX_CORE WindowsRuntimeSystemExtensions.AsTask <StorageFolder>( GetStore().CreateFolderAsync(path), CancellationToken.None ).Wait(); #else GetStore().CreateDirectory(path); #endif }
public static string GetClipboardData() { try { return(WindowsRuntimeSystemExtensions.AsTask <string>(Clipboard.GetContent().GetTextAsync()).Result); } catch { return(null); } }
protected override async Task DoExecuteAsync() { var result = await WindowsRuntimeSystemExtensions.AsTask(Characteristic.ReadValueAsync(CacheMode)).ConfigureAwait(false); if (result.Status == GattCommunicationStatus.Unreachable) { throw new DeviceUnreachableException(); } Bytes = ToArraySafe(result.Value); }
public override void Flush() { try { WindowsRuntimeSystemExtensions.AsTask <bool>(this.backend.FlushAsync()).Wait(); } catch (Exception ex) { throw FileStream.RethrowException(ex); } }
/// <summary> /// 确保在UI线程同步调用给定方法 /// </summary> /// <param name="p_action"></param> public static void RunSync(Action p_action) { if (SysVisual.Dispatcher.HasThreadAccess) { p_action(); } else { WindowsRuntimeSystemExtensions.AsTask(SysVisual.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(p_action))).Wait(); } }
public static void Move(string sourceFileName, string destFileName) { try { WindowsRuntimeSystemExtensions.AsTask(FileHelper.GetFileForPathOrURI(sourceFileName).MoveAsync((IStorageFolder)FileHelper.GetFolderForPathOrURI(destFileName), Path.GetFileName(destFileName))).Wait(); } catch (Exception ex) { throw File.GetRethrowException(ex); } }
internal static StorageFolder GetFolderForURI(string uri) { uri = uri.ToLower(); StorageFolder storageFolder1; if (uri.StartsWith("ms-appdata:///local/")) { storageFolder1 = ApplicationData.Current.LocalFolder; uri = uri.Replace("ms-appdata:///local/", ""); } else if (uri.StartsWith("ms-appdata:///roaming/")) { storageFolder1 = ApplicationData.Current.RoamingFolder; uri = uri.Replace("ms-appdata:///roaming/", ""); } else { if (!uri.StartsWith("ms-appdata:///temp/")) { throw new Exception("Unsupported URI: " + uri); } storageFolder1 = ApplicationData.Current.TemporaryFolder; uri = uri.Replace("ms-appdata:///temp/", ""); } string[] strArray = uri.Split(new char[1] { '/' }); for (int index = 0; index < strArray.Length - 1; ++index) { Task <IReadOnlyList <StorageFolder> > task = WindowsRuntimeSystemExtensions.AsTask <IReadOnlyList <StorageFolder> >(storageFolder1.CreateFolderQuery().GetFoldersAsync()); task.Wait(); if (task.Status != TaskStatus.RanToCompletion) { throw new Exception("Failed to find folder: " + strArray[index]); } IReadOnlyList <StorageFolder> result = task.Result; bool flag = false; foreach (StorageFolder storageFolder2 in (IEnumerable <StorageFolder>)result) { if (storageFolder2.Name == strArray[index]) { storageFolder1 = storageFolder2; flag = true; break; } } if (!flag) { throw new Exception("Folder not found: " + strArray[index]); } } return(storageFolder1); }
public async Task <int> WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { StreamSocket socket = this._socket; if (null == socket) { throw new InvalidOperationException("The socket is not open"); } IBuffer iBuffer = WindowsRuntimeBufferExtensions.AsBuffer(buffer, offset, length); return((int)await WindowsRuntimeSystemExtensions.AsTask <uint, uint>(socket.OutputStream.WriteAsync(iBuffer), cancellationToken).ConfigureAwait(false)); }
private static StorageFile TryGetFile(string path) { //Debug.WriteLine("TryGetFile: "+path); StorageFile answer = null; #if WINDOWS_APP { IStorageItem item = WindowsRuntimeSystemExtensions.AsTask <IStorageItem>( GetStore().TryGetItemAsync(path), CancellationToken.None ).Result; if ((item != null) && (item.IsOfType(StorageItemTypes.File))) { answer = (StorageFile)item; } } #elif true //WINDOWS_PHONE_APP { // WindowsPhoneApp StorageFolder doesn't have TryGetItemAsync, // so the code gets a little messier on this platform. Researched // various online advice, such as: // http://suchan.cz/2014/07/file-io-best-practices-in-windows-and-phone-apps-part-1-available-apis-and-file-exists-checking/ // http://blogs.msdn.com/b/shashankyerramilli/archive/2014/02/17/check-if-a-file-exists-in-windows-phone-8-and-winrt-without-exception.aspx // Decided we do not want Crittercism SDK to be seen throwing // 'System.AggregateException' wrapping 'System.IO.FileNotFoundException' // visible in Crittercism user's VS2013 "Output" console. Iteration // avoids this, is good enough for MSDN blogger to consider it, and // we like to think the Crittercism SDK actually will not be calling // this method very much. String directoryName = Path.GetDirectoryName(path); StorageFolder store = TryGetFolder(directoryName); if (store != null) { String fileName = Path.GetFileName(path); IReadOnlyList <StorageFile> files = WindowsRuntimeSystemExtensions.AsTask <IReadOnlyList <StorageFile> >( store.GetFilesAsync(), CancellationToken.None ).Result; foreach (StorageFile file in files) { if (file.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase)) { answer = file; break; } } } } #endif //Debug.WriteLine("TryGetFile: ---> "+answer); return(answer); }
internal static DateTimeOffset GetCreationTime(string path) { #if NETFX_CORE { StorageFile file = WindowsRuntimeSystemExtensions.AsTask <StorageFile>( GetStore().GetFileAsync(path), CancellationToken.None ).Result; return(file.DateCreated); } #else return(GetStore().GetCreationTime(path)); #endif }
internal static Stream OpenFileForReading(StorageFile file) { Task <IRandomAccessStream> task = WindowsRuntimeSystemExtensions.AsTask <IRandomAccessStream>(file.OpenAsync(FileAccessMode.Read)); task.Wait(); if (task.Status != TaskStatus.RanToCompletion) { throw new Exception("Failed to open file!"); } else { return(WindowsRuntimeStreamExtensions.AsStreamForRead((IInputStream)task.Result)); } }
public static Stream OpenFileForReading(System.Uri uri) { Task <StorageFile> task = WindowsRuntimeSystemExtensions.AsTask <StorageFile>(StorageFile.GetFileFromApplicationUriAsync(uri)); task.Wait(); if (task.Status != TaskStatus.RanToCompletion) { throw new Exception("Filed to open file " + uri.ToString()); } else { return(FileHelper.OpenFileForReading(task.Result)); } }