Here are the examples of the csharp api System.IO.MemoryStream.WriteByte(byte) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
658 Examples
19
Source : InMemoryUploadStream.cs
with MIT License
from disunity-hq
with MIT License
from disunity-hq
public override void WriteByte(byte value) {
_buffer.WriteByte(value);
}
19
Source : HttpUtility.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
public static string UrlDecode (byte [] bytes, int offset, int count, Encoding e)
{
if (bytes == null)
return null;
if (count == 0)
return String.Empty;
if (bytes == null)
throw new ArgumentNullException ("bytes");
if (offset < 0 || offset > bytes.Length)
throw new ArgumentOutOfRangeException ("offset");
if (count < 0 || offset + count > bytes.Length)
throw new ArgumentOutOfRangeException ("count");
StringBuilder output = new StringBuilder ();
MemoryStream acc = new MemoryStream ();
int end = count + offset;
int xchar;
for (int i = offset; i < end; i++) {
if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
if (acc.Length > 0) {
output.Append (GetChars (acc, e));
acc.SetLength (0);
}
xchar = GetChar (bytes, i + 2, 4);
if (xchar != -1) {
output.Append ((char) xchar);
i += 5;
continue;
}
} else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
acc.WriteByte ((byte) xchar);
i += 2;
continue;
}
}
if (acc.Length > 0) {
output.Append (GetChars (acc, e));
acc.SetLength (0);
}
if (bytes [i] == '+') {
output.Append (' ');
} else {
output.Append ((char) bytes [i]);
}
}
if (acc.Length > 0) {
output.Append (GetChars (acc, e));
}
acc = null;
return output.ToString ();
}
19
Source : HttpUtility.cs
with MIT License
from dotnet-campus
with MIT License
from dotnet-campus
public static byte [] UrlDecodeToBytes (byte [] bytes, int offset, int count)
{
if (bytes == null)
return null;
if (count == 0)
return new byte [0];
int len = bytes.Length;
if (offset < 0 || offset >= len)
throw new ArgumentOutOfRangeException("offset");
if (count < 0 || offset > len - count)
throw new ArgumentOutOfRangeException("count");
MemoryStream result = new MemoryStream ();
int end = offset + count;
for (int i = offset; i < end; i++){
char c = (char) bytes [i];
if (c == '+') {
c = ' ';
} else if (c == '%' && i < end - 2) {
int xchar = GetChar (bytes, i + 1, 2);
if (xchar != -1) {
c = (char) xchar;
i += 2;
}
}
result.WriteByte ((byte) c);
}
return result.ToArray ();
}
19
Source : Mjpeg.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public static byte[] ProcessMjpegFrame(List<RTPPacket> framePackets)
{
uint TypeSpecific, FragmentOffset, Type, type, Quality, Width, Height;
ushort RestartInterval = 0, RestartCount = 0;
//A byte which is bit mapped
byte PrecisionTable = 0;
ArraySegment<byte> tables = default(ArraySegment<byte>);
//Using a new MemoryStream for a Buffer
using (System.IO.MemoryStream Buffer = new System.IO.MemoryStream())
{
//Loop each packet
foreach (RTPPacket packet in framePackets.OrderBy(x => x.Header.SequenceNumber))
{
//Payload starts at offset 0
int offset = 0;
//Handle Extension Headers
//if (packet.Extensions)
//{
// This could be OnVif extension etc
// http://www.onvif.org/specs/stream/ONVIF-Streaming-Spec-v220.pdf
// Decode
// packet.ExtensionBytes;
// In a Derived Implementation
//}
//Decode RtpJpeg Header
TypeSpecific = (uint)(packet.Payload[offset++]);
FragmentOffset = (uint)(packet.Payload[offset++] << 16 | packet.Payload[offset++] << 8 | packet.Payload[offset++]);
#region RFC2435 - The Type Field
/*
4.1. The Type Field
The Type field defines the abbreviated table-specification and
additional JFIF-style parameters not defined by JPEG, since they are
not present in the body of the transmitted JPEG data.
Three ranges of the type field are currently defined. Types 0-63 are
reserved as fixed, well-known mappings to be defined by this doreplacedent
and future revisions of this doreplacedent. Types 64-127 are the same as
types 0-63, except that restart markers are present in the JPEG data
and a Restart Marker header appears immediately following the main
JPEG header. Types 128-255 are free to be dynamically defined by a
session setup protocol (which is beyond the scope of this doreplacedent).
Of the first group of fixed mappings, types 0 and 1 are currently
defined, along with the corresponding types 64 and 65 that indicate
the presence of restart markers. They correspond to an abbreviated
table-specification indicating the "Baseline DCT sequential" mode,
8-bit samples, square pixels, three components in the YUV color
space, standard Huffman tables as defined in [1, Annex K.3], and a
single interleaved scan with a scan component selector indicating
components 1, 2, and 3 in that order. The Y, U, and V color planes
correspond to component numbers 1, 2, and 3, respectively. Component
1 (i.e., the luminance plane) uses Huffman table number 0 and
quantization table number 0 (defined below) and components 2 and 3
(i.e., the chrominance planes) use Huffman table number 1 and
quantization table number 1 (defined below).
Type numbers 2-5 are reserved and SHOULD NOT be used. Applications
based on previous versions of this doreplacedent (RFC 2035) should be
updated to indicate the presence of restart markers with type 64 or
65 and the Restart Marker header.
The two RTP/JPEG types currently defined are described below:
horizontal vertical Quantization
types component samp. fact. samp. fact. table number
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | 1 (Y) | 2 | 1 | 0 |
| 0, 64 | 2 (U) | 1 | 1 | 1 |
| | 3 (V) | 1 | 1 | 1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | 1 (Y) | 2 | 2 | 0 |
| 1, 65 | 2 (U) | 1 | 1 | 1 |
| | 3 (V) | 1 | 1 | 1 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
These sampling factors indicate that the chrominance components of
type 0 video is downsampled horizontally by 2 (often called 4:2:2)
while the chrominance components of type 1 video are downsampled both
horizontally and vertically by 2 (often called 4:2:0).
Types 0 and 1 can be used to carry both progressively scanned and
interlaced image data. This is encoded using the Type-specific field
in the main JPEG header. The following values are defined:
0 : Image is progressively scanned. On a computer monitor, it can
be displayed as-is at the specified width and height.
1 : Image is an odd field of an interlaced video signal. The
height specified in the main JPEG header is half of the height
of the entire displayed image. This field should be de-
interlaced with the even field following it such that lines
from each of the images alternate. Corresponding lines from
the even field should appear just above those same lines from
the odd field.
2 : Image is an even field of an interlaced video signal.
3 : Image is a single field from an interlaced video signal, but
it should be displayed full frame as if it were received as
both the odd & even fields of the frame. On a computer
monitor, each line in the image should be displayed twice,
doubling the height of the image.
*/
#endregion
Type = (uint)(packet.Payload[offset++]);
type = Type & 1;
if (type > 3 || type > 6) throw new ArgumentException("Type numbers 2-5 are reserved and SHOULD NOT be used. Applications on RFC 2035 should be updated to indicate the presence of restart markers with type 64 or 65 and the Restart Marker header.");
Quality = packet.Payload[offset++];
Width = (uint)(packet.Payload[offset++] * 8); // This should have been 128 or > and the standard would have worked for all resolutions
Height = (uint)(packet.Payload[offset++] * 8);// Now in certain highres profiles you will need an OnVif extension before the RtpJpeg Header
//It is worth noting Rtp does not care what you send and more tags such as comments and or higher resolution pictures may be sent and these values will simply be ignored.
if(Width == 0 || Height == 0)
{
//, Width, Height
logger.Warn("ProcessMjpegFrame could not determine either the width:" + Width + " or height: "+ Height + "of the jpeg frame");
}
//Restart Interval 64 - 127
if (Type > 63 && Type < 128)
{
/*
This header MUST be present immediately after the main JPEG header
when using types 64-127. It provides the additional information
required to properly decode a data stream containing restart markers.
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Restart Interval |F|L| Restart Count |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
RestartInterval = (ushort)(packet.Payload[offset++] << 8 | packet.Payload[offset++]);
RestartCount = (ushort)((packet.Payload[offset++] << 8 | packet.Payload[offset++]) & 0x3fff);
}
//QTables Only occur in the first packet
if (FragmentOffset == 0)
{
//If the quality > 127 there are usually Quantization Tables
if (Quality > 127)
{
if ((packet.Payload[offset++]) != 0)
{
//Must Be Zero is Not Zero
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
}
//Precision
PrecisionTable = (packet.Payload[offset++]);
#region RFC2435 Length Field
/*
The Length field is set to the length in bytes of the quantization
table data to follow. The Length field MAY be set to zero to
indicate that no quantization table data is included in this frame.
See section 4.2 for more information. If the Length field in a
received packet is larger than the remaining number of bytes, the
packet MUST be discarded.
When table data is included, the number of tables present depends on
the JPEG type field. For example, type 0 uses two tables (one for
the luminance component and one shared by the chrominance
components). Each table is an array of 64 values given in zig-zag
order, identical to the format used in a JFIF DQT marker segment.
For each quantization table present, a bit in the Precision field
specifies the size of the coefficients in that table. If the bit is
zero, the coefficients are 8 bits yielding a table length of 64
bytes. If the bit is one, the coefficients are 16 bits for a table
length of 128 bytes. For 16 bit tables, the coefficients are
presented in network byte order. The rightmost bit in the Precision
field (bit 15 in the diagram above) corresponds to the first table
and each additional table uses the next bit to the left. Bits beyond
those corresponding to the tables needed by the type in use MUST be
ignored.
*/
#endregion
//Length of all tables
ushort Length = (ushort)(packet.Payload[offset++] << 8 | packet.Payload[offset++]);
//If there is Table Data Read it
if (Length > 0)
{
tables = new ArraySegment<byte>(packet.Payload, offset, (int)Length);
offset += (int)Length;
}
else if (Length > packet.Payload.Length - offset)
{
continue; // The packet must be discarded
}
else // Create it from the Quality
{
tables = new ArraySegment<byte>(CreateQuantizationTables(Quality, type, PrecisionTable));
}
}
else // Create from the Quality
{
tables = new ArraySegment<byte>(CreateQuantizationTables(type, Quality, PrecisionTable));
}
byte[] header = CreateJFIFHeader(type, Width, Height, tables, PrecisionTable, RestartInterval);
Buffer.Write(header, 0, header.Length);
}
//Write the Payload data from the offset
Buffer.Write(packet.Payload, offset, packet.Payload.Length - offset);
}
//Check for EOI Marker
Buffer.Seek(-1, System.IO.SeekOrigin.Current);
if (Buffer.ReadByte() != Tags.EndOfInformation)
{
Buffer.WriteByte(Tags.Prefix);
Buffer.WriteByte(Tags.EndOfInformation);
}
//Go back to the beginning
Buffer.Position = 0;
//This article explains in detail what exactly happens: http://support.microsoft.com/kb/814675
//In short, for a lifetime of an Image constructed from a stream, the stream must not be destroyed.
//Image = new System.Drawing.Bitmap(System.Drawing.Image.FromStream(Buffer, true, true));
//DO NOT USE THE EMBEDDED COLOR MANGEMENT
// Image = System.Drawing.Image.FromStream(Buffer, false, true);
return Buffer.GetBuffer();
}
}
19
Source : PSAnalyze.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public override void WriteByte(byte value) {
lock (_sync) {
base.Position = _lastWritePosition;
base.WriteByte(value);
_lastWritePosition = Position;
}
}
19
Source : TSPacket.cs
with BSD 2-Clause "Simplified" License
from double-hi
with BSD 2-Clause "Simplified" License
from double-hi
public byte[] GetBytes() {
byte[] result = new byte[188];
var ms = new MemoryStream(result);
ms.Position = 0;
byte[] head = new byte[4];
head[0] = 0x47;
head[1] = (byte)((transport_error_indicator << 7) | (payload_unit_start_indicator << 6) | (transport_priority << 5) | (PID >> 8 & 0x001f));
head[2] = (byte)(PID & 0x00ff);
head[3] = (byte)((transport_scrambling_control << 6) | (adaptation_field_control << 4) | (continuity_counter & 0x0F));
ms.Write(head, 0, head.Length);
if (payload_unit_start_indicator == 1 && adaptation_field_control != 3)
ms.WriteByte(0x00);//1个字节的占位
if (AdaptationField != null) {
var adapBuffer = AdaptationField.GetBytes();
ms.Write(adapBuffer, 0, adapBuffer.Length);
}
if (data != null) {
ms.Write(data, 0, data.Length);
}
return result;
}
19
Source : MpqStream.cs
with MIT License
from Drake53
with MIT License
from Drake53
private Stream GetCompressedStream(Stream baseStream, MpqFileFlags targetFlags, MpqCompressionType compressionType, int targetBlockSize)
{
var resultStream = new MemoryStream();
var singleUnit = targetFlags.HasFlag(MpqFileFlags.SingleUnit);
void TryCompress(uint bytes)
{
var offset = baseStream.Position;
var compressedStream = compressionType switch
{
MpqCompressionType.ZLib => ZLibCompression.Compress(baseStream, (int)bytes, true),
_ => throw new NotSupportedException(),
};
// Add one because CompressionType byte not written yet.
var length = compressedStream.Length + 1;
if (!singleUnit && length >= bytes)
{
baseStream.CopyTo(resultStream, offset, (int)bytes, StreamExtensions.DefaultBufferSize);
}
else
{
resultStream.WriteByte((byte)compressionType);
compressedStream.Position = 0;
compressedStream.CopyTo(resultStream);
}
compressedStream.Dispose();
if (singleUnit)
{
baseStream.Dispose();
}
}
19
Source : StringExtensions.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
public static IObservable<string> ToStrings(this IObservable<byte> source)
{
MemoryStream ms = new();
return Observable.Create<string>(observer =>
{
return source.Subscribe(
onNext: b =>
{
if (b != 0)
{
ms.WriteByte(b);
return;
}
string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);
observer.OnNext(s);
ms.SetLength(0);
},
onError: observer.OnError,
onCompleted: () =>
{
if (ms.Position == 0)
observer.OnCompleted();
else
observer.OnError(new InvalidDataException("ToStrings: invalid termination."));
});
});
}
19
Source : ToStringArraysTest.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
private void AddMessage(string str)
{
var start = ms.Position;
ms.Position += 4;
Encoding.UTF8.GetBytes(str).ToList().ForEach(ms.WriteByte);
ms.WriteByte(0);
var len = Convert.ToInt32(ms.Position - start - 4);
var prefix = IPAddress.NetworkToHostOrder(len);
var lastPos = ms.Position;
ms.Position = start;
BitConverter.GetBytes(prefix).ToList().ForEach(ms.WriteByte);
ms.Position = lastPos;
}
19
Source : LengthPrefixExtensions.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
public static IEnumerable<byte[]> ToArraysFromBytesWithLengthPrefix(this IEnumerable<byte> source)
{
int length = -1;
MemoryStream ms = new();
foreach (byte b in source)
{
ms.WriteByte(b);
if (length == -1 && ms.Position == 4)
{
length = DecodeMessageLength(ms);
ms.SetLength(0);
}
else if (length == ms.Length)
{
yield return ms.ToArray(); // array copy
length = -1;
ms.SetLength(0);
}
}
if (ms.Position != 0)
throw new InvalidDataException($"Invalid length: {length}.");
}
19
Source : LengthPrefixExtensions.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
public static async IAsyncEnumerable<byte[]> ToArraysFromBytesWithLengthPrefix(this IAsyncEnumerable<byte> source)
{
int length = -1;
MemoryStream ms = new();
await foreach (byte b in source.ConfigureAwait(false))
{
ms.WriteByte(b);
if (length == -1 && ms.Position == 4)
{
length = DecodeMessageLength(ms);
ms.SetLength(0);
}
else if (length == ms.Length)
{
yield return ms.ToArray(); // array copy
length = -1;
ms.SetLength(0);
}
}
if (ms.Position != 0)
throw new InvalidDataException("ToArraysFromBytesWithLengthPrefix: invalid termination.");
}
19
Source : LengthPrefixExtensions.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
public static IObservable<byte[]> ToArraysFromBytesWithLengthPrefix(this IObservable<byte> source)
{
int length = -1;
MemoryStream ms = new();
return Observable.Create<byte[]>(observer =>
{
return source.Subscribe(
onNext: b =>
{
ms.WriteByte(b);
if (length == -1 && ms.Position == 4)
{
length = DecodeMessageLength(ms);
ms.SetLength(0);
}
else if (length == ms.Length)
{
observer.OnNext(ms.ToArray()); // array copy
length = -1;
ms.SetLength(0);
}
},
onError: observer.OnError,
onCompleted: () =>
{
if (ms.Position == 0)
observer.OnCompleted();
else
observer.OnError(new InvalidDataException("ToArraysFromBytesWithLengthPrefix: incomplete."));
});
});
}
19
Source : StringExtensions.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
public static IEnumerable<string> ToStrings(this IEnumerable<byte> source)
{
MemoryStream ms = new();
foreach (byte b in source)
{
if (b != 0)
{
ms.WriteByte(b);
continue;
}
string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);
ms.SetLength(0);
yield return s;
}
if (ms.Position != 0)
throw new InvalidDataException("ToStrings: no termination(1).");
}
19
Source : StringExtensions.cs
with Apache License 2.0
from dshe
with Apache License 2.0
from dshe
public static async IAsyncEnumerable<string> ToStrings(this IAsyncEnumerable<byte> source)
{
MemoryStream ms = new();
await foreach (byte b in source.ConfigureAwait(false))
{
if (b != 0)
{
ms.WriteByte(b);
continue;
}
string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Position);
ms.SetLength(0);
yield return s;
}
if (ms.Position != 0)
throw new InvalidDataException("ToStrings: invalid termination.");
}
19
Source : ImageAttrib.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
private static byte[] ToByteArray(
Format imageType,
byte[] imageData)
{
MemoryStream bOut = new MemoryStream();
bOut.WriteByte(0x10); bOut.WriteByte(0x00); bOut.WriteByte(0x01);
bOut.WriteByte((byte) imageType);
bOut.Write(Zeroes, 0, Zeroes.Length);
bOut.Write(imageData, 0, imageData.Length);
return bOut.ToArray();
}
19
Source : NotationData.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
private static byte[] createData(
bool humanReadable,
string notationName,
string notationValue)
{
MemoryStream os = new MemoryStream();
// (4 octets of flags, 2 octets of name length (M),
// 2 octets of value length (N),
// M octets of name data,
// N octets of value data)
// flags
os.WriteByte(humanReadable ? (byte)0x80 : (byte)0x00);
os.WriteByte(0x0);
os.WriteByte(0x0);
os.WriteByte(0x0);
byte[] nameData, valueData = null;
int nameLength, valueLength;
nameData = Encoding.UTF8.GetBytes(notationName);
nameLength = System.Math.Min(nameData.Length, 0xFF);
valueData = Encoding.UTF8.GetBytes(notationValue);
valueLength = System.Math.Min(valueData.Length, 0xFF);
// name length
os.WriteByte((byte)(nameLength >> 8));
os.WriteByte((byte)(nameLength >> 0));
// value length
os.WriteByte((byte)(valueLength >> 8));
os.WriteByte((byte)(valueLength >> 0));
// name
os.Write(nameData, 0, nameLength);
// value
os.Write(valueData, 0, valueLength);
return os.ToArray();
}
19
Source : CcmBlockCipher.cs
with GNU General Public License v3.0
from DSorlov
with GNU General Public License v3.0
from DSorlov
public virtual int ProcessByte(
byte input,
byte[] outBytes,
int outOff)
{
data.WriteByte(input);
return 0;
}
19
Source : ByteBuffer.cs
with Apache License 2.0
from eaba
with Apache License 2.0
from eaba
public ByteBuffer Put(byte b)
{
stream.WriteByte(b);
return this;
}
19
Source : TcpServer.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
private void HandleClientComm(object pcb)
{
PCB p = (PCB)pcb;
System.Net.Sockets.TcpClient tcpClient = p.Client;
object lockObj = new object();
try
{
try
{
OnConnectEstablishEvent(new ConnectEstablishEventArgs(p.ThreadId));
}
catch (Exception e)
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
}
System.Net.Sockets.NetworkStream clientStream = tcpClient.GetStream();
TcpCacheStream tcpStream = new TcpCacheStream(clientStream);
while (true)
{
MessageHead msgHead = new MessageHead();
try
{
bool disconnected = false;
object msg = null;
//Recevie data
//Stream tcpStream = clientStream;
byte[] revBuf = new byte[4];
int offset = 0;
while (offset < 4)
{
int len;
try
{
len = tcpStream.Read(revBuf, offset, 4 - offset);
}
catch
{
disconnected = true;
break;
}
if (len == 0)
{
//Disconnect
disconnected = true;
break;
}
offset += len;
}
if (disconnected)
{
break;
}
msgHead.Event = BitConverter.ToInt16(revBuf, 0);
msgHead.Flag = (MessageFlag)BitConverter.ToInt16(revBuf, 2);
bool isAsync = (msgHead.Flag & MessageFlag.ASyncMessage) != 0;
int clreplacedId = -1;
if (isAsync)
{
if (!Hubble.Framework.IO.Stream.ReadToBuf(tcpStream, revBuf, 0, 4))
{
disconnected = true;
break;
}
else
{
clreplacedId = BitConverter.ToInt32(revBuf, 0);
}
}
if ((msgHead.Flag & MessageFlag.NullData) == 0)
{
if ((msgHead.Flag & MessageFlag.CustomSerialization) != 0)
{
if (RequireCustomSerialization != null)
{
Hubble.Framework.Serialization.IMySerialization mySerializer =
RequireCustomSerialization(msgHead.Event, null);
if (mySerializer == null)
{
throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
msgHead.Event));
}
msg = mySerializer.Deserialize(tcpStream, mySerializer.Version);
}
else
{
throw new Exception("RequireCustomSerialization of TcpClient is null!");
}
}
else if ((msgHead.Flag & MessageFlag.IsString) == 0)
{
IFormatter formatter = new BinaryFormatter();
msg = formatter.Deserialize(tcpStream);
}
else
{
if ((msgHead.Flag & MessageFlag.IsString) != 0 &&
(msgHead.Flag & MessageFlag.ASyncMessage) != 0)
{
MemoryStream m = new MemoryStream();
byte b = (byte)tcpStream.ReadByte();
while (b != 0)
{
m.WriteByte(b);
b = (byte)tcpStream.ReadByte();
}
m.Position = 0;
using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
{
msg = sr.ReadToEnd();
}
}
else
{
MemoryStream m = new MemoryStream();
byte[] buf = new byte[1024];
int len = 0;
do
{
len = tcpStream.Read(buf, 0, buf.Length);
if (buf[len - 1] == 0)
{
m.Write(buf, 0, len - 1);
break;
}
else
{
m.Write(buf, 0, len);
}
} while (true);
m.Position = 0;
using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
{
msg = sr.ReadToEnd();
}
}
}
}
MessageReceiveEventArgs receiveEvent = new MessageReceiveEventArgs(
this, msgHead, msg, p.ThreadId, clreplacedId, tcpClient,
clientStream, lockObj);
Hubble.Framework.Serialization.IMySerialization customSerializer = null;
try
{
OnMessageReceiveEvent(receiveEvent);
customSerializer = receiveEvent.CustomSerializtion;
}
catch (System.Threading.ThreadAbortException)
{
receiveEvent.ReturnMsg = new System.Threading.ThreadInterruptedException("Thread abort. Maybe execute select too long. Please check the error log.");
System.Threading.Thread.ResetAbort();
}
catch (Exception e)
{
receiveEvent.ReturnMsg = e;
}
if (!isAsync)
{
ReturnMessage(lockObj, tcpClient, msgHead, receiveEvent.ReturnMsg, customSerializer);
}
}
catch (Exception innerException)
{
try
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(msgHead, innerException));
}
catch
{
}
if (tcpClient.Connected)
{
tcpClient.Close();
}
throw innerException;
}
}
tcpClient.Close();
}
catch (Exception e)
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
}
finally
{
try
{
OnDisconnectEvent(new DisconnectEventArgs(p.ThreadId));
}
catch (Exception e)
{
OnMessageReceiveErrorEvent(new MessageReceiveErrorEventArgs(e));
}
RetPCB(p);
}
}
19
Source : TcpClient.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
private void AsyncMessageRecv()
{
TcpCacheStream tcpStream = new TcpCacheStream(_ClientStream);
while (true)
{
try
{
object result;
//Recevie data
byte[] revBuf = new byte[8];
int offset = 0;
while (offset < 8)
{
int len = tcpStream.Read(revBuf, offset, 8 - offset);
if (len == 0)
{
throw new Exception("Tcp stream closed!");
}
offset += len;
}
MessageHead head = new MessageHead();
head.Event = BitConverter.ToInt16(revBuf, 0);
head.Flag = (MessageFlag)BitConverter.ToInt16(revBuf, 2);
int clreplacedId = BitConverter.ToInt32(revBuf, 4);
if ((head.Flag & MessageFlag.NullData) == 0)
{
if ((head.Flag & MessageFlag.CustomSerialization) != 0)
{
if (RequireCustomSerialization != null)
{
Hubble.Framework.Serialization.IMySerialization mySerializer =
RequireCustomSerialization(head.Event, null);
if (mySerializer == null)
{
throw new Exception(string.Format("RequireCustomSerialization of Event = {0} is null!",
head.Event));
}
result = mySerializer.Deserialize(tcpStream, mySerializer.Version);
}
else
{
throw new Exception("RequireCustomSerialization of TcpClient is null!");
}
}
else if ((head.Flag & MessageFlag.IsString) == 0)
{
IFormatter formatter = new BinaryFormatter();
result = formatter.Deserialize(tcpStream);
}
else
{
MemoryStream m = new MemoryStream();
byte b = (byte)tcpStream.ReadByte();
while (b != 0)
{
m.WriteByte(b);
b = (byte)tcpStream.ReadByte();
}
m.Position = 0;
using (StreamReader sr = new StreamReader(m, Encoding.UTF8))
{
result = sr.ReadToEnd();
}
if ((head.Flag & MessageFlag.IsException) != 0)
{
string[] strs = Hubble.Framework.Text.Regx.Split(result as string, "innerStackTrace:");
result = new InnerServerException(strs[0], strs[1]);
}
}
if (AsyncMessageRecieved != null)
{
AsyncMessageRecieved(new ASyncPackage(clreplacedId, result));
}
}
}
catch(Exception e)
{
lock (this)
{
Close();
}
ThreadClosed = true;
if (AsyncMessageRecieved != null)
{
AsyncMessageRecieved(new ASyncPackage(-1, new TcpRemoteCloseException(e.Message)));
}
return;
}
}
}
19
Source : UnicodeString.cs
with Apache License 2.0
from eaglet2006
with Apache License 2.0
from eaglet2006
public static int Encode(MemoryStream tempMem, byte[] buffer, int index, string word, string preString, long position, long length)
{
tempMem.Position = 0;
VLong vPosition = new VLong(position);
VLong vLength = new VLong(length);
int i = 0;
while (i < preString.Length)
{
if (i >= word.Length)
{
break;
}
if (preString[i] == 0)
{
//PreString end with zero
break;
}
if (word[i] == preString[i])
{
i++;
}
else
{
break;
}
}
int preMatchLen = i;
if (preMatchLen >= word.Length)
{
throw new System.IO.IOException(string.Format("Reduplicate word:{0} in head!", word));
}
tempMem.WriteByte((byte)preMatchLen);
vPosition.WriteToStream(tempMem);
vLength.WriteToStream(tempMem);
byte[] utf8Buffer = Encoding.UTF8.GetBytes(word.Substring(preMatchLen, word.Length - preMatchLen));
tempMem.Write(utf8Buffer, 0, utf8Buffer.Length);
long tempMemLen = tempMem.Position;
if (tempMemLen + 1 >= 256)
{
throw new System.IO.IOException(string.Format("Word:{0} is too long to insert to head!", word));
}
if (tempMemLen + 1 >= buffer.Length - index)
{
return -1;
}
buffer[index] = (byte)tempMemLen;
index++;
tempMem.Position = 0;
tempMem.Read(buffer, index, (int)tempMemLen);
return (int)(index + tempMemLen);
}
19
Source : Interop.cs
with MIT License
from egramtel
with MIT License
from egramtel
internal static string IntPtrToString(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
{
return null;
}
using (var data = new MemoryStream())
{
int offset = 0;
while (true)
{
byte b = Marshal.ReadByte(ptr, offset++);
if (b == 0)
{
break;
}
data.WriteByte(b);
}
return Encoding.UTF8.GetString(data.ToArray());
}
}
19
Source : NodeProviderOutOfProcBase.cs
with MIT License
from enricosada
with MIT License
from enricosada
public void SendData(INodePacket packet)
{
MemoryStream writeStream = new MemoryStream();
INodePacketTranslator writeTranslator = NodePacketTranslator.GetWriteTranslator(writeStream);
try
{
writeStream.WriteByte((byte)packet.Type);
// Pad for the packet length
writeStream.Write(BitConverter.GetBytes((int)0), 0, 4);
packet.Translate(writeTranslator);
// Now plug in the real packet length
writeStream.Position = 1;
writeStream.Write(BitConverter.GetBytes((int)writeStream.Length - 5), 0, 4);
#if FALSE
if (trace) // Avoid method call
{
CommunicationsUtilities.Trace(nodeId, "Sending Packet of type {0} with length {1}", packet.Type.ToString(), writeStream.Length - 5);
}
#endif
#if FEATURE_MEMORYSTREAM_GETBUFFER
byte[] writeStreamBuffer = writeStream.GetBuffer();
#else
byte[] writeStreamBuffer = writeStream.ToArray();
#endif
for (int i = 0; i < writeStream.Length; i += MaxPacketWriteSize)
{
int lengthToWrite = Math.Min((int)writeStream.Length - i, MaxPacketWriteSize);
if ((int)writeStream.Length - i <= MaxPacketWriteSize)
{
// We are done, write the last bit asynchronously. This is actually the general case for
// most packets in the build, and the asynchronous behavior here is desirable.
#if FEATURE_APM
_serverToClientStream.BeginWrite(writeStreamBuffer, i, lengthToWrite, PacketWriteComplete, null);
#else
_serverToClientStream.WriteAsync(writeStreamBuffer, i, lengthToWrite);
#endif
return;
}
else
{
// If this packet is longer that we can write in one go, then we need to break it up. We can't
// return out of this function and let the rest of the system continue because another operation
// might want to send data immediately afterward, and that could result in overlapping writes
// to the pipe on different threads.
#if FEATURE_APM
IAsyncResult result = _serverToClientStream.BeginWrite(writeStream.GetBuffer(), i, lengthToWrite, null, null);
_serverToClientStream.EndWrite(result);
#else
_serverToClientStream.Write(writeStreamBuffer, i, lengthToWrite);
#endif
}
}
}
catch (IOException e)
{
// Do nothing here because any exception will be caught by the async read handler
CommunicationsUtilities.Trace(_nodeId, "EXCEPTION in SendData: {0}", e);
}
catch (ObjectDisposedException) // This happens if a child dies unexpectedly
{
// Do nothing here because any exception will be caught by the async read handler
}
}
19
Source : SharedMemory.cs
with MIT License
from enricosada
with MIT License
from enricosada
internal void Write(DualQueue<LocalCallDescriptor> objectsToWrite, DualQueue<LocalCallDescriptor> objectsToWriteHiPriority, bool blockUntilDone)
{
Debug.replacedert(type == SharedMemoryType.WriteOnly, "Should only be calling Write from a writeonly shared memory object");
lock (writeLock)
{
// Loop as long as there are objects availiable and room in the shared memory.
// If blockUntilDone is set continue to loop until all of the objects in both queues are sent.
while ((objectsToWrite.Count > 0 || objectsToWriteHiPriority.Count > 0) &&
((blockUntilDone && notFullFlag.WaitOne()) || !IsFull))
{
bool isFull = false;
long writeStartPosition = writeStream.Position;
bool writeEndMarker = false;
// Put as many LocalCallDescriptor objects as possible into the shared memory
while (!isFull && (objectsToWrite.Count > 0 || objectsToWriteHiPriority.Count > 0))
{
long writeResetPosition = writeStream.Position;
DualQueue<LocalCallDescriptor> currentQueue = objectsToWriteHiPriority.Count > 0 ? objectsToWriteHiPriority : objectsToWrite;
// writeBytesRemaining == 0 is when we are currently not sending a multi part object through
// the shared memory
if (writeBytesRemaining == 0)
{
// Serialize the object to the memory stream
SerializeCallDescriptorToStream(currentQueue);
// If the size of the serialized object plus the end marker fits within the shared memory
// dequeue the object as it is going to be sent.
if ((writeStream.Position + sizeof(byte)) <= size)
{
currentQueue.Dequeue();
writeEndMarker = true;
}
else
{
// The serialized object plus the end marker is larger than the shared memory buffer
// Check if it necessary break down the object into multiple buffers
// If the memoryStream was empty before trying to serialize the object
// create a frame marker with the size of the object and send through the shared memory
if (writeResetPosition == 0)
{
// We don't want to switch from low priority to high priority queue in the middle of sending a large object
// so we make a record of which queue contains the large object
largeObjectsQueue = currentQueue;
// Calculate the total number of bytes that needs to be sent
writeBytesRemaining = (int)(writeStream.Position + sizeof(byte));
// Send a frame marker out to the reader containing the size of the object
writeStream.Position = 0;
// Write the frameMarkerId byte and then the amount of bytes for the large object
writeStream.WriteByte((byte)ObjectType.FrameMarker);
binaryWriter.Write((Int32)writeBytesRemaining);
writeEndMarker = true;
}
else
{
// Some items were placed in the shared Memory buffer, erase the last one which was too large
// and say the buffer is full so it can be sent
writeStream.Position = writeResetPosition;
}
isFull = true;
}
}
else
{
if (writeStream.Position == 0)
{
// Serialize the object which will be split across multiple buffers
SerializeCallDescriptorToStream(largeObjectsQueue);
writeStream.WriteByte((byte)ObjectType.EndMarker);
}
break;
}
}
// If a multi-buffer object is being sent and the large object is still larger or equal to the shard memory buffer - send the next chunk of the object
if (writeBytesRemaining != 0 && writeStream.Position >= size)
{
// Set write Length to an entire buffer length or just the remaining portion
int writeLength = writeBytesRemaining > size ? size : writeBytesRemaining;
//Write the length of the buffer to the memory file
Marshal.WriteInt32((IntPtr)pageFileView, (int)writeLength);
Marshal.Copy
(
writeStream.GetBuffer(), // Source Buffer
(int)(writeStream.Position - writeBytesRemaining), // Start index
(IntPtr)((int)pageFileView + 4), //Destination (+4 because of the int written to the memory file with the write length)
(int)writeLength // Length of bytes to write
);
writeBytesRemaining = writeBytesRemaining - writeLength;
IncrementUnreadBatchCounter();
// Once the object is fully sent - remove it from the queue
if (writeBytesRemaining == 0)
{
largeObjectsQueue.Dequeue();
}
isFull = true;
}
if (writeEndMarker)
{
writeStream.WriteByte((byte)ObjectType.EndMarker);
// Need to verify the WriteInt32 and ReadInt32 are always atomic operations
//writeSizeMutex.WaitOne();
// Write the size of the buffer to send to the memory stream
Marshal.WriteInt32((IntPtr)pageFileView, (int)writeStream.Position);
//writeSizeMutex.ReleaseMutex();
Marshal.Copy
(
writeStream.GetBuffer(), // Buffer
(int)writeStartPosition, // Start Position
(IntPtr)((int)pageFileView + writeStartPosition + 4), // Destination + 4 for the int indicating the size of the data to be copied to the memory file
(int)(writeStream.Position - writeStartPosition) // Length of data to copy to memory file
);
IncrementUnreadBatchCounter();
}
if (isFull)
{
MarkAsFull();
writeStream.SetLength(0);
}
}
}
}
19
Source : SharedMemory.cs
with MIT License
from enricosada
with MIT License
from enricosada
private void SerializeCallDescriptorToStream(DualQueue<LocalCallDescriptor> objectsToWrite)
{
// Get the object by peeking at the queue rather than dequeueing the object. This is done
// because we only want to dequeue the object when it has completely been put in shared memory.
// This may be done right away if the object is small enough to fit in the shared memory or
// may happen after a the object is sent as a number of smaller chunks.
object objectToWrite = objectsToWrite.Peek();
Debug.replacedert(objectToWrite != null, "Expect to get a non-null object from the queue");
if (objectToWrite is LocalCallDescriptorForPostBuildResult)
{
writeStream.WriteByte((byte)ObjectType.PostBuildResult);
((LocalCallDescriptorForPostBuildResult)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForPostBuildRequests)
{
writeStream.WriteByte((byte)ObjectType.PostBuildRequests);
((LocalCallDescriptorForPostBuildRequests)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForPostLoggingMessagesToHost)
{
writeStream.WriteByte((byte)ObjectType.PostLoggingMessagesToHost);
((LocalCallDescriptorForPostLoggingMessagesToHost)objectToWrite).WriteToStream(binaryWriter, loggingTypeCache);
}
else if (objectToWrite is LocalCallDescriptorForInitializeNode)
{
writeStream.WriteByte((byte)ObjectType.InitializeNode);
((LocalCallDescriptorForInitializeNode)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForInitializationComplete)
{
writeStream.WriteByte((byte)ObjectType.InitializationComplete);
((LocalCallDescriptorForInitializationComplete)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForUpdateNodeSettings)
{
writeStream.WriteByte((byte)ObjectType.UpdateNodeSettings);
((LocalCallDescriptorForUpdateNodeSettings)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForRequestStatus)
{
writeStream.WriteByte((byte)ObjectType.RequestStatus);
((LocalCallDescriptorForRequestStatus)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForPostingCacheEntriesToHost)
{
writeStream.WriteByte((byte)ObjectType.PostCacheEntriesToHost);
((LocalCallDescriptorForPostingCacheEntriesToHost)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForGettingCacheEntriesFromHost)
{
writeStream.WriteByte((byte)ObjectType.GetCacheEntriesFromHost);
((LocalCallDescriptorForGettingCacheEntriesFromHost)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForShutdownComplete)
{
writeStream.WriteByte((byte)ObjectType.ShutdownComplete);
((LocalCallDescriptorForShutdownComplete)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForShutdownNode)
{
writeStream.WriteByte((byte)ObjectType.ShutdownNode);
((LocalCallDescriptorForShutdownNode)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForPostIntrospectorCommand)
{
writeStream.WriteByte((byte)ObjectType.PostIntrospectorCommand);
((LocalCallDescriptorForPostIntrospectorCommand)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalReplyCallDescriptor)
{
writeStream.WriteByte((byte)ObjectType.GenericSingleObjectReply);
((LocalReplyCallDescriptor)objectToWrite).WriteToStream(binaryWriter);
}
else if (objectToWrite is LocalCallDescriptorForPostStatus)
{
writeStream.WriteByte((byte)ObjectType.PostStatus);
((LocalCallDescriptorForPostStatus)objectToWrite).WriteToStream(binaryWriter);
}
else
{
// If the object is not one of the well known local descriptors, use .net Serialization to serialize the object
writeStream.WriteByte((byte)ObjectType.NetSerialization);
binaryFormatter.Serialize(writeStream, objectToWrite);
}
}
19
Source : NodeEndpointOutOfProcBase.cs
with MIT License
from enricosada
with MIT License
from enricosada
private void RunReadLoop(Stream localReadPipe, Stream localWritePipe,
Queue<INodePacket> localPacketQueue, AutoResetEvent localPacketAvailable, AutoResetEvent localTerminatePacketPump)
{
// Ordering of the wait handles is important. The first signalled wait handle in the array
// will be returned by WaitAny if multiple wait handles are signalled. We prefer to have the
// terminate event triggered so that we cannot get into a situation where packets are being
// spammed to the endpoint and it never gets an opportunity to shutdown.
CommunicationsUtilities.Trace("Entering read loop.");
byte[] headerByte = new byte[5];
#if FEATURE_APM
IAsyncResult result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null);
#else
Task<int> readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length);
#endif
bool exitLoop = false;
do
{
// Ordering is important. We want packetAvailable to supercede terminate otherwise we will not properly wait for all
// packets to be sent by other threads which are shutting down, such as the logging thread.
WaitHandle[] handles = new WaitHandle[] {
#if FEATURE_APM
result.AsyncWaitHandle,
#else
((IAsyncResult)readTask).AsyncWaitHandle,
#endif
localPacketAvailable, localTerminatePacketPump };
int waitId = WaitHandle.WaitAny(handles);
switch (waitId)
{
case 0:
{
int bytesRead = 0;
try
{
#if FEATURE_APM
bytesRead = localReadPipe.EndRead(result);
#else
bytesRead = readTask.Result;
#endif
}
catch (Exception e)
{
// Lost communications. Abort (but allow node reuse)
CommunicationsUtilities.Trace("Exception reading from server. {0}", e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Inactive);
exitLoop = true;
break;
}
if (bytesRead != headerByte.Length)
{
// Incomplete read. Abort.
if (bytesRead == 0)
{
CommunicationsUtilities.Trace("Parent disconnected abruptly");
}
else
{
CommunicationsUtilities.Trace("Incomplete header read from server. {0} of {1} bytes read", bytesRead, headerByte.Length);
}
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
NodePacketType packetType = (NodePacketType)Enum.ToObject(typeof(NodePacketType), headerByte[0]);
int packetLength = BitConverter.ToInt32(headerByte, 1);
try
{
_packetFactory.DeserializeAndRoutePacket(0, packetType, NodePacketTranslator.GetReadTranslator(localReadPipe, _sharedReadBuffer));
}
catch (Exception e)
{
// Error while deserializing or handling packet. Abort.
CommunicationsUtilities.Trace("Exception while deserializing packet {0}: {1}", packetType, e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
#if FEATURE_APM
result = localReadPipe.BeginRead(headerByte, 0, headerByte.Length, null, null);
#else
readTask = CommunicationsUtilities.ReadAsync(localReadPipe, headerByte, headerByte.Length);
#endif
}
break;
case 1:
case 2:
try
{
int packetCount = localPacketQueue.Count;
// Write out all the queued packets.
while (packetCount > 0)
{
INodePacket packet;
lock (_packetQueue)
{
packet = localPacketQueue.Dequeue();
}
MemoryStream packetStream = new MemoryStream();
INodePacketTranslator writeTranslator = NodePacketTranslator.GetWriteTranslator(packetStream);
packetStream.WriteByte((byte)packet.Type);
// Pad for packet length
packetStream.Write(BitConverter.GetBytes((int)0), 0, 4);
// Reset the position in the write buffer.
packet.Translate(writeTranslator);
// Now write in the actual packet length
packetStream.Position = 1;
packetStream.Write(BitConverter.GetBytes((int)packetStream.Length - 5), 0, 4);
#if FEATURE_MEMORYSTREAM_GETBUFFER
localWritePipe.Write(packetStream.GetBuffer(), 0, (int)packetStream.Length);
#else
ArraySegment<byte> packetStreamBuffer;
if (packetStream.TryGetBuffer(out packetStreamBuffer))
{
localWritePipe.Write(packetStreamBuffer.Array, packetStreamBuffer.Offset, packetStreamBuffer.Count);
}
else
{
localWritePipe.Write(packetStream.ToArray(), 0, (int)packetStream.Length);
}
#endif
packetCount--;
}
}
catch (Exception e)
{
// Error while deserializing or handling packet. Abort.
CommunicationsUtilities.Trace("Exception while serializing packets: {0}", e);
ExceptionHandling.DumpExceptionToFile(e);
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
break;
}
if (waitId == 2)
{
CommunicationsUtilities.Trace("Disconnecting voluntarily");
ChangeLinkStatus(LinkStatus.Failed);
exitLoop = true;
}
break;
default:
ErrorUtilities.ThrowInternalError("waitId {0} out of range.", waitId);
break;
}
}
while (!exitLoop);
}
19
Source : CreateCSharpManifestResourceName_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
#endif
[Trait("Category", "mono-osx-failing")]
public void Regress172107()
{
// Can't embed the 'Ã' directly because the string is Unicode already and the Unicode<-->ANSI transform
// isn't bidirectional.
MemoryStream sourcesStream = (MemoryStream)StreamHelpers.StringToStream("namespace d?a { clreplaced Clreplaced {} }");
// Instead, directly write the ANSI character into the memory buffer.
sourcesStream.Seek(11, SeekOrigin.Begin);
sourcesStream.WriteByte(0xc3); // Plug the 'Ã' in
sourcesStream.Seek(0, SeekOrigin.Begin);
string result =
CreateCSharpManifestResourceName.CreateManifestNameImpl
(
@"irrelevant",
null,
true,
null, // Root namespace
null,
null,
sourcesStream,
null
);
MemoryStream m = new MemoryStream();
m.Write(new byte[] { 0x64, 0xc3, 0x61, 0x2e, 0x43, 0x6c, 0x61, 0x73, 0x73 }, 0, 9); // dÃa.Clreplaced in ANSI
m.Flush();
m.Seek(0, SeekOrigin.Begin);
#if FEATURE_ENCODING_DEFAULT
StreamReader r = new StreamReader(m, System.Text.Encoding.Default, true); // HIGHCHAR: Test reads ANSI because that's the scenario.
#else
StreamReader r = new StreamReader(m, System.Text.Encoding.ASCII, true); // HIGHCHAR: Test reads ANSI because that's the scenario.
#endif
string clreplacedName = r.ReadToEnd();
replacedert.Equal(clreplacedName, result);
}
19
Source : CreateCSharpManifestResourceName_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
#endif
[Trait("Category", "mono-osx-failing")]
public void Regress249540()
{
// Special character is 'Ä' in UTF8: 0xC3 84
MemoryStream sourcesStream = (MemoryStream)StreamHelpers.StringToStream("namespace d??a { clreplaced Clreplaced {} }");
// Instead, directly write the ANSI character into the memory buffer.
sourcesStream.Seek(11, SeekOrigin.Begin);
sourcesStream.WriteByte(0xc3); // Plug the first byte of 'Ä' in.
sourcesStream.WriteByte(0x84); // Plug the second byte of 'Ä' in.
sourcesStream.Seek(0, SeekOrigin.Begin);
string result =
CreateCSharpManifestResourceName.CreateManifestNameImpl
(
@"irrelevant",
null,
true,
null, // Root namespace
null,
null,
sourcesStream,
null
);
replacedert.Equal("d\u00C4a.Clreplaced", result);
}
19
Source : StreamMappedString_Tests.cs
with MIT License
from enricosada
with MIT License
from enricosada
[Fact]
public void Regress_Mutation_ForceANSIWorks_RelatedTo172107()
{
// Can't embed the 'Ã' directly because the string is Unicode already and the Unicode<-->ANSI transform
// isn't bidirectional.
MemoryStream sourcesStream = (MemoryStream)StreamHelpers.StringToStream("namespace d?a { clreplaced Clreplaced {} }");
// Instead, directly write the ANSI character into the memory buffer.
sourcesStream.Seek(11, SeekOrigin.Begin);
sourcesStream.WriteByte(0xc3); // Plug the 'Ã' in
sourcesStream.Seek(0, SeekOrigin.Begin);
// Should not throw an exception because we force ANSI.
StreamMappedString s = new StreamMappedString(sourcesStream, /* forceANSI */ true);
s.GetAt(11);
}
19
Source : Gyu0.cs
with MIT License
from evandixon
with MIT License
from evandixon
private static void TryCompressSkip(byte[] data, long offset, MemoryStream output, ref CompressionResult result)
{
try
{
var count = 0;
while (data[offset + count] == 0 && count < 0x11F)
{
count++;
}
if (count > 0)
{
if (count < 0x1F)
{
var compressionRatio = count;
if (compressionRatio > result.CompressionRatio)
{
result.InputByteCount = count;
result.OutputByteCount = 1;
output.WriteByte((byte)(0xE0 + count - 1));
}
}
else
{
var compressionRatio = count * 0.5f;
if (compressionRatio > result.CompressionRatio)
{
result.InputByteCount = count;
result.OutputByteCount = 2;
output.WriteByte(0xFF);
output.WriteByte((byte)(count - 0x20));
}
}
}
}
catch (IndexOutOfRangeException)
{
// EOF means failure
}
}
19
Source : Gyu0.cs
with MIT License
from evandixon
with MIT License
from evandixon
public static IBinaryDataAccessor Compress(IReadOnlyBinaryDataAccessor input)
{
var output = new MemoryStream((int)input.Length / 2);
var inputData = input.ReadArray();
void writeArray(byte[] array) {
output.Write(array, 0, array.Length);
};
writeArray(Encoding.ASCII.GetBytes("GYU0"));
writeArray(BitConverter.GetBytes(inputData.Length));
long dataOffset = 0;
var compressionResult = new CompressionResult();
while (dataOffset < inputData.LongLength)
{
// Try each of the compression algorithms without copying data first.
// If we get a result, write that to the output right away.
// Otherwise, try copying the least amount of data followed by one of the algorithms.
TryCompress(inputData, dataOffset, output, ref compressionResult);
if (!compressionResult.Valid)
{
var copyOffset = dataOffset;
var copyCommandOffset = output.Position;
output.Position++;
while (!compressionResult.Valid && copyOffset - dataOffset < 31 && copyOffset < inputData.LongLength)
{
output.WriteByte(inputData[copyOffset]);
copyOffset++;
TryCompress(inputData, copyOffset, output, ref compressionResult);
}
var currPos = output.Position;
output.Position = copyCommandOffset;
output.WriteByte((byte)(0x80 + copyOffset - dataOffset - 1));
output.Position = currPos;
dataOffset = copyOffset;
}
if (compressionResult.Valid)
{
dataOffset += compressionResult.InputByteCount;
}
}
// Write EOF marker
output.WriteByte(0x7F);
output.WriteByte(0xFF);
// Trim any excess bytes that may have been written by the TryCompress* methods
output.SetLength(output.Position);
return new BinaryFile(output.ToArray());
}
19
Source : Gyu0.cs
with MIT License
from evandixon
with MIT License
from evandixon
public static IBinaryDataAccessor Compress(IReadOnlyBinaryDataAccessor input)
{
var output = new MemoryStream((int)input.Length / 2);
var inputData = input.ReadArray();
void writeArray(byte[] array) {
output.Write(array, 0, array.Length);
};
writeArray(Encoding.ASCII.GetBytes("GYU0"));
writeArray(BitConverter.GetBytes(inputData.Length));
long dataOffset = 0;
var compressionResult = new CompressionResult();
while (dataOffset < inputData.LongLength)
{
// Try each of the compression algorithms without copying data first.
// If we get a result, write that to the output right away.
// Otherwise, try copying the least amount of data followed by one of the algorithms.
TryCompress(inputData, dataOffset, output, ref compressionResult);
if (!compressionResult.Valid)
{
var copyOffset = dataOffset;
var copyCommandOffset = output.Position;
output.Position++;
while (!compressionResult.Valid && copyOffset - dataOffset < 31 && copyOffset < inputData.LongLength)
{
output.WriteByte(inputData[copyOffset]);
copyOffset++;
TryCompress(inputData, copyOffset, output, ref compressionResult);
}
var currPos = output.Position;
output.Position = copyCommandOffset;
output.WriteByte((byte)(0x80 + copyOffset - dataOffset - 1));
output.Position = currPos;
dataOffset = copyOffset;
}
if (compressionResult.Valid)
{
dataOffset += compressionResult.InputByteCount;
}
}
// Write EOF marker
output.WriteByte(0x7F);
output.WriteByte(0xFF);
// Trim any excess bytes that may have been written by the TryCompress* methods
output.SetLength(output.Position);
return new BinaryFile(output.ToArray());
}
19
Source : Gyu0.cs
with MIT License
from evandixon
with MIT License
from evandixon
private static void TryCompressSplitCopy(byte[] data, long offset, MemoryStream output, ref CompressionResult result)
{
try
{
var sep = data[offset];
var count = 1;
while (data[offset + count * 2] == sep && data[offset + count * 2 + 1] != sep && count < 0x21)
{
count++;
}
if (count >= 2)
{
var compressionRatio = count * 2.0f / (2.0f + count);
if (compressionRatio > result.CompressionRatio)
{
result.InputByteCount = count * 2;
result.OutputByteCount = 2 + count;
output.WriteByte((byte)(0xA0 + count - 2));
output.WriteByte(sep);
for (int i = 0; i < count; i++)
{
output.WriteByte(data[offset + i * 2 + 1]);
}
}
}
}
catch (IndexOutOfRangeException)
{
// EOF means failure
}
}
19
Source : Gyu0.cs
with MIT License
from evandixon
with MIT License
from evandixon
private static void TryCompressFill(byte[] data, long offset, MemoryStream output, ref CompressionResult result)
{
try
{
var fill = data[offset];
var count = 1;
while (data[offset + count] == fill && count < 0x21)
{
count++;
}
if (count >= 2)
{
var compressionRatio = count * 0.5f;
if (compressionRatio > result.CompressionRatio)
{
result.InputByteCount = count;
result.OutputByteCount = 2;
output.WriteByte((byte)(0xC0 + count - 2));
output.WriteByte(fill);
}
}
}
catch (IndexOutOfRangeException)
{
// EOF means failure
}
}
19
Source : Gyu0.cs
with MIT License
from evandixon
with MIT License
from evandixon
private static void TryCompressPrevious(byte[] data, long offset, MemoryStream output, ref CompressionResult result)
{
// Don't waste time trying to look behind if there's nothing written yet
if (offset == 0) return;
try
{
// Search output up to 0x400 bytes behind for the longest subsequence of bytes found in data starting at offset.
// The common substring must be between 2 and 33 bytes long.
var maxLookbehindDistance = Math.Min(0x400, (int)offset);
if (maxLookbehindDistance < 2) return;
var maxLength = Math.Min(33, (int)Math.Min(maxLookbehindDistance, data.Length - offset));
var lookbehindData = new Span<byte>(data, (int)(offset - maxLookbehindDistance), maxLookbehindDistance);
var lookaheadData = new Span<byte>(data, (int)offset, maxLength);
int matchLength = 0;
int matchPos = -1;
int[,] longestCommonSuffixes = new int[lookbehindData.Length + 1, lookaheadData.Length + 1];
for (int i = 0; i <= lookbehindData.Length; i++)
{
for (int j = 0; j <= lookaheadData.Length; j++)
{
if (i == 0 || j == 0)
{
longestCommonSuffixes[i, j] = 0;
}
else if (lookbehindData[i - 1] == lookaheadData[j - 1])
{
longestCommonSuffixes[i, j] = longestCommonSuffixes[i - 1, j - 1] + 1;
if (longestCommonSuffixes[i, j] > matchLength && longestCommonSuffixes[i, j] == j)
{
matchLength = longestCommonSuffixes[i, j];
matchPos = i - matchLength;
}
}
else
{
longestCommonSuffixes[i, j] = 0;
}
}
}
if (matchLength >= 2)
{
var compressionRatio = matchLength * 0.5f;
if (compressionRatio > result.CompressionRatio)
{
var matchOffset = matchPos - maxLookbehindDistance;
result.InputByteCount = matchLength;
result.OutputByteCount = 2;
output.WriteByte((byte)((byte)((matchLength - 2) << 2) | (byte)((matchOffset >> 8) & 3)));
output.WriteByte((byte)(matchOffset & 0xFF));
}
}
}
catch (IndexOutOfRangeException)
{
// EOF means failure
}
}
19
Source : PDFSimpleExport.Images.cs
with MIT License
from FastReports
with MIT License
from FastReports
private MemoryStream GetMask(int[] raw_pixels)
{
MemoryStream mask_stream = new MemoryStream(raw_pixels.Length);
bool alpha = false;
byte pixel;
for (int i = 0; i < raw_pixels.Length; i++)
{
pixel = (byte)(((UInt32)raw_pixels[i]) >> 24);
if (!alpha && pixel != 0xff)
alpha = true;
mask_stream.WriteByte(pixel);
}
if (alpha)
{
mask_stream.Position = 0;
return mask_stream;
}
return null;
}
19
Source : YPF.cs
with MIT License
from fengberd
with MIT License
from fengberd
public void Write(BinaryWriter writer, int engine, Func<byte[], uint> nameHash, Func<byte[], uint> dataHash)
{
writer.Write(YPFHeader);
writer.Write(engine);
writer.Write(Entries.Count);
writer.BaseStream.Position = 32;
List<long> entryPosition = new List<long>();
foreach (var entry in Entries)
{
var name = Encoding.GetEncoding("SHIFT-JIS").GetBytes(entry.Name);
writer.Write(nameHash(name));
int length = entry.Name.Length;
if (NameLengthTable.ContainsKey(length))
{
length = NameLengthTable[length];
}
writer.Write((byte)(255 - length));
writer.Write(name.Select(c => (byte)~c).ToArray());
writer.Write((byte)entry.Type);
writer.Write(entry.Compressed);
writer.Write(entry.Size);
entryPosition.Add(writer.BaseStream.Position);
writer.Write(0); // Compressed size placeholder
writer.Write(0L); // Data offset placeholder
writer.Write(0); // Hash placeholder
}
for (int i = 0; i < Entries.Count; i++)
{
var entry = Entries[i];
var data = entry.Data;
if (entry.Compressed)
{
using (var ms = new MemoryStream())
{
ms.WriteByte(0x78);
ms.WriteByte(0xDA);
using (var deflate = new DeflateStream(ms, CompressionLevel.Optimal, true))
{
deflate.Write(entry.Data, 0, entry.Size);
}
data = ms.ToArray();
}
}
writer.Write(data);
long dataOffset = writer.BaseStream.Position;
writer.BaseStream.Position = entryPosition[i];
entry.CompressedSize = data.Length;
writer.Write(entry.CompressedSize);
if(engine >= 480)
{
writer.Write(dataOffset - data.Length);
}
else
{
writer.Write((int)(dataOffset - data.Length));
}
writer.Write(dataHash(data));
writer.BaseStream.Position = dataOffset;
}
}
19
Source : Utils.cs
with GNU General Public License v3.0
from fengberd
with GNU General Public License v3.0
from fengberd
public static string ReadText(IntPtr hProcess,IntPtr address)
{
using(MemoryStream ms = new MemoryStream())
{
int offset = 0;
byte read;
while((read = ReadMemory(hProcess,address + offset,1)[0]) != 0)
{
ms.WriteByte(read);
offset++;
}
var data = ms.ToArray();
return Encoding.UTF8.GetString(data,0,data.Length);
}
}
19
Source : Deck.cs
with Mozilla Public License 2.0
from finol-digital
with Mozilla Public License 2.0
from finol-digital
public string SerializeHsd()
{
using (var memoryStream = new MemoryStream())
{
memoryStream.WriteByte(0);
Varint.Write(memoryStream, 1);
Varint.Write(memoryStream, 1);
Dictionary<Card, int> cardCounts = GetCardCounts();
List<Card> extraCards = GetExtraCards();
List<KeyValuePair<Card, int>> singleCopy = cardCounts.Where(x => x.Value == 1).ToList();
List<KeyValuePair<Card, int>> doubleCopy = cardCounts.Where(x => x.Value == 2).ToList();
List<KeyValuePair<Card, int>> nCopy = cardCounts.Where(x => x.Value > 2).ToList();
singleCopy.RemoveAll(cardCount => extraCards.Contains(cardCount.Key));
doubleCopy.RemoveAll(cardCount => extraCards.Contains(cardCount.Key));
nCopy.RemoveAll(cardCount => extraCards.Contains(cardCount.Key));
Varint.Write(memoryStream, extraCards.Count);
foreach (Card card in extraCards)
Varint.Write(memoryStream, card.GetPropertyValueInt(SourceGame.DeckFileAltId));
Varint.Write(memoryStream, singleCopy.Count);
foreach (KeyValuePair<Card, int> cardCount in singleCopy)
Varint.Write(memoryStream, cardCount.Key.GetPropertyValueInt(SourceGame.DeckFileAltId));
Varint.Write(memoryStream, doubleCopy.Count);
foreach (KeyValuePair<Card, int> cardCount in doubleCopy)
Varint.Write(memoryStream, cardCount.Key.GetPropertyValueInt(SourceGame.DeckFileAltId));
Varint.Write(memoryStream, nCopy.Count);
foreach (KeyValuePair<Card, int> cardCount in nCopy)
{
Varint.Write(memoryStream, cardCount.Key.GetPropertyValueInt(SourceGame.DeckFileAltId));
Varint.Write(memoryStream, cardCount.Value);
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
19
Source : Varint.cs
with Mozilla Public License 2.0
from finol-digital
with Mozilla Public License 2.0
from finol-digital
public static void Write(MemoryStream memoryStream, int value)
{
if (value == 0)
memoryStream.WriteByte(0);
else
{
byte[] bytes = GetBytes((ulong) value);
memoryStream.Write(bytes, 0, bytes.Length);
}
}
19
Source : Varint.cs
with Mozilla Public License 2.0
from finol-digital
with Mozilla Public License 2.0
from finol-digital
private static byte[] GetBytes(ulong value)
{
using (var memoryStream = new MemoryStream())
{
while (value != 0)
{
ulong b = value & 0x7f;
value >>= 7;
if (value != 0)
b |= 0x80;
memoryStream.WriteByte((byte) b);
}
return memoryStream.ToArray();
}
}
19
Source : Query.cs
with MIT License
from ForkGG
with MIT License
from ForkGG
private byte[] FullStats(int number)
{
// Declare vars
MemoryStream stream = new MemoryStream();
byte[] numberbytes = BitConverter.GetBytes(number).Reverse().ToArray();
// Writing stream bytes
stream.WriteByte(0xFE); // Magic
stream.WriteByte(0xFD); // Magic
stream.WriteByte(0x00); // Type
stream.WriteByte(0x01); // Session
stream.WriteByte(0x01); // Session
stream.WriteByte(0x01); // Session
stream.WriteByte(0x01); // Session
stream.Write(numberbytes, 0, 4); // Challenge
stream.WriteByte(0x00); // Padding
stream.WriteByte(0x00); // Padding
stream.WriteByte(0x00); // Padding
stream.WriteByte(0x00); // Padding
// Preparing byte array
byte[] sendme = stream.ToArray();
// Closing stream for save resources
stream.Close();
// Return data
return ConnectToServer(sendme);
}
19
Source : Query.cs
with MIT License
from ForkGG
with MIT License
from ForkGG
private int Handshake()
{
// Declare vars
MemoryStream stream = new MemoryStream();
// Writing stream bytes
stream.WriteByte(0xFE); // Magic
stream.WriteByte(0xFD); // Magic
stream.WriteByte(0x09); // Type
stream.WriteByte(0x01); // Session
stream.WriteByte(0x01); // Session
stream.WriteByte(0x01); // Session
stream.WriteByte(0x01); // Session
// Preparing byte array
byte[] sendme = stream.ToArray();
// Closing stream for save resources
stream.Close();
// Returned data
byte[] receivedBytes = ConnectToServer(sendme);
string number = "";
for (int i = 0; i < receivedBytes.Length; i++)
{
if (i > 4 && receivedBytes[i] != 0x00)
{
number += (char)receivedBytes[i];
}
}
// Return token
return int.Parse(number);
}
19
Source : NFC.iOS.cs
with MIT License
from franckbour
with MIT License
from franckbour
public static byte[] ToByteArray(this NFCNdefMessage message)
{
var records = message?.Records;
// Empty message: single empty record
if (records == null || records.Length == 0)
{
records = new NFCNdefPayload[] { null };
}
var m = new MemoryStream();
for (var i = 0; i < records.Length; i++)
{
var record = records[i];
var typeNameFormat = record?.TypeNameFormat ?? NFCTypeNameFormat.Empty;
var payload = record?.Payload;
var id = record?.Identifier;
var type = record?.Type;
var flags = (byte)typeNameFormat;
// Message begin / end flags. If there is only one record in the message, both flags are set.
if (i == 0)
flags |= 0x80; // MB (message begin = first record in the message)
if (i == records.Length - 1)
flags |= 0x40; // ME (message end = last record in the message)
// cf (chunked records) not supported yet
// SR (Short Record)?
if (payload == null || payload.Length < 255)
flags |= 0x10;
// ID present?
if (id != null && id.Length > 0)
flags |= 0x08;
m.WriteByte(flags);
// Type length
if (type != null)
m.WriteByte((byte)type.Length);
else
m.WriteByte(0);
// Payload length 1 byte (SR) or 4 bytes
if (payload == null)
{
m.WriteByte(0);
}
else
{
if ((flags & 0x10) != 0)
{
// SR
m.WriteByte((byte)payload.Length);
}
else
{
// No SR (Short Record)
var payloadLength = (uint)payload.Length;
m.WriteByte((byte)(payloadLength >> 24));
m.WriteByte((byte)(payloadLength >> 16));
m.WriteByte((byte)(payloadLength >> 8));
m.WriteByte((byte)(payloadLength & 0x000000ff));
}
}
// ID length
if (id != null && (flags & 0x08) != 0)
m.WriteByte((byte)id.Length);
// Type length
if (type != null && type.Length > 0)
m.Write(type.ToArray(), 0, (int)type.Length);
// ID data
if (id != null && id.Length > 0)
m.Write(id.ToArray(), 0, (int)id.Length);
// Payload data
if (payload != null && payload.Length > 0)
m.Write(payload.ToArray(), 0, (int)payload.Length);
}
return m.ToArray();
}
19
Source : XMConverter.cs
with GNU General Public License v2.0
from fstarred
with GNU General Public License v2.0
from fstarred
private byte[] GetPatternData(PatternData patternData, InstrumentData[] instruments, int numChannels, int numMasterTrackColumns)
{
byte noteBit = 1;
byte instrumentBit = 2;
byte volumeColBit = 4;
byte effectTypeBit = 8;
byte effectParamBit = 16;
byte emptyBit = 128;
byte allValuesFilledBit = (byte)(noteBit + instrumentBit + volumeColBit + effectTypeBit + effectParamBit + emptyBit);
MemoryStream patternDataStream = new MemoryStream();
// A Carl Corcoran idea, useful to know which is the last sample played by an x channel
System.Collections.Generic.Dictionary<int, SampleData?> playingSamplesMap = new System.Collections.Generic.Dictionary<int, SampleData?>();
byte[] masterTrackCommand = new byte[2];
bool isMasterTrackCommandUsed = false;
// force number of mastertrack columns to parse at x value, therefore any column beyond the x value will be ignored
// NOTE: if applied parseOnlyGlobalVolumeFromMT, other effect but Global Volume will be ignored
const int maxMasterTrackColumnToParse = 1;
int numMasterTrackColumnsToParse = maxMasterTrackColumnToParse;
// numMasterTrackColumns -- count of MT columns in module
// numMasterTrackColumnsToParse -- count of MT columns to parse
if (numMasterTrackColumnsToParse > numMasterTrackColumns)
numMasterTrackColumnsToParse = numMasterTrackColumns;
// parse only global volume from MasterTrack
const bool parseOnlyGlobalVolumeFromMT = false;
int currentMasterTrackIndex = 0;
int masterTrackIndexLimitForCurrentRow = 0;
for (int i = 0; i < patternData.TracksLineData.Length; i++)
{
xmUtils.ComputeTickPerRowForCurrentLine(patternData.TracksLineData, i, numChannels);
int currentRow = i / numChannels;
int currentChannel = i % numChannels + 1;
if (currentChannel == 1)
{
if (isMasterTrackCommandUsed)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, "Some MasterTrack command were not used due to missing free command effects slots");
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
//currentMasterTrackColumnToParse = 0;
isMasterTrackCommandUsed = false;
currentMasterTrackIndex = currentRow * numMasterTrackColumns;
masterTrackIndexLimitForCurrentRow = currentMasterTrackIndex + numMasterTrackColumnsToParse;
}
while (currentMasterTrackIndex < masterTrackIndexLimitForCurrentRow && !isMasterTrackCommandUsed)
{
MasterTrackLineData masterTrackLineData = patternData.MasterTrackLineData[currentMasterTrackIndex];
if (masterTrackLineData.IsSet)
{
masterTrackCommand = xmUtils.GetCommandsFromMasterTrack(masterTrackLineData.EffectNumber, masterTrackLineData.EffectValue, parseOnlyGlobalVolumeFromMT);
if (masterTrackCommand[0] + masterTrackCommand[1] > 0)
{
isMasterTrackCommandUsed = true;
//break;
}
}
//currentMasterTrackColumnToParse++;
currentMasterTrackIndex++;
}
TrackLineData trackLineData = patternData.TracksLineData[i];
if (trackLineData.IsSet || isMasterTrackCommandUsed)
{
byte compressionValue = emptyBit;
byte xmNote = 0;
byte xmInstrument = 0;
byte xmVolume = 0;
byte xmEffectNumber = 0;
byte xmEffectValue = 0;
bool isEffectCommandUsed = false;
bool isVolumeCommandUsed = false;
bool isPanningCommandUsed = false;
if (trackLineData.Note != null)
{
try
{
xmNote = XMUtils.GetXMNote(trackLineData.Note);
compressionValue = (byte)(compressionValue + noteBit);
}
catch (ConversionException e)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, e.Message);
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
}
if (trackLineData.Instrument != null)
{
compressionValue = (byte)(compressionValue + instrumentBit);
xmInstrument = (byte)(Int16.Parse(trackLineData.Instrument, System.Globalization.NumberStyles.HexNumber) + 1);
if (xmNote != 0)
{
int xmSample = xmUtils.GetPlayedSampleFromKeymap(xmNote, xmInstrument);
// figure out which sample will play for this.
if (instruments[xmInstrument - 1].Samples.Length > xmSample )
{
playingSamplesMap[currentChannel] = instruments[xmInstrument - 1].Samples[xmSample];
}
}
}
// the currently playing sample in the channel
SampleData? currentlyPlayingSample = null;
if (playingSamplesMap.ContainsKey(currentChannel))
currentlyPlayingSample = playingSamplesMap[currentChannel];
int sampleDefaultVolume = currentlyPlayingSample != null ?
currentlyPlayingSample.Value.DefaultVolume : maxSampleVolume;
float sampleVolume = 1.0f;
if (currentlyPlayingSample != null)
{
sampleVolume = currentlyPlayingSample.Value.Volume;
}
if (trackLineData.EffectNumber != null)
{
try
{
byte[] values = xmUtils.GetXMEffect(trackLineData.EffectNumber, trackLineData.EffectValue, xmNote, xmInstrument);
if ((values[0] + values[1]) > 0)
{
isEffectCommandUsed = true;
xmEffectNumber = values[0];
xmEffectValue = values[1];
}
}
catch (ConversionException e)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, e.Message);
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
}
// volume column (volume column got priority before panning)
if (trackLineData.Volume != null)
{
xmVolume = xmUtils.GetVolumeColumnEffectFromVolume(trackLineData.Volume);
isVolumeCommandUsed = xmVolume > 0;
if (isVolumeCommandUsed == false && isEffectCommandUsed == false)
{
// transpose possible parseable command from volume to effect columns
// G|U|D|I|O|B|Q|R|Y|C
byte[] values = xmUtils.TransposeVolumeToCommandEffect(trackLineData.Volume);
if ((values[0] + values[1]) > 0)
{
isEffectCommandUsed = true;
xmEffectNumber = values[0];
xmEffectValue = values[1];
}
}
}
// only with VOLUME_SCALING_MODE = COLUMN
if (Settings.VolumeScalingMode == VOLUME_SCALING_MODE.COLUMN)
{
bool sampleNeedsVolumeScaling =
currentlyPlayingSample != null && currentlyPlayingSample.Value.Volume != 1.0;
bool doesTriggerSample = trackLineData.Note != null && trackLineData.Instrument != null;
// if volume column command is used, then scale it
if (sampleNeedsVolumeScaling && isVolumeCommandUsed && XMExtras.IsVolumeSetOnVolumeColumn(xmVolume))
{
try
{
xmVolume = XMExtras.ScaleVolumeFromVolumeCommand(xmVolume, sampleVolume);
}
catch (ConversionException e)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, e.Message);
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
sampleNeedsVolumeScaling = false;
}
// if effect command is used, then scale it
if (sampleNeedsVolumeScaling && isEffectCommandUsed && XMExtras.IsVolumeSetOnEffectColumn(xmEffectNumber))
{
try
{
xmEffectValue = XMExtras.ScaleVolumeFromEffectCommand(xmEffectValue, sampleVolume);
}
catch (ConversionException e)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, e.Message);
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
sampleNeedsVolumeScaling = false;
}
// if sample is triggered and needs volume scaling, check for any free slot
if (sampleNeedsVolumeScaling && doesTriggerSample)
{
// the real sample volume is relative with the default volume
sampleVolume *= (float)currentlyPlayingSample.Value.DefaultVolume / (float)maxSampleVolume;
// try to fill on volume column first
if (isVolumeCommandUsed == false)
{
try
{
xmVolume = XMExtras.ScaleVolumeFromVolumeCommand(sampleVolume);
isVolumeCommandUsed = true;
}
catch (ConversionException e)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, e.Message);
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
sampleNeedsVolumeScaling = false;
}
// try to fill on effect column
if (sampleNeedsVolumeScaling && isEffectCommandUsed == false)
{
byte[] values = new byte[2];
// transpose possible parseable command from volume to effect columns
// G|U|D|J|K|Q|B|R|Y|C
try
{
values = XMExtras.ScaleVolumeFromEffectCommand(sampleVolume);
}
catch (Exception e)
{
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, e.Message);
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
if ((values[0] + values[1]) > 0)
{
isEffectCommandUsed = true;
xmEffectNumber = values[0];
xmEffectValue = values[1];
}
sampleNeedsVolumeScaling = false;
}
}
// if still sample needs scaling a conversion error is thrown
if (sampleNeedsVolumeScaling)
{
// no empty slot free, a log error conversion is thrown
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, "Cannot apply scaled volume for this channel due to missing free slots");
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
}
// delay column
if (trackLineData.Delay != null)
{
if (isEffectCommandUsed == false)
{
byte[] values = xmUtils.TransposeDelayToCommandEffect(trackLineData.Delay);
isEffectCommandUsed = true;
xmEffectNumber = values[0];
xmEffectValue = values[1];
}
else
{
// no empty slot free, a log error conversion is thrown
string errorMessage = string.Format("row {0}, channel {1}: {2}", currentRow, currentChannel, "Cannot apply delay for this channel due to missing free slots");
OnReportProgress(new EventReportProgressArgs(errorMessage, MsgType.ERROR));
}
}
// panning column
if (trackLineData.Panning != null)
{
if (isVolumeCommandUsed == false)
{
xmVolume = xmUtils.GetVolumeColumnEffectFromPanning(trackLineData.Panning);
isPanningCommandUsed = xmVolume > 0;
}
if (isPanningCommandUsed == false && isEffectCommandUsed == false)
{
byte[] values = xmUtils.TransposePanningToCommandEffect(trackLineData.Panning);
if ((values[0] + values[1]) > 0)
{
isEffectCommandUsed = true;
xmEffectNumber = values[0];
xmEffectValue = values[1];
}
}
}
// apply global commands to the current effect column
if (isMasterTrackCommandUsed && !isEffectCommandUsed)
{
isEffectCommandUsed = true;
xmEffectNumber = masterTrackCommand[0];
xmEffectValue = masterTrackCommand[1];
//currentMasterTrackColumnToParse++;
isMasterTrackCommandUsed = false;
}
// xm volume column binary switch
if (isPanningCommandUsed || isVolumeCommandUsed)
compressionValue = (byte)(compressionValue + volumeColBit);
if (xmEffectNumber > 0)
compressionValue = (byte)(compressionValue + effectTypeBit);
if (xmEffectValue > 0)
compressionValue = (byte)(compressionValue + effectParamBit);
// this might require a little explanation.
// row/track data, wherever is not completely filled with note, instrument, volume col,
// effect type, effect value
// is packaged in this way:
// the first byte means the type of values, and from second the values to put.
// an empty row/track data byte is byte value 128
// the values order, starting from the less significant bit are
//
// 1 1 1 1 1
// note instrument volume col effect type effect value
//
// so, for example, a value of 26 in bit is 11010 that means note, instrument and effect type filled.
// Therefore the first byte will be 154 (128 + 26)
// See the specs for a better idea
// writes the package byte only if not all values are valorized
if (compressionValue != allValuesFilledBit)
{
patternDataStream.WriteByte(compressionValue);
}
// checks for every bit of package byte to understand which values has to store in
if (((compressionValue & 0x1)) > 0)
{
patternDataStream.WriteByte(xmNote);
}
if (((compressionValue & 0x3) >> 1) > 0)
{
patternDataStream.WriteByte(xmInstrument);
}
if (((compressionValue & 0x7) >> 2) > 0)
{
patternDataStream.WriteByte(xmVolume);
}
if (((compressionValue & 0xf) >> 3) > 0)
{
patternDataStream.WriteByte(xmEffectNumber);
}
if (((compressionValue & 0x1f) >> 4) > 0)
{
patternDataStream.WriteByte(xmEffectValue);
}
}
else
{
patternDataStream.WriteByte(emptyBit);
}
}
return patternDataStream.ToArray();
}
19
Source : CustomCommand.cs
with Apache License 2.0
from gamesparks
with Apache License 2.0
from gamesparks
internal CustomCommand Configure(int opCode, int sender, Stream lps, RTData data, int limit, IRTSessionInternal session, int packetSize)
{
ms = PooledObjects.MemoryStreamPool.Pop();
this.packetSize = packetSize;
this.opCode = opCode;
this.sender = sender;
this.data = data;
this.session = session;
this.limit = limit;
this.limitedStream = null;
if (lps != null) {
limitedStream = PooledObjects.LimitedPositionStreamPool.Pop ();
for (int i = 0; i < limit; i++) {
byte read = (byte)lps.ReadByte ();
ms.WriteByte (read);
}
ms.Position = 0;
limitedStream.Wrap (ms, limit);
}
return this;
}
19
Source : FlvMetadata.cs
with GNU General Public License v3.0
from Genteure
with GNU General Public License v3.0
from Genteure
private static void EncodeScriptDataValue(MemoryStream ms, object value)
{
switch (value)
{
case int number:
{
double asDouble = number;
ms.WriteByte((byte)AMFTypes.Number);
ms.Write(BitConverter.GetBytes(asDouble).ToBE(), 0, sizeof(double));
break;
}
case double number:
{
ms.WriteByte((byte)AMFTypes.Number);
ms.Write(BitConverter.GetBytes(number).ToBE(), 0, sizeof(double));
break;
}
case bool boolean:
{
ms.WriteByte((byte)AMFTypes.Boolean);
if (boolean)
{
ms.WriteByte(1);
}
else
{
ms.WriteByte(0);
}
break;
}
case string text:
{
var b = Encoding.UTF8.GetBytes(text);
if (b.Length >= ushort.MaxValue)
{
ms.WriteByte((byte)AMFTypes.LongString);
ms.Write(BitConverter.GetBytes((uint)b.Length).ToBE(), 0, sizeof(uint));
}
else
{
ms.WriteByte((byte)AMFTypes.String);
ms.Write(BitConverter.GetBytes((ushort)b.Length).ToBE(), 0, sizeof(ushort));
}
ms.Write(b, 0, b.Length);
break;
}
case Dictionary<string, object> d:
{
ms.WriteByte((byte)AMFTypes.Object);
foreach (var item in d)
{
var b = Encoding.UTF8.GetBytes(item.Key);
ms.Write(BitConverter.GetBytes((ushort)b.Length).ToBE(), 0, sizeof(ushort));
ms.Write(b, 0, b.Length);
EncodeScriptDataValue(ms, item.Value);
}
ms.WriteByte(0);
ms.WriteByte(0);
ms.WriteByte(9);
break;
}
case List<object> l:
{
ms.WriteByte((byte)AMFTypes.StrictArray);
ms.Write(BitConverter.GetBytes((uint)l.Count), 0, sizeof(uint));
foreach (var item in l)
{
EncodeScriptDataValue(ms, item);
}
break;
}
case DateTime dateTime:
{
ms.WriteByte((byte)AMFTypes.Date);
ms.Write(BitConverter.GetBytes(dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds).ToBE(), 0, sizeof(double));
ms.Write(BitConverter.GetBytes((short)0).ToBE(), 0, sizeof(short)); // UTC
break;
}
default:
throw new NotSupportedException("Type " + value.GetType().FullName + " is not supported");
}
}
19
Source : WavUtil.cs
with The Unlicense
from ghorsington
with The Unlicense
from ghorsington
private static MemoryStream CreateEmpty()
{
var memoryStream = new MemoryStream();
const byte emptyByte = new byte();
for (int i = 0; i < HEADER_SIZE; i++) //preparing the header
memoryStream.WriteByte(emptyByte);
return memoryStream;
}
19
Source : Client.cs
with MIT License
from gigajew
with MIT License
from gigajew
public void Send(IPacket packet)
{
if (!Connected)
return;
byte[] serializedPacket = null;
using (MemoryStream stream = new MemoryStream())
{
serializer.Serialize(stream, packet);
serializedPacket = stream.ToArray();
stream.SetLength(0L);
stream.WriteByte((byte)serializedPacket.Length);
stream.WriteByte((byte)(serializedPacket.Length >> 8));
stream.WriteByte((byte)(serializedPacket.Length >> 16));
stream.WriteByte((byte)(serializedPacket.Length >> 24));
stream.Write(serializedPacket, 0, serializedPacket.Length);
serializedPacket = stream.ToArray();
}
socket.BeginSend(serializedPacket, 0, serializedPacket.Length, SocketFlags.None, EndSend, this);
}
19
Source : WebSocketFrameWriter.cs
with MIT License
from GiovanniZambiasi
with MIT License
from GiovanniZambiasi
public static void Write(WebSocketOpCode opCode, ArraySegment<byte> fromPayload, MemoryStream toStream, bool isLastFrame, bool isClient)
{
MemoryStream memoryStream = toStream;
byte finBitSetAsByte = isLastFrame ? (byte)0x80 : (byte)0x00;
byte byte1 = (byte)(finBitSetAsByte | (byte)opCode);
memoryStream.WriteByte(byte1);
// NB, set the mask flag if we are constructing a client frame
byte maskBitSetAsByte = isClient ? (byte)0x80 : (byte)0x00;
// depending on the size of the length we want to write it as a byte, ushort or ulong
if (fromPayload.Count < 126)
{
byte byte2 = (byte)(maskBitSetAsByte | (byte)fromPayload.Count);
memoryStream.WriteByte(byte2);
}
else if (fromPayload.Count <= ushort.MaxValue)
{
byte byte2 = (byte)(maskBitSetAsByte | 126);
memoryStream.WriteByte(byte2);
BinaryReaderWriter.WriteUShort((ushort)fromPayload.Count, memoryStream, false);
}
else
{
byte byte2 = (byte)(maskBitSetAsByte | 127);
memoryStream.WriteByte(byte2);
BinaryReaderWriter.WriteULong((ulong)fromPayload.Count, memoryStream, false);
}
// if we are creating a client frame then we MUST mack the payload as per the spec
if (isClient)
{
byte[] maskKey = new byte[WebSocketFrameCommon.MaskKeyLength];
_random.NextBytes(maskKey);
memoryStream.Write(maskKey, 0, maskKey.Length);
// mask the payload
ArraySegment<byte> maskKeyArraySegment = new ArraySegment<byte>(maskKey, 0, maskKey.Length);
WebSocketFrameCommon.ToggleMask(maskKeyArraySegment, fromPayload);
}
memoryStream.Write(fromPayload.Array, fromPayload.Offset, fromPayload.Count);
}
See More Examples