Here are the examples of the csharp api System.IO.Stream.Dispose() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3188 Examples
19
View Source File : LogFileWriter.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public void Write(byte[] buffer, int writeLen)
{
lock (lck)
{
if (logFile == null)
return;
if (logFile.Position > 2 * 1024 * 1024)
{
logFile.Flush();
logFile.Dispose();
logFile = new FileStream(
Log.GetLogFileName(compType),
FileMode.Append,
FileAccess.Write,
FileShare.Read
);
}
logFile.Write(buffer, 0, writeLen);
logFile.Write(lineFeed, 0, lineFeed.Length);
if (!needsFlush)
needsFlush = true;
}
}
19
View Source File : EdisFace.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private bool ReplyWithFile(HttpListenerContext ctx, string fileName)
{
Stream fs;
if (!File.Exists(fileName))
return false;
try
{
fs = File.OpenRead(fileName);
}
catch(Exception e)
{
Log.Error("{0} - {1}", fileName, e.Message);
return false;
}
ctx.Response.ContentLength64 = fs.Length;
ctx.Response.StatusCode = 200;
ctx.Response.ContentEncoding = Encoding.ASCII;
ctx.Response.ContentType = MimeTypeFromExt(Path.GetExtension(fileName));
fs.CopyTo(ctx.Response.OutputStream);
fs.Close();
fs.Dispose();
return true;
}
19
View Source File : LogFileWriter.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public void Dispose()
{
lock (lck)
{
ManualResetEvent mre = new ManualResetEvent(false);
flushTimer.Dispose(mre);
mre.WaitOne();
logFile.Dispose();
logFile = null;
mre.Dispose();
}
}
19
View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private static void RequestWaiter(object o)
{
NamedPipeServerStream nps = null;
while (active)
{
nps = CreatePipe();
if (nps == null)
{
Thread.Sleep(1000);
continue;
}
try
{
nps.WaitForConnection();
if (!active)
{
nps.Close();
nps.Dispose();
nps = null;
}
}
catch (Exception e)
{
Log.Warning("pipe connection wait aborted. {0}", e.Message);
nps = null;
}
if (nps != null)
RegisterRequestReceiver(nps);
}
Log.Verbose("Pipe connection waiter Tid#{0} closed.", Thread.CurrentThread.ManagedThreadId);
}
19
View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private static void WaitIo(object obj)
{
uint totalBytes;
int readLen = 0;
byte[] buffer = new byte[32 * 1024];
NamedPipeServerStream nps = (NamedPipeServerStream)obj;
RequestObject reqObj;
Log.Verbose("Thread#{0} waiting for available incoming data",
Thread.CurrentThread.ManagedThreadId);
if (nps.Read(buffer, 0, 4) > 0)
{
totalBytes = BitConverter.ToUInt32(buffer, 0);
readLen = nps.Read(buffer, 0, buffer.Length);
reqObj = new RequestObject(nps, buffer, readLen);
if (!reqObj.IsEnqueued)
reqObj = null;
}
else
{
nps.Disconnect();
nps.Close();
nps.Dispose();
nps = null;
}
buffer = null;
}
19
View Source File : RequestBridge.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private static void AbortBlockingWaitOfPipeServer(int count)
{
for (int i = 0; i < count; i++)
{
NamedPipeClientStream nspc = new NamedPipeClientStream("sozluk_request_bridge_pipe");
nspc.Connect();
nspc.Close();
nspc.Dispose();
}
}
19
View Source File : CelesteNetConnection.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void Dispose() {
Writer?.Dispose();
Stream?.Dispose();
}
19
View Source File : DisposeActionStream.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
protected override void Dispose(bool disposing) {
Action?.Invoke();
Inner.Dispose();
}
19
View Source File : PositionAwareStream.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
Inner.Dispose();
}
19
View Source File : ScAllColumnTypes.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public async Task Exec(IScenarioContext context)
{
bool isPostgres = context.Dialect == SqlDialect.PgSql;
var table = new TableItAllColumnTypes(isPostgres);
await context.Database.Statement(table.Script.DropAndCreate());
var testData = GetTestData(isPostgres);
await InsertDataInto(table, testData)
.MapData(Mapping)
.Exec(context.Database);
var mapper = new Mapper(new MapperConfiguration(cfg =>
{
cfg.AddDataReaderMapping();
var map = cfg.CreateMap<IDataRecord, AllColumnTypesDto>();
map
.ForMember(nameof(table.ColByteArraySmall), c => c.Ignore())
.ForMember(nameof(table.ColByteArrayBig), c => c.Ignore())
.ForMember(nameof(table.ColNullableByteArraySmall), c => c.Ignore())
.ForMember(nameof(table.ColNullableByteArrayBig), c => c.Ignore())
.ForMember(nameof(table.ColNullableFixedSizeByteArray), c => c.Ignore())
.ForMember(nameof(table.ColFixedSizeByteArray), c => c.Ignore());
if (isPostgres)
{
map
.ForMember(nameof(table.ColByte), c => c.Ignore())
.ForMember(nameof(table.ColNullableByte), c => c.Ignore());
}
if (context.Dialect == SqlDialect.MySql)
{
map
.ForMember(nameof(table.ColBoolean), c => c.MapFrom((r, dto) => r.GetBoolean(r.GetOrdinal(nameof(table.ColBoolean)))))
.ForMember(nameof(table.ColNullableBoolean), c => c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableBoolean))) ? (bool?)null : r.GetBoolean(r.GetOrdinal(nameof(table.ColNullableBoolean)))))
.ForMember(nameof(table.ColGuid), c => c.MapFrom((r, dto) => r.GetGuid(r.GetOrdinal(nameof(table.ColGuid)))))
.ForMember(nameof(table.ColNullableGuid), c=>c.MapFrom((r, dto) => r.IsDBNull(r.GetOrdinal(nameof(table.ColNullableGuid)))? (Guid?)null : r.GetGuid(r.GetOrdinal(nameof(table.ColNullableGuid)))));
}
}));
var expr = Select(table.Columns)
.From(table).Done();
context.WriteLine(PgSqlExporter.Default.ToSql(expr));
var result = await expr
.QueryList(context.Database, r =>
{
var allColumnTypesDto = mapper.Map<IDataRecord, AllColumnTypesDto>(r);
allColumnTypesDto.ColByteArrayBig = StreamToByteArray(table.ColByteArrayBig.GetStream(r));
allColumnTypesDto.ColByteArraySmall = table.ColByteArraySmall.Read(r);
allColumnTypesDto.ColNullableByteArrayBig = table.ColNullableByteArrayBig.Read(r);
allColumnTypesDto.ColNullableByteArraySmall = table.ColNullableByteArraySmall.Read(r);
allColumnTypesDto.ColFixedSizeByteArray = table.ColFixedSizeByteArray.Read(r);
allColumnTypesDto.ColNullableFixedSizeByteArray = table.ColNullableFixedSizeByteArray.Read(r);
return allColumnTypesDto;
});
static byte[] StreamToByteArray(Stream stream)
{
var buffer = new byte[stream.Length];
using MemoryStream ms = new MemoryStream(buffer);
stream.CopyTo(ms);
var result = buffer;
stream.Dispose();
return result;
}
for (int i = 0; i < testData.Length; i++)
{
if (!Equals(testData[i], result[i]))
{
var props = typeof(AllColumnTypesDto).GetProperties();
foreach (var propertyInfo in props)
{
context.WriteLine($"{propertyInfo.Name}: {propertyInfo.GetValue(testData[i])} - {propertyInfo.GetValue(result[i])}");
}
throw new Exception("Input and output are not identical!");
}
}
if (context.Dialect == SqlDialect.TSql)
{
var data = await Select(AllTypes.GetColumns(table))
.From(table)
.QueryList(context.Database, (r) => AllTypes.Read(r, table));
if (data.Count != 2)
{
throw new Exception("Incorrect reading using models");
}
await InsertDataInto(table, data).MapData(AllTypes.GetMapping).Exec(context.Database);
}
Console.WriteLine("'All Column Type Test' is preplaceded");
}
19
View Source File : HeifStreamWriter.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (this.stream != null)
{
if (this.ownsStream)
{
this.stream.Dispose();
}
this.stream = null;
}
}
base.Dispose(disposing);
}
19
View Source File : AvifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private ImageGridDescriptor TryGetImageGridDescriptor(uint itemId)
{
IItemInfoEntry entry = TryGereplacedemInfoEntry(itemId);
if (entry != null && entry.ItemType == ItemInfoEntryTypes.ImageGrid)
{
ItemLocationEntry locationEntry = TryGereplacedemLocation(itemId);
if (locationEntry != null)
{
if (locationEntry.TotalItemSize < ImageGridDescriptor.SmallDescriptorLength)
{
ExceptionUtil.ThrowFormatException("Invalid image grid descriptor length.");
}
using (AvifItemData itemData = ReadItemData(locationEntry))
{
Stream stream = null;
try
{
stream = itemData.GetStream();
using (EndianBinaryReader imageGridReader = new EndianBinaryReader(stream, this.reader.Endianess, this.arrayPool))
{
stream = null;
return new ImageGridDescriptor(imageGridReader, itemData.Length);
}
}
finally
{
stream?.Dispose();
}
}
}
}
return null;
}
19
View Source File : AvifWriter.AvifWriterState.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private static ItemDataBox CreateItemDataBox(ImageGridMetadata imageGridMetadata, IArrayPoolService arrayPool)
{
ImageGridDescriptor imageGridDescriptor = new ImageGridDescriptor(imageGridMetadata);
byte[] dataBoxBuffer = new byte[imageGridDescriptor.GetSize()];
MemoryStream stream = null;
try
{
stream = new MemoryStream(dataBoxBuffer);
using (BigEndianBinaryWriter writer = new BigEndianBinaryWriter(stream, leaveOpen: false, arrayPool))
{
stream = null;
// The ImageGridDescriptor is shared between the color and alpha image.
imageGridDescriptor.Write(writer);
}
}
finally
{
stream?.Dispose();
}
return new ItemDataBox(dataBoxBuffer);
}
19
View Source File : HeifReaderFactory.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public static HeifReader CreateFromFile(string path)
{
HeifReader reader;
FileStream fileStream = null;
try
{
fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
if (!fileStream.CanSeek)
{
throw new IOException(Properties.Resources.FileStreamDoesNotSupportSeeking);
}
if (fileStream.Length <= HeifStreamReader.MaxReadBufferSize)
{
byte[] bytes = CopyStreamToByteArray(fileStream);
reader = new HeifByteArrayReader(bytes);
}
else
{
reader = new HeifStreamReader(fileStream, ownsStream: true);
fileStream = null;
}
}
finally
{
fileStream?.Dispose();
}
return reader;
}
19
View Source File : HeifReaderFactory.cs
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
License : GNU Lesser General Public License v3.0
Project Creator : 0xC0000054
public static HeifReader CreateFromStream(Stream stream, bool ownsStream)
{
Validate.IsNotNull(stream, nameof(stream));
HeifReader reader;
// If the stream is a MemoryStream with an accessible buffer we can avoid
// having to copy data to a temporary buffer when reading from the stream.
// This check excludes types that are derived from MemoryStream because they may invalidate the
// underlying buffer when the stream is disposed.
if (stream.GetType() == typeof(MemoryStream) && ((MemoryStream)stream).TryGetBuffer(out var buffer))
{
reader = new HeifByteArrayReader(buffer);
// The doreplacedentation for GetBuffer indicates that the buffer remains valid after the MemoryStream is disposed.
if (ownsStream)
{
stream.Dispose();
}
}
else
{
if (stream.Length <= HeifStreamReader.MaxReadBufferSize)
{
byte[] bytes = CopyStreamToByteArray(stream);
if (ownsStream)
{
stream.Dispose();
}
reader = new HeifByteArrayReader(bytes);
}
else
{
reader = new HeifStreamReader(stream, ownsStream);
}
}
return reader;
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
private static StreamSegment TryParseExifMetadataHeader(AvifItemData data)
{
// The EXIF data block has a header consisting of a big-endian 4-byte unsigned integer
// that indicates the number of bytes that come before the start of the TIFF header.
// See ISO/IEC 23008-12:2017 section A.2.1.
StreamSegment stream = null;
Stream avifItemStream = null;
try
{
avifItemStream = data.GetStream();
long tiffStartOffset = avifItemStream.TryReadUInt32BigEndian();
if (tiffStartOffset != -1)
{
long origin = avifItemStream.Position + tiffStartOffset;
ulong length = data.Length - (ulong)tiffStartOffset - sizeof(uint);
if (length > 0 && length <= long.MaxValue)
{
stream = new StreamSegment(avifItemStream, origin, (long)length);
// The StreamSegment will take ownership of the existing stream.
avifItemStream = null;
}
}
}
finally
{
avifItemStream?.Dispose();
}
return stream;
}
19
View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
private void WaitForConnectionCallback(IAsyncResult result)
{
if (server == null)
{
return;
}
try
{
server.EndWaitForConnection(result);
}
catch (ObjectDisposedException)
{
return;
}
byte[] replySizeBuffer = new byte[sizeof(int)];
server.ProperRead(replySizeBuffer, 0, replySizeBuffer.Length);
int messageLength = BitConverter.ToInt32(replySizeBuffer, 0);
byte[] messageBytes = new byte[messageLength];
server.ProperRead(messageBytes, 0, messageLength);
List<string> parameters = DecodeMessageBuffer(messageBytes);
if (!TryGetValue(parameters[0], "command=", out string command))
{
throw new InvalidOperationException("The first item must be a command.");
}
if (command.Equals("gmic_qt_get_max_layer_size", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
InputMode inputMode = ParseInputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_get_max_layer_size' received. mode=" + inputMode.ToString());
#endif
string reply = GetMaxLayerSize(inputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_get_cropped_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the input mode.");
}
if (!TryGetValue(parameters[2], "croprect=", out string packedCropRect))
{
throw new InvalidOperationException("The third item must be the crop rectangle.");
}
InputMode inputMode = ParseInputMode(mode);
RectangleF cropRect = GetCropRectangle(packedCropRect);
#if DEBUG
System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
"'gmic_qt_get_cropped_images' received. mode={0}, cropRect={1}",
inputMode.ToString(), cropRect.ToString()));
#endif
string reply = PrepareCroppedLayers(inputMode, cropRect);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_output_images", StringComparison.Ordinal))
{
if (!TryGetValue(parameters[1], "mode=", out string mode))
{
throw new InvalidOperationException("The second item must be the output mode.");
}
OutputMode outputMode = ParseOutputMode(mode);
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_output_images' received. mode=" + outputMode.ToString());
#endif
List<string> outputLayers = parameters.GetRange(2, parameters.Count - 2);
string reply = ProcessOutputImage(outputLayers, outputMode);
SendMessage(server, reply);
}
else if (command.Equals("gmic_qt_release_shared_memory", StringComparison.Ordinal))
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("'gmic_qt_release_shared_memory' received.");
#endif
for (int i = 0; i < memoryMappedFiles.Count; i++)
{
memoryMappedFiles[i].Dispose();
}
memoryMappedFiles.Clear();
SendMessage(server, "done");
}
else if (command.Equals("gmic_qt_get_max_layer_data_length", StringComparison.Ordinal))
{
// This command is used to prevent images larger than 4GB from being used on a 32-bit version of G'MIC.
// Attempting to map an image that size into memory would cause an integer overflow when casting a 64-bit
// integer to the unsigned 32-bit size_t type.
long maxDataLength = 0;
foreach (GmicLayer layer in layers)
{
maxDataLength = Math.Max(maxDataLength, layer.Surface.Scan0.Length);
}
server.Write(BitConverter.GetBytes(sizeof(long)), 0, 4);
server.Write(BitConverter.GetBytes(maxDataLength), 0, 8);
}
// Wait for the acknowledgment that the client is done reading.
if (server.IsConnected)
{
byte[] doneMessageBuffer = new byte[4];
int bytesRead = 0;
int bytesToRead = doneMessageBuffer.Length;
do
{
int n = server.Read(doneMessageBuffer, bytesRead, bytesToRead);
bytesRead += n;
bytesToRead -= n;
} while (bytesToRead > 0 && server.IsConnected);
}
// Start a new server and wait for the next connection.
server.Dispose();
server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
server.BeginWaitForConnection(WaitForConnectionCallback, null);
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public void Dispose()
{
if (stream != null && !leaveOpen)
{
stream.Dispose();
stream = null;
}
}
19
View Source File : BigEndianBinaryWriter.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public void Dispose()
{
if (this.stream != null)
{
if (!this.leaveOpen)
{
this.stream.Dispose();
}
this.stream = null;
}
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public void Dispose()
{
if (!this.disposed)
{
this.disposed = true;
DisposableUtil.Free(ref this.bufferFromArrayPool);
this.buffer = null;
if (this.stream != null)
{
if (!this.leaveOpen)
{
this.stream.Dispose();
}
this.stream = null;
}
}
}
19
View Source File : StreamSegment.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.isOpen = false;
if (this.stream != null && !this.leaveOpen)
{
this.stream.Dispose();
this.stream = null;
}
}
base.Dispose(disposing);
}
19
View Source File : EndianBinaryReader.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
public void Dispose()
{
if (stream != null)
{
if (!leaveOpen)
{
stream.Dispose();
}
stream = null;
}
}
19
View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054
License : GNU General Public License v3.0
Project Creator : 0xC0000054
public void Dispose()
{
if (!disposed)
{
disposed = true;
for (int i = 0; i < layers.Count; i++)
{
layers[i].Dispose();
}
for (int i = 0; i < memoryMappedFiles.Count; i++)
{
memoryMappedFiles[i].Dispose();
}
if (OutputImageState != null)
{
OutputImageState.Dispose();
OutputImageState = null;
}
if (server != null)
{
server.Dispose();
server = null;
}
}
}
19
View Source File : ExifParser.cs
License : MIT License
Project Creator : 0xC0000054
License : MIT License
Project Creator : 0xC0000054
internal static ExifValueCollection Parse(byte[] exifBytes)
{
if (exifBytes == null)
{
throw new ArgumentNullException(nameof(exifBytes));
}
ExifValueCollection metadataEntries = null;
MemoryStream stream = null;
try
{
stream = new MemoryStream(exifBytes);
Endianess? byteOrder = TryDetectTiffByteOrder(stream);
if (byteOrder.HasValue)
{
using (EndianBinaryReader reader = new EndianBinaryReader(stream, byteOrder.Value))
{
stream = null;
ushort signature = reader.ReadUInt16();
if (signature == TiffConstants.Signature)
{
uint ifdOffset = reader.ReadUInt32();
List<ParserIFDEntry> entries = ParseDirectories(reader, ifdOffset);
metadataEntries = new ExifValueCollection(ConvertIFDEntriesToMetadataEntries(reader, entries));
}
}
}
}
catch (EndOfStreamException)
{
}
finally
{
stream?.Dispose();
}
return metadataEntries;
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public void Dispose()
{
driveStream?.Dispose();
((IDisposable)Decrypter)?.Dispose();
Cts?.Dispose();
}
19
View Source File : RedisIO.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Dispose()
{
if (_pipeline != null) _pipeline.Dispose();
if (_stream != null)
{
try { _stream.Close(); } catch { }
try { _stream.Dispose(); } catch { }
}
}
19
View Source File : RedisPipeline.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void Dispose()
{
_buffer.Dispose();
}
19
View Source File : DefaultRedisSocket.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void ReleaseSocket()
{
lock (_connectLock)
{
if (_socket != null)
{
try { _socket.Shutdown(SocketShutdown.Both); } catch { }
try { _socket.Close(); } catch { }
try { _socket.Dispose(); } catch { }
_socket = null;
}
if (_stream != null)
{
try { _stream.Close(); } catch { }
try { _stream.Dispose(); } catch { }
_stream = null;
}
_reader = null;
}
}
19
View Source File : RedisIO.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void SetStream(Stream stream)
{
if (_stream != null)
{
try { _stream.Close(); } catch { }
try { _stream.Dispose(); } catch { }
}
_stream = stream;
_reader = new RedisReader(this);
_pipeline = new RedisPipeline(this);
}
19
View Source File : PipelineAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static void EndPipe(IRedisSocket rds, IEnumerable<PipelineCommand> cmds)
{
var err = new List<PipelineCommand>();
var ms = new MemoryStream();
try
{
var respWriter = new RespHelper.Resp3Writer(ms, rds.Encoding, rds.Protocol);
foreach (var cmd in cmds)
respWriter.WriteCommand(cmd.Command);
if (rds.IsConnected == false) rds.Connect();
ms.Position = 0;
ms.CopyTo(rds.Stream);
foreach (var pc in cmds)
{
pc.RedisResult = rds.Read(pc.Command);
pc.Result = pc.Parse(pc.RedisResult);
if (pc.RedisResult.IsError) err.Add(pc);
#if isasync
pc.TrySetResult(pc.Result, pc.RedisResult.IsError ? new RedisServerException(pc.RedisResult.SimpleError) : null);
#endif
}
}
finally
{
ms.Close();
ms.Dispose();
}
if (err.Any())
{
var sb = new StringBuilder();
for (var a = 0; a < err.Count; a++)
{
var cmd = err[a].Command;
if (a > 0) sb.Append("\r\n");
sb.Append(err[a].RedisResult.SimpleError).Append(" {").Append(cmd.ToString()).Append("}");
}
throw new RedisServerException(sb.ToString());
}
}
19
View Source File : FrmRazorTemplates.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
private void buttonX1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxX1.Text))
{
ToastNotification.ToastBackColor = Color.Red;
ToastNotification.ToastForeColor = Color.White;
ToastNotification.ToastFont = new Font("微软雅黑", 15);
ToastNotification.Show(this, "模版名称不允许为空", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
return;
}
string path = Path.Combine(Environment.CurrentDirectory, "Templates");
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
TemplatesName = textBoxX1.Text;
TemplatesPath = Path.Combine(path, $"{textBoxX1.Text}.tpl");
if (File.Exists(TemplatesPath))
{
ToastNotification.ToastBackColor = Color.Red;
ToastNotification.ToastForeColor = Color.White;
ToastNotification.ToastFont = new Font("微软雅黑", 15);
ToastNotification.Show(this, "模版名称己存在", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
return;
}
using (var sr = File.Create(TemplatesPath))
{
sr.Close();
sr.Dispose();
}
this.Close();
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static void SaveLog(string strreplacedle, Exception ex)
{
try
{
string path = Path.Combine(StartupPath(), "guiLogs");
string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
if (!File.Exists(FilePath))
{
FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
FsCreate.Close();
FsCreate.Dispose();
}
FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
StreamWriter SwWrite = new StreamWriter(FsWrite);
string strContent = ex.ToString();
SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
SwWrite.Write(strContent);
SwWrite.WriteLine(Environment.NewLine);
SwWrite.WriteLine(" ");
SwWrite.Flush();
SwWrite.Close();
}
catch { }
}
19
View Source File : EventSourceReader.cs
License : MIT License
Project Creator : 3ventic
License : MIT License
Project Creator : 3ventic
public void Dispose()
{
_IsDisposed = true;
Stream?.Dispose();
Hc.CancelPendingRequests();
Hc.Dispose();
}
19
View Source File : MP3FileWriter.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
public override void Flush()
{
// write remaining data
if (inPosition > 0)
Encode();
// finalize compression
int rc = _lame.Flush(outBuffer, outBuffer.Length);
if (rc > 0)
outStream.Write(outBuffer, 0, rc);
// Cannot continue after flush, so clear output stream
if (disposeOutput)
outStream.Dispose();
outStream = null;
}
19
View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public void Disconnect()
{
if (Log != null)
Log.Close();
Log = null;
Connected = false;
WorkerThread.Join();
try
{
Connection.Close();
}
catch { }
Connection.Dispose();
Connection = null;
Mode = OperatingMode.Disconnected;
MachinePosition = new Vector3();
WorkOffset = new Vector3();
FeedRateRealtime = 0;
CurrentTLO = 0;
if (PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
Status = "Disconnected";
DistanceMode = ParseDistanceMode.Absolute;
Unit = ParseUnit.Metric;
Plane = ArcPlane.XY;
BufferState = 0;
FeedOverride = 100;
RapidOverride = 100;
SpindleOverride = 100;
if (OverrideChanged != null)
OverrideChanged.Invoke();
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
if (PinStateChanged != null)
PinStateChanged.Invoke();
ToSend.Clear();
ToSendPriority.Clear();
Sent.Clear();
ToSendMacro.Clear();
}
19
View Source File : MP3FileWriter.cs
License : MIT License
Project Creator : 3wz
License : MIT License
Project Creator : 3wz
protected override void Dispose(bool final)
{
if (_lame != null && outStream != null)
Flush();
if (_lame != null)
{
_lame.Dispose();
_lame = null;
}
if (outStream != null && disposeOutput)
{
outStream.Dispose();
outStream = null;
}
base.Dispose(final);
}
19
View Source File : CodedInputStream.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public void Dispose()
{
if (!leaveOpen)
{
input.Dispose();
}
}
19
View Source File : CodedOutputStream.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public void Dispose()
{
Flush();
if (!leaveOpen)
{
output.Dispose();
}
}
19
View Source File : DefatultAlipayHelper.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
private async Task<FTFOutput> FTFGenQRCode(AlipayTradePrecreateContentBuilder input, string asyncNotifyUrl, Action<AlipayF2FPrecreateResult> loopQueryAction, FTFConfig fTFConfig)
{
// 参数检测
var isAsyncNotify = !asyncNotifyUrl.IsNullOrWhiteSpace();
if (!isAsyncNotify && loopQueryAction == null)
{
throw new NullReferenceException("轮询模式下 loopQueryAction 不能为空!");
}
// 收款账号检测,如果为空则默认填入全局配置的Uid
if (input.seller_id.IsNullOrWhiteSpace())
{
input.seller_id = this._alipayService.Options.Uid;
}
Bitmap bitmap = null;
MemoryStream memoryStream = null;
var message = string.Empty;
//推荐使用轮询撤销机制,不推荐使用异步通知,避免单边账问题发生。
AlipayF2FPrecreateResult precreateResult = null;
// 异步通知
if (isAsyncNotify)
{
precreateResult = await _alipayF2FService.TradePrecreateAsync(input, asyncNotifyUrl);
}// 同步轮询
else
{
precreateResult = await _alipayF2FService.TradePrecreateAsync(input);
}
switch (precreateResult.Status)
{
case F2FResultEnum.SUCCESS:
// 将链接用二维码工具生成二维码打印出来,顾客可以用支付宝钱包扫码支付。
bitmap = RenderQrCode(precreateResult.response.QrCode);
// 同步轮询模式,触发轮询回调函数
if (!isAsyncNotify)
{
loopQueryAction.Invoke(precreateResult);
}
break;
case F2FResultEnum.FAILED:
message = $"生成二维码失败: {precreateResult.response.Body}";
break;
case F2FResultEnum.UNKNOWN:
message = "生成二维码失败:" + (precreateResult.response == null ? "配置或网络异常,请检查后重试" : "系统异常,请更新外部订单后重新发起请求");
break;
}
// 如果位图为空,则生成错误提示二维码
if (bitmap == null)
{
bitmap = new Bitmap(fTFConfig == null ? this._fTFConfig?.QRCodeGenErrorImageFullPath : fTFConfig.QRCodeGenErrorImageFullPath);
}
// 转换成字节数组
memoryStream = new MemoryStream();
bitmap.Save(memoryStream, ImageFormat.Png);
var imgBuffer = memoryStream.GetBuffer();
// 释放资源
memoryStream.Dispose();
bitmap.Dispose();
return new FTFOutput()
{
QRCodeImageBuffer = imgBuffer,
IsSuccess = precreateResult.Status == F2FResultEnum.SUCCESS,
Message = message
};
}
19
View Source File : AssemblyLoading.cs
License : MIT License
Project Creator : 71
License : MIT License
Project Creator : 71
[MethodImpl(MethodImplOptions.NoInlining)]
private static replacedembly LoadCore(replacedemblyLoadContext ctx, string path)
{
using (FileStream fs = File.OpenRead(path))
{
// Load from a stream instead of loading from path, in order
// to avoid locking the file.
string pdbFile = Path.ChangeExtension(path, ".pdb");
if (!File.Exists(pdbFile))
return ctx.LoadFromStream(fs);
FileStream pdbFs = null;
try
{
pdbFs = File.OpenRead(pdbFile);
return ctx.LoadFromStream(fs, pdbFs);
}
catch
{
return ctx.LoadFromStream(fs);
}
finally
{
pdbFs?.Dispose();
}
}
}
19
View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
protected override async void Dispose(bool disposing)
{
base.Dispose(disposing);
if (!_disposed)
{
_disposed = true;
if (_recordFileData != null)
{
try
{
var filePath = _recordFileData.Name;
using (var recordFile = new FileStream(filePath.Substring(0, filePath.Length - 5) + ".flv", FileMode.OpenOrCreate))
{
recordFile.SetLength(0);
recordFile.Seek(0, SeekOrigin.Begin);
await recordFile.WriteAsync(FlvMuxer.MultiplexFlvHeader(true, true));
var metaData = _metaData.Data[1] as Dictionary<string, object>;
metaData["duration"] = ((double)_currentTimestamp) / 1000;
metaData["keyframes"] = _keyframes;
_metaData.MessageHeader.MessageLength = 0;
var dataTagLen = FlvMuxer.MultiplexFlv(_metaData).Length;
var offset = recordFile.Position + dataTagLen;
for (int i = 0; i < _keyframeFilePositions.Count; i++)
{
_keyframeFilePositions[i] = (double)_keyframeFilePositions[i] + offset;
}
await recordFile.WriteAsync(FlvMuxer.MultiplexFlv(_metaData));
_recordFileData.Seek(0, SeekOrigin.Begin);
await _recordFileData.CopyToAsync(recordFile);
_recordFileData.Dispose();
File.Delete(filePath);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
_recordFile?.Dispose();
}
}
19
View Source File : WebSocketPlayController.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
foreach (var c in _cleanupActions)
{
c();
}
_recordFile?.Dispose();
}
disposedValue = true;
}
}
19
View Source File : FlvDemuxer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public async Task<byte[]> AttachStream(Stream stream, bool disposeOld = false)
{
if (disposeOld)
{
_stream?.Dispose();
}
var headerBuffer = new byte[9];
await stream.ReadBytesAsync(headerBuffer);
_stream = stream;
return headerBuffer;
}
19
View Source File : UserLicense.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static void ShowLicense()
{
if(!agreeLicense)
{
string bundleN = "userlicense";
replacedetBundle ab = null; // You probably want this to be defined somewhere more global.
replacedembly asm = replacedembly.GetExecutingreplacedembly();
foreach (string res in asm.GetManifestResourceNames())
{
using (Stream s = asm.GetManifestResourceStream(res))
{
if (s == null) continue;
byte[] buffer = new byte[s.Length];
s.Read(buffer, 0, buffer.Length);
s.Dispose();
string bundleName = Path.GetExtension(res).Substring(1);
if (bundleName != bundleN) continue;
Logger.Log("Loading bundle " + bundleName);
ab = replacedetBundle.LoadFromMemory(buffer); // Store this somewhere you can access again.
}
}
var _canvas = ab.Loadreplacedet<GameObject>("userlicense");
UnityEngine.Object.Instantiate(_canvas);
Logger.Log("Show User License");
}
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
public static byte[] FromAudioClip(AudioClip audioClip, out string filepath, bool saveAsFile = true, string dirname = "recordings")
{
MemoryStream stream = new MemoryStream();
const int headerSize = 44;
// get bit depth
UInt16 bitDepth = 16; //BitDepth (audioClip);
// NB: Only supports 16 bit
//Debug.replacedertFormat (bitDepth == 16, "Only converting 16 bit is currently supported. The audio clip data is {0} bit.", bitDepth);
// total file size = 44 bytes for header format and audioClip.samples * factor due to float to Int16 / sbyte conversion
int fileSize = audioClip.samples * BlockSize_16Bit + headerSize; // BlockSize (bitDepth)
// chunk descriptor (riff)
WriteFileHeader(ref stream, fileSize);
// file header (fmt)
WriteFileFormat(ref stream, audioClip.channels, audioClip.frequency, bitDepth);
// data chunks (data)
WriteFileData(ref stream, audioClip, bitDepth);
byte[] bytes = stream.ToArray();
// Validate total bytes
Debug.replacedertFormat(bytes.Length == fileSize, "Unexpected AudioClip to wav format byte count: {0} == {1}", bytes.Length, fileSize);
// Save file to persistant storage location
if (saveAsFile)
{
filepath = string.Format("{0}/{1}/{2}.{3}", Application.persistentDataPath, dirname, DateTime.UtcNow.ToString("yyMMdd-HHmmss-fff"), "wav");
Directory.CreateDirectory(Path.GetDirectoryName(filepath));
File.WriteAllBytes(filepath, bytes);
//Debug.Log ("Auto-saved .wav file: " + filepath);
}
else
{
filepath = null;
}
stream.Dispose();
return bytes;
}
19
View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802
License : GNU General Public License v3.0
Project Creator : a2659802
private static byte[] ConvertAudioClipDataToInt16ByteArray(float[] data)
{
MemoryStream dataStream = new MemoryStream();
int x = sizeof(Int16);
Int16 maxValue = Int16.MaxValue;
int i = 0;
while (i < data.Length)
{
dataStream.Write(BitConverter.GetBytes(Convert.ToInt16(data[i] * maxValue)), 0, x);
++i;
}
byte[] bytes = dataStream.ToArray();
// Validate converted bytes
Debug.replacedertFormat(data.Length * x == bytes.Length, "Unexpected float[] to Int16 to byte[] size: {0} == {1}", data.Length * x, bytes.Length);
dataStream.Dispose();
return bytes;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : abanu-org
License : MIT License
Project Creator : abanu-org
[MethodImpl(MethodImplOptions.Synchronized)]
private static void Start()
{
while (true)
{
try
{
stream?.Dispose();
}
catch
{
}
try
{
client?.Dispose();
}
catch
{
}
try
{
thRead?.Abort();
}
catch
{
}
try
{
thWrite?.Abort();
}
catch
{
}
thRead = null;
thWrite = null;
ms.SetLength(0);
WriteQueue.Clear();
try
{
client = new TcpClient();
Console.WriteLine("Connecting...");
client.Connect("localhost", 2244);
Console.WriteLine("Connected");
receiveBufSize = client.ReceiveBufferSize;
stream = client.GetStream();
thRead = new Thread(ReadThread);
thRead.Start();
thWrite = new Thread(WriteThread);
thWrite.Start();
IsConnecting = false;
break;
}
catch (SocketException ex)
{
Console.WriteLine(ex);
Thread.Sleep(3000);
}
}
}
19
View Source File : FileReader.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public static StreamReader OpenFile(string fileName, Encoding defaultEncoding)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
try {
return OpenStream(fs, defaultEncoding);
// don't use finally: the stream must be kept open until the StreamReader closes it
} catch {
fs.Dispose();
throw;
}
}
19
View Source File : AudioOut.cs
License : Apache License 2.0
Project Creator : ac87
License : Apache License 2.0
Project Creator : ac87
public void AddBytesToPlay(byte[] bytes)
{
if (_waveOut == null)
{
_waveOut = new WaveOut();
_waveOut.PlaybackStopped += (sender, args) =>
{
_waveStream.Dispose();
_ms.Dispose();
_ms = null;
OnAudioPlaybackStateChanged?.Invoke(false);
};
}
if (_ms == null)
_ms = new MemoryStream();
_ms.Write(bytes, 0, bytes.Length);
}
19
View Source File : ProcessChannel.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void Dispose(bool disposing)
{
if (disposing)
{
_inServer?.Dispose();
_outServer?.Dispose();
_inClient?.Dispose();
_outClient?.Dispose();
}
}
See More Examples