private T SafeExecute <T>(Func <Stream, T> operation, bool doThrow) where T : struct { try { Connect(); if (_streamImplementation == null) { if (doThrow) { throw new TimeoutException("Stream is disconnected. Retrying next time."); } return(default(T)); } return(operation(_streamImplementation)); } catch (IOException x) { _streamImplementation?.Dispose(); _streamImplementation = null; if (doThrow) { throw new TimeoutException("Error executing operation. Retrying next time", x); } return(default(T)); } }
private async Task <byte[]> GenerateContentAsync() { _htmlToPdfDocument = new HtmlToPdfDocument { GlobalSettings = new PdfGlobalSettings { DocumentTitle = "Sample", }, ObjectSettings = { new PdfObjectSettings { HtmlContent = _htmlContent, }, }, }; Stream?stream = null; #pragma warning disable IDISP001 // Dispose created. var ms = new MemoryStream(); #pragma warning restore IDISP001 // Dispose created. try { await _sut !.ConvertAsync( _htmlToPdfDocument !, length => { stream?.Dispose(); stream = _recyclableMemoryStreamManager.GetStream( Guid.NewGuid(), "wkhtmltox", length); return(stream); }, CancellationToken.None) .ConfigureAwait(false); stream !.Position = 0; await stream.CopyToAsync(ms).ConfigureAwait(false); return(ms.ToArray()); } finally { #if NETCOREAPP3_1 || NET if (stream != null) { await stream.DisposeAsync().ConfigureAwait(false); } await ms.DisposeAsync().ConfigureAwait(false); #else stream?.Dispose(); ms?.Dispose(); #endif } }
/// <summary> /// Creates a new connected TCP client connected to Tor SOCKS5 endpoint. /// </summary> /// <param name="host">Tor SOCKS5 host.</param> /// <param name="port">Tor SOCKS5 port.</param> /// <param name="useSsl">Whether to use SSL to send the HTTP request over Tor.</param> /// <param name="circuit">Tor circuit we want to use in authentication.</param> /// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param> /// <returns>New <see cref="TorTcpConnection"/> instance.</returns> /// <exception cref="TorConnectionException">When <see cref="ConnectAsync(TcpClient, CancellationToken)"/> fails.</exception> public async Task <TorTcpConnection> ConnectAsync(string host, int port, bool useSsl, ICircuit circuit, CancellationToken cancellationToken = default) { TcpClient?tcpClient = null; Stream? transportStream = null; try { tcpClient = new(TorSocks5EndPoint.AddressFamily); tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 30); tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 5); tcpClient.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 5); transportStream = await ConnectAsync(tcpClient, cancellationToken).ConfigureAwait(false); await HandshakeAsync(tcpClient, circuit, cancellationToken).ConfigureAwait(false); await ConnectToDestinationAsync(tcpClient, host, port, cancellationToken).ConfigureAwait(false); if (useSsl) { transportStream = await UpgradeToSslAsync(tcpClient, host).ConfigureAwait(false); } bool allowRecycling = !useSsl && (circuit is DefaultCircuit or PersonCircuit); TorTcpConnection result = new(tcpClient, transportStream, circuit, allowRecycling); transportStream = null; tcpClient = null; return(result); } finally { transportStream?.Dispose(); tcpClient?.Dispose(); } }
/// <summary> /// Creates a new connected TCP client connected to Tor SOCKS5 endpoint. /// </summary> /// <param name="host">Tor SOCKS5 host.</param> /// <param name="port">Tor SOCKS5 port.</param> /// <param name="useSsl">Whether to use SSL to send the HTTP request over Tor.</param> /// <param name="isolateStream"><c>true</c> if a new Tor circuit is required for this HTTP request.</param> /// <param name="cancellationToken">Cancellation token to cancel the asynchronous operation.</param> /// <returns>New <see cref="TorTcpConnection"/> instance.</returns> /// <exception cref="TorConnectionException">When <see cref="ConnectAsync(TcpClient, CancellationToken)"/> fails.</exception> public async Task <TorTcpConnection> ConnectAsync(string host, int port, bool useSsl, bool isolateStream, CancellationToken cancellationToken = default) { TcpClient?tcpClient = null; Stream? transportStream = null; try { tcpClient = new(TorSocks5EndPoint.AddressFamily); transportStream = await ConnectAsync(tcpClient, cancellationToken).ConfigureAwait(false); await HandshakeAsync(tcpClient, isolateStream, cancellationToken).ConfigureAwait(false); await ConnectToDestinationAsync(tcpClient, host, port, cancellationToken).ConfigureAwait(false); if (useSsl) { transportStream = await UpgradeToSslAsync(tcpClient, host).ConfigureAwait(false); } TorTcpConnection result = new(tcpClient, transportStream, allowRecycling : !useSsl && !isolateStream); transportStream = null; tcpClient = null; return(result); } finally { transportStream?.Dispose(); tcpClient?.Dispose(); } }
/// <summary> /// Disposes the stream if set to do so /// </summary> public void Dispose() { if (ShouldDispose) { _stream?.Dispose(); } }
public async Task WhenIConvertHtmlToPdfTimes(int count) { for (int i = 0; i < count; i++) { #pragma warning disable RCS1212 // Remove redundant assignment. Stream?stream = null; await _sut !.ConvertAsync( _htmlToPdfDocument !, length => { stream = _recyclableMemoryStreamManager.GetStream( Guid.NewGuid(), "wkhtmltox", length); return(stream); }, CancellationToken.None).ConfigureAwait(false); #pragma warning restore RCS1212 // Remove redundant assignment. #if NETCOREAPP3_1 || NET if (stream != null) { await stream.DisposeAsync().ConfigureAwait(false); } #else stream?.Dispose(); #endif } }
public override async Task DownloadFiles(DownloadRequest request, IServerStreamWriter <DownloadResponse> responseStream, ServerCallContext context) { foreach (var i in request.FileNames) { var result = new DownloadResponse(); Stream?stream = null; try { stream = await seaweed.DownloadAsync(i); } catch { // ignored } var succeeded = true; if (stream != null) { stream.Seek(0, SeekOrigin.Begin); } else { succeeded = false; } result.Result.Add(new DownloadResult { Content = succeeded ? await ByteString.FromStreamAsync(stream) : ByteString.Empty, FileName = i, Succeeded = succeeded }); await responseStream.WriteAsync(result); stream?.Dispose(); } }
protected override ValueTask CloseAsyncCore(ConnectionCloseMethod method, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return(ValueTask.FromCanceled(cancellationToken)); } try { if (method != ConnectionCloseMethod.GracefulShutdown) { // Dispose must be called first in order to cause a connection reset, // as NetworkStream.Dispose() will call Shutdown(Both). _socket.Dispose(); } // Since CreatePipe() calls CreateStream(), so _stream should be present even in the pipe case: _stream?.Dispose(); } catch (SocketException socketException) { return(ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(socketException))); } catch (Exception ex) { return(ValueTask.FromException(ex)); } return(default);
/// <summary> /// Loads the transition table from an embedded resource. /// </summary> public static ushort[] Transitions(string resourceName) { var fullResourceName = BasePath + resourceName; var assembly = Assembly.GetExecutingAssembly(); Stream?stream = null; try { stream = assembly.GetManifestResourceStream(fullResourceName); if (stream == null) { throw new FileNotFoundException($"Resource is missing: {resourceName}"); } using var reader = new StreamReader(stream); stream = null; var result = reader.ReadToEnd(); var lines = result.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries); var ints = lines.Select(line => Convert.ToInt32(line, CultureInfo.InvariantCulture)); return(ints.Select(i => i < 0 ? 0 : i).Select(i => (ushort)i).ToArray()); } finally { stream?.Dispose(); } }
/// <summary> /// Compresses the response stream if the browser allows it. /// </summary> private static MemoryStream CompressResponse(Stream responseStream, HttpApplication app, string key) { MemoryStream dataStream = new MemoryStream(); StreamCopy(responseStream, dataStream); responseStream.Dispose(); byte[] buffer = dataStream.ToArray(); dataStream.Dispose(); MemoryStream ms = new MemoryStream(); Stream compress = null; if (IsEncodingAccepted(DEFLATE)) { compress = new DeflateStream(ms, CompressionMode.Compress); app.Application.Add(key + "enc", DEFLATE); } else if (IsEncodingAccepted(GZIP)) { compress = new GZipStream(ms, CompressionMode.Compress); app.Application.Add(key + "enc", DEFLATE); } compress.Write(buffer, 0, buffer.Length); compress.Dispose(); return ms; }
public bool VerifyCrc() { if (armoredDataReader.State == ReaderState.Headers) { // Skip past headers armoredDataReader.ReadHeaderLines(); } if (armoredDataReader.State == ReaderState.ClearText) { // Skip past clear text using var literalDataStream = new LiteralDataStream(armoredDataReader); literalDataStream.CopyTo(Stream.Null); // Skip past headers armoredDataReader.ReadHeaderLines(); } if (armoredDataReader.State == ReaderState.Base64) { if (armoredDataStream == null) { this.crc24 = new Crc24(); this.armoredDataStream = new CryptoStream(new ArmoredDataStream(armoredDataReader), crc24, CryptoStreamMode.Read); } armoredDataStream?.CopyTo(Stream.Null); armoredDataStream?.Dispose(); } Debug.Assert(this.armoredDataReader.State == ReaderState.CRC); var crcTail = this.armoredDataReader.ReadCrcAndFooter(); Debug.Assert(this.crc24 != null); return(crcTail.SequenceEqual(this.crc24.Hash !)); }
public async Task ExecuteResultAsync(ActionContext context) { Stream?content = null; try { switch (format) { case ExportImageFormat.Png: content = icon.SaveAsPng(); context.HttpContext.Response.ContentType = "image/png"; break; case ExportImageFormat.Svg: content = icon.SaveAsSvg(); context.HttpContext.Response.ContentType = "image/svg+xml"; break; default: throw new NotSupportedException($"The image format '{format}' is not supported by {nameof(IdenticonResult)}."); } context.HttpContext.Response.ContentLength = content.Length; await content.CopyToAsync(context.HttpContext.Response.Body); } finally { content?.Dispose(); } }
public void Dispose() { Unbind(); _extractor?.Dispose(); _extractor = null; _rootStream?.Dispose(); _rootStream = null; }
public void DisposeBasic() { Content?.Dispose(); Content = null; DisposableStream?.Close(); DisposableStream?.Dispose(); DisposableStream = null; }
public void Dispose() { if (!_disposedValue) { _readerProvider.Dispose(); _temporaryPdbStream?.Dispose(); _disposedValue = true; } }
protected override void Dispose(bool disposing) { if (disposing) { _decompressionStream?.Dispose(); _stream.Dispose(); } base.Dispose(disposing); }
private void ResetRead() { _jsonReader?.Close(); _jsonReader = null; _reader?.Dispose(); _reader = null; _responseStream?.Dispose(); _responseStream = null; }
public object GetView(IPackageContent selectedFile, IReadOnlyList <IPackageContent> peerFiles) { DiagnosticsClient.TrackEvent("PdbFileViewer"); AssemblyDebugDataViewModel?data = null; // Get the PE file, exe or dll that matches var filename = Path.GetFileNameWithoutExtension(selectedFile.Name); var pe = peerFiles.FirstOrDefault(pc => pc.Path != selectedFile.Path && Path.GetFileNameWithoutExtension(pc.Name) !.Equals(filename, StringComparison.OrdinalIgnoreCase) && (".dll".Equals(Path.GetExtension(pc.Name), StringComparison.OrdinalIgnoreCase) || ".exe".Equals(Path.GetExtension(pc.Name), StringComparison.OrdinalIgnoreCase))); Stream?peStream = null; try { if (pe != null) // we have a matching file { peStream = StreamUtility.MakeSeekable(pe.GetStream(), true); } // This might throw an exception because we don't know if it's a full PDB or portable // Try anyway in case it succeeds as a ppdb try { using (var stream = StreamUtility.MakeSeekable(selectedFile.GetStream(), true)) { data = new AssemblyDebugDataViewModel(AssemblyMetadataReader.ReadDebugData(peStream, stream)); } return(new ScrollViewer { HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Auto, Content = new Controls.PdbFileViewer { DataContext = data } }); } catch (ArgumentNullException) { } } finally { peStream?.Dispose(); } return(new TextBlock() { Text = "Full PDB files rquired the EXE or DLL to be alongside." }); }
public override async ValueTask DisposeAsync() { _ffmpegStream?.Dispose(); _ffmpegProcess?.Dispose(); _ffmpegProcess = null; _ffmpegStream = null; await base.DisposeAsync(); }
public Task <DocumentDebugInfoReader?> GetDocumentDebugInfoReaderAsync(string dllPath, CancellationToken cancellationToken) { var dllStream = IOUtilities.PerformIO(() => File.OpenRead(dllPath)); if (dllStream is null) { return(Task.FromResult <DocumentDebugInfoReader?>(null)); } Stream?pdbStream = null; DocumentDebugInfoReader?result = null; var peReader = new PEReader(dllStream); try { if (peReader.TryOpenAssociatedPortablePdb(dllPath, pdbPath => File.OpenRead(pdbPath), out var pdbReaderProvider, out _)) { Contract.ThrowIfNull(pdbReaderProvider); result = new DocumentDebugInfoReader(peReader, pdbReaderProvider); } // TODO: Otherwise call the debugger to find the PDB from a symbol server etc. if (result is null) { // Debugger needs: // - PDB MVID // - PDB Age // - PDB TimeStamp // - PDB Path // - DLL Path // // Most of this info comes from the CodeView Debug Directory from the dll } } catch (BadImageFormatException) { // If the PDB is corrupt in some way we can just ignore it, and let the system fall through to another provider // TODO: Log this to the output window: https://github.com/dotnet/roslyn/issues/57352 result = null; } finally { // If we're returning a result then it will own the disposal of the reader, but if not // then we need to do it ourselves. if (result is null) { pdbStream?.Dispose(); peReader.Dispose(); } } return(Task.FromResult <DocumentDebugInfoReader?>(result)); }
/// <summary> /// Releases the unmanaged resources used by ZipArchive and optionally finishes writing the archive and releases the managed resources. /// </summary> /// <param name="disposing">true to finish writing the archive and release unmanaged and managed resources, false to release only unmanaged resources.</param> private void Dispose(bool disposing) { if (disposing && !_isDisposed) { ArchiveStream.Dispose(); _backingStream?.Dispose(); ArchiveReader?.Dispose(); _isDisposed = true; } }
public void Dispose() { if (_writer is not null) { // Write null reference tag _writer.WriteByte((byte)Tags.NullReference); _writer.Complete(); } _stream?.Dispose(); }
protected override void Dispose(bool disposing) { if (disposing) { // This is important. Disposing original response content will cancel the gRPC call. _inner.Dispose(); _innerStream?.Dispose(); } base.Dispose(disposing); }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _bodyStream?.Dispose(); } _disposed = true; } }
internal static void DisposeStreamIfNotBuffered(ref Stream?stream) { // We want to keep the ContentStream readable // even after the response is disposed but only if it's a // buffered memory stream otherwise we can leave a network // connection hanging open if (stream is not MemoryStream) { stream?.Dispose(); stream = null; } }
public void Release() { if (!_hasLock) { throw new InvalidOperationException("Cannot release a mutex that has not been aquired"); } _hasLock = false; _openStream?.Dispose(); _openStream = null; _lockFile.Delete(); }
/// <summary> /// Releases resources associated to this object. /// </summary> public void Dispose() { if (!_isDisposed) { _stateHolder.Dispose(); _standardInput?.Dispose(); _standardOutput?.Dispose(); _standardError?.Dispose(); _isDisposed = true; } }
/// <summary> /// Disposes the resources. /// </summary> /// <param name="disposing">True to include releasing managed resource.</param> protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { JsonGameStringDocument.Dispose(); _streamForAsync?.Dispose(); } _disposedValue = true; } }
public void Close(DiagnosticBag diagnostics) { try { _streamToDispose?.Dispose(); } catch (Exception e) { var messageProvider = _compiler.MessageProvider; var diagnosticInfo = new DiagnosticInfo(messageProvider, messageProvider.ERR_OutputWriteFailed, _filePath, e.Message); diagnostics.Add(messageProvider.CreateDiagnostic(diagnosticInfo)); } }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (disposing) { _stream?.Dispose(); _tcpClient?.Dispose(); } _disposed = true; }
public static async Task <BackupReader> OpenArchiveAsync(this IBackupArchiveLocation backupArchiveLocation, string id, IJsonSerializer serializer) { Stream?stream = null; try { stream = await backupArchiveLocation.OpenStreamAsync(id); return(new BackupReader(serializer, stream)); } catch (IOException) { stream?.Dispose(); throw new BackupRestoreException("The backup archive is correupt and cannot be opened."); } catch (Exception) { stream?.Dispose(); throw; } }
private void dataFileLoadedCallback(Stream stream, bool succeeded) { try { enableButtons(); MessageBoxManager.Show("Image Status", "Data Loaded: " + succeeded); if (succeeded) Debug.Log("Data Value: " + stream.ReadByte()); } catch (Exception e) { MessageBoxManager.Show("Error", e.Message); } finally { // NOTE: Make sure you dispose of this stream !!! if (stream != null) stream.Dispose(); } }
private void setup() { if (client == null || client.Connected == false) { try { Debug.Log("trying to connect to " + host + ":" + port); client = new TcpClient(); client.Connect(host, port); if (stream != null)stream.Dispose(); stream = client.GetStream(); } catch(Exception e) { Debug.LogError("network error: " + e.Message); if (stream != null)stream.Dispose(); stream = null; client = null; } } }
private async Task PlayBobRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken) { // Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange. using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create()) { // Send the ephemeral ECDH public key to Alice. var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray(); await WriteAsync(channel, ecdhPublicKey, cancellationToken); // Authenticate to Alice that this is really Bob's ephemeral public key. byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey); await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken); // Read Alice's reply. It consists of her own ephemeral public key and signature. byte[] alicePublicDH = await ReadAsync(channel, cancellationToken); byte[] aliceSignedDH = await ReadAsync(channel, cancellationToken); // Authenticate Alice's public key. Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, alicePublicDH, aliceSignedDH)); // Deserialize Alice's public key and derive the shared secret from it. var aliceDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(alicePublicDH); byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(aliceDHPK); var encryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7) .CreateSymmetricKey(encryptionKeyMaterial); // Bob reads Alice's secret message using the shared secret that both parties derived, // but never transmitted. using (var aes = CryptoStream.ReadFrom(channel, WinRTCrypto.CryptographicEngine.CreateDecryptor(encryptionKey))) { byte[] plaintext = await ReadAsync(aes, cancellationToken); // Assert that the plaintext is as it was expected to be. CollectionAssertEx.AreEqual(SecretMessage, plaintext); } channel.Dispose(); } }
private async Task PlayAliceRoleAsync(ICryptographicKey ownSigningKey, ICryptographicKey othersSigningPublicKey, Stream channel, CancellationToken cancellationToken) { // Create ephemeral ECDH key pair, to prepare for the symmetric encryption key exchange. using (var ecdhKeyPair = NetFxCrypto.ECDiffieHellman.Create()) { // Alice receives Bob's ECDH public key and signature. byte[] bobPublicDH = await ReadAsync(channel, cancellationToken); byte[] bobSignedDH = await ReadAsync(channel, cancellationToken); // Alice verifies Bob's signature to be sure it's his key. Assert.True(WinRTCrypto.CryptographicEngine.VerifySignature(othersSigningPublicKey, bobPublicDH, bobSignedDH)); // Alice replies to Bob's public key by transmitting her own public key and signature. var ecdhPublicKey = ecdhKeyPair.PublicKey.ToByteArray(); await WriteAsync(channel, ecdhPublicKey, cancellationToken); byte[] ecdhPublicKeySignature = WinRTCrypto.CryptographicEngine.Sign(ownSigningKey, ecdhPublicKey); await WriteAsync(channel, ecdhPublicKeySignature, cancellationToken); // Derive a shared secret with Bob by combining Alice's private key with Bob's public key. var bobDHPK = NetFxCrypto.ECDiffieHellmanCngPublicKey.FromByteArray(bobPublicDH); byte[] encryptionKeyMaterial = ecdhKeyPair.DeriveKeyMaterial(bobDHPK); var symmetricEncryptionKey = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.AesCbcPkcs7) .CreateSymmetricKey(encryptionKeyMaterial); // Alice also adds a secret message. using (var aes = CryptoStream.WriteTo(channel, WinRTCrypto.CryptographicEngine.CreateEncryptor(symmetricEncryptionKey))) { await aes.WriteAsync(SecretMessage, 0, SecretMessage.Length, cancellationToken); } channel.Dispose(); } }
private void CreateZip(Stream stream, ZipArchiveMode mode) { try { if (mode != ZipArchiveMode.Read && mode != ZipArchiveMode.Create && mode != ZipArchiveMode.Update) throw new ArgumentOutOfRangeException("mode"); // If the mode parameter is set to Read, the stream must support reading. if (mode == ZipArchiveMode.Read && !stream.CanRead) throw new ArgumentException("Stream must support reading for Read archive mode"); // If the mode parameter is set to Create, the stream must support writing. if (mode == ZipArchiveMode.Create && !stream.CanWrite) throw new ArgumentException("Stream must support writing for Create archive mode"); // If the mode parameter is set to Update, the stream must support reading, writing, and seeking. if (mode == ZipArchiveMode.Update && (!stream.CanRead || !stream.CanWrite || !stream.CanSeek)) throw new ArgumentException("Stream must support reading, writing and seeking for Update archive mode"); try { zipFile = mode != ZipArchiveMode.Create && stream.Length != 0 ? SharpCompress.Archive.Zip.ZipArchive.Open(stream) : SharpCompress.Archive.Zip.ZipArchive.Create(); } catch (Exception e) { throw new InvalidDataException("The contents of the stream are not in the zip archive format.", e); } entries = new Dictionary<string, ZipArchiveEntry>(); if (Mode != ZipArchiveMode.Create) { foreach (var entry in zipFile.Entries) { var zipEntry = new ZipArchiveEntry(this, entry); entries[entry.Key] = zipEntry; } } } catch { if (!leaveStreamOpen) stream.Dispose(); throw; } }
main(int argc, string []argv) { int s; if (((argv[1][0] == '-') || (argv[1][0] == '-')) && ((argv[1][1] == 'h') || (argv[1][1] == '?'))) { Console.Out.WriteLine( "This program is to make 'signatures' of known c library calls for the dcc " + "program. It needs as the first arg the name of a library file, and as the " + "second arg, the name of the signature file to be generated." ); Environment.Exit(0); } if (argc <= 2) { Console.Out.WriteLine("Usage: makedsig <libname> <signame>\nor makedsig -h for help\n"); Environment.Exit(1); } try { f = new FileStream(argv[1], FileMode.Open); } catch { Console.WriteLine("Cannot read {0}", argv[1]); Environment.Exit(2); } try { f2 = new FileStream(argv[2], FileMode.Create); } catch { Console.WriteLine("Cannot write {0}", argv[2]); Environment.Exit(2); } Console.Error.Write("Seed: "); s = Convert.ToInt32(Console.In.ReadLine()); var rnd = new Random(s); numKeys = readSyms(); /* Read the keys (symbols) */ Console.WriteLine("Num keys: {0}; vertices: {1}", numKeys, (int)(numKeys*C)); hashParams( /* Set the parameters for the hash table */ numKeys, /* The number of symbols */ PATLEN, /* The length of the pattern to be hashed */ 256, /* The character set of the pattern (0-FF) */ '\0', /* Minimum pattern character value */ (int)(numKeys*C)); /* C is the sparseness of the graph. See Czech, Havas and Majewski for details */ /* The following two functions are in perfhlib.c */ map(); /* Perform the mapping. This will call getKey() repeatedly */ assign(); /* Generate the function g */ saveFile(); /* Save the resultant information */ f.Dispose(); f2.Dispose(); }
public void DisposeStream(ZipFileEntry _zfe, Stream s) { if (_zfe.Method == Compression.Deflate) s.Dispose(); }
private void imageLoadedCallback(Stream stream, bool succeeded) { enableButtons(); MessageBoxManager.Show("Image Status", "Image Loaded: " + succeeded); if (!succeeded) { if (stream != null) stream.Dispose(); return; } try { var data = new byte[stream.Length]; stream.Read(data, 0, data.Length); var newImage = new Texture2D(4, 4); newImage.LoadImage(data); newImage.Apply(); ReignImage.sprite = Sprite.Create(newImage, new Rect(0, 0, newImage.width, newImage.height), new Vector2(.5f, .5f)); } catch (Exception e) { MessageBoxManager.Show("Error", e.Message); } finally { // NOTE: Make sure you dispose of this stream !!! if (stream != null) stream.Dispose(); } }
private void NetworkRun() { while (!doShutdown) { // connection necessary? if (client == null || !client.Connected) { try { client = new TcpClient(); lock (thisLock) { debug.Enqueue("trying to connect to pd"); } client.Connect(host, port); if (stream != null)stream.Dispose(); stream = client.GetStream(); suppressErrors = false; } catch(Exception e) { Error("network error: " + e.Message); if (stream != null)stream.Dispose(); stream = null; client = null; Thread.Sleep (3 * 1000); } } // deliver messages try { lock (thisLock) { readyToQueuePdMessage = client != null && client.Connected; while (client.Connected && stream != null && readyToSend.Count > 0) { string message = readyToSend.Dequeue(); // low level mgs send byte[] ba = asciiEncoding.GetBytes(message.Trim().TrimEnd(new char[]{';'}).Trim() + ";"); stream.Write(ba, 0, ba.Length); suppressErrors = false; } } } catch(Exception e) { Error("network error: " + e.Message); if (stream != null)stream.Dispose(); stream = null; client = null; Thread.Sleep (3 * 1000); } // sleep a while Thread.Sleep(5); } }
//' delegate void ExceptionCode(); public static MemoryStream Strip(Stream inputStream) { //We will try to strip the header and footer for any gzip compressed stream here //This is needed for Deflate testing var outputStream = new MemoryStream(); bool fText, fCRC, fextra, fname, fComment; Byte flag; int len; int value; //Header //See RFC 1952 - ftp://swrinde.nde.swri.edu/pub/png/documents/zlib/rfc-gzip.html // or http://madhaus.utcs.utoronto.ca/links/ftp/doc/rfc/rfc1952.txt //skip the first 3 bytes - ID and CM SkipBytes(inputStream, 3); //flag flag = (Byte)inputStream.ReadByte(); fText = ((flag & 1) != 0); fCRC = ((flag & 2) != 0); fextra = ((flag & 4) != 0); fname = ((flag & 8) != 0); fComment = ((flag & 16) != 0); //MTIME, XFL and OS SkipBytes(inputStream, 6); if (fextra) { len = inputStream.ReadByte(); len |= (inputStream.ReadByte() << 8); SkipBytes(inputStream, len); } if (fname) { ReadUntilZero(inputStream); } if (fComment) { ReadUntilZero(inputStream); } if (fCRC) { SkipBytes(inputStream, 2); } //body //We will now write the body to the output file List<Byte> bitlist = new List<Byte>(); while ((value = inputStream.ReadByte()) != -1) { bitlist.Add((Byte)value); // outputStream.WriteByte((Byte)value); } // outputStream.Close(); inputStream.Dispose(); //Footer //The correct way to find a footer would be to read the compressed blocks but we try a different approach //All we know about it is that it is the last 8 bytes and we will read the last 8 bytes as the footer //We can confirm this by comparing the size of the decompressed file with the size specified in the footer //To do this, we need to decompress the file //@TODO!! - is it worth it?? // outputStream = new MemoryStream(outputFileName, FileMode.Create, FileAccess.Write); // inputStream = new MemoryStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read); // outputStream.Flush(); Byte[] bits = new Byte[bitlist.Count - 8]; bitlist.CopyTo(0, bits, 0, bitlist.Count - 8); outputStream.Write(bits, 0, bits.Length); outputStream.Position = 0; return outputStream; }
public void Close(Stream stream) { stream.Close(); stream.Dispose(); }
private Stream OpenInWriteMode() { if (_everOpenedForWrite) throw new IOException(SR.CreateModeWriteOnceAndOneEntryAtATime); //we assume that if another entry grabbed the archive stream, that it set this entry's _everOpenedForWrite property to true by calling WriteLocalFileHeaderIfNeeed Debug.Assert(_archive.IsStillArchiveStreamOwner(this)); _everOpenedForWrite = true; CheckSumAndSizeWriteStream crcSizeStream = GetDataCompressor(_archive.ArchiveStream, true, (object o, EventArgs e) => { //release the archive stream _archive.ReleaseArchiveStream(this); _outstandingWriteStream = null; }); _outstandingWriteStream = new DirectToArchiveWriterStream(crcSizeStream, this); return new WrappedStream(_outstandingWriteStream, (object o, EventArgs e) => _outstandingWriteStream.Dispose()); }
private static void NegativeConsoleOutputTests(Stream stream) { //ConsoleStream.Length should throw NotSupportedException Assert.Throws<NotSupportedException>(() => { long x = stream.Length; }); //ConsoleStream.get_Position should throw NotSupportedException Assert.Throws<NotSupportedException>(() => { long x = stream.Position; }); //ConsoleStream.set_Position should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Position = 50L); //ConsoleStream.SetLength should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.SetLength(50L)); // Flushing a stream is fine. stream.Flush(); //Read and write methods //ConsoleStream.Read(null) should throw ArgumentNullException Assert.Throws<ArgumentNullException>(() => stream.Read(null, 0, 1)); //ConsoleStream.Read() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, -1, 0)); //ConsoleStream.Read() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(new byte[] { 0, 1 }, 0, -1)); //ConsoleStream.Read() should throw ArgumentException Assert.Throws<ArgumentException>(() => stream.Read(new byte[] { 0, 1 }, 0, 50)); //ConsoleStream.Read() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 2)); //ConsoleStream.Write() should throw ArgumentNullException Assert.Throws<ArgumentNullException>(() => stream.Write(null, 0, 1)); //ConsoleStream.Write() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, -1, 0)); //ConsoleStream.Write() should throw ArgumentOutOfRangeException Assert.Throws<ArgumentOutOfRangeException>(() => stream.Write(new byte[] { 0, 1 }, 0, -1)); //ConsoleStream.Write() should throw ArgumentException Assert.Throws<ArgumentException>(() => stream.Write(new byte[] { 0, 1 }, 0, 50)); //ConsoleStream.Write() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Seek(0L, SeekOrigin.Begin)); // Close the stream and make sure we can no longer read, write or flush stream.Dispose(); //ConsoleStream.Read() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Read(new byte[] { 0, 1 }, 0, 1)); //ConsoleStream.Write() should throw NotSupportedException Assert.Throws<NotSupportedException>(() => stream.Write(new byte[] { 0, 1 }, 0, 1)); //ConsoleStream.Flush() should throw NotSupportedException Assert.Throws<ObjectDisposedException>(() => stream.Flush()); }
/// <summary> /// Save xls file to temp location in server /// </summary> /// <param name="fileInputStream">Stream Object</param> /// <param name="xlsFilePath">xls file's path</param> /// <returns>true if successful else false</returns> private bool SaveXlsFileToTempLocation(Stream fileInputStream, string xlsFilePath) { bool isSaved = true; try { int length = 256; int bytesRead = 0; Byte[] buffer = new Byte[length]; // write the required bytes using (FileStream fs = new FileStream(xlsFilePath, FileMode.Create)) { do { bytesRead = fileInputStream.Read(buffer, 0, length); fs.Write(buffer, 0, bytesRead); } while (bytesRead == length); } fileInputStream.Dispose(); } catch (Exception ex) { isSaved = false; Global.CreateExceptionString(ex, null); } return isSaved; }
protected void Page_Load(object sender, EventArgs e) { byte[] byteData = null; try { if (context == null) { context = ContextUtil.getInstance(Server.MapPath(".")); encrypt = context.getOuterEncrypt(); } if (encoder == null) encoder = ParamEncoder.getInstance(); if (decoder == null) decoder = ParamDecoder.getInstance(); encoder.outEncoder = context.getOuterResolve(); decoder.outDecoder = context.getOuterResolve(); Stream input = Request.InputStream; if (input.CanRead) { byteData = new byte[input.Length]; input.Read(byteData, 0, (int)input.Length); input.Close(); input.Dispose(); // 解密 if (encrypt != null) byteData = encrypt.decrypt(byteData); dataVo = decoder.decoder(byteData); Type serviceCls = context.getService(context.getServiceNameSpace() + "." + dataVo.ServiceName); MethodInfo method = serviceCls.GetMethod(dataVo.MethodName); object result = method.Invoke(System.Activator.CreateInstance(serviceCls), dataVo.Param); dataVo.Result = result; dataVo.ResultStatus = "success"; byte[] resultData = encoder.encode(dataVo); if (encrypt != null) resultData = encrypt.encrypt(resultData); output = Response.OutputStream; output.Write(resultData, 0, resultData.Length); output.Flush(); output.Close(); output.Dispose(); } else { } } catch(Exception exc) { if (dataVo == null && byteData != null) dataVo = decoder.decoder(byteData); if (dataVo == null) dataVo = new DataVO(); dataVo.ResultStatus = "error"; dataVo.ErrorMessage = exc.ToString(); byte[] resultData = encoder.encode(dataVo); if (encrypt != null) resultData = encrypt.encrypt(resultData); output = Response.OutputStream; output.Write(resultData, 0, resultData.Length); output.Flush(); output.Close(); output.Dispose(); } }