public void Dispose() { if (_stream != null) { _stream.Dispose(); } }
public void Seek(ulong position) { if (requestedPosition != position) { if (inputStream != null) { inputStream.Dispose(); inputStream = null; } Debug.WriteLine("Seek: {0:N0} -> {1:N0}", requestedPosition, position); requestedPosition = position; } }
public void Seek(ulong position) { if (Position != position) { if (_inputStream != null) { _inputStream.Dispose(); _inputStream = null; } Debug.WriteLine("Seek: {0:N0} -> {1:N0}", Position, position); Position = position; } }
private async Task RetreivePlaylist(IStorageItem item) { if (item is StorageFile) { Char chr = '.'; String path = (item as StorageFile).Path; Char[] chrArray = new Char[] { chr }; if (path.Split(chrArray).Count <String>() != 1) { return; } else { IInputStream inputStream = await(item as StorageFile).OpenSequentialReadAsync(); try { Stream stream = inputStream.AsStreamForRead(); (new StreamReader(stream)).ReadToEnd(); } finally { if (inputStream != null) { inputStream.Dispose(); } } } } }
public void CheckShutdown() { // cryptor?.Dispose(); // cryptor = null; // outboundChan = null; if (recvData != null) { ZeroMemory(recvData); } if (udpClient != null) { udpClient.MessageReceived -= UdpClient_MessageReceived; } try { tcpInputStream?.Dispose(); udpOutputStream?.Dispose(); } catch (ObjectDisposedException) { } // networkStream = null; try { client?.Dispose(); udpClient?.Dispose(); } catch (ObjectDisposedException) { } try { udpSendLock.Dispose(); } catch (ObjectDisposedException) { } // client = null; // udpClient = null; }
async public static void Log(string s) { using (var releaser = await myLock.LockAsync()) { StorageFile sfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("errorlog.txt", CreationCollisionOption.OpenIfExists); using (IRandomAccessStream rasw = await sfile.OpenAsync(FileAccessMode.ReadWrite)) { IBuffer ibuf = null; using (IInputStream inputStream = rasw.GetInputStreamAt(0)) { ulong size = rasw.Size; DataReader dataReader = new DataReader(inputStream); await dataReader.LoadAsync((uint)size); ibuf = dataReader.ReadBuffer((uint)size); inputStream.Dispose(); } if (ibuf.Length < 64000) { await rasw.WriteAsync(ibuf); } await rasw.WriteAsync(CryptographicBuffer.ConvertStringToBinary("\r\n" + DateTime.Now.ToUniversalTime().ToString() + " : " + s, BinaryStringEncoding.Utf8)); rasw.Seek(0); await rasw.FlushAsync(); rasw.Dispose(); } } }
/// <summary> /// Load the settings from a file /// </summary> /// <param name="filename">Name of settings file</param> /// <returns></returns> public static async Task <AppSettings> RestoreAsync(string filename) { try { StorageFile sessionFile = await SettingsFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); if (sessionFile == null) { return(new AppSettings()); } IInputStream sessionInputStream = await sessionFile.OpenReadAsync(); var serializer = new XmlSerializer(typeof(AppSettings)); AppSettings temp = (AppSettings)serializer.Deserialize(sessionInputStream.AsStreamForRead()); sessionInputStream.Dispose(); return(temp); } catch (Exception ex) { Debug.WriteLine("AppSettings.RestoreAsync(): " + ex.Message); // Log telemetry event about this exception var events = new Dictionary <string, string> { { "AppSettings", ex.Message } }; App.Controller.TelemetryClient.TrackEvent("FailedToRestoreSettings", events); // If settings.xml file is corrupted and cannot be read - behave as if it does not exist. return(new AppSettings()); } }
private void ResetRequest() { if (sendRequestOperation != null) { sendRequestOperation.Cancel(); sendRequestOperation = null; } if (readAsInputStreamOperation != null) { readAsInputStreamOperation.Cancel(); readAsInputStreamOperation = null; } if (readOperation != null) { readOperation.Cancel(); readOperation = null; } if (inputStream != null) { inputStream.Dispose(); inputStream = null; } if (httpRequest != null) { httpRequest.Dispose(); httpRequest = null; } }
public void Dispose() { _cts.Cancel(); _input.Dispose(); _output.Dispose(); _serialDevice.Dispose(); }
static async private Task RestoreAsync <T>() { StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); if (sessionFile == null) { return; } IInputStream sessionInputStream = await sessionFile.OpenReadAsync(); //Using DataContractSerializer , look at the cat-class // var sessionSerializer = new DataContractSerializer(typeof(List<object>), new Type[] { typeof(T) }); //_data = (List<object>)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead()); //Using XmlSerializer , look at the Dog-class try { var serializer = new XmlSerializer(typeof(List <object>), new Type[] { typeof(T) }); _data = (List <object>)serializer.Deserialize(sessionInputStream.AsStreamForRead()); } catch (System.InvalidOperationException) { throw new Exception("Restore Error"); } finally { sessionInputStream.Dispose(); } }
public void Dispose() { _isOpen = false; _cts.Cancel(); _input.Dispose(); _output.Dispose(); _serialDevice.Dispose(); }
protected virtual void Dispose(bool disposing) { if (disposing) { if (stream != null) { stream.Dispose(); } } }
public static async Task OnReceived(IInputStream dataStream, HostName remoteAddress) { IBuffer buffer = new Windows.Storage.Streams.Buffer(ReadBufferSize); await dataStream.ReadAsync(buffer, ReadBufferSize, InputStreamOptions.None); dataStream.Dispose(); var info = Encoding.UTF8.GetString(buffer.ToArray()); // TODO process unicast }
public void Dispose( ) { if (stream != null) { stream.Dispose(); stream = null; } GC.SuppressFinalize(this); }
public void Seek(ulong position) { if (Position != position) { if (inputStream != null) { inputStream.Dispose(); inputStream = null; } Position = position; } }
/// <summary> /// Load the settings from a file /// </summary> /// <param name="filename">Name of settings file</param> /// <returns></returns> public static async Task <AppSettings> RestoreAsync(string filename) { try { await SettingsFolder.GetFileAsync(filename); } catch (FileNotFoundException) { StorageFile securityLogFile = await SettingsFolder.CreateFileAsync(@"settings.xml", CreationCollisionOption.FailIfExists); await FileIO.AppendTextAsync(securityLogFile, "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine); await FileIO.AppendTextAsync(securityLogFile, "<AppSettings xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine); await FileIO.AppendTextAsync(securityLogFile, "</AppSettings>" + Environment.NewLine); } try { StorageFile sessionFile = await SettingsFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); if (sessionFile == null) { return(new AppSettings()); } IInputStream sessionInputStream = await sessionFile.OpenReadAsync(); var serializer = new XmlSerializer(typeof(AppSettings)); AppSettings temp = (AppSettings)serializer.Deserialize(sessionInputStream.AsStreamForRead()); sessionInputStream.Dispose(); return(temp); } catch (Exception ex) { Debug.WriteLine("AppSettings.RestoreAsync(): " + ex.Message); // Log telemetry event about this exception var events = new Dictionary <string, string> { { "AppSettings", ex.Message } }; TelemetryHelper.TrackEvent("FailedToRestoreSettings", events); // If settings.xml file is corrupted and cannot be read - behave as if it does not exist. return(new AppSettings()); } }
static async private Task RestoreAsync <T>(string filename) { StorageFile sessionFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists); if (sessionFile == null) { return; } IInputStream sessionInputStream = await sessionFile.OpenReadAsync(); var serializer = new XmlSerializer(typeof(List <object>), new Type[] { typeof(T) }); _data = (List <object>)serializer.Deserialize(sessionInputStream.AsStreamForRead()); sessionInputStream.Dispose(); }
/// <summary> /// Load object from file /// </summary> /// <param name="fileName"></param> /// <returns></returns> public async Task <T> LoadAsync(string fileName) { fileName = fileName + GetFileExtension(); try { StorageFile file = null; StorageFolder folder = await GetFolderAsync().ConfigureAwait(false); var contains = await folder.ContainsFileAsync(fileName).ConfigureAwait(false); if (contains) { file = await folder.GetFileAsync(fileName); //Deserialize to object with JSON or XML serializer T result = default(T); switch (_serializerType) { case StorageSerializer.JSON: var data = await FileIO.ReadTextAsync(file); result = JsonConvert.DeserializeObject <T>(data); break; case StorageSerializer.XML: XmlSerializer serializer = new XmlSerializer(typeof(T)); IInputStream sessionInputStream = await file.OpenReadAsync(); result = (T)serializer.Deserialize(sessionInputStream.AsStreamForRead()); sessionInputStream.Dispose(); break; } return(result); } else { return(default(T)); } } catch (Exception ex) { //Unable to load contents of file throw; } }
public virtual void Dispose() { try { StreamAccessLock.Wait(); _IsDisposed = true; _InputStream?.Dispose(); _InputStream = null; } finally { StreamAccessLock.Release(); } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). _inputStream.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
public static async Task OnReceived(IInputStream dataStream, HostName remoteAddress) { IBuffer buffer = new Windows.Storage.Streams.Buffer(ReadBufferSize); await dataStream.ReadAsync(buffer, ReadBufferSize, InputStreamOptions.None); dataStream.Dispose(); var info = Encoding.UTF8.GetString(buffer.ToArray()); if (info.StartsWith(WindowsGoodbyeAuthTask.DeviceAlivePrefix) && info.Length > WindowsGoodbyeAuthTask.DeviceAlivePrefix.Length) { var payload = Convert.FromBase64String(info.Substring(WindowsGoodbyeAuthTask.DeviceAlivePrefix.Length)); if (payload.Length != 16) { return; } var guid = new Guid(payload); var session = WindowsGoodbyeAuthTask.deviceSessions.FirstOrDefault(s => s.DeviceInDb.DeviceId == guid); if (session != null) { session.Status = DeviceStatus.Established; } WindowsGoodbyeAuthTask.findAuth = false; } else if (info.StartsWith(WindowsGoodbyeAuthTask.AuthResponsePrefix) && info.Length > WindowsGoodbyeAuthTask.AuthResponsePrefix.Length) { var payload = Convert.FromBase64String(info.Substring(WindowsGoodbyeAuthTask.DeviceAlivePrefix.Length)); if (payload.Length <= 18) { return; } var guidBytes = new byte[16]; Array.Copy(payload, guidBytes, 16); var guid = new Guid(guidBytes); var session = WindowsGoodbyeAuthTask.deviceSessions.FirstOrDefault(s => s.DeviceInDb.DeviceId == guid); if (session == null) { return; } var resultBytes = new byte[payload.Length - 16]; Array.Copy(payload, 16, resultBytes, 0, resultBytes.Length); session.ResultBytes = resultBytes; WindowsGoodbyeAuthTask.AuthResultReceivedEvent.Set(); } }
/// <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(); } }
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) { } }
public void CheckShutdown() { try { inputStream?.Dispose(); } catch (ObjectDisposedException) { } try { outputStream?.Dispose(); } catch (ObjectDisposedException) { } try { socket.Dispose(); } catch (ObjectDisposedException) { } }
public static async Task <Int32> ReadMusicData() { Int32 num; try { StorageFile fileAsync = await ApplicationData.Current.LocalFolder.GetFileAsync(readwrite.filename); IInputStream inputStream = await fileAsync.OpenSequentialReadAsync(); try { DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(MusicData)); App.musicdata = dataContractSerializer.ReadObject(WindowsRuntimeStreamExtensions.AsStreamForRead(inputStream)) as MusicData; } finally { if (inputStream != null) { inputStream.Dispose(); } } } catch (FileNotFoundException fileNotFoundException) { App.musicdata = new MusicData(); num = 1; return(num); } catch (Exception exception1) { Exception exception = exception1; App.ShowError(String.Concat("Error while reading music data: ", exception.Message.ToString())); App.musicdata = new MusicData(); num = 1; return(num); } Boolean flag = await App.musicdata.CheckForNewMusic(); num = (!flag ? 0 : 2); return(num); }
public static async Task OnReceived(IInputStream dataStream, HostName remoteAddress) { IBuffer buffer = new Windows.Storage.Streams.Buffer(ReadBufferSize); await dataStream.ReadAsync(buffer, ReadBufferSize, InputStreamOptions.None); dataStream.Dispose(); var info = Encoding.UTF8.GetString(buffer.ToArray()); if (info.StartsWith(PairingRequestPrefix) && info.Length > PairingRequestPrefix.Length) { var payload = info.Substring(PairingRequestPrefix.Length); UdpEventPublisher.FirePairingRequestReceived(payload, IPAddress.Parse(remoteAddress.CanonicalName)); } else if (info.StartsWith(PairingTerminate)) { UdpEventPublisher.FirePairingTerminateReceived(IPAddress.Parse(remoteAddress.CanonicalName)); } }
/// <summary> /// Create new file based on the IInputStream under Images folder. /// </summary> /// <param name="fileName">Image File Name</param> /// <param name="sourceStream">IInputStream of the image you want to save</param> /// <param name="options">Creation Collision Option</param> /// <returns>New file name</returns> async static public Task <string> SaveImageAsync(string fileName, IInputStream sourceStream, CreationCollisionOption options) { try { var storage = Windows.Storage.ApplicationData.Current.LocalFolder; var imgFolderName = FolderNames.Images.ToString(); var folder = await storage.CreateFolderAsync(imgFolderName, Windows.Storage.CreationCollisionOption.OpenIfExists); var file = await folder.CreateFileAsync(fileName, options); using (var fileStream = await file.OpenStreamForWriteAsync()) { await RandomAccessStream.CopyAsync(sourceStream, fileStream.AsOutputStream()); } sourceStream.Dispose(); return(file.Name); } catch (Exception) { return(null); } }
//-------------------------------------------------------------------------zamykanie polaczenia private void disconnect() { if (reader != null) { reader.Dispose(); reader = null; } if (writer != null) { writer.Dispose(); writer = null; } if (socket != null) { socket.Dispose(); socket = null; } if (stream != null) { stream.Dispose(); stream = null; } if (buffer != null) { buffer = null; } if (rfcommProvider != null) { rfcommProvider.StopAdvertising(); rfcommProvider = null; } if (socketListener != null) { socketListener.Dispose(); socketListener = null; } }
static async private Task <T> RestoreAsync <T>(string filename) { StorageFile sessionFile = await ApplicationData.Current.LocalFolder.GetFileAsync(filename); if (sessionFile == null) { return(default(T)); } IInputStream sessionInputStream = await sessionFile.OpenReadAsync(); //Using DataContractSerializer , look at the cat-class var sessionSerializer = new DataContractSerializer(typeof(T), new DataContractSerializerSettings { }); var data = (T)sessionSerializer.ReadObject(sessionInputStream.AsStreamForRead()); //Using XmlSerializer , look at the Dog-class //var serializer = new XmlSerializer(typeof(List<object>), new Type[] { typeof(T) }); //_data = (List<object>)serializer.Deserialize(sessionInputStream.AsStreamForRead()); sessionInputStream.Dispose(); return(data); }
//private async Task<XDocument> LoadAsync(string path) //{ // StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\"); // StorageFile file = await sf.GetFileAsync(Path.GetFileName(path)); // IBuffer ibuf = null; // byte[] b; // bool excCaught = false; // try // { // using (IRandomAccessStream ras = await file.OpenReadAsync()) // { // b = new byte[ras.Size]; // ibuf = await ras.ReadAsync(CryptographicBuffer.CreateFromByteArray(b), (uint)ras.Size, InputStreamOptions.None); // ras.Dispose(); // } // } // catch (System.UnauthorizedAccessException ex) // { // excCaught = true; // } // if (excCaught) // { // using (IRandomAccessStream ras = await file.OpenReadAsync()) // { // b = new byte[ras.Size]; // ibuf = await ras.ReadAsync(CryptographicBuffer.CreateFromByteArray(b), (uint)ras.Size, InputStreamOptions.None); // ras.Dispose(); // } // } // CryptographicBuffer.CopyToByteArray(ibuf, out b); // char[] ch = System.Text.Encoding.UTF8.GetChars(b); // string s = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, ibuf); // s = EncryptionProvider.Decrypt(s, EncryptionProvider.PublicKey); // StringReader sreader = new StringReader(s); // while (sreader.Peek() == 65279) // { // sreader.Read(); // } // XDocument xdoc = XDocument.Load(sreader, LoadOptions.None); // return xdoc; //} private async Task <XDocument> LoadAsync(string path) { StorageFolder sf = await ApplicationData.Current.LocalFolder.GetFolderAsync(@"data\"); StorageFile file = await sf.GetFileAsync(Path.GetFileName(path)); IBuffer ibuf = null; byte[] b; using (IRandomAccessStream ras = await file.OpenReadAsync()) { using (IInputStream inputStream = ras.GetInputStreamAt(0)) { ulong size = ras.Size; DataReader dataReader = new DataReader(inputStream); await dataReader.LoadAsync((uint)size); ibuf = dataReader.ReadBuffer((uint)size); inputStream.Dispose(); } ras.Dispose(); } CryptographicBuffer.CopyToByteArray(ibuf, out b); // char[] ch = System.Text.Encoding.UTF8.GetChars(b); // string s = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, ibuf); string s = EncryptionProvider.DecryptToString(ibuf); StringReader sreader = new StringReader(s); while (sreader.Peek() == 65279) { sreader.Read(); } XDocument xdoc = XDocument.Load(sreader, LoadOptions.None); return(xdoc); }