Beispiel #1
0
 public static byte[] TransfromXmlStringToHtml(System.Xml.Xsl.XslCompiledTransform xsl, System.Xml.XPath.XPathDocument xpathDoc, System.Xml.Xsl.XsltArgumentList xpathParameter = null)
 {
     byte[] result;
     using (System.IO.Stream str = new System.IO.MemoryStream()) {
         xsl.Transform(xpathDoc, xpathParameter, str);
         str.Position = 0;
         if (str.ReadByte() == bomBuffer[0] && str.ReadByte() == bomBuffer[1] && str.ReadByte() == bomBuffer[2])
         {
             str.Position = 3;
             result       = new byte[str.Length - 3];
         }
         else
         {
             str.Position = 0;
             result       = new byte[str.Length];
         }
         if (str.Length > 0)
         {
             str.Read(result, 0, result.Length);
         }
         else
         {
             result = new byte[0];
         }
         xsl.TemporaryFiles.Delete();
         return(result);
     }
 }
Beispiel #2
0
 object System.Collections.IList.this[int Index] {
     get {
         Validate();
         if (Index > Length())
         {
             return(null);
         }
         long SavedPos;
         byte Result;
         try {
             SavedPos        = Buffer.Position;
             Buffer.Position = (long)Index;
             Result          = (byte)Buffer.ReadByte();
             Buffer.Position = SavedPos;
         } catch (System.Exception Excpt) {
             Err.Add(Excpt);
             return(null);
         }
         return(Result);
     }
     set {
         Validate();
         long SavedPos;
         try {
             SavedPos        = Buffer.Position;
             Buffer.Position = (long)Index;
             Buffer.WriteByte((byte)value);
             Buffer.Position = SavedPos;
         }
         catch (System.Exception Excpt) {
         }
     }
 }
Beispiel #3
0
        internal static int U2FTransportsFromAttnCert(X509ExtensionCollection exts)
        {
            var u2ftransports = 0;

            foreach (var ext in exts)
            {
                if (ext.Oid.Value.Equals("1.3.6.1.4.1.45724.2.1.1"))
                {
                    using (var ms = new System.IO.MemoryStream(ext.RawData.ToArray()))
                    {
                        if (0x3 != ms.ReadByte())
                        {
                            throw new Fido2VerificationException("Expected bit string");
                        }
                        if (0x2 != ms.ReadByte())
                        {
                            throw new Fido2VerificationException("Expected integer value");
                        }
                        var unusedBits = ms.ReadByte(); // number of unused bits
                        // https://fidoalliance.org/specs/fido-u2f-v1.2-ps-20170411/fido-u2f-authenticator-transports-extension-v1.2-ps-20170411.html
                        u2ftransports = ms.ReadByte();  // do something with this?
                    }
                }
            }
            return(u2ftransports);
        }
Beispiel #4
0
 public static byte[] AaguidFromAttnCertExts(X509ExtensionCollection exts)
 {
     byte[] aaguid = null;
     foreach (var ext in exts)
     {
         if (ext.Oid.Value.Equals("1.3.6.1.4.1.45724.1.1.4")) // id-fido-gen-ce-aaguid
         {
             aaguid = new byte[16];
             var ms = new System.IO.MemoryStream(ext.RawData.ToArray());
             // OCTET STRING
             if (0x4 != ms.ReadByte())
             {
                 throw new Fido2VerificationException("Expected octet string value");
             }
             // AAGUID
             if (0x10 != ms.ReadByte())
             {
                 throw new Fido2VerificationException("Unexpected length for aaguid");
             }
             ms.Read(aaguid, 0, 0x10);
             //The extension MUST NOT be marked as critical
             if (true == ext.Critical)
             {
                 throw new Fido2VerificationException("extension MUST NOT be marked as critical");
             }
         }
     }
     return(aaguid);
 }
Beispiel #5
0
        public static int U2FTransportsFromAttnCert(X509ExtensionCollection exts)
        {
            var u2ftransports = 0;

            foreach (var ext in exts)
            {
                if (ext.Oid.Value.Equals("1.3.6.1.4.1.45724.2.1.1"))
                {
                    var ms = new System.IO.MemoryStream(ext.RawData.ToArray());
                    // BIT STRING
                    if (0x3 != ms.ReadByte())
                    {
                        throw new Fido2VerificationException("Expected bit string");
                    }
                    if (0x2 != ms.ReadByte())
                    {
                        throw new Fido2VerificationException("Expected integer value");
                    }
                    var unused = ms.ReadByte();    // unused byte
                    // https://fidoalliance.org/specs/fido-u2f-v1.1-id-20160915/fido-u2f-authenticator-transports-extension-v1.1-id-20160915.html#fido-u2f-certificate-transports-extension
                    u2ftransports = ms.ReadByte(); // do something with this?
                }
            }
            return(u2ftransports);
        }
Beispiel #6
0
        public Byte ReadByte()
        {
            var b = BaseStream.ReadByte();

            if (b == -1)
            {
                throw new System.IO.EndOfStreamException();
            }
            return((Byte)(b));
        }
Beispiel #7
0
        public CompactUInt16(System.IO.MemoryStream ms)
        {
            byte bt1 = (byte)ms.ReadByte();

            if (bt1 >= 0x80)     //0x8* => у нас двухбайтная длина
            {
                bt1 -= 0x80;
                byte bt2 = (byte)ms.ReadByte();
                value = BitConverter.ToUInt16(new byte[] { bt2, bt1 }, 0);
            }
            else
            {
                value = bt1;
            }
        }
Beispiel #8
0
        public static (bool success, UInt32 value) ExtractMultiByte(this System.IO.MemoryStream strm)
        {
            uint len          = 0;
            int  numBytesRead = 0;

            do
            {
                len = len << 7;
                byte theByte = (byte)strm.ReadByte();
                len += (uint)theByte & 0x7F;      // Upper bit denots "theres still another length byte to come"
                numBytesRead++;

                // Bad length, we allow 4 byte at max!
                if (numBytesRead >= 3)
                {
                    return(false, 0);
                }

                if ((theByte & 0x80) == 0)
                {
                    break;
                }
            } while (true);

            return(true, len);
        }
 public static int readByte(byte[] data)
 {
     using (var ms = new System.IO.MemoryStream(data))
     {
         return(ms.ReadByte());
     }
 }
Beispiel #10
0
        public static ObjectBusMessage Deserialize(byte[] buffer)
        {
            Guid      requestID;
            Guid      chunks;
            Exception exception;

            using (System.IO.MemoryStream MS = new System.IO.MemoryStream(buffer, false)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader(MS)) {
                    requestID = new Guid(BR.ReadBytes(16));
                    chunks    = new Guid(BR.ReadBytes(16));
                }
                if (MS.ReadByte() == 1)
                {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    object deserializedObject = BF.Deserialize(MS);
                    if (deserializedObject is Exception)
                    {
                        exception = (Exception)deserializedObject;
                    }
                    else
                    {
                        throw new Exception("buffer contains an object of invalid type, expected System.Exception.");
                    }
                }
                else
                {
                    exception = null;
                }
            }
            return(new TopLevelChunksResponseMessage(requestID, chunks, exception));
        }
        public static TransparentStreamFlushResponseMessage Deserialize(byte[] buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            Guid      streamID;
            Guid      requestID;
            Exception exception;

            using (System.IO.MemoryStream MS = new System.IO.MemoryStream(buffer)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader(MS)) {
                    streamID  = new Guid(BR.ReadBytes(16));
                    requestID = new Guid(BR.ReadBytes(16));
                    if (MS.ReadByte() == 1)
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        object deserializedObject = BF.Deserialize(MS);
                        if (deserializedObject is Exception)
                        {
                            exception = (Exception)deserializedObject;
                        }
                        else
                        {
                            throw new Exception("buffer contains an object of invalid type, expected System.Exception.");
                        }
                    }
                    else
                    {
                        exception = null;
                    }
                }
            }
            return(new TransparentStreamFlushResponseMessage(streamID, requestID, exception));
        }
Beispiel #12
0
        public void readBytes(ByteArray byteArray, uint offset, uint length)
        {
            if (isclosed)
            {
                throw new EOFException();
            }

            byteArray.createMs();
            if (byteArray.ms.Length < offset)
            {
                byteArray.ms.SetLength(offset);
            }
            byteArray.ms.Position = offset;

            if (length == 0)
            {
                length = bytesAvailable;
            }
            else if (length > bytesAvailable)
            {
                throw new EOFException();
            }
            int writebytes = 0;

            ms.Position = position;
            while (ms.Position < ms.Length && writebytes < length)
            {
                writebytes++;
                byteArray.ms.WriteByte((byte)ms.ReadByte());
            }
            //ms.Position = position;
            position = (uint)ms.Position;
        }
Beispiel #13
0
        /// <summary>
        /// クリップボードの"Preferred DropEffect"を調べる
        /// </summary>
        public static DragDropEffects GetPreferredDropEffect(IDataObject data)
        {
            DragDropEffects dde = DragDropEffects.None;

            if (data != null)
            {
                //Preferred DropEffect形式のデータを取得する
                System.IO.MemoryStream ms =
                    (System.IO.MemoryStream)data.GetData("Preferred DropEffect");
                if (ms != null)
                {
                    //先頭のバイトからDragDropEffectsを取得する
                    dde = (DragDropEffects)ms.ReadByte();

                    if (dde == (DragDropEffects.Copy | DragDropEffects.Link))
                    {
                    }
                    else if (dde == DragDropEffects.Move)
                    {
                    }
                }
            }

            return(dde);
        }
Beispiel #14
0
        public static Bitmap GetBackgroundPic(I_DLE device, int address, byte mode, byte g_code_id, ref string desc)
        {
            RGS_SetBackgroundPic_frame frame=null;
            System.IO.MemoryStream ms;
            byte[] cmdText = new byte[] { 0x98, mode, g_code_id };
            SendPackage pkg = new SendPackage(CmdType.CmdQuery, CmdClass.A, address, cmdText);
            device.Send(pkg);
            if (pkg.result != CmdResult.ACK)
                throw new Exception("cmd error:" + pkg.result);

            byte frame_no = pkg.ReturnTextPackage.Text[3]; //0x98 frame_no
            ms = new System.IO.MemoryStream(1024 * 1024*3);
            for (int i = 1; i <= frame_no; i++)
            {
                cmdText = new byte[] {0x98,mode,g_code_id,(byte)i };

                pkg = new SendPackage(CmdType.CmdQuery, CmdClass.A, address, cmdText);

                device.Send(pkg);

                frame = new RGS_SetBackgroundPic_frame(pkg.ReturnTextPackage);

                ms.Write(frame.g_pattern_color, 0, frame.g_pattern_color.Length);

            }

            Bitmap pic = new Bitmap(frame.g_width, frame.g_height);

            ms.Position = 0;

            for(int y =0;y<frame.g_height;y++)
                for (int x = 0; x < frame.g_width; x++)
                {
                   // int r, g, b;
                    //r = ms.ReadByte();
                    //g = ms.ReadByte();
                    //b = ms.ReadByte();
                    pic.SetPixel(x, y, Color.FromArgb(ms.ReadByte(),ms.ReadByte(), ms.ReadByte()));
                }

               desc= System.Text.Encoding.Unicode.GetString(frame.g_desc);

            ms.Dispose();
            return pic;
        }
Beispiel #15
0
 public override byte ReadByte()
 {
     try
     {
         return((byte)buffer.ReadByte());
     }
     catch (ObjectDisposedException)
     {
         throw new System.IO.IOException("read past EOF");
     }
 }
 public override BaseMsg decode(byte[] data)
 {
     using (var stream = new System.IO.MemoryStream(data))
     {
         stream.ReadByte();
         StreamHelp.readLenAndByte(stream, out tableid);
         StreamHelp.readLenAndByte(stream, out key);
         StreamHelp.readLenAndByte(stream, out value);
         return(this);
     }
 }
 /// <summary> Reads a single bit from the input.
 ///
 /// </summary>
 /// <returns> The read bit (0 or 1)
 ///
 /// </returns>
 /// <exception cref="IOException">If an I/O error occurred
 /// </exception>
 /// <exception cref="EOFException">If teh end of file has been reached
 ///
 /// </exception>
 internal int readBit()
 {
     if (bpos == 0)
     {
         // Is bit buffer empty?
         if (bbuf != 0xFF)
         {
             // No bit stuffing
             if (usebais)
             {
                 bbuf = bais.ReadByte();
             }
             else
             {
                 bbuf = in_Renamed.read();
             }
             bpos = 8;
             if (bbuf == 0xFF)
             {
                 // If new bit stuffing get next byte
                 if (usebais)
                 {
                     nextbbuf = bais.ReadByte();
                 }
                 else
                 {
                     nextbbuf = in_Renamed.read();
                 }
             }
         }
         else
         {
             // We had bit stuffing, nextbuf can not be 0xFF
             bbuf = nextbbuf;
             bpos = 7;
         }
     }
     return((bbuf >> --bpos) & 0x01);
 }
        public static byte[] parseStreamToArrayByte(System.IO.MemoryStream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position  = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return(buffer);
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
 public override byte ReadByte()
 {
     // Performance might be improved by reading ahead into an array of
     // eg. 128 bytes and readByte() from there.
     if (curAvail == 0)
     {
         curBufIndex++;
         curBuf = buffers[curBufIndex];                     // index out of bounds when too many bytes requested
         curBuf.Seek(0, System.IO.SeekOrigin.Begin);
         curAvail = bufSizes[curBufIndex];
     }
     curAvail--;
     return((byte)curBuf.ReadByte());
 }
Beispiel #20
0
        static StackObject *ReadByte_14(ILIntepreter __intp, StackObject *__esp, IList <object> __mStack, CLRMethod __method, bool isNewObj)
        {
            ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;
            StackObject *ptr_of_this_method;
            StackObject *__ret = ILIntepreter.Minus(__esp, 1);

            ptr_of_this_method = ILIntepreter.Minus(__esp, 1);
            System.IO.MemoryStream instance_of_this_method = (System.IO.MemoryStream) typeof(System.IO.MemoryStream).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack));
            __intp.Free(ptr_of_this_method);

            var result_of_this_method = instance_of_this_method.ReadByte();

            __ret->ObjectType = ObjectTypes.Integer;
            __ret->Value      = result_of_this_method;
            return(__ret + 1);
        }
Beispiel #21
0
 public static object Deserialize(ArraySegment <byte> buffer)
 {
     using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer.Array, 0, buffer.Count))
     {
         stream.Position = 0;
         int type = stream.ReadByte();
         if (type == 1)
         {
             return(ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, typeof(LogModel)));
         }
         else
         {
             return(ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, typeof(StatModel)));
         }
     }
 }
Beispiel #22
0
 public static object Deserialize(ArraySegment<byte> buffer)
 {
     using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer.Array,0,buffer.Count))
     {
         stream.Position = 0;
         int type = stream.ReadByte();
         if (type == 1)
         {
             return ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, typeof(LogModel));
         }
         else
         {
             return ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(stream, null, typeof(StatModel));
         }
     }
 }
 /*
  * This routine reads bits in from a stream.  The bits are all sitting
  * in a buffer, and this code pulls them out, one at a time.  When the
  * buffer has been emptied, that triggers a new stream read, and the
  * pointers are reset.  This routine is set up to allow for dummy
  * bits/bytes to be read in after the end of of the stream is reached.
  * All be zero(0) valued bits however. This is because we have to keep
  * feeding bits into the pipeline to be decoded so that the old stuff
  * that is 16 bits upstream can be pushed out.
  */
 private ushort input_bit()
 {
     if (input_bits_left == 0)
     {
         if (input_bytes_left > 0)
         {
             current_input_byte = Convert.ToByte(input_buffer.ReadByte());
         }
         else
         {
             return(0);
         }
         input_bytes_left--;
         input_bits_left = 8;
     }
     input_bits_left--;
     return(Convert.ToUInt16((current_input_byte >> input_bits_left) & 1));
 }
Beispiel #24
0
 public override byte ReadByte()
 {
     // Performance might be improved by reading ahead into an array of
     // e.g. 128 bytes and readByte() from there.
     if (curAvail == 0)
     {
         curBufIndex++;
         if (curBufIndex >= buffers.Length)
         {
             throw new System.IO.IOException("read past EOF");
         }
         curBuf = buffers[curBufIndex];
         curBuf.Seek(0, System.IO.SeekOrigin.Begin);
         curAvail = bufSizes[curBufIndex];
     }
     curAvail--;
     return((byte)curBuf.ReadByte());
 }
        static void Main()
        {
            string text = "In-memory text.";

            byte[] bytes = Encoding.UTF8.GetBytes(text);
            using (var memoryStream = new System.IO.MemoryStream(bytes))
            {
                while (true)
                {
                    int readByte = memoryStream.ReadByte();
                    if (readByte == -1)
                    {
                        break;
                    }
                    Console.WriteLine((char)readByte);
                }
            }
        }
Beispiel #26
0
        private int DisplayMemory(StringBuilder sb, System.IO.MemoryStream ms)
        {
            int  b            = 0;
            long DisplayLimit = ms.Length < 1000L ? ms.Length : 1000;

            for (; ms.Position != DisplayLimit;)
            {
                b = ms.ReadByte();
                if (b == 0)
                {
                    sb.Append("\x1");
                }
                else
                {
                    sb.Append(((char)b).ToString());
                }
            }
            return(b);
        }
Beispiel #27
0
 public static string GenerateHexDump(byte[] data) {
     if (data == null || data.Length == 0)
         return "";
     int size = data.Length;
     //ByteBuffer buffer = new ByteBuffer(data);
     System.IO.MemoryStream buffer = new System.IO.MemoryStream(data);
     //long remaining = (buffer.Length - buffer.Position);
     string ascii = "";
     //StringBuilder sb = new StringBuilder((buffer.Remaining * 3) - 1);
     StringBuilder sb = new StringBuilder(((int)(buffer.Length - buffer.Position) * 3) - 1);
     System.IO.StringWriter writer = new System.IO.StringWriter(sb);
     int lineCount = 0;
     for (int i = 0; i < size; i++) {
         int val = buffer.ReadByte() & 0xFF;
         writer.Write((char)highDigits[val]);
         writer.Write((char)lowDigits[val]);
         writer.Write(" ");
         ascii += GetAsciiEquivalent(val) + " ";
         lineCount++;
         if (i == 0)
             continue;
         if ((i + 1) % 8 == 0)
             writer.Write("  ");
         if ((i + 1) % 16 == 0) {
             writer.Write(" ");
             writer.Write(ascii);
             writer.WriteLine();
             ascii = "";
             lineCount = 0;
         } else if (i == size - 1) {///HALF-ASSED ATTEMPT TO GET THE LAST LINE OF ASCII TO LINE UP CORRECTLY
             //while(lineCount < 84) {
             //    writer.Write(" ");
             //    lineCount++;
             //}
             for (int y = lineCount; y < 25; y++) {
                 writer.Write(" ");
             }
             writer.Write(ascii);
             writer.WriteLine();
         }
     }
     return sb.ToString();
 }
        protected override object IGetObject(System.IO.MemoryStream bytes)
        {
            object obj;
            byte   comprobarNull = (byte)bytes.ReadByte();

            if (comprobarNull == ElementoBinario.NULL)
            {
                obj = null;
            }
            else if (comprobarNull == ElementoBinario.NOTNULL)
            {
                obj = JGetObject(bytes);
            }
            else
            {
                throw new TipoException();
            }
            return(obj);
        }
        }         // End Function Decompress

        public static byte[] Decompress(byte[] inputBytes)
        {
            byte[] retVal = null;

            SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder();

            using (System.IO.MemoryStream strmInStream = new System.IO.MemoryStream(inputBytes))
            {
                strmInStream.Seek(0, 0);

                using (System.IO.MemoryStream strmOutStream = new System.IO.MemoryStream())
                {
                    byte[] properties2 = new byte[5];
                    if (strmInStream.Read(properties2, 0, 5) != 5)
                    {
                        throw (new System.Exception("input .lzma is too short"));
                    }

                    long outSize = 0;
                    for (int i = 0; i < 8; i++)
                    {
                        int v = strmInStream.ReadByte();
                        if (v < 0)
                        {
                            throw (new System.Exception("Can't Read 1"));
                        }
                        outSize |= ((long)(byte)v) << (8 * i);
                    } // Next i

                    decoder.SetDecoderProperties(properties2);

                    long compressedSize = strmInStream.Length - strmInStream.Position;
                    decoder.Code(strmInStream, strmOutStream, compressedSize, outSize, null);

                    retVal = strmOutStream.ToArray();
                } // End Using newOutStream
            }     // End Using newInStream

            return(retVal);
        } // End Function Decompress
        public static ObjectBusMessage Deserialize(byte[] bytes)
        {
            Guid requestID;

            Table[]   tables;
            Exception exception;

            using (System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes, false)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader(MS)) {
                    requestID = new Guid(BR.ReadBytes(16));
                    tables    = new Table[BR.ReadInt32()];
                    for (int n = 0; n != tables.Length; n++)
                    {
                        tables [n] = Table.Deserialize(BR.ReadBytes(BR.ReadInt32()));
                    }
                    if (MS.ReadByte() == 1)
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        object deserializedObject = BF.Deserialize(MS);
                        if (deserializedObject is Exception)
                        {
                            exception = (Exception)deserializedObject;
                        }
                        else if (deserializedObject is string)
                        {
                            exception = new Exception((string)deserializedObject);
                        }
                        else
                        {
                            throw new Exception("buffer contains an object of invalid type, expected System.Exception.");
                        }
                    }
                    else
                    {
                        exception = null;
                    }
                    return(new GetTablesResponseMessage(requestID, tables, exception));
                }
            }
        }
Beispiel #31
0
        private byte[] GetBMPData(BitmapFrame Frame)
        {
            System.IO.MemoryStream DataStream = new System.IO.MemoryStream();
            BmpBitmapEncoder       encoder    = new BmpBitmapEncoder();

            encoder.Frames.Add(Frame);
            encoder.Save(DataStream);
            encoder             = null;
            DataStream.Position = 14;
            System.IO.BinaryReader DataStreamReader    = new System.IO.BinaryReader(DataStream, System.Text.UTF32Encoding.UTF32);
            System.IO.MemoryStream OutDataStream       = new System.IO.MemoryStream();
            System.IO.BinaryWriter OutDataStreamWriter = new System.IO.BinaryWriter(OutDataStream, System.Text.UTF32Encoding.UTF32);
            OutDataStreamWriter.Write(DataStreamReader.ReadUInt32());
            OutDataStreamWriter.Write(DataStreamReader.ReadInt32());
            int height = DataStreamReader.ReadInt32();

            if (height > 0)
            {
                height = height * 2;
            }
            else if (height < 0)
            {
                height = -(height * 2);
            }
            else
            {
                height = 0;
            }
            OutDataStreamWriter.Write(height);
            for (int i = 26; i <= DataStream.Length - 1; i++)
            {
                OutDataStream.WriteByte((byte)(DataStream.ReadByte()));
            }
            byte[] data = OutDataStream.GetBuffer();
            OutDataStreamWriter.Close();
            OutDataStream.Close();
            DataStreamReader.Close();
            DataStream.Close();
            return(data);
        }
Beispiel #32
0
        static int _m_ReadByte(RealStatePtr L)
        {
            try {
                ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);


                System.IO.MemoryStream gen_to_be_invoked = (System.IO.MemoryStream)translator.FastGetCSObj(L, 1);



                {
                    int gen_ret = gen_to_be_invoked.ReadByte(  );
                    LuaAPI.xlua_pushinteger(L, gen_ret);



                    return(1);
                }
            } catch (System.Exception gen_e) {
                return(LuaAPI.luaL_error(L, "c# exception:" + gen_e));
            }
        }
        public static ObjectBusMessage Deserialize(byte[] bytes)
        {
            Console.WriteLine("GetRowsResponseMessage.Deserialize()");
            Guid      requestID;
            Exception exception;

            using (System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes, false)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader(MS)) {
                    requestID = new Guid(BR.ReadBytes(16));
                    int rc = BR.ReadInt32();
                    Console.WriteLine("Response contains {0} rows", rc);
                    System.Collections.Generic.List <BD2.Conv.Frontend.Table.Row> rows = new  System.Collections.Generic.List <BD2.Conv.Frontend.Table.Row> ();
                    for (int n = 0; n != rc; n++)
                    {
                        Row r = Row.Deserialize(BR.ReadBytes(BR.ReadInt32()));
                        rows.Add(r);
                    }
                    if (MS.ReadByte() == 1)
                    {
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        object deserializedObject = BF.Deserialize(MS);
                        if (deserializedObject is Exception)
                        {
                            exception = (Exception)deserializedObject;
                        }
                        else
                        {
                            throw new Exception("buffer contains an object of invalid type, expected System.Exception.");
                        }
                    }
                    else
                    {
                        exception = null;
                    }
                    return(new GetRowsResponseMessage(requestID, rows, exception));
                }
            }
        }
 public static TransparentStreamCanReadResponseMessage Deserialize(byte[] buffer)
 {
     if (buffer == null)
         throw new ArgumentNullException ("buffer");
     Guid streamID;
     Guid requestID;
     bool canRead;
     Exception exception;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             streamID = new Guid (BR.ReadBytes (16));
             requestID = new Guid (BR.ReadBytes (16));
             canRead = BR.ReadBoolean ();
             if (MS.ReadByte () == 1) {
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 object deserializedObject = BF.Deserialize (MS);
                 if (deserializedObject is Exception) {
                     exception = (Exception)deserializedObject;
                 } else {
                     throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                 }
             } else
                 exception = null;
         }
     }
     return new TransparentStreamCanReadResponseMessage (streamID, requestID, canRead, exception);
 }
Beispiel #35
0
        private void CreateSystemNameTable()
        {
            var table_size = BitConverter.ToUInt32( this.pm_.ReadMemory( this.system_table_config_.TableSizeAddress, 4 ), 0 );
            var pointer_address = BitConverter.ToUInt32( this.pm_.ReadMemory( this.system_table_config_.PointerAddress, 4 ), 0 );
            var table = this.pm_.ReadMemory( pointer_address, table_size );

            using( var ms = new System.IO.MemoryStream( table ) ) {
                for( var i=0; i<this.system_table_config_.RecordMaxLength; ++i ) {
                    var b = 0;
                    var name_data = new KOEI.WP7_2012.Horse.Name.NameData() {
                        Id = (uint)i,
                        Type = KOEI.WP7_2012.Horse.Name.NameDataType.SYSTEM,
                    };
                    using( var buff = new System.IO.MemoryStream() ) {
                        while( true ) {
                            if( ( b = ms.ReadByte() ) == -1 ) {
                                throw new Exception("馬名テーブルが解析できませんでした");
                            }
                            if( !IsKana( (byte)b ) && !IsEnglish( (byte)b ) ) {
                                throw new Exception("馬名テーブルが解析できませんでした(カナ)");
                            }
                            if( !IsKana( (byte)b ) ) {
                                ms.Seek( -1, System.IO.SeekOrigin.Current );
                                name_data.Kana = KOEI.WP7_2012.Helper.KoeiCode.ToString( buff.ToArray() );
                                break;
                            }
                            buff.WriteByte( (byte)b );
                        }
                    }
                    using( var buff = new System.IO.MemoryStream() ) {
                        while( true ) {
                            if( ( b = ms.ReadByte() ) == -1 ) {
                                break;
            //								throw new Exception("馬名テーブルが解析できませんでした");
                            }
                            if( !IsKana( (byte)b ) && !IsEnglish( (byte)b ) && i != this.system_table_config_.RecordMaxLength ) {
                                throw new Exception("馬名テーブルが解析できませんでした(英語)");
                            }
                            if( !IsEnglish( (byte)b ) ) {
                                ms.Seek( -1, System.IO.SeekOrigin.Current );
                                name_data.English = KOEI.WP7_2012.Helper.KoeiCode.ToString( buff.ToArray() );
                                break;
                            }
                            // ①とか余計な文字は無視する
                            if( ( b >= 0x57 && b <= 0x9E ) || b == 0xFD ) {
                                buff.WriteByte( (byte)b );
                            }
                        }
                    }
                    this.name_data_dic_[i] = name_data;
                }
            }
        }
Beispiel #36
0
 public static ObjectBusMessage Deserialize(byte[] bytes)
 {
     Console.WriteLine ("GetRowsResponseMessage.Deserialize()");
     Guid requestID;
     Exception exception;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             requestID = new Guid (BR.ReadBytes (16));
             int rc = BR.ReadInt32 ();
             Console.WriteLine ("Response contains {0} rows", rc);
             System.Collections.Generic.List<BD2.Conv.Frontend.Table.Row> rows = new  System.Collections.Generic.List<BD2.Conv.Frontend.Table.Row> ();
             for (int n = 0; n != rc; n++) {
                 Row r = Row.Deserialize (BR.ReadBytes (BR.ReadInt32 ()));
                 rows.Add (r);
             }
             if (MS.ReadByte () == 1) {
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 object deserializedObject = BF.Deserialize (MS);
                 if (deserializedObject is Exception) {
                     exception = (Exception)deserializedObject;
                 } else {
                     throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                 }
             } else
                 exception = null;
             return new GetRowsResponseMessage (requestID, rows, exception);
         }
     }
 }
        public static ObjectBusMessage Deserialize(byte[] buffer)
        {
            Guid requestID;
            Guid chunks;
            Exception exception;

            using (System.IO.MemoryStream MS = new System.IO.MemoryStream (buffer, false)) {
                using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
                    requestID = new Guid (BR.ReadBytes (16));
                    chunks = new Guid (BR.ReadBytes (16));
                }
                if (MS.ReadByte () == 1) {
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                    object deserializedObject = BF.Deserialize (MS);
                    if (deserializedObject is Exception) {
                        exception = (Exception)deserializedObject;
                    } else {
                        throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                    }
                } else
                    exception = null;
            }
            return new TopLevelChunksResponseMessage (requestID, chunks, exception);
        }
Beispiel #38
0
 public static ObjectBusMessage Deserialize(byte[] bytes)
 {
     Guid requestID;
     Table[] tables;
     Exception exception;
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream (bytes, false)) {
         using (System.IO.BinaryReader BR = new System.IO.BinaryReader (MS)) {
             requestID = new Guid (BR.ReadBytes (16));
             tables = new Table[BR.ReadInt32 ()];
             for (int n = 0; n != tables.Length; n++) {
                 tables [n] = Table.Deserialize (BR.ReadBytes (BR.ReadInt32 ()));
             }
             if (MS.ReadByte () == 1) {
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 object deserializedObject = BF.Deserialize (MS);
                 if (deserializedObject is Exception) {
                     exception = (Exception)deserializedObject;
                 } else if (deserializedObject is string) {
                     exception = new Exception ((string)deserializedObject);
                 } else {
                     throw new Exception ("buffer contains an object of invalid type, expected System.Exception.");
                 }
             } else
                 exception = null;
             return new GetTablesResponseMessage (requestID, tables, exception);
         }
     }
 }
Beispiel #39
0
 private static void ParseAvcConfig(
     MediaStreamDescription stream, 
     List<MediaStreamSample> samples, 
     byte[] data)
 {
     System.IO.Stream ios = new System.IO.MemoryStream(data);
     ios.Seek(5, System.IO.SeekOrigin.Begin);
     int num_sps = ios.ReadByte() & 0x1f;
     for (int i = 0; i < num_sps; ++i)
     {
         int len_sps = (ios.ReadByte() << 8) | ios.ReadByte();
         byte[] sps = new byte[len_sps];
         ios.Read(sps, 0, len_sps);
         samples.Add(new MediaStreamSample(
             stream, 
             new System.IO.MemoryStream(sps), 
             0, 
             len_sps, 
             0, 
             new Dictionary<MediaSampleAttributeKeys, string>()));
     }
     int num_pps = ios.ReadByte();
     for (int i = 0; i < num_pps; ++i)
     {
         int len_pps = (ios.ReadByte() << 8) | ios.ReadByte();
         byte[] pps = new byte[len_pps];
         ios.Read(pps, 0, len_pps);
         samples.Add(new MediaStreamSample(
             stream, 
             new System.IO.MemoryStream(pps), 
             0, 
             len_pps, 
             0, 
             new Dictionary<MediaSampleAttributeKeys, string>()));
     }
 }
Beispiel #40
0
 public static byte[] TransfromXmlStringToHtml(System.Xml.Xsl.XslCompiledTransform xsl, System.Xml.XPath.XPathDocument xpathDoc, System.Xml.Xsl.XsltArgumentList xpathParameter = null)
 {
     byte[] result;
     using (System.IO.Stream str = new System.IO.MemoryStream()) {
         xsl.Transform(xpathDoc, xpathParameter, str);
         str.Position = 0;
         if (str.ReadByte() == bomBuffer[0] && str.ReadByte() == bomBuffer[1] && str.ReadByte() == bomBuffer[2]) {
             str.Position = 3;
             result = new byte[str.Length - 3];
         } else {
             str.Position = 0;
             result = new byte[str.Length];
         }
         if (str.Length > 0) {
             str.Read(result, 0, result.Length);
         } else {
             result = new byte[0];
         }
         xsl.TemporaryFiles.Delete();
         return result;
     }
 }
Beispiel #41
0
        /// <summary>
        /// Writes the packets to a memory stream and creates the default header and quantization tables if necessary.
        /// Assigns Image from the result
        /// </summary>
        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 document
               and future revisions of this document. 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 document).

               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 document (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 = (uint)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)
                    {
                        logger.WarnFormat("ProcessMjpegFrame could not determine either the width or height of the jpeg frame (width={0}, height={1}).", Width, Height);
                    }

                    //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();
            }
        }
        public static IEnumerable<TBUserNote> GetUserNotes(IWebAgent webAgent, string subName)
        {
            var request = webAgent.CreateGet(String.Format(ToolBoxUserNotesWiki, subName));
            var reqResponse = webAgent.ExecuteRequest(request);
            var response = JObject.Parse(reqResponse["data"]["content_md"].Value<string>());

            int version = response["ver"].Value<int>();
            string[] mods = response["constants"]["users"].Values<string>().ToArray();

            string[] warnings = response["constants"]["warnings"].Values<string>().ToArray();

            if (version < 6) throw new ToolBoxUserNotesException("Unsupported ToolBox version");

            try
            {
                var data = Convert.FromBase64String(response["blob"].Value<string>());

                string uncompressed;
                using (System.IO.MemoryStream compressedStream = new System.IO.MemoryStream(data))
                {
                    compressedStream.ReadByte();
                    compressedStream.ReadByte(); //skips first to bytes to fix zlib block size
                    using (DeflateStream blobStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
                    {
                        using (var decompressedReader = new System.IO.StreamReader(blobStream))
                        {
                            uncompressed = decompressedReader.ReadToEnd();
                        }

                    }
                }

                JObject users = JObject.Parse(uncompressed);

                List<TBUserNote> toReturn = new List<TBUserNote>();
                foreach (KeyValuePair<string, JToken> user in users)
                {
                    var x = user.Value;
                    foreach (JToken note in x["ns"].Children())
                    {

                        TBUserNote uNote = new TBUserNote();
                        uNote.AppliesToUsername = user.Key;
                        uNote.SubName = subName;
                        uNote.SubmitterIndex = note["m"].Value<int>();
                        uNote.Submitter = mods[uNote.SubmitterIndex];
                        uNote.NoteTypeIndex = note["w"].Value<int>();
                        uNote.NoteType = warnings[uNote.NoteTypeIndex];
                        uNote.Message = note["n"].Value<string>();
                        uNote.Timestamp = UnixTimeStamp.UnixTimeStampToDateTime(note["t"].Value<long>());
                        uNote.Url = UnsquashLink(subName, note["l"].ValueOrDefault<string>());

                        toReturn.Add(uNote);
                    }
                }
                return toReturn;
            }
            catch (Exception e)
            {
                throw new ToolBoxUserNotesException("An error occured while processing Usernotes wiki. See inner exception for details", e);
            }
        }
Beispiel #43
0
        // TODO: re-add encryption
        private void BeginReceiveCallback(IAsyncResult ar)
        {
            Queue<Action> actionQueue = new Queue<Action>();
            try
            {
                TcpClient lEndPoint = EndPoint;
                Thread.MemoryBarrier();
                if (lEndPoint == null)
                {
                    ("NoEndPoint for " + this.DisplayName).Log();
                    fragmentBuffer = new byte[0];
                    return;
                }
                int cb = lEndPoint.Client.EndReceive(ar);

                if (cb == 0)
                {
                    //Disconnect();
                    return;
                }

                byte[] receiveBuffer = ar.AsyncState as byte[];

                if (fragmentBuffer.Length > 0)
                {
                    var temp = new byte[cb + fragmentBuffer.Length];
                    fragmentBuffer.CopyTo(temp, 0);
                    Array.ConstrainedCopy(receiveBuffer, 0, temp, fragmentBuffer.Length, cb);
                    fragmentBuffer = new byte[0];
                    receiveBuffer = temp;
                }
                else
                {
                    var temp = new byte[cb];
                    Array.ConstrainedCopy(receiveBuffer, 0, temp, 0, cb);
                    receiveBuffer = temp;
                }

                //("MCNC: receiveBuffer=" + System.Text.Encoding.ASCII.GetString(receiveBuffer)).Log();

                var stream = new System.IO.MemoryStream(receiveBuffer);
                using (var reader = new System.IO.BinaryReader(stream))
                {
                    while (stream.Position < stream.Length && stream.ReadByte() == 0x1b)
                    {
                        var lastReadPosition = stream.Position - 1;
                        object o = null;
                        try
                        {
                            var len = reader.ReadUInt16();
                            byte[] payload = new byte[len];
                            stream.Read(payload, 0, payload.Length);
                            using (var payloadStream = new System.IO.MemoryStream(payload))
                            {
                                o = Serializer.ReadObject(payloadStream);
                            }
                        }
                        catch (Exception ex)
                        {
                            //("MCNC: lastReadPosition=" + lastReadPosition + " currentPosition=" + stream.Position).Log();

                            ex.Log();
                            // TODO: log/debug exception types thrown here, not documented on MSDN and it's not clear how to handle a buffer underrun in ReadObject
                            // TODO: if the exception is due to an unknown type, the fragmentBuffer logic will result in a deadlock on the network (always retrying a bad object)
                            o = null;
                        }

                        if (o == null)
                        {
                            stream.Seek(lastReadPosition, System.IO.SeekOrigin.Begin);
                            fragmentBuffer = new byte[stream.Length - lastReadPosition];
                            stream.Read(fragmentBuffer, 0, fragmentBuffer.Length);
                            break;
                        }
                        else
                        {
                            EnqueueAction(actionQueue, o);
                        }
                    }
                }

                if (actionQueue.Count == 0)
                {
                    ("NoActions for " + this.DisplayName).Log();
                    return;
                }

                #region process action queue

                while (actionQueue.Count > 0)
                {
                    Action action = actionQueue.Dequeue();
                    if (action != null)
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception ex)
                        {
                            ex.Log();
                        }
                    }
                }

                #endregion process action queue
            }
            catch (SocketException)
            {
                Disconnect();
            }
            catch (ObjectDisposedException)
            {
                Disconnect();
            }
            catch (Exception ex)
            {
                ex.Log();
            }
            finally
            {
                StartReceiving();
            }
        }
Beispiel #44
0
		/// <summary> Return the packed packet headers for a given tile.
		/// 
		/// </summary>
		/// <returns> An input stream containing the packed packet headers for a
		/// particular tile
		/// 
		/// </returns>
		/// <exception cref="IOException">If an I/O error occurs while reading from the
		/// encoder header stream
		/// 
		/// </exception>
		public virtual System.IO.MemoryStream getPackedPktHead(int tile)
		{
			
			if (pkdPktHeaders == null)
			{
				int i, t;
				pkdPktHeaders = new System.IO.MemoryStream[nTiles];
				for (i = nTiles - 1; i >= 0; i--)
				{
					pkdPktHeaders[i] = new System.IO.MemoryStream();
				}
				if (nPPMMarkSeg != 0)
				{
					// If this is first time packed packet headers are requested,
					// create packed packet headers from Nppm and Ippm fields
					int nppm;
					int nTileParts = tileOfTileParts.Count;
					byte[] temp;
					System.IO.MemoryStream pph;
					System.IO.MemoryStream allNppmIppm = new System.IO.MemoryStream();
					
					// Concatenate all Nppm and Ippm fields
					for (i = 0; i < nPPMMarkSeg; i++)
					{
						byte[] temp_byteArray;
						temp_byteArray = pPMMarkerData[i];
						allNppmIppm.Write(temp_byteArray, 0, temp_byteArray.Length);
					}
					pph = new System.IO.MemoryStream(allNppmIppm.ToArray());
					
					// Read all packed packet headers and concatenate for each
					// tile part
					for (i = 0; i < nTileParts; i++)
					{
						t = ((System.Int32) tileOfTileParts[i]);
						// get Nppm value
						nppm = (pph.ReadByte() << 24) | (pph.ReadByte() << 16) | (pph.ReadByte() << 8) | (pph.ReadByte());
						
						temp = new byte[nppm];
						// get ippm field
                        pph.Read(temp, 0, temp.Length); //SupportClass.ReadInput(pph, temp, 0, temp.Length);
						byte[] temp_byteArray2;
						temp_byteArray2 = temp;
						pkdPktHeaders[t].Write(temp_byteArray2, 0, temp_byteArray2.Length);
					}
				}
				else
				{
					int tp;
					// Write all packed packet headers to pkdPktHeaders
					for (t = nTiles - 1; t >= 0; t--)
					{
						for (tp = 0; tp < nTileParts[t]; tp++)
						{
							for (i = 0; i < nPPTMarkSeg[t][tp]; i++)
							{
								byte[] temp_byteArray3;
								temp_byteArray3 = tilePartPkdPktHeaders[t][tp][i];
								pkdPktHeaders[t].Write(temp_byteArray3, 0, temp_byteArray3.Length);
							}
						}
					}
				}
			}
			
			return new System.IO.MemoryStream(pkdPktHeaders[tile].ToArray());
		}