public override byte[] GetMessageBody()
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream()) {
         using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter(MS)) {
             BW.Write(requestID.ToByteArray());
             BW.Write(rows.Count);
             Console.WriteLine("Sending {0} rows in response", rows.Count);
             foreach (BD2.Conv.Frontend.Table.Row r in rows)
             {
                 byte[] buf = r.Serialize();
                 BW.Write(buf.Length);
                 BW.Write(buf);
             }
             if (exception == null)
             {
                 MS.WriteByte(0);
             }
             else
             {
                 MS.WriteByte(1);
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                 BF.Serialize(MS, exception);
             }
             return(MS.ToArray());
         }
     }
 }
        public void RomMetadataCredits_ContainsEvilBytes_ProducesExpectedUnicodeString()
        {
            using (var metadataCreditsStream = new System.IO.MemoryStream())
            {
                var bytes = new byte[255];
                metadataCreditsStream.WriteByte(1); // Programmer credit
                for (var i = 1; i <= 255; ++i)
                {
                    metadataCreditsStream.WriteByte((byte)i);
                    bytes[i - 1] = (byte)i;
                }
                metadataCreditsStream.Seek(0, System.IO.SeekOrigin.Begin);
                using (var reader = new INTV.Core.Utility.BinaryReader(metadataCreditsStream))
                {
                    var streamLength = metadataCreditsStream.Length;
                    var credits      = new RomMetadataCredits((uint)streamLength);
                    var bytesDecoded = credits.Deserialize(reader);

                    // The first byte is 0x01 -- which is stuffed in credits parsing, so "stuff" it here.
                    var expectedString = System.Text.Encoding.UTF8.GetString(bytes, 1, 254);
                    Assert.Equal(streamLength, bytesDecoded);
                    Assert.Equal(expectedString, credits.Programming.First());
                }
            }
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fc"></param>
        /// <param name="sim"></param>
        /// <param name="userData"></param>
        /// <returns></returns>
        static public byte[] MakeDtuCommand(byte fc, string sim, byte[] userData)
        {
            int userDataLen = userData != null ? userData.Length : 0;

            //if ( userData != null )
            //    userDataLen = userData.Length;
            byte[] cmd = new byte[SGDefine.MIN_PA_LEN + userDataLen];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(cmd);
            ms.WriteByte(SGDefine.HEAD_VALUE);
            ms.WriteByte(fc);
            ms.Write(GetDtuLengthBytes(userDataLen + SGDefine.MIN_PA_LEN), 0, 2);

            byte[] simbs = SGDtu.GetSimNumberBytes(sim);
            ms.Write(simbs, 0, simbs.Length);

            if (userData != null && userData.Length > 0)
            {
                ms.Write(userData, 0, userData.Length);
            }
            ms.WriteByte(SGDefine.TAIL_VALUE);

            //return ms.GetBuffer();
            return(ms.ToArray());
            //return (byte[])ms;
        }
Beispiel #4
0
        /// <summary>
        /// Create the bytes-package to request data from the PLC. You have to specify the memory type (dataType),
        /// the address of the memory, the address of the byte and the bytes count.
        /// </summary>
        /// <param name="dataType">MemoryType (DB, Timer, Counter, etc.)</param>
        /// <param name="db">Address of the memory to be read</param>
        /// <param name="startByteAdr">Start address of the byte</param>
        /// <param name="count">Number of bytes to be read</param>
        /// <returns></returns>
        private static void BuildReadDataRequestPackage(System.IO.MemoryStream stream, DataType dataType, int db, int startByteAdr, int count = 1)
        {
            //single data req = 12
            stream.WriteByteArray(new byte[] { 0x12, 0x0a, 0x10 });
            switch (dataType)
            {
            case DataType.Timer:
            case DataType.Counter:
                stream.WriteByte((byte)dataType);
                break;

            default:
                stream.WriteByte(0x02);
                break;
            }

            stream.WriteByteArray(Word.ToByteArray((ushort)(count)));
            stream.WriteByteArray(Word.ToByteArray((ushort)(db)));
            stream.WriteByte((byte)dataType);
            var overflow = (int)(startByteAdr * 8 / 0xffffU); // handles words with address bigger than 8191

            stream.WriteByte((byte)overflow);
            switch (dataType)
            {
            case DataType.Timer:
            case DataType.Counter:
                stream.WriteByteArray(Types.Word.ToByteArray((ushort)(startByteAdr)));
                break;

            default:
                stream.WriteByteArray(Types.Word.ToByteArray((ushort)((startByteAdr) * 8)));
                break;
            }
        }
Beispiel #5
0
        private static byte[] EncodeDER(byte[][] data)
        {
            byte[] payload;
            using (var ms = new System.IO.MemoryStream())
            {
                foreach (var b in data)
                {
                    ms.WriteByte(0x02);
                    var isNegative = (b[0] & 0x80) != 0;

                    EncodeDERLength(ms, (uint)(b.Length + (isNegative ? 1 : 0)));
                    if (isNegative)
                    {
                        ms.WriteByte(0);
                    }
                    ms.Write(b, 0, b.Length);
                }

                payload = ms.ToArray();
            }

            using (var ms = new System.IO.MemoryStream())
            {
                ms.WriteByte(0x30);
                EncodeDERLength(ms, (uint)payload.Length);
                ms.Write(payload, 0, payload.Length);
                return(ms.ToArray());
            }
        }
 public override byte[] GetMessageBody()
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream()) {
         using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter(MS)) {
             BW.Write(requestID.ToByteArray());
             BW.Write(tables.Length);
             for (int n = 0; n != tables.Length; n++)
             {
                 byte[] bytes = tables [n].Serialize();
                 BW.Write(bytes.Length);
                 BW.Write(bytes);
             }
             if (exception == null)
             {
                 MS.WriteByte(0);
             }
             else
             {
                 MS.WriteByte(1);
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                 long p = MS.Position;
                 try {
                     BF.Serialize(MS, exception);
                 } catch {
                     MS.Position = p;
                     BF.Serialize(MS, exception.ToString());
                     MS.SetLength(MS.Position);
                 }
             }
             return(MS.ToArray());
         }
     }
 }
        public void LuigiMetadataBlock_InflateStringWithBadCharacters_ProducesExpectedStringMetadata()
        {
            using (var metadataStream = new System.IO.MemoryStream())
            {
                var stringPayload = new byte[255]; // put the values 1..255 as a "string" in a name metadata
                for (var i = 0; i < 255; ++i)
                {
                    stringPayload[i] = (byte)(256 - i);
                }
                var metadataPayload = new System.IO.MemoryStream();
                metadataPayload.WriteByte((byte)LuigiMetadataIdTag.Name);
                metadataPayload.WriteByte((byte)stringPayload.Length);
                metadataPayload.Write(stringPayload, 0, stringPayload.Length);
                var payload = metadataPayload.ToArray();
                metadataStream.WriteByte((byte)LuigiDataBlockType.Metadata);
                var payloadLengthBytes = BitConverter.GetBytes((ushort)payload.Length);
                metadataStream.Write(payloadLengthBytes, 0, payloadLengthBytes.Length);
                var headerCrc = Crc8.OfBlock(metadataStream.ToArray());
                metadataStream.WriteByte(headerCrc);
                var payloadCrc      = Crc32.OfBlock(payload, Crc32Polynomial.Castagnoli);
                var payloadCrcBytes = BitConverter.GetBytes(payloadCrc);
                metadataStream.Write(payloadCrcBytes, 0, payloadCrcBytes.Length);
                metadataStream.Write(payload, 0, payload.Length);
                metadataStream.Seek(0, System.IO.SeekOrigin.Begin);

                var metadataBlock = LuigiMetadataBlock.Inflate(metadataStream) as LuigiMetadataBlock;

                var expectedString = System.Text.Encoding.UTF8.GetString(stringPayload).Trim('\0');
                Assert.Equal(expectedString, metadataBlock.LongNames.First());
            }
        }
        public void LuigiMetadataBlock_InflateUnknownBlock_ProducesBaseMetadataBlock()
        {
            using (var rawMetadataBlock = new System.IO.MemoryStream())
            {
                rawMetadataBlock.WriteByte((byte)LuigiDataBlockType.Metadata);
                rawMetadataBlock.WriteByte(2);
                rawMetadataBlock.WriteByte(0); // two byte payload length
                var headerCrc = Crc8.OfBlock(rawMetadataBlock.ToArray());
                rawMetadataBlock.WriteByte(headerCrc);
                var payload         = new byte[] { 0xED, 2 };
                var payloadCrc      = Crc32.OfBlock(payload, Crc32Polynomial.Castagnoli);
                var payloadCrcBytes = BitConverter.GetBytes(payloadCrc);
                rawMetadataBlock.Write(payloadCrcBytes, 0, payloadCrcBytes.Length);
                rawMetadataBlock.Write(payload, 0, payload.Length);
                rawMetadataBlock.Seek(0, System.IO.SeekOrigin.Begin);

                var data = rawMetadataBlock.ToArray();
                using (var reader = new BinaryReader(rawMetadataBlock))
                {
                    var metadataBlock = LuigiMetadataBlock.Inflate(reader);

                    Assert.NotNull(metadataBlock);
                    Assert.Equal(headerCrc, metadataBlock.HeaderCrc);
                    Assert.Equal(payloadCrc, metadataBlock.PayloadCrc);
                    Assert.True(metadataBlock is LuigiMetadataBlock);
                }
            }
        }
Beispiel #9
0
        void ComputeBootGod()
        {
            // inefficient, sloppy, etc etc
            Emulation.Cores.Nintendo.NES.NES.BootGodDB.Initialize();
            var chrrom = _memoryDomains["CHR VROM"];
            var prgrom = _memoryDomains["PRG ROM"];

            var ms = new System.IO.MemoryStream();

            for (int i = 0; i < prgrom.Size; i++)
            {
                ms.WriteByte(prgrom.PeekByte(i));
            }
            if (chrrom != null)
            {
                for (int i = 0; i < chrrom.Size; i++)
                {
                    ms.WriteByte(chrrom.PeekByte(i));
                }
            }

            string sha1 = BizHawk.Common.BufferExtensions.BufferExtensions.HashSHA1(ms.ToArray());

            Console.WriteLine("Hash for BootGod: {0}", sha1);

            // Bail out on ROM's known to not be playable by this core
            if (HashBlackList.Contains(sha1))
            {
                throw new UnsupportedGameException("Game known to not be playable in this core");
            }

            sha1 = "sha1:" + sha1;             // huh?
            var carts = Emulation.Cores.Nintendo.NES.NES.BootGodDB.Instance.Identify(sha1);

            if (carts.Count > 0)
            {
                Console.WriteLine("BootGod entry found: {0}", carts[0].name);
                switch (carts[0].system)
                {
                case "NES-PAL":
                case "NES-PAL-A":
                case "NES-PAL-B":
                case "Dendy":
                    Console.WriteLine("Bad region {0}! Failing over...", carts[0].system);
                    throw new UnsupportedGameException("Unsupported region!");

                default:
                    break;
                }

                BootGodStatus = RomStatus.GoodDump;
                BootGodName   = carts[0].name;
            }
            else
            {
                Console.WriteLine("No BootGod entry found.");
                BootGodStatus = null;
                BootGodName   = null;
            }
        }
Beispiel #10
0
        /// <summary>Read a single-byte CString from a bitstream</summary>
        /// <param name="s">Endian stream to read from</param>
        /// <param name="ms">Stream to write the character's bytes to</param>
        /// <param name="maxLength">Optional maximum length of this specific string</param>
        void ReadCStringSingleByte(IO.BitStream s, System.IO.MemoryStream ms, int maxLength)
        {
            byte character;

            if (maxLength > 0)
            {
                int x = 0;
                while ((character = s.ReadByte()) != 0 && ++x <= maxLength)
                {
                    ms.WriteByte(character);
                }
            }
            else if (!mStorage.IsFixedLength)
            {
                while ((character = s.ReadByte()) != 0)
                {
                    ms.WriteByte(character);
                }
            }
            else
            {
                byte[] characters = s.ReadBytes(mFixedLengthByteLength);

                int x;
                for (x = 0; x < characters.Length; x++)
                {
                    if (characters[x] == 0)
                    {
                        break;
                    }
                }

                ms.Write(characters, 0, x);
            }
        }
Beispiel #11
0
        /// <summary>
        /// QuotedPrintable编码接码
        /// </summary>
        /// <param name="p_Text">原始文字</param>
        /// <param name="p_Encoding">编码方式</param>
        /// <returns>接码后信息</returns>
        public static string DecodeQuotedPrintable(string p_Text, System.Text.Encoding p_Encoding)
        {
            System.IO.MemoryStream _Stream = new System.IO.MemoryStream();
            char[] _CharValue = p_Text.ToCharArray();
            for (int i = 0; i != _CharValue.Length; i++)
            {
                switch (_CharValue[i])
                {
                case '=':
                    if (_CharValue[i + 1] == '\r' || _CharValue[i + 1] == '\n')
                    {
                        i += 2;
                    }
                    else
                    {
                        try
                        {
                            _Stream.WriteByte(Convert.ToByte(_CharValue[i + 1].ToString() + _CharValue[i + 2].ToString(), 16));
                            i += 2;
                        }
                        catch
                        {
                            _Stream.WriteByte(Convert.ToByte(_CharValue[i]));
                        }
                    }
                    break;

                default:
                    _Stream.WriteByte(Convert.ToByte(_CharValue[i]));
                    break;
                }
            }
            return(p_Encoding.GetString(_Stream.ToArray()));
        }
 private bool Process(byte[] buffer, int length)
 {
     for (var i = 0; i < length; ++i)
     {
         if (buffer[i] == '\r')
         {
             ++i;
             if (i < length)
             {
                 if (buffer[i] == '\n')
                 {
                     if (OnTelegram != null && m_stream.Capacity > 0)
                     {
                         OnTelegram(m_stream.ToArray());
                     }
                     m_stream = new System.IO.MemoryStream();
                 }
                 else
                 {
                     m_stream.WriteByte(buffer[i]);
                 }
             }
         }
         else
         {
             m_stream.WriteByte(buffer[i]);
         }
     }
     return(true);
 }
Beispiel #13
0
 public override byte[] GetMessageBody()
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream()) {
         using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter(MS)) {
             BW.Write(requestID.ToByteArray());
             BW.Write(columns.Length);
             for (int n = 0; n != columns.Length; n++)
             {
                 byte[] columnBytes = columns [n].Serialize();
                 BW.Write(columnBytes.Length);
                 BW.Write(columnBytes);
             }
             if (exception == null)
             {
                 MS.WriteByte(0);
             }
             else
             {
                 MS.WriteByte(1);
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                 BF.Serialize(MS, exception);
             }
             return(MS.ToArray());
         }
     }
 }
Beispiel #14
0
 public static byte[] MakePushScript(byte[] data)
 {
     if (data == null)
         throw new ArgumentNullException();
     using (System.IO.MemoryStream writer = new System.IO.MemoryStream())
     {
         if (data.Length <= (int)OpCode.PUSHBYTES75)
         {
             writer.WriteByte((byte)data.Length);
             writer.Write(data, 0, data.Length);
         }
         else if (data.Length < 0x100)
         {
             writer.WriteByte((byte)OpCode.PUSHDATA1);
             writer.WriteByte((byte)data.Length);
             writer.Write(data, 0, data.Length);
         }
         else if (data.Length < 0x10000)
         {
             writer.WriteByte((byte)OpCode.PUSHDATA2);
             writer.Write(BitConverter.GetBytes((ushort)data.Length), 0, 2);
             writer.Write(data, 0, data.Length);
         }
         else// if (data.Length < 0x100000000L)
         {
             writer.WriteByte((byte)OpCode.PUSHDATA4);
             writer.Write(BitConverter.GetBytes((UInt32)data.Length), 0, 4);
             writer.Write(data, 0, data.Length);
         }
         return writer.ToArray();
     }
 }
Beispiel #15
0
        protected void Send(SyslogMessage message, ISyslogMessageSerializer serializer, bool flush = true)
        {
            if (transportStream == null)
            {
                throw new System.IO.IOException("No transport stream exists");
            }

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                byte[] datagramBytes = serializer.Serialize(message);

                if (messageTransfer.Equals(MessageTransfer.OctetCounting))
                {
                    byte[] messageLength = System.Text.Encoding.ASCII.GetBytes(datagramBytes.Length.ToString(System.Globalization.CultureInfo.InvariantCulture));
                    memoryStream.Write(messageLength, 0, messageLength.Length);
                    memoryStream.WriteByte(32); // Space
                }

                memoryStream.Write(datagramBytes, 0, datagramBytes.Length);

                if (messageTransfer.Equals(MessageTransfer.NonTransparentFraming))
                {
                    memoryStream.WriteByte(trailer); // LF
                }

                transportStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }

            if (flush && !(transportStream is System.Net.Sockets.NetworkStream))
            {
                transportStream.Flush();
            }
        }
Beispiel #16
0
 public static void SwapUDWordAndWrite(uint value, System.IO.MemoryStream ms)
 {
     value = SwapUDWord(value);
     ms.WriteByte((byte)((value & 0x000000FF) >> 0));
     ms.WriteByte((byte)((value & 0x0000FF00) >> 8));
     ms.WriteByte((byte)((value & 0x00FF0000) >> 16));
     ms.WriteByte((byte)((value & 0xFF000000) >> 24));
 }
Beispiel #17
0
 public ECDHEPSKServerKeyExchange(ECDHEKeyExchange keyExchange)
 {
     _EllipticCurveType = TEllipticCurveType.NamedCurve;
     _EllipticCurve     = keyExchange.Curve;
     System.IO.MemoryStream stream = new System.IO.MemoryStream();
     stream.WriteByte((byte)_EllipticCurveType);
     NetworkByteOrderConverter.WriteUInt16(stream, (ushort)_EllipticCurve);
     byte[] pointEncoded = keyExchange.PublicKey.Q.GetEncoded(false);
     stream.WriteByte((byte)pointEncoded.Length);
     stream.Write(pointEncoded, 0, pointEncoded.Length);
     _ServerParams = stream.ToArray();
 }
 public ECDHEPSKServerKeyExchange(ECDHEKeyExchange keyExchange)
 {
     _EllipticCurveType = TEllipticCurveType.NamedCurve;
     _EllipticCurve = keyExchange.Curve;
     System.IO.MemoryStream stream = new System.IO.MemoryStream();
     stream.WriteByte((byte)_EllipticCurveType);
     NetworkByteOrderConverter.WriteUInt16(stream, (ushort)_EllipticCurve);
     byte[] pointEncoded = keyExchange.PublicKey.Q.GetEncoded(false);
     stream.WriteByte((byte)pointEncoded.Length);
     stream.Write(pointEncoded, 0, pointEncoded.Length);
     _ServerParams = stream.ToArray();
 }
Beispiel #19
0
        public override AbstractEditor CreateEditor()
        {
            ObjectEditor.StructField[] fields = new NekoKun.ObjectEditor.StructField[this.fields.Count];
            this.fields.Values.CopyTo(fields, 0);

            Dictionary <string, object> param = new Dictionary <string, object>();

            param["Views"] = this.views;

            if (this.arrayMode)
            {
                var array = new ObjectEditor.ArrayEditor(new ObjectEditor.StructEditor(param, fields));
                array.ClipboardFormat = this.clipboardFormat;
                array.LoadObject      = (item) =>
                {
                    var ms = new System.IO.MemoryStream(item);
                    ms.Seek(4, System.IO.SeekOrigin.Begin);
                    return(LoadItem((NekoKun.Serialization.RubyMarshal.RubyMarshal.Load(ms) as RubyArray)[0]));
                };
                array.DumpObject = (item) =>
                {
                    var ms = new System.IO.MemoryStream();
                    ms.WriteByte(0);
                    ms.WriteByte(0);
                    ms.WriteByte(0);
                    ms.WriteByte(0);
                    NekoKun.Serialization.RubyMarshal.RubyMarshal.Dump(ms, new RubyArray(new List <object>()
                    {
                        this.CreateRubyObject(this.className, item as ObjectEditor.Struct)
                    }));
                    ms.Seek(0, System.IO.SeekOrigin.Begin);
                    System.IO.BinaryWriter bw = new System.IO.BinaryWriter(ms);
                    bw.Write((int)ms.Length - 4);
                    return(ms.ToArray());
                };
                array.CreateDefaultObject = () =>
                {
                    ObjectEditor.Struct obj = new ObjectEditor.Struct();
                    foreach (var item in this.fields.Values)
                    {
                        obj[item] = item.DefaultValue;
                    }
                    return(obj);
                };
                return(new ObjectEditor.ObjectFileEditor(this, array));
            }
            else
            {
                return(new ObjectEditor.ObjectFileEditor(this, new ObjectEditor.StructEditor(param, fields)));
            }
        }
 /*
  * The output bit routine just has to set a bit in the current byte
  * if requested to.  After that, it updates the mask.  If the mask
  * shows that the current byte is filled up, it is time to go to the
  * next character in the buffer.  If the next character is past the
  * end of the buffer, it is time to flush the buffer.
  */
 private void output_bit(int bit)
 {
     if (Convert.ToBoolean(bit))
     {
         current_output_byte |= output_mask;
     }
     output_mask >>= 1;
     if (output_mask == 0)
     {
         output_mask = 0x80;
         output_buffer.WriteByte(current_output_byte);
         current_output_byte = 0;
     }
 }
Beispiel #21
0
        private void start()
        {
            //Debug.Assert(MAPSIZE == 64, "The BlockBulkTransfer message requires a map size of 64.");

            for (byte x = 0; x < MAPSIZE; x++)
                for (byte y = 0; y < MAPSIZE; y += 16)
                {
                    NetBuffer msgBuffer = infsN.CreateBuffer();
                    msgBuffer.Write((byte)Infiniminer.InfiniminerMessage.BlockBulkTransfer);
                    if (!compression)
                    {
                        msgBuffer.Write(x);
                        msgBuffer.Write(y);
                        for (byte dy = 0; dy < 16; dy++)
                            for (byte z = 0; z < MAPSIZE; z++)
                                msgBuffer.Write((byte)(infs.blockList[x, y + dy, z]));
                        if (client.Status == NetConnectionStatus.Connected)
                            infsN.SendMessage(msgBuffer, client, NetChannel.ReliableUnordered);
                    }
                    else
                    {
                        //Compress the data so we don't use as much bandwith - Xeio's work
                        var compressedstream = new System.IO.MemoryStream();
                        var uncompressed = new System.IO.MemoryStream();
                        var compresser = new System.IO.Compression.GZipStream(compressedstream, System.IO.Compression.CompressionMode.Compress);

                        //Send a byte indicating that yes, this is compressed
                        msgBuffer.Write((byte)255);

                        //Write everything we want to compress to the uncompressed stream
                        uncompressed.WriteByte(x);
                        uncompressed.WriteByte(y);

                        for (byte dy = 0; dy < 16; dy++)
                            for (byte z = 0; z < MAPSIZE; z++)
                                uncompressed.WriteByte((byte)(infs.blockList[x, y + dy, z]));

                        //Compress the input
                        compresser.Write(uncompressed.ToArray(), 0, (int)uncompressed.Length);
                        //infs.ConsoleWrite("Sending compressed map block, before: " + uncompressed.Length + ", after: " + compressedstream.Length);
                        compresser.Close();

                        //Send the compressed data
                        msgBuffer.Write(compressedstream.ToArray());
                        if (client.Status == NetConnectionStatus.Connected)
                            infsN.SendMessage(msgBuffer, client, NetChannel.ReliableUnordered);
                    }
                }
            conn.Abort();
        }
Beispiel #22
0
 public async new Task Send(byte[] data)
 {
     byte[] fullData;
     using (var stream = new System.IO.MemoryStream())
     {
         stream.WriteByte((byte)(data.Length + 3)); // 长度
         stream.WriteByte(0xFF);                    // CommAdr
         stream.Write(data, 0, data.Length);        // 数据
         var bytes = stream.ToArray();
         var hash  = CRC16.Compute(bytes);          // 计算CRC16
         stream.Write(hash, 0, hash.Length);
         fullData = stream.ToArray();
     }
     await Task.Run(() => base.Send(fullData));
 }
Beispiel #23
0
        /* TLS 1.2
         * 01 01 // CertificateTypes
         * 00 0C // SignatureAlgorithms len
         * 04 01 05 01 06 01 08 04 08 05 08 06 // SignatureAlgorithms
         * 00 00 // opaque DistinguishedName
         */
        public CertificateRequest(ClientCertificateType[] clientCertTypes = null, SignatureAlgorithm[] clientCertSAs = null) : base(null)
        {
            CertificateTypes = clientCertTypes ?? new[]
            {
                ClientCertificateType.rsa_sign,
            };
            SignatureAlgorithms = clientCertSAs ?? new[]
            {
                SignatureAlgorithm.rsa_pkcs1_sha256, SignatureAlgorithm.rsa_pkcs1_sha384, SignatureAlgorithm.rsa_pkcs1_sha512,
                SignatureAlgorithm.rsa_pss_rsae_sha256, SignatureAlgorithm.rsa_pss_rsae_sha384, SignatureAlgorithm.rsa_pss_rsae_sha512,
                SignatureAlgorithm.ecdsa_secp256r1_sha256, SignatureAlgorithm.ecdsa_secp384r1_sha384, SignatureAlgorithm.ecdsa_secp521r1_sha512,
            };
            using (var ms = new System.IO.MemoryStream())
            {
                // ClientCertificateTypes length byte
                ms.WriteByte((byte)CertificateTypes.Length);
                // ClientCertificateTypes
                ms.Write(CertificateTypes.Select(a => (byte)a).ToArray(), 0, CertificateTypes.Length);
                // SignatureAlgorithms length ushort
                ms.WriteValue((ushort)(SignatureAlgorithms.Length * 2));
                // SignatureAlgorithms
                foreach (var sa in SignatureAlgorithms)
                {
                    ms.WriteValue((ushort)(sa));
                }
                //DistinguishedName
                ms.WriteValue((ushort)0);

                Data = ms.ToArray();
            }
        }
        public override ScalarValue Decode(System.IO.Stream in_Renamed)
        {
            var buffer = new System.IO.MemoryStream();
            int byt;
            do
            {
                try
                {
                    byt = in_Renamed.ReadByte();

                    if (byt < 0)
                    {
                        return null;
                    }
                }
                catch (System.IO.IOException e)
                {
                    throw new RuntimeException(e);
                }

                buffer.WriteByte((Byte) byt);
            }
            while ((byt & STOP_BIT) == 0);

            return new BitVectorValue(new BitVector(buffer.ToArray()));
        }
Beispiel #25
0
        public Certificate(X509Certificate2[] publicCerts, bool tls13) : base(null)
        {
            Certs = publicCerts;
            var certs = new List <byte>();

            foreach (var cert in publicCerts)
            {
                var raw = cert.GetRawCertData();
                var len = Utils.UInt24Bytes((uint)raw.Length);
                certs.AddRange(len);
                certs.AddRange(raw);
                if (tls13)
                {
                    certs.AddRange(new byte[] { 0x00, 0x00 }); // Certificate Extensions
                }
            }

            var totalLen      = (uint)certs.Count;
            var totalLenBytes = Utils.UInt24Bytes(totalLen);

            using (var ms = new System.IO.MemoryStream())
            {
                if (tls13)
                {
                    ms.WriteByte(0x00);     // request_context
                }
                ms.Write(totalLenBytes, 0, totalLenBytes.Length);
                ms.Write(certs.ToArray(), 0, certs.Count);

                Data = ms.ToArray();
            }
        }
        public override ScalarValue Decode(System.IO.Stream in_Renamed)
        {
            var buffer = new System.IO.MemoryStream();
            byte byt;

            try
            {
                do
                {
                    byt = (byte)in_Renamed.ReadByte();
                    buffer.WriteByte( byt);
                }
                while ((byt & STOP_BIT) == 0);
            }
            catch (System.IO.IOException e)
            {
                throw new RuntimeException(e);
            }

            byte[] bytes = buffer.ToArray();
            bytes[bytes.Length - 1] &=  (0x7f);

            if (bytes[0] == 0)
            {
                if (!ByteUtil.IsEmpty(bytes))
                    Global.HandleError(Error.FastConstants.R9_STRING_OVERLONG, null);
                if (bytes.Length > 1 && bytes[1] == 0)
                    return new StringValue("\u0000");
                return new StringValue("");
            }

            return new StringValue(System.Text.Encoding.UTF8.GetString(bytes));
        }
Beispiel #27
0
        public override ScalarValue Decode(System.IO.Stream in_Renamed)
        {
            var buffer = new System.IO.MemoryStream();
            int byt;

            do
            {
                try
                {
                    byt = in_Renamed.ReadByte();

                    if (byt < 0)
                    {
                        return(null);
                    }
                }
                catch (System.IO.IOException e)
                {
                    throw new RuntimeException(e);
                }

                buffer.WriteByte((Byte)byt);
            }while ((byt & STOP_BIT) == 0);

            return(new BitVectorValue(new BitVector(buffer.ToArray())));
        }
Beispiel #28
0
        /// <summary>
        /// Expands the specified info.
        /// </summary>
        /// <param name="info">optional context and application specific information (can be a zero-length string)</param>
        /// <param name="l">length of output keying material in octets (&lt;= 255*HashLen)</param>
        /// <returns>OKM (output keying material) of L octets</returns>
        public byte[] Expand(byte[] info, int l)
        {
            if (info == null) info = new byte[0];

            hmac.Key = this.prk;

            var n = (int) System.Math.Ceiling(l * 1f / hashLength);
            var t = new byte[n * hashLength];

            using (var ms = new System.IO.MemoryStream())
            {
                var prev = new byte[0];

                for (var i = 1; i <= n; i++)
                {
                    ms.Write(prev, 0, prev.Length);
                    if (info.Length > 0) ms.Write(info, 0, info.Length);
                    ms.WriteByte((byte)(0x01 * i));

                    prev = hmac.ComputeHash(ms.ToArray());

                    Array.Copy(prev, 0, t, (i - 1) * hashLength, hashLength);

                    ms.SetLength(0); //reset
                }
            }

            var okm = new byte[l];
            Array.Copy(t, okm, okm.Length);

            return okm;
        }
        public void ProcessRequest(HttpContext context)
        {
            var req = context.Request;
            var rep = context.Response;

            req.ContentType = "application/json";
            var fileName = req["fileName"];

            if (String.IsNullOrWhiteSpace(fileName))
            {
                fileName = Guid.NewGuid().ToString();
            }
            using (System.IO.BinaryReader reader = new System.IO.BinaryReader(req.InputStream))
            {
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                int bte;
                while ((bte = reader.Read()) != -1)
                {
                    ms.WriteByte((byte)bte);
                }
                var arrayBytes = ms.ToArray();
                var base64     = System.Text.Encoding.UTF8.GetString(arrayBytes);
                var data       = Convert.FromBase64String(base64);

                var fileFullPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Static/" + fileName);

                this.AppedOrCreate(fileFullPath, data);
            }
            rep.Write("{\"FileName\":\"" + fileName + "\"}");
        }
Beispiel #30
0
        public static List <ExpanderData> LoadSystemData()
        {
            try
            {
                List <ExpanderData> res = null;
                string data             = ToolBoxWindow.Resources.ToolBoxDataKernel;
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream(data.Length))
                {
                    foreach (char c in data)
                    {
                        stream.WriteByte(Convert.ToByte(c));
                    }
                    stream.Position = 0;

                    res = LoadDatafromXml(stream);
                    stream.Close();
                }
                return(res);
            }
            catch (Exception ex)
            {
                Schematix.Core.Logger.Log.Error("Load ToolBox data error.", ex);
                return(new List <ExpanderData>());
            }
        }
Beispiel #31
0
        /* TLS 1.3
         * 00 // opaque certificate_request_context
         * 00 2a // extension len
         * 00 0d 00 26 // SignatureAlgorithm extension len
         * 00 24 // SignatureAlgorithms len
         * 04 03 05 03 06 03 08 07 08 08 08 09 08 0a 08 0b 08 04 08 05 08 06 04 01 05 01 06 01 03 03 02 03 03 01 02 01
         */
        public CertificateRequest(byte[] cert_request_context, SignatureAlgorithm[] clientCertSAs = null) : base(null)
        {
            //https://tools.ietf.org/html/rfc8446#page-70
            //In addition, the signature algorithm MUST be compatible with the key in the sender's end-entity certificate.
            //RSA signatures MUST use an RSASSA - PSS algorithm, regardless of whether RSASSA-PKCS1 - v1_5 algorithms appear in "signature_algorithms".
            //The SHA - 1 algorithm MUST NOT be used in any signatures of CertificateVerify messages.
            CertificateTypes    = new ClientCertificateType[0];
            SignatureAlgorithms = clientCertSAs ?? new[]
            {
                SignatureAlgorithm.rsa_pss_rsae_sha256, SignatureAlgorithm.rsa_pss_rsae_sha384, SignatureAlgorithm.rsa_pss_rsae_sha512,
                SignatureAlgorithm.ecdsa_secp256r1_sha256, SignatureAlgorithm.ecdsa_secp384r1_sha384, SignatureAlgorithm.ecdsa_secp521r1_sha512,
            };

            var extBytes = new Extensions.SignatureAlgorithms(SignatureAlgorithms).Data;

            using (var ms = new System.IO.MemoryStream())
            {
                // certificate_request_context
                if (cert_request_context != null && cert_request_context.Length > 0)
                {
                    ms.WriteValue(cert_request_context, new[] { (byte)cert_request_context.Length });
                }
                else
                {
                    ms.WriteByte((byte)0);
                }
                // Extensions total length ushort
                ms.WriteValue((ushort)(extBytes.Length));
                // SignatureAlgorithms Extension
                ms.Write(extBytes, 0, extBytes.Length);

                Data = ms.ToArray();
            }
        }
Beispiel #32
0
 private static byte[] EncodeDER(byte[][] data)
 {
     byte[] payload;
     using(var ms = new System.IO.MemoryStream())
     {
         foreach(var b in data)
         {
             ms.WriteByte(0x02);
             var isNegative = (b[0] & 0x80) != 0;
             
             EncodeDERLength(ms, (uint)(b.Length + (isNegative ? 1 : 0)));
             if (isNegative)
                 ms.WriteByte(0);
             ms.Write(b, 0, b.Length);                    
         }
     
         payload = ms.ToArray();
     }
 
     using(var ms = new System.IO.MemoryStream())
     {
         ms.WriteByte(0x30);
         EncodeDERLength(ms, (uint)payload.Length);
         ms.Write(payload, 0, payload.Length);
         return ms.ToArray();
     }
 }
Beispiel #33
0
        static byte[] HkdfLabel(string label, byte[] context, ushort len)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                var lenBytes   = Utils.UInt16Bytes(len);
                var labelBytes = Encoding.ASCII.GetBytes("tls13 " + label);

                ms.Write(lenBytes, 0, lenBytes.Length);
                ms.WriteByte((byte)labelBytes.Length);
                ms.Write(labelBytes, 0, labelBytes.Length);
                ms.WriteByte((byte)context.Length);
                ms.Write(context, 0, context.Length);

                return(ms.ToArray());
            }
        }
Beispiel #34
0
        private void Send(InputBase input)
        {
            try
            {
                if (ClientSocket == null || !ClientSocket.Connected)
                {
                    // not connected
                    throw new SocketException();
                }

                byte[] buf = null;

                using (var stream = new System.IO.MemoryStream())
                {
                    using (var writer = new System.IO.BinaryWriter(stream))
                    {
                        stream.Seek(3, System.IO.SeekOrigin.Begin);
                        Serializer.WriteObject(stream, input);
                        var len = (ushort)(stream.Position - 3);
                        stream.Seek(0, System.IO.SeekOrigin.Begin);
                        stream.WriteByte(0x1b);
                        writer.Write(len);
                        buf = stream.ToArray();
                    }
                }

                SocketError socketError;
                ClientSocket.BeginSend(buf, 0, buf.Length, SocketFlags.None, out socketError, BeginSendCallback, ClientSocket);
            }
            catch
            {
                this.Detach();
                throw;
            }
        }
Beispiel #35
0
        /// <summary>
        /// Patches the section at the given offset with the specified value.
        /// </summary>
        /// <param name="offset">The offset.</param>
        /// <param name="linkType">Type of the link.</param>
        /// <param name="value">The value.</param>
        public void ApplyPatch(long offset, LinkType linkType, long value)
        {
            long pos = _sectionStream.Position;

            _sectionStream.Position = offset;

            // Apply the patch
            switch (linkType & LinkType.SizeMask)
            {
            case LinkType.I1:
                _sectionStream.WriteByte((byte)value);
                break;

            case LinkType.I2:
                _sectionStream.Write(_littleEndianBitConverter.GetBytes((ushort)value), 0, 2);
                break;

            case LinkType.I4:
                _sectionStream.Write(_littleEndianBitConverter.GetBytes((uint)value), 0, 4);
                break;

            case LinkType.I8:
                _sectionStream.Write(_littleEndianBitConverter.GetBytes(value), 0, 8);
                break;
            }

            _sectionStream.Position = pos;
        }
        byte ReadSetBytes(byte[] result)
        {
            long length = 0L;

            using (var ms = new System.IO.MemoryStream())
            {
                foreach (var item in this.Set)
                {
                    var bs = System.Text.Encoding.ASCII.GetBytes(
                        item);

                    ms.Write(bs, 0, bs.Length);

                    ms.WriteByte(0);
                }

                ms.Seek(0L, System.IO.SeekOrigin.Begin);

                ms.Read(result, 0, result.Length);

                length = ms.Length;
            }

            return(Convert.ToByte(length));
        }
Beispiel #37
0
		private byte [] GenerateTestMemory()
		{
			System.IO.MemoryStream stm = new System.IO.MemoryStream();
			for (int i = 0; i < 1024; ++i)
			{
				stm.WriteByte((byte)i);
			}
			return stm.ToArray();
		}
Beispiel #38
0
        public static ArraySegment<byte> Serialize(object message, byte[] buffer)
        {

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer))
            {
                stream.Position = 0;
                if (message is LogModel)
                {
                    stream.WriteByte((byte)1);
                }
                else
                {
                    stream.WriteByte((byte)2);
                }
                ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(stream, message);
                return new ArraySegment<byte>(buffer, 0, (int)stream.Position);
            }
        }
Beispiel #39
0
        public override void Encode()
        {
            int x = rectangle.X;
            int y = rectangle.Y;
            int w = rectangle.Width;
            int h = rectangle.Height;

            //Console.WriteLine("Landed at ZRLE start!");

            int rawDataSize = w * h * (this.framebuffer.BitsPerPixel / 8);
            byte[] data = new byte[rawDataSize];
            int currentX, currentY;
            int tileW, tileH;

            //Bitmap bmp = PixelGrabber.GrabImage(rectangle.Width, rectangle.Height, pixels);
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                for (currentY = y; currentY < y + h; currentY += TILE_HEIGHT)
                {
                    tileH = TILE_HEIGHT;
                    tileH = Math.Min(tileH, y + h - currentY);
                    for (currentX = x; currentX < x + w; currentX += TILE_WIDTH)
                    {
                        tileW = TILE_WIDTH;
                        tileW = Math.Min(tileW, x + w - currentX);

                        int[] pixelz = CopyPixels(pixels, w, currentX, currentY, tileW, tileH);

                        byte subencoding = 0;
                        ms.WriteByte(subencoding);
                        //PixelGrabber.GrabPixels(pixels, new Rectangle(currentX, currentY, tileW, tileH), this.framebuffer);

                        for (int i = 0; i < pixelz.Length; ++i)
                        {
                            int bb = 0;

                            //The CPixel structure (Compressed Pixel) has 3 bytes, opposed to the normal pixel which has 4.
                            byte[] bytes = new byte[3];
                            int pixel = pixelz[i];

                            bytes[bb++] = (byte)(pixel & 0xFF);
                            bytes[bb++] = (byte)((pixel >> 8) & 0xFF);
                            bytes[bb++] = (byte)((pixel >> 16) & 0xFF);
                            //bytes[b++] = (byte)((pixel >> 24) & 0xFF);

                            ms.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                byte[] uncompressed = ms.ToArray();
                this.bytes = uncompressed;
            }
        }
        public override byte[] GetBytes(int countBytes)
        {
            using (var okm = new System.IO.MemoryStream())
            {
                do
                {
                    if (k_unused > 0)
                    {
                        var min = Math.Min(k_unused, countBytes);
                        okm.Write(k, hashLength - k_unused, min);
                        countBytes -= min;
                        k_unused -= min;
                    }

                    if (countBytes == 0) break;
                    var n = countBytes / hashLength;
                    if (countBytes % hashLength > 0) ++n;
                    using (var hmac_msg = new System.IO.MemoryStream())
                    {
                        for (var i = 1; i <= n; ++i)
                        {
                            hmac_msg.Write(k, 0, k.Length);
                            if (context != null)
                                hmac_msg.Write(context, 0, context.Length);

                            hmac_msg.WriteByte(counter);
                            checked { ++counter; };
                            k = hmac.ComputeHash(hmac_msg.GetBuffer(), 0, (int)hmac_msg.Length);
                            okm.Write(k, 0, i < n ? hashLength : countBytes);
                            countBytes -= hashLength;
                            hmac_msg.SetLength(0);
                        }
                        k_unused = -countBytes;
                    }// using hmac_msg
                } while (false);
                return okm.ToArray();
            }// using okm
        }
Beispiel #41
0
        public byte[] stringToBig5Bytes(string text)
        {
            //byte[] b = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.GetEncoding("big5"), System.Text.Encoding.Unicode.GetBytes(text));
            //return b;

            char[] chars = text.ToCharArray();
            byte[] b;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            for (int i = 0; i < text.Length; i++)
            {

                if (chars[i] >= 0xe000 && chars[i] <= 0xE4BE)
                {
                    ms.WriteByte((byte)((chars[i] + 0x1A40) / 256));
                    ms.WriteByte((byte)((chars[i] + 0x1A40) % 256));
                }
                else
                {
                    b = System.Text.Encoding.Convert(System.Text.Encoding.Unicode, System.Text.Encoding.GetEncoding("big5"), System.Text.Encoding.Unicode.GetBytes(chars, i, 1));

                    for (int j = 0; j < b.Length; j++)
                        ms.WriteByte(b[j]);
                }
                //if (b.Length == 2 && b[1] * 256 + b[0] >= 0xE000 && b[1] * 256 + b[0] <= 0xE05f)
                //{
                //    ms.WriteByte((byte)(b[0] + 0x1A));
                //    ms.WriteByte(b[1]);

                //}
                //else
                //{

                //}
            }

            return ms.ToArray();
        }
Beispiel #42
0
        void SetTemVDData(string devname, int dir, int milek, int milem, System.Data.DataSet ds)
        {
            System.Text.StringBuilder sql = new StringBuilder();
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            ms.WriteByte(0x21);
            ms.WriteByte((byte)dir);
            ms.WriteByte((byte)(milek/256));
            ms.WriteByte((byte)(milek % 256));
            ms.WriteByte((byte)((milem ) / 256));
            ms.WriteByte((byte)((milem ) % 256));
            ms.WriteByte((byte)ds.Tables[1].Rows.Count); //lanecnt
            ms.WriteByte(0); //odd
            System.DateTime dt= DateTime.Now;
            dt=dt.AddSeconds(-dt.Second).AddMinutes(-5);
            dt=dt.AddMinutes(-(dt.Minute % 5));
            //sql.Append("select ");
            //for(int i=0;i<ds.Tables[1].Rows.Count;i++)
            //{

            //}

               // string sql = "select small_car_volume_lane1,big_car_volume,connect_car_volume,small_car_speed,big_car_speed,connect_car_speed,average_occupancy from tblvddata5min where devicename='{0}' and timestamp='{1}' ";
            System.Data.Odbc.OdbcConnection cn = new System.Data.Odbc.OdbcConnection(RemoteInterface.DbCmdServer.getDbConnectStr());
            System.Data.Odbc.OdbcCommand cmd=new System.Data.Odbc.OdbcCommand();
            cmd.Connection = cn;

            try
            {

                cn.Open();

                for (int i = 0; i < (byte)ds.Tables[1].Rows.Count; i++)
                {
                    sql = new StringBuilder("select ");
                    sql.Append("small_car_volume_lane").Append(i + 1).Append(",");
                    sql.Append("big_car_volume_lane").Append(i + 1).Append(",");
                    sql.Append("connect_car_volume_lane").Append(i + 1).Append(",");

                    sql.Append("small_car_speed_lane").Append(i + 1).Append(",");
                    sql.Append("big_car_speed_lane").Append(i + 1).Append(",");
                    sql.Append("connect_car_speed_lane").Append(i + 1).Append(",");
                    sql.Append("average_occupancy_lane").Append(i + 1).Append(",");

                    sql.Remove(sql.ToString().Length - 1, 1).Append(" from tblvddata5min   where devicename='{0}' and timestamp='{1}'");
                    cmd.CommandText = string.Format(sql.ToString(), devname, RemoteInterface.DbCmdServer.getTimeStampString(dt));

                    System.Data.Odbc.OdbcDataReader rd = cmd.ExecuteReader();
                    if (!rd.Read())
                    {
                        rd.Close();
                        continue;
                    }

                 //   System.Data.DataRow r = ds.Tables[1].Rows[i];

                    ms.WriteByte((byte)i); //loopid
                    ms.WriteByte(0); //odd
                    int car_vol = System.Convert.ToInt32(rd[0]);
                    ms.WriteByte((byte)(car_vol / 256));
                    ms.WriteByte((byte)(car_vol % 256));
                    int big_vol = System.Convert.ToInt32(rd[1]);
                    ms.WriteByte((byte)(big_vol / 256));
                    ms.WriteByte((byte)(big_vol % 256));
                    int cn_vol = System.Convert.ToInt32(rd[2]);
                    ms.WriteByte((byte)(cn_vol / 256));
                    ms.WriteByte((byte)(cn_vol % 256));
                    int carspd = System.Convert.ToByte(rd[3]);
                    ms.WriteByte((byte)carspd);
                    carspd = System.Convert.ToByte(rd[4]);
                    ms.WriteByte((byte)carspd);

                    carspd = System.Convert.ToByte(rd[5]);
                    ms.WriteByte((byte)carspd);
                    ms.WriteByte(System.Convert.ToByte(rd[6]));

                    rd.Close();

                }
            }
            catch (Exception ex)
            {
                ConsoleServer.WriteLine(ex.Message + "," + ex.StackTrace);
            }
            finally
            {
                cn.Close();
            }

            Comm.SendPackage pkg=new Comm.SendPackage(Comm.CmdType.CmdSet,Comm.CmdClass.A,0xffff,ms.ToArray());
            Program.mfcc_tem.manager[TEM_DEVNAME].Send(pkg);
        }
Beispiel #43
0
 private String __GetCString__( System.IO.MemoryStream ms )
 {
     // '\0'を読み飛ばす
     while(true) {
         if( ms.ReadByte() != 0 ) {
             ms.Seek( -1, System.IO.SeekOrigin.Current );
             break;
         }
     }
     using( var temp = new System.IO.MemoryStream() ) {
         while(true) {
             var b = ms.ReadByte();
             if( b == -1 ) {
                 throw new Exception("レース名テーブルが解析できませんでした");
             }
             if( b == 0 ) {
                 return System.Text.Encoding.GetEncoding(932).GetString( temp.ToArray() );
             }
             temp.WriteByte( (byte)b );
         }
     }
 }
        public virtual sbyte[] get8bitByteArray(int dataLength)
        {
            int length = dataLength;
            int intData = 0;
            System.IO.MemoryStream output = new System.IO.MemoryStream();

            do
            {
                canvas.println("Length: " + length);
                intData = getNextBits(8);
                output.WriteByte((byte) intData);
                length--;
            }
            while (length > 0);
            return SystemUtils.ToSByteArray(output.ToArray());
        }
		/// <summary> This method creates the tileparts from the buffered tile headers,
		/// packet headers and packet data
		/// 
		/// </summary>
		/// <exception cref="java.io.IOException">If an I/O error ocurred.
		/// 
		/// </exception>
		private void  createTileParts()
		{
			int i, prem, t, length;
            int pIndex; // phIndex removed
			int tppStart;
			int tilePart;
			int p, np, nomnp;
			int numTileParts;
			int numPackets;
			System.IO.MemoryStream temp = new System.IO.MemoryStream();
			byte[] tempByteArr;
			
			// Create tile parts
			tileParts = new byte[nt][][];
			maxtp = 0;
			
			for (t = 0; t < nt; t++)
			{
				// Calculate number of tile parts. If tileparts are not used, 
				// put all packets in the first tilepart
				if (pptp == 0)
					pptp = ppt[t];
				prem = ppt[t];
				//UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
				numTileParts = (int) System.Math.Ceiling(((double) prem) / pptp);
				numPackets = packetHeaders[t].Length;
				maxtp = (numTileParts > maxtp)?numTileParts:maxtp;
				tileParts[t] = new byte[numTileParts][];
				
				// Create all the tile parts for tile t
				tppStart = 0;
				pIndex = 0;
				p = 0;
				//phIndex = 0;
				
				for (tilePart = 0; tilePart < numTileParts; tilePart++)
				{
					
					// Calculate number of packets in this tilepart
					nomnp = (pptp > prem)?prem:pptp;
					np = nomnp;
					
					// Write tile part header
					if (tilePart == 0)
					{
						// Write original tile part header up to SOD marker
						temp.Write(tileHeaders[t], 0, tileHeaders[t].Length - 2);
					}
					else
					{
						// Write empty header of length TP_HEAD_LEN-2
						temp.Write(new byte[TP_HEAD_LEN - 2], 0, TP_HEAD_LEN - 2);
					}
					
					// Write PPT marker segments if PPT used
					if (pptUsed)
					{
						int pptLength = 3; // Zppt and Lppt
						int pptIndex = 0;
						int phLength;
						
						p = pIndex;
						while (np > 0)
						{
							phLength = packetHeaders[t][p].Length;
							
							// If the total legth of the packet headers is greater
							// than MAX_LPPT, several PPT markers are needed
							if (pptLength + phLength > CSJ2K.j2k.codestream.Markers.MAX_LPPT)
							{
								
								temp.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8));
								temp.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPT & 0x00FF));
								temp.WriteByte((System.Byte) SupportClass.URShift(pptLength, 8));
								temp.WriteByte((System.Byte) pptLength);
								temp.WriteByte((System.Byte) pptIndex++);
								for (i = pIndex; i < p; i++)
								{
									temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length);
								}
								pptLength = 3; // Zppt and Lppt
								pIndex = p;
							}
							pptLength += phLength;
							p++;
							np--;
						}
						// Write last PPT marker
						temp.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPT, 8));
						temp.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPT & 0x00FF));
						temp.WriteByte((System.Byte) SupportClass.URShift(pptLength, 8));
						temp.WriteByte((System.Byte) pptLength);
						temp.WriteByte((System.Byte) pptIndex);
						for (i = pIndex; i < p; i++)
						{
							
							temp.Write(packetHeaders[t][i], 0, packetHeaders[t][i].Length);
						}
					}
					pIndex = p;
					np = nomnp;
					
					// Write SOD marker
					temp.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOD, 8));
					temp.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.SOD & 0x00FF));
					
					// Write packet data and packet headers if PPT and PPM not used
					for (p = tppStart; p < tppStart + np; p++)
					{
						if (!tempSop)
						{
							temp.Write(sopMarkSeg[t][p], 0, CSJ2K.j2k.codestream.Markers.SOP_LENGTH);
						}
						
						if (!(ppmUsed || pptUsed))
						{
							temp.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length);
						}
						
						temp.Write(packetData[t][p], 0, packetData[t][p].Length);
					}
					tppStart += np;
					
					// Edit tile part header
					tempByteArr = temp.ToArray();
					tileParts[t][tilePart] = tempByteArr;
					length = (int)temp.Length;
					
					if (tilePart == 0)
					{
						// Edit first tile part header
						tempByteArr[6] = (byte) (SupportClass.URShift(length, 24)); // Psot
						tempByteArr[7] = (byte) (SupportClass.URShift(length, 16));
						tempByteArr[8] = (byte) (SupportClass.URShift(length, 8));
						tempByteArr[9] = (byte) (length);
						tempByteArr[10] = (byte) SupportClass.Identity((0)); // TPsot
						tempByteArr[11] = (byte) (numTileParts); // TNsot
					}
					else
					{
						// Edit tile part header
						tempByteArr[0] = (byte) (SupportClass.URShift(CSJ2K.j2k.codestream.Markers.SOT, 8)); // SOT
						tempByteArr[1] = (byte) (CSJ2K.j2k.codestream.Markers.SOT & 0x00FF);
						tempByteArr[2] = (byte) SupportClass.Identity((0)); // Lsot
						tempByteArr[3] = (byte) SupportClass.Identity((10));
						tempByteArr[4] = (byte) (SupportClass.URShift(t, 8)); // Isot
						tempByteArr[5] = (byte) (t); // 
						tempByteArr[6] = (byte) (SupportClass.URShift(length, 24)); // Psot
						tempByteArr[7] = (byte) (SupportClass.URShift(length, 16));
						tempByteArr[8] = (byte) (SupportClass.URShift(length, 8));
						tempByteArr[9] = (byte) (length);
						tempByteArr[10] = (byte) (tilePart); //TPsot
						tempByteArr[11] = (byte) (numTileParts); // TNsot
					}
					//UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'"
					//temp.reset();
                    temp.SetLength(0);
					prem -= np;
				}
			}
			temp.Close();
		}
Beispiel #46
0
        public static void SetGenericDisplay(I_DLE device, int address, RGS_GenericDisplay_Data data)
        {
            System.IO.MemoryStream ms=new System.IO.MemoryStream();
            ms.WriteByte(0x9c);
            ms.WriteByte(data.mode);
            ms.WriteByte(data.graph_code_id);
            ms.WriteByte((byte)data.icons.Length);
            for (int i = 0; i < data.icons.Length; i++)
            {
                ms.WriteByte(data.icons[i].icon_code_id);

                ms.WriteByte((byte)(data.icons[i].x / 256));
                ms.WriteByte((byte)(data.icons[i].x % 256));

                ms.WriteByte((byte)(data.icons[i].y/256));
                ms.WriteByte((byte)(data.icons[i].y%256));
            }
            ms.WriteByte((byte)data.msgs.Length);
            for (int i = 0; i < data.msgs.Length; i++)
            {
                byte[] code_big5 = RemoteInterface.Utils.Util.StringToBig5Bytes(data.msgs[i].messgae);// Comm.RGS30_Extend.ToBig5Bytes(data.msgs[i].messgae);

                ms.WriteByte((byte)code_big5.Length);
                ms.Write(code_big5, 0, code_big5.Length);
                for (int j = 0; j < data.msgs[i].messgae.Length; j++)
                {
                    ms.WriteByte(data.msgs[i].forecolor[j].R);
                    ms.WriteByte(data.msgs[i].forecolor[j].G);
                    ms.WriteByte(data.msgs[i].forecolor[j].B);
                    ms.WriteByte(data.msgs[i].backcolor[j].R);
                    ms.WriteByte(data.msgs[i].backcolor[j].G);
                    ms.WriteByte(data.msgs[i].backcolor[j].B);

                }
                ms.WriteByte((byte)(data.msgs[i].x / 256));
                ms.WriteByte((byte)(data.msgs[i].x % 256));
                ms.WriteByte((byte)(data.msgs[i].y / 256));
                ms.WriteByte((byte)(data.msgs[i].y % 256));

            }

            ms.WriteByte((byte)data.sections.Length);
            for (int i = 0; i < data.sections.Length; i++)
            {
                ms.WriteByte(data.sections[i].section_id);
                ms.WriteByte(data.sections[i].status);
            }
            byte[]text=new byte[ms.Position];
            System.Array.Copy(ms.GetBuffer(),text,text.Length);
            SendPackage pkg = new SendPackage(CmdType.CmdSet, CmdClass.A, address, text);
            device.Send(pkg);
            if (pkg.result != CmdResult.ACK)
                throw new Exception(pkg.result.ToString());
        }
 public override byte[] GetMessageBody()
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream ()) {
         using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter (MS)) {
             BW.Write (streamID.ToByteArray ());
             BW.Write (requestID.ToByteArray ());
             BW.Write (canRead);
             if (exception == null) {
                 MS.WriteByte (0);
             } else {
                 MS.WriteByte (1);
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 BF.Serialize (MS, exception);
             }
         }
         return MS.ToArray ();
     }
 }
		/// <summary> This method writes the new codestream to the file. 
		/// 
		/// </summary>
		/// <param name="fi">The file to write the new codestream to
		/// 
		/// </param>
		/// <exception cref="java.io.IOException">If an I/O error ocurred.
		/// 
		/// </exception>
		private void  writeNewCodestream(BufferedRandomAccessFile fi)
		{
			int t, p, tp; // i removed
			int numTiles = tileParts.Length;
			int[][] packetHeaderLengths = new int[numTiles][];
			for (int i2 = 0; i2 < numTiles; i2++)
			{
				packetHeaderLengths[i2] = new int[maxtp];
			}
			byte[] temp;
			int length;
			
			// Write main header up to SOT marker
			fi.write(mainHeader, 0, mainHeader.Length);
			
			// If PPM used write all packet headers in PPM markers
			if (ppmUsed)
			{
				System.IO.MemoryStream ppmMarkerSegment = new System.IO.MemoryStream();
				int numPackets;
				int totNumPackets;
				int ppmIndex = 0;
				int ppmLength;
				int pStart, pStop;
				int[] prem = new int[numTiles];
				
				// Set number of remaining packets 
				for (t = 0; t < numTiles; t++)
				{
					prem[t] = packetHeaders[t].Length;
				}
				
				// Calculate Nppm values 
				for (tp = 0; tp < maxtp; tp++)
				{
					for (t = 0; t < numTiles; t++)
					{
						if (tileParts[t].Length > tp)
						{
							totNumPackets = packetHeaders[t].Length;
							// Calculate number of packets in this tilepart
							numPackets = (tp == tileParts[t].Length - 1)?prem[t]:pptp;
							
							pStart = totNumPackets - prem[t];
							pStop = pStart + numPackets;
							
							// Calculate number of packet header bytes for this
							// tile part
							for (p = pStart; p < pStop; p++)
								packetHeaderLengths[t][tp] += packetHeaders[t][p].Length;
							
							prem[t] -= numPackets;
						}
					}
				}
				
				// Write first PPM marker
				ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8));
				ppmMarkerSegment.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPM & 0x00FF));
				ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value
				ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value
				ppmMarkerSegment.WriteByte((System.Byte) 0); // zppm
				ppmLength = 3;
				ppmIndex++;
				
				// Set number of remaining packets 
				for (t = 0; t < numTiles; t++)
					prem[t] = packetHeaders[t].Length;
				
				// Write all PPM markers and information
				for (tp = 0; tp < maxtp; tp++)
				{
					for (t = 0; t < numTiles; t++)
					{
						
						if (tileParts[t].Length > tp)
						{
							totNumPackets = packetHeaders[t].Length;
							
							// Calculate number of packets in this tilepart
							numPackets = (tp == tileParts[t].Length - 1)?prem[t]:pptp;
							
							pStart = totNumPackets - prem[t];
							pStop = pStart + numPackets;
							
							// If Nppm value wont fit in current PPM marker segment
							// write current PPM marker segment and start new
							if (ppmLength + 4 > CSJ2K.j2k.codestream.Markers.MAX_LPPM)
							{
								// Write current PPM marker
								temp = ppmMarkerSegment.ToArray();
								length = temp.Length - 2;
								temp[2] = (byte) (SupportClass.URShift(length, 8));
								temp[3] = (byte) length;
								fi.write(temp, 0, length + 2);
								
								// Start new PPM marker segment
								//UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'"
								//ppmMarkerSegment.reset();
                                ppmMarkerSegment.SetLength(0);
								ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8));
								ppmMarkerSegment.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPM & 0x00FF));
								ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value
								ppmMarkerSegment.WriteByte((System.Byte) 0); // Temporary Lppm value
								ppmMarkerSegment.WriteByte((System.Byte) ppmIndex++); // zppm
								ppmLength = 3;
							}
							
							// Write Nppm value
							length = packetHeaderLengths[t][tp];
							ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(length, 24));
							ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(length, 16));
							ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(length, 8));
							ppmMarkerSegment.WriteByte((System.Byte) length);
							ppmLength += 4;
							
							// Write packet headers
							for (p = pStart; p < pStop; p++)
							{
								length = packetHeaders[t][p].Length;
								
								// If next packet header value wont fit in 
								// current PPM marker segment write current PPM 
								// marker segment and start new
								if (ppmLength + length > CSJ2K.j2k.codestream.Markers.MAX_LPPM)
								{
									// Write current PPM marker
									temp = ppmMarkerSegment.ToArray();
									length = temp.Length - 2;
									temp[2] = (byte) (SupportClass.URShift(length, 8));
									temp[3] = (byte) length;
									fi.write(temp, 0, length + 2);
									
									// Start new PPM marker segment
									//UPGRADE_ISSUE: Method 'java.io.ByteArrayOutputStream.reset' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javaioByteArrayOutputStreamreset'"
									//ppmMarkerSegment.reset();
                                    ppmMarkerSegment.SetLength(0);
									ppmMarkerSegment.WriteByte((System.Byte) SupportClass.URShift(CSJ2K.j2k.codestream.Markers.PPM, 8));
									ppmMarkerSegment.WriteByte((System.Byte) (CSJ2K.j2k.codestream.Markers.PPM & 0x00FF));
									ppmMarkerSegment.WriteByte((System.Byte) 0); // Temp Lppm value
									ppmMarkerSegment.WriteByte((System.Byte) 0); // Temp Lppm value
									ppmMarkerSegment.WriteByte((System.Byte) ppmIndex++); // zppm
									ppmLength = 3;
								}
								
								// write packet header 
								ppmMarkerSegment.Write(packetHeaders[t][p], 0, packetHeaders[t][p].Length);
								ppmLength += packetHeaders[t][p].Length;
							}
							prem[t] -= numPackets;
						}
					}
				}
				// Write last PPM marker segment
				temp = ppmMarkerSegment.ToArray();
				length = temp.Length - 2;
				temp[2] = (byte) (SupportClass.URShift(length, 8));
				temp[3] = (byte) length;
				fi.write(temp, 0, length + 2);
			}
			
			// Write tile parts interleaved
			for (tp = 0; tp < maxtp; tp++)
			{
				for (t = 0; t < nt; t++)
				{
					if (tileParts[t].Length > tp)
					{
						temp = tileParts[t][tp];
						length = temp.Length;
						fi.write(temp, 0, length);
					}
				}
			}
			fi.writeShort(CSJ2K.j2k.codestream.Markers.EOC);
		}
Beispiel #49
0
        public static void RGS_setPolygons(I_DLE device, int address, byte g_code_id, RGS_PolygonData polygonData)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            ms.WriteByte(0x9a);
            ms.WriteByte(g_code_id);
            ms.WriteByte((byte)polygonData.polygons.Length);//section_count

            for (byte section_id = 1; section_id <= polygonData.polygons.Length; section_id++)
            {
                ms.WriteByte(section_id);//section_id
                ms.WriteByte((byte)polygonData.polygons[section_id - 1].points.Length);//length
                for (int point_inx = 0; point_inx < polygonData.polygons[section_id - 1].points.Length; point_inx++)
                {
                    ms.WriteByte((byte)(polygonData.polygons[section_id - 1].points[point_inx].X / 256));
                    ms.WriteByte((byte)(polygonData.polygons[section_id - 1].points[point_inx].X % 256));
                    ms.WriteByte((byte)(polygonData.polygons[section_id - 1].points[point_inx].Y / 256));
                    ms.WriteByte((byte)(polygonData.polygons[section_id - 1].points[point_inx].Y % 256));
                }
            }

             byte[]text=new byte[ms.Position];
             System.Array.Copy(ms.GetBuffer(),text,ms.Position);

             SendPackage pkg = new SendPackage(CmdType.CmdSet, CmdClass.A, address, text);
             device.Send(pkg);
        }
Beispiel #50
0
        public static void Write(this System.IO.Stream stream, FcgiRequest req)
        {
            var mstream = new System.IO.MemoryStream();
              mstream.WriteByte(req.Version);
              mstream.WriteByte((byte)req.Type);
              mstream.WriteByte((byte)(req.RequestId / 256));
              mstream.WriteByte((byte)(req.RequestId % 256));
              mstream.WriteByte((byte)(req.Content.Length / 256));
              mstream.WriteByte((byte)(req.Content.Length % 256));
              mstream.WriteByte((byte)(req.Padding.Length));
              mstream.WriteByte(0);
              mstream.Write(req.Content, 0, req.Content.Length);
              mstream.Write(req.Padding, 0, req.Padding.Length);
              var message = mstream.ToArray();
              stream.Write(message, 0, message.Length);

              //Program.Log(string.Format("  {0}:{1}, {2}:{3}:{4}", req.Version, req.Type, req.RequestId, req.Content.Hex(), req.Padding.Hex()));
        }
Beispiel #51
0
 private static byte[] EncodePEM(byte[][] data)
 {
     using(var ms = new System.IO.MemoryStream())
     {
         foreach(var n in data)
         {
             var isNegative = (n[0] & 0x80) != 0;
             EncodePEMLength(ms, (uint)(n.Length + (isNegative ? 1 : 0)));
             if (isNegative)
                 ms.WriteByte(0);
             ms.Write(n, 0, n.Length);
         }
         return ms.ToArray();
     }
 }
Beispiel #52
0
 public ActionResult Download()
 {
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     ms.WriteByte(0);
     return File(ms, "application/zip", "file.zip");
 }
        private static void GetClipboardContentForHtml(StringBuilder sbContent, out System.IO.MemoryStream utf8Stream)
        {
            byte[] sourceBytes = Encoding.Unicode.GetBytes(sbContent.ToString());
            byte[] destinationBytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, sourceBytes);

            // Marshal.SystemDefaultCharSize is 2 on WinXP Pro - so the offsets seem to be in character counts instead of bytes. 
            // Test on JPN and Win9x machines.
            int bytecountEndOfFragment = 135 + destinationBytes.Length;
            int bytecountEndOfHtml = bytecountEndOfFragment + 36;
            string prefix = string.Format(CultureInfo.InvariantCulture, DATAGRIDVIEW_htmlPrefix, bytecountEndOfHtml.ToString("00000000", CultureInfo.InvariantCulture), bytecountEndOfFragment.ToString("00000000", CultureInfo.InvariantCulture)) + DATAGRIDVIEW_htmlStartFragment;
            sbContent.Insert(0, prefix);
            sbContent.Append(DATAGRIDVIEW_htmlEndFragment);

            sourceBytes = Encoding.Unicode.GetBytes(sbContent.ToString());
            destinationBytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, sourceBytes);

            utf8Stream = new System.IO.MemoryStream(bytecountEndOfHtml + 1);
            utf8Stream.Write(destinationBytes, 0, bytecountEndOfHtml);
            utf8Stream.WriteByte((byte)0);
            
            #if DEBUG
            Debug.Assert(destinationBytes[97] == '<');
            Debug.Assert(destinationBytes[bytecountEndOfHtml-1] == '>');
            Debug.Assert(destinationBytes[133] == '<');
            Debug.Assert(destinationBytes[bytecountEndOfFragment] == '<');
            #endif
        }
Beispiel #54
0
 public override byte[] GetMessageBody()
 {
     using (System.IO.MemoryStream MS = new System.IO.MemoryStream ()) {
         using (System.IO.BinaryWriter BW = new System.IO.BinaryWriter (MS)) {
             BW.Write (requestID.ToByteArray ());
             BW.Write (tables.Length);
             for (int n = 0; n != tables.Length; n++) {
                 byte[] bytes = tables [n].Serialize ();
                 BW.Write (bytes.Length);
                 BW.Write (bytes);
             }
             if (exception == null) {
                 MS.WriteByte (0);
             } else {
                 MS.WriteByte (1);
                 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter BF = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter ();
                 long p = MS.Position;
                 try {
                     BF.Serialize (MS, exception);
                 } catch {
                     MS.Position = p;
                     BF.Serialize (MS, exception.ToString ());
                     MS.SetLength (MS.Position);
                 }
             }
             return MS.ToArray ();
         }
     }
 }
Beispiel #55
0
        //----------------------Read CDU
        private TextPackage ReadText()
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte data;
            TextPackage ret = new TextPackage();

            while (true)
            {
                data =(byte) stream.ReadByte();
                ms.WriteByte(data);
                if (data == 0xF8 || data == 0xC7)
                    break;
            }

            byte[] databuff = ms.ToArray();

            uint LCR = 0;
            byte lcr1, lcr2;
            for (int i = 0; i < databuff.Length - 3; i++)  //cal lcr
                LCR += databuff[i];
            LCR =(uint)( (~LCR) + 1);  //2's complement
            lcr1 =(byte)( LCR & 0x0f);
            lcr2 =(byte)( (LCR >> 4) & 0x0f);
            ret.Text = new byte[databuff.Length - 3];

            ret.CCU_EndCode = databuff[databuff.Length - 1];

            System.Array.Copy(databuff, ret.Text, ret.Text.Length);
            if (!(lcr1 == databuff[databuff.Length - 2] && lcr2 == databuff[databuff.Length - 3]))
            {

                ret.SetErrBit((int)V2DLE.DLE_ERR_LCR,true);
                ret.eErrorDescription="LCR Error!";
                ret.LRC =(byte)( (lcr2 << 4) | lcr1);

            }
            else
            {
                ret.LRC = (byte)LCR;
            }

            if(this.OnReceiveText!=null)
            this.OnReceiveText(this, ret);
            return ret;
        }
Beispiel #56
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 CD_RW_Packet[] Packetize_CD_RW(byte[] subchannels)
        {
            Console.WriteLine("{0}", subchannels.Length);
            CD_RW_Packet[] packets = new CD_RW_Packet[4];

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            for (int pack = 0; pack < 4; pack++)
                for (int column = 0; column < 24; column++)
                    ms.WriteByte(subchannels[(pack * 24) + offsets[column]]);

            ms.Seek(0, System.IO.SeekOrigin.Begin);
            byte[] packetized = ms.ToArray();

            for (int i = 0; i < 4; i++)
            {
                packets[i].parityQ = new byte[2];
                packets[i].data = new byte[16];
                packets[i].parityP = new byte[4];

                packets[i].command = (byte)(packetized[0 + i * 24] & 0x3F);
                packets[i].instruction = (byte)(packetized[1 + i * 24] & 0x3F);

                packets[i].parityQ[0] = (byte)(packetized[2 + i * 24] & 0x3F);
                packets[i].parityQ[1] = (byte)(packetized[3 + i * 24] & 0x3F);
                packets[i].data[0] = (byte)(packetized[4 + i * 24] & 0x3F);
                packets[i].data[1] = (byte)(packetized[5 + i * 24] & 0x3F);
                packets[i].data[2] = (byte)(packetized[6 + i * 24] & 0x3F);
                packets[i].data[3] = (byte)(packetized[7 + i * 24] & 0x3F);
                packets[i].data[4] = (byte)(packetized[8 + i * 24] & 0x3F);
                packets[i].data[5] = (byte)(packetized[9 + i * 24] & 0x3F);
                packets[i].data[6] = (byte)(packetized[10 + i * 24] & 0x3F);
                packets[i].data[7] = (byte)(packetized[11 + i * 24] & 0x3F);
                packets[i].data[8] = (byte)(packetized[12 + i * 24] & 0x3F);
                packets[i].data[9] = (byte)(packetized[13 + i * 24] & 0x3F);
                packets[i].data[10] = (byte)(packetized[14 + i * 24] & 0x3F);
                packets[i].data[11] = (byte)(packetized[15 + i * 24] & 0x3F);
                packets[i].data[12] = (byte)(packetized[16 + i * 24] & 0x3F);
                packets[i].data[13] = (byte)(packetized[17 + i * 24] & 0x3F);
                packets[i].data[14] = (byte)(packetized[18 + i * 24] & 0x3F);
                packets[i].data[15] = (byte)(packetized[19 + i * 24] & 0x3F);
                packets[i].parityP[0] = (byte)(packetized[20 + i * 24] & 0x3F);
                packets[i].parityP[1] = (byte)(packetized[21 + i * 24] & 0x3F);
                packets[i].parityP[2] = (byte)(packetized[22 + i * 24] & 0x3F);
                packets[i].parityP[3] = (byte)(packetized[23 + i * 24] & 0x3F);
            }

            return packets;
        }
Beispiel #58
0
        private byte[] PackData(int address ,byte[] text)
        {
            byte[] data;
            ushort dlecnt = 0;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            ms.WriteByte(DLE);
            ms.WriteByte(STX);
            ms.WriteByte(this.GetSeq());
            ms.WriteByte((byte)(address / 256));
            ms.WriteByte( (byte)(address % 256));
            ms.WriteByte((byte)(text.Length / 256));
            ms.WriteByte((byte)(text.Length % 256));
            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] == DLE)
                {
                    ms.WriteByte(text[i]);
                    dlecnt++;
                }
                ms.WriteByte(text[i]);
            }
            ms.WriteByte(DLE);
            ms.WriteByte(ETX);

            ms.GetBuffer()[5] = (byte)((text.Length + dlecnt+10) / 256);
            ms.GetBuffer()[6] = (byte)((text.Length + dlecnt+10) % 256);

              byte LRC = 0;
              for (int i = 0; i < ms.Length; i++)
                  LRC ^= ms.GetBuffer()[i];
              ms.WriteByte(LRC);
              data= ms.ToArray();

              return data;
            /*
            byte[] data = new byte[10 + text.Length];
            int inx = 0;
               data[0] = DLE;
            data[1] = STX;
            data[2] = this.GetSeq();
            data[3] = (byte)(address / 256);
            data[4] = (byte)(address % 256);
            data[5] = (byte)(text.Length / 256);
            data[6] = (byte)(text.Length % 256);

            for (inx = 0; inx < text.Length; inx++)
                data[7 + inx] = text[inx];
            data[7 + inx] = DLE;
            data[8 + inx] = ETX;

            byte LRC = 0;
            for (int i = 0; i < data.Length - 1; i++)
                LRC ^= data[i];

            data[data.Length - 1] = LRC;

            return data; */
        }
Beispiel #59
0
        private TextPackage ReadText()
        {
            int Seq=0,Address=0,Len=0,LRC=0;//,HeadLRC=0;
            byte[] text=null;
            TextPackage textPackage = new TextPackage();
            Seq = stream.ReadByte();
            Address = stream.ReadByte() * 256;
            Address+= stream.ReadByte();
            Len = stream.ReadByte() * 256;
            Len += stream.ReadByte();
             //   HeadLRC = stream.ReadByte();
            Len -= 10;
            textPackage.Seq = Seq;
            textPackage.Address = Address;

            //if (HeadLRC != (((Address >> 8) & 0x00ff) ^ (Address & 0x00ff) ^ ((Len >> 8) & 0x00ff) ^ (Len & 0x00ff)))
            //{
            //  // textPackage.HasErrors = true;
            //    textPackage.SetErrBit(V2DLE.DLE_ERR_FRAME, true);
            //    textPackage.eErrorDescription += "Hearder LRC Error!\r\n";
            //    //Console.WriteLine("Hearder LRC Error!");
            //    return textPackage;
            //}
            //else
            //{

                text = new byte[Len];
                int rlen = 0;

                do
                {
                    rlen+=stream.Read(text,rlen, Len-rlen);

                } while (rlen != Len);
                //for (int i = 0; i < Len; i++)
                //    text[i] = (byte)stream.ReadByte();

                stream.ReadByte();   //READ DLE
                stream.ReadByte();    // READ ETX

                LRC= STX ^ Seq ^ETX ^ (Len+10) /256 ^ (Len+10)%256 ;
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                bool isDLE=false;
                for (int i = 0; i < text.Length; i++)
                {
                    LRC ^= text[i];
                    if (text[i] != DLE)
                    {
                        ms.WriteByte(text[i]);
                        isDLE = false;
                    }
                    else  //double dle 處理
                    {
                        if (isDLE) //2nd dle
                            isDLE = false;
                        else  // 1st dle
                        {
                            isDLE = true;
                            ms.WriteByte(text[i]);
                        }
                    }

                }

                int tmp = stream.ReadByte();
                if (LRC !=tmp)// stream.ReadByte())
                {
                    textPackage.SetErrBit(TCDLE30.DLE_ERR_LCR, true);
                    textPackage.eErrorDescription += "LRC Error!\r\n";
                    Console.WriteLine("LRC Error!");
                    return textPackage;
                }
                else
                {
                   textPackage.Text=text;
                   textPackage.LRC = LRC;
                   return textPackage;

                }

              //  }
        }
Beispiel #60
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fc"></param>
        /// <param name="sim"></param>
        /// <param name="userData"></param>
        /// <returns></returns>
        public static byte[] MakeDtuCommand(byte fc, string sim, byte[] userData)
        {
            int userDataLen = userData != null ? userData.Length : 0;
            //if ( userData != null )
            //    userDataLen = userData.Length;
            byte[] cmd = new byte[SGDefine.MIN_PA_LEN + userDataLen];
            System.IO.MemoryStream ms = new System.IO.MemoryStream(cmd);
            ms.WriteByte(SGDefine.HEAD_VALUE);
            ms.WriteByte(fc);
            ms.Write(GetDtuLengthBytes(userDataLen + SGDefine.MIN_PA_LEN), 0, 2);

            byte[] simbs = SGDtu.GetSimNumberBytes(sim);
            ms.Write(simbs, 0, simbs.Length);

            if (userData != null && userData.Length > 0)
                ms.Write(userData, 0, userData.Length);
            ms.WriteByte(SGDefine.TAIL_VALUE);

            //return ms.GetBuffer();
            return ms.ToArray();
            //return (byte[])ms;
        }