Beispiel #1
0
    /// <summary>
    /// Create a packet that will send a custom object creation call.
    /// It is expected that the first byte that follows will identify which function will be parsing this packet later.
    /// </summary>

    static public void CreateEx(int rccID, bool persistent, GameObject go, params object[] objs)
    {
        if (go != null)
        {
            int index = IndexOf(go);

            if (isConnected)
            {
                if (index != -1)
                {
                    BinaryWriter writer = mInstance.mClient.BeginSend(Packet.RequestCreate);
                    writer.Write((ushort)index);
                    writer.Write(GetFlag(go, persistent));
                    writer.Write((byte)rccID);
                    writer.WriteArray(objs);
                    EndSend();
                    return;
                }
                else
                {
                    Debug.LogError("\"" + go.name + "\" has not been added to TNManager's list of objects, so it cannot be instantiated.\n" +
                                   "Consider placing it into the Resources folder and passing its name instead.", go);
                }
            }

            objs = BinaryExtensions.CombineArrays(go, objs);
            UnityTools.ExecuteAll(GetRCCs(), (byte)rccID, objs);
            UnityTools.Clear(objs);
        }
    }
Beispiel #2
0
        /// <summary>
        /// Calculate <c>QR</c> code format
        /// </summary>
        /// <param name="error">
        /// The error code information.
        /// </param>
        /// <param name="mask">
        /// The mask.
        /// </param>
        private void CalculateFormat(QrError error, QrMask mask)
        {
            // Get error bits
            if (this.debugData != null)
            {
                this.debugData.Append("- Calculating format bits...\n");
            }

            // Get 5 bits of format information
            int formatInfo = (QrErrorBits.GetBits(error) << 3) | BinaryExtensions.BinToDec(mask.GetBits());

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Format information error and mask bits: "
                    + BinaryExtensions.BinaryToString(BinaryExtensions.DecToBin(formatInfo)) + "\n");
                this.debugData.Append("- Calculating BCH (15,5) code for information bits...\n");
            }

            int bchCode = QrBoseChaudhuriHocquenghem.CalculateBch(formatInfo, QrConst.GenPolyFormat);

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- BCH (15,5) error code: " + BinaryExtensions.BinaryToString(BinaryExtensions.DecToBin(bchCode))
                    + "\n");
            }

            // Append BCH code to format info
            formatInfo = (formatInfo << 10) | bchCode;

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Format information with appended BCH: "
                    + BinaryExtensions.BinaryToString(BinaryExtensions.DecToBin(formatInfo)) + "\n");
                this.debugData.Append(
                    "- Calculating XOR with format constant: "
                    + BinaryExtensions.BinaryToString(BinaryExtensions.DecToBin(QrConst.ConstFormatXor)) + "\n");
            }

            formatInfo = formatInfo ^ QrConst.ConstFormatXor;

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Final format: " + BinaryExtensions.BinaryToString(BinaryExtensions.DecToBin(formatInfo, 15))
                    + "\n");
            }

            List <bool> formatBits = BinaryExtensions.DecToBin(formatInfo, 15);

            // Reverse, because our QRCode is inserting backwards
            formatBits.Reverse();

            foreach (bool t in formatBits)
            {
                this.output.Enqueue(t);
            }
        }
Beispiel #3
0
        /// <summary>
        ///   Serializes a Message to a Sachiel buffer and sets the Raw property.
        ///   If you are attempting to serialize a request endpoint, set includeEndpointAsHeader to true to automatically set the header.
        /// </summary>
        /// <returns></returns>
        public async Task <byte[]> Serialize(int allocate = 0, bool includeEndpointAsHeader = false)
        {
            var messageStream = new MemoryStream(allocate);
            var headerStream  = new MemoryStream();

            try
            {
                if (!IsCompatibile(Source.GetType()))
                    throw new InvalidSerializationException($"{Source.GetType()} is not based on Message."); }

                // For IPC purposes people might wish to use request both ways, this should allow them to do that.
                if (includeEndpointAsHeader)
                {
                    var attribute = Source.GetType().GetTypeInfo().GetCustomAttribute <SachielEndpoint>(false);
                    if (attribute == null)
                    {
                        throw new InvalidOperationException("No SachielEndpoint attribute is present on message.");
                    }
                    Header.Endpoint = attribute?.Name;
                }
                //Throw is the header is null.
                if (string.IsNullOrEmpty(Header?.Endpoint))
                {
                    throw new InvalidOperationException("Message headers cannot be null.");
                }
                Serialize(ref headerStream, Target.Header);
                await UnsafeArrayIo.WriteArray(messageStream, BinaryExtensions.EncodeVariableLengthQuantity((ulong)headerStream.Length), true);

                await UnsafeArrayIo.WriteArray(messageStream, headerStream.ToArray(), true);

                Serialize(ref messageStream, Target.Source);
                return(messageStream.ToArray());
            }
Beispiel #4
0
        /// <summary>
        /// Read page bytes from disk
        /// </summary>
        public virtual byte[] ReadPage(uint pageID)
        {
            var buffer   = new byte[BasePage.PAGE_SIZE];
            var position = BasePage.GetSizeOfPages(pageID);

            // position cursor
            if (_stream.Position != position)
            {
                _stream.Seek(position, SeekOrigin.Begin);
            }

            // read bytes from data file
            _stream.Read(buffer, 0, BasePage.PAGE_SIZE);

            // when reading the header, check the password
            if (pageID == 0 && _crypto != null)
            {
                // I know, header page will be double read (it's the price for isolated concerns)
                var header = (HeaderPage)BasePage.ReadPage(buffer);

                if (BinaryExtensions.BinaryCompareTo(_password, header.Password) != 0)
                {
                    throw LiteException.DatabaseWrongPassword();
                }
            }
            else if (_crypto != null)
            {
                buffer = _crypto.Decrypt(buffer);
            }

            return(buffer);
        }
Beispiel #5
0
        public void AddBinaryNull_Should_NotAddLogEventDetail()
        {
            var logEvent = new LogEvent <StandardLoglevel>(_ => { }, StandardLoglevel.Warning);

            BinaryExtensions.Binary <StandardLoglevel>(logEvent, null).Should().BeSameAs(logEvent);
            logEvent.Details.OfType <Binary>().Any().Should().BeFalse();
        }
Beispiel #6
0
    /// <summary>
    /// Create a packet that will send a custom object creation call.
    /// It is expected that the first byte that follows will identify which function will be parsing this packet later.
    /// </summary>

    static public void CreateEx(int rccID, bool persistent, string path, params object[] objs)
    {
        GameObject go = LoadGameObject(path);

        if (go != null)
        {
            if (isConnected)
            {
                if (mInstance != null && mInstance.mClient.isSwitchingScenes)
                {
                    Debug.LogWarning("Trying to create an object while switching scenes. Call will be ignored.");
                }

                BinaryWriter writer = mInstance.mClient.BeginSend(Packet.RequestCreate);
                byte         flag   = GetFlag(go, persistent);
                writer.Write((ushort)65535);
                writer.Write(flag);
                writer.Write(path);
                writer.Write((byte)rccID);
                writer.WriteArray(objs);
                EndSend();
                return;
            }

            objs = BinaryExtensions.CombineArrays(go, objs);
            UnityTools.ExecuteAll(GetRCCs(), (byte)rccID, objs);
            UnityTools.Clear(objs);
        }
        else
        {
            Debug.LogError("Unable to load " + path);
        }
    }
Beispiel #7
0
        public void AddBinaryData_Should_AddLogEventDetail()
        {
            var data     = new byte[] { 48, 49, 50, 51 };
            var logEvent = new LogEvent <StandardLoglevel>(_ => { }, StandardLoglevel.Warning);

            BinaryExtensions.Binary <StandardLoglevel>(logEvent, data).Should().BeSameAs(logEvent);
            logEvent.Details.OfType <Binary>().Single().Data.SequenceEqual(data).Should().BeTrue();
        }
Beispiel #8
0
        public void Deserialize(BEReader br)
        {
            Header.Deserialize(br);
            Payload = CreateFromPayloadType(Header.PayloadType);

            byte[]       buf           = br.ReadToEnd();
            BinaryReader payloadReader = BinaryExtensions.ReaderFromBytes(buf);

            Payload.Deserialize(payloadReader);
        }
Beispiel #9
0
        public void GetByteLengthTest()
        {
            int i1 = 0;
            int i2 = 0;

            Assert.AreEqual(8, BinaryExtensions.GetByteLength(i1, i2));
            short s1 = 0;

            Assert.AreEqual(10, BinaryExtensions.GetByteLength(i1, i2, s1));
            long l1 = 0;

            Assert.AreEqual(18, BinaryExtensions.GetByteLength(i1, i2, s1, l1));
        }
        public static ulong?GetNullableUnsignedLong(IDataRecord reader, int index)
        {
            if (reader.IsDBNull(index))
            {
                return(default(ulong?));
            }
            var value = reader.GetValue(index);
            var bytes = (byte[])value;

            if (bytes.Length == 0)
            {
                return(default(ulong?));
            }

            return(BinaryExtensions.RowVersionBytesToUInt64(bytes));
        }
        private byte[] ReadAndDecryptChunk(Stream stream)
        {
            var reader = new BEReader(stream);

            // 0xde, 0xad
            reader.ReadBytes(2);

            var length = reader.ReadUInt16();

            var encryptedPayloadLength = length + BinaryExtensions.CalculatePaddingSize(length, 16);

            var encryptedPayloadBytes    = new byte[encryptedPayloadLength];
            var encryptedPayloadPosition = 0;

            while (encryptedPayloadPosition < encryptedPayloadLength - 1)
            {
                var received = reader.ReadBytes(encryptedPayloadLength - encryptedPayloadPosition);
                received.CopyTo(encryptedPayloadBytes, encryptedPayloadPosition);
                encryptedPayloadPosition += received.Length;
            }

            var signature = reader.ReadBytes(32);

            var bodyWriter = new BEWriter();

            bodyWriter.Write(new byte[] { 0xde, 0xad });
            bodyWriter.Write(length);
            bodyWriter.Write(encryptedPayloadBytes);

            var messageSignature = _cryptoContext.CalculateMessageSignature(bodyWriter.ToArray());

            if (!signature.SequenceEqual(messageSignature))
            {
                throw new InvalidDataException("Invalid message signature.");
            }

            var decryptedPayload = _cryptoContext.Decrypt(encryptedPayloadBytes);

            return(decryptedPayload.Take(length).ToArray());
        }
Beispiel #12
0
        /// <summary>
        /// The do mask.
        /// </summary>
        /// <param name="codeMask">
        /// The mask.
        /// </param>
        private void DoMask(QrMask codeMask)
        {
            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 9 ------------------\n- Executing mask on data pixels: "
                    + BinaryExtensions.BinaryToString(codeMask.GetBits()) + "\n");
            }

            int counter = 0;

            for (int i = 0; i < this.picture.GetLength(0); i++)
            {
                for (int j = 0; j < this.picture.GetLength(1); j++)
                {
                    int x = this.picture.GetLength(0) - i - 1;
                    int y = this.picture.GetLength(1) - j - 1;

                    if (codeMask.Test(y, x) && (this.staticData[x, y] == false) && (this.picture[x, y] != QrPixel.Empty))
                    {
                        this.picture[x, y] = (this.picture[x, y] == QrPixel.White) ? QrPixel.Black : QrPixel.White;

                        counter++;

                        if ((this.breakPoint == QrBreakPoint.Mask) && (this.debugData != null))
                        {
                            this.picture[x, y] = QrPixel.Mask;
                        }
                    }
                }
            }

            if (this.debugData != null)
            {
                this.debugData.Append("- Mask (" + codeMask + ") written to: " + counter + " pixels.\n\n");
            }
        }
Beispiel #13
0
        public void FromBinaryNullStringTest()
        {
            Action act = () => BinaryExtensions.FromBinary <SerializableObjectFake>(null);

            act.Should().Throw <ArgumentNullException>();
        }
Beispiel #14
0
 public void LogEventNull_ShouldThrow_ArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() => BinaryExtensions.Binary <StandardLoglevel>(null, new byte[] { 0x00, 0x01, 0x02, 0x03 }));
 }
Beispiel #15
0
        /// <summary>
        /// The process.
        /// </summary>
        /// <exception cref="ArgumentException">
        /// Throws argument exception if wrong type or version are selected
        /// </exception>
        /// <exception cref="Exception">
        /// Throws exception if text is too long for the matrix
        /// </exception>
        private void Process()
        {
            // Preprocess
            // -> one of the parameters was not set, simple mode
            // -> create structure of QR Image
            this.ChooseVersions();

            if (this.debugData != null)
            {
                this.img = new QrImage(this.version, this.mask, this.breakPoint);

                this.debugData.Append(this.img.GetDebugData());
            }
            else
            {
                this.img = new QrImage(this.version, this.mask);
            }

            if ((this.breakPoint == QrBreakPoint.CreatedMatrix) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 1 -------");

                return;
            }

            // Step one - sending type to output
            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 1 ------------------\n- Sending type bits (4) to output ...\n");
            }

            switch (this.type)
            {
            case QrType.Numeric:
                this.output.Enqueue(false);
                this.output.Enqueue(false);
                this.output.Enqueue(false);
                this.output.Enqueue(true);

                break;

            case QrType.AlphaNumeric:
                this.output.Enqueue(false);
                this.output.Enqueue(false);
                this.output.Enqueue(true);
                this.output.Enqueue(false);

                break;

            case QrType.Binary:
                this.output.Enqueue(false);
                this.output.Enqueue(true);
                this.output.Enqueue(false);
                this.output.Enqueue(false);

                break;

            case QrType.Japanese:
                this.output.Enqueue(true);
                this.output.Enqueue(false);
                this.output.Enqueue(false);
                this.output.Enqueue(false);

                break;

            default:
                throw new ArgumentException("Wrong QRType selected.");
            }

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Sent 4 bytes of output: " + BinaryExtensions.BinaryToString(this.output) + "\n\n");
            }

            if ((this.breakPoint == QrBreakPoint.OutputTypeBits) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 2 -------");

                return;
            }

            // Step two - write length of string
            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 2 ------------------\n- Calculating bit size for data length ...\n");
            }

            byte strLength;

            if ((this.version.Version >= 1) && (this.version.Version <= 9))
            {
                switch (this.type)
                {
                case QrType.Numeric:
                    strLength = 10;
                    break;

                case QrType.AlphaNumeric:
                    strLength = 9;
                    break;

                case QrType.Binary:
                    strLength = 8;
                    break;

                case QrType.Japanese:
                    strLength = 8;
                    break;

                default:
                    strLength = 0;
                    break;
                }
            }
            else if ((this.version.Version >= 10) && (this.version.Version <= 26))
            {
                switch (this.type)
                {
                case QrType.Numeric:
                    strLength = 12;
                    break;

                case QrType.AlphaNumeric:
                    strLength = 11;
                    break;

                case QrType.Binary:
                    strLength = 16;
                    break;

                case QrType.Japanese:
                    strLength = 10;
                    break;

                default:
                    strLength = 0;
                    break;
                }
            }
            else if ((this.version.Version >= 27) && (this.version.Version <= 40))
            {
                switch (this.type)
                {
                case QrType.Numeric:
                    strLength = 14;
                    break;

                case QrType.AlphaNumeric:
                    strLength = 13;
                    break;

                case QrType.Binary:
                    strLength = 16;
                    break;

                case QrType.Japanese:
                    strLength = 12;
                    break;

                default:
                    strLength = 0;
                    break;
                }
            }
            else
            {
                throw new ArgumentException("Wrong QRVersion selected.");
            }

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- QR Type: " + this.type + ", QR Version: " + this.version.Version + ", Bit size: " + strLength
                    + " bits.\n");
            }

            // Write length to output
            int length = this.text.Length;

            this.ToOutput(BinaryExtensions.DecToBin(length, strLength));

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Stored data length to output: "
                    + BinaryExtensions.BinaryToString(BinaryExtensions.DecToBin(length, strLength)) + "\n");
                this.debugData.Append(
                    "- Data stored in output: " + BinaryExtensions.BinaryToString(this.output) + "\n\n");
            }

            if ((this.breakPoint == QrBreakPoint.OutputDataLength) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 3 -------");

                return;
            }

            // Step 3 - encoding entry text
            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 3 ------------------\n- Creating code table for input ...\n");
            }

            QrCodeTable table = new QrCodeTable(this.type);

            if (this.debugData != null)
            {
                this.debugData.Append("- Checking for odd input length.\n");
            }

            // Odd text length handling
            if (length % 2 == 1)
            {
                if (this.debugData != null)
                {
                    this.debugData.Append(" - Text length is odd, reducing size for one character.\n");
                }

                length = length - 1;
            }

            if (this.debugData != null)
            {
                this.debugData.Append("- Writing characters ...\n");
            }

            for (int i = 0; i < length; i += 2)
            {
                // Get number
                int calc = (table.GetCharCount() * table.GetCodeByChar(this.text[i]))
                           + table.GetCodeByChar(this.text[i + 1]);

                if (this.debugData != null)
                {
                    this.debugData.Append(
                        " - Characters: " + this.text[i] + ", " + this.text[i + 1] + ": (" + table.GetCharCount()
                        + " * " + table.GetCodeByChar(this.text[i]) + ") + " + table.GetCodeByChar(this.text[i + 1])
                        + " = " + calc + "\n");
                }

                // Write number, why 11 bits for each sign?????
                // Experimental: strLength as calculated for size.
                this.ToOutput(BinaryExtensions.DecToBin(calc, 11));
            }

            // Handling last 6 bits for odd length
            if (this.text.Length % 2 == 1)
            {
                if (this.debugData != null)
                {
                    this.debugData.Append(
                        "- Writing last (odd) character " + this.text[this.text.Length - 1] + " with " + 6 + " bits: "
                        + table.GetCodeByChar(this.text[this.text.Length - 1]) + "\n");
                }

                this.ToOutput(BinaryExtensions.DecToBin(table.GetCodeByChar(this.text[this.text.Length - 1]), 6));
            }

            if (this.debugData != null)
            {
                this.debugData.Append("- Input successfully encoded to binary.\n\n");
            }

            if ((this.breakPoint == QrBreakPoint.EncodedDataToBinary) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 4 -------");

                return;
            }

            // Step 4 - finishing binary string
            if (this.debugData != null)
            {
                this.debugData.Append("------------------ Step 4 ------------------\n- Finishing binary string ...\n");
            }

            // Calculate maximum bit length
            int maxBits = this.version.DataSize * 8;

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Maximum bits for current version: " + maxBits + " current bits: " + this.output.Count + "\n");
            }

            // Add zeros to end of bit string, if we are missing them
            int bitOverflow = 0;

            while (this.output.Count < maxBits)
            {
                this.output.Enqueue(false);

                bitOverflow++;

                if (bitOverflow >= 4)
                {
                    break;
                }
            }

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Added " + bitOverflow + " bits to binary output. Total: " + this.output.Count + " bits.\n\n");
            }

            if ((this.breakPoint == QrBreakPoint.FinishedBinary) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 5 -------");

                return;
            }

            // Step 5 - breaking the bit string into bytes
            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 5 ------------------\n- Dividing bits into bytes (8 bits per byte) ...\n");
                this.debugData.Append("- Current output size: " + this.output.Count + " bits\n");
            }

            // For now we will just make sure it is divided by 8, we will not convert to bytes unless required.
            while (this.output.Count % 8 != 0)
            {
                this.output.Enqueue(false);
            }

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Added zeros to output, current size: " + this.output.Count + " bits, "
                    + (this.output.Count / 8) + " bytes.\n\n");
            }

            if ((this.breakPoint == QrBreakPoint.BrokenBinary) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 6 -------");

                return;
            }

            // Step 6 - inserting characters
            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 6 ------------------\n- Inserting characters to fill missing data string ...\n");
            }

            // If we have too many bits
            if ((this.output.Count / 8) > this.version.DataSize)
            {
                throw new Exception("Text is too long for current matrix.");
            }

            // If we have less or exact number of bits
            List <bool> defaultBlock1 = BinaryExtensions.DecToBin(236, 8);
            List <bool> defaultBlock2 = BinaryExtensions.DecToBin(17, 8);

            // Fill matrix until it is full as specified in version
            int fillCount = 0;

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "- Current output size: " + (this.output.Count / 8) + ", missing: "
                    + (this.version.DataSize - (this.output.Count / 8)) + " bytes.\n");
                this.debugData.Append("- Added bytes: ");
            }

            while ((this.output.Count / 8) < this.version.DataSize)
            {
                if ((fillCount % 2) == 0)
                {
                    if (this.debugData != null)
                    {
                        this.debugData.Append("236, ");
                    }

                    this.ToOutput(defaultBlock1);
                }
                else
                {
                    if (this.debugData != null)
                    {
                        this.debugData.Append("17, ");
                    }

                    this.ToOutput(defaultBlock2);
                }

                fillCount++;
            }

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "\n- Output size filled to match data size: " + (this.output.Count / 8) + "/"
                    + this.version.DataSize + " bytes\n\n");
            }

            if ((this.breakPoint == QrBreakPoint.MissingBytes) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 7 -------");

                return;
            }

            // Step 7 - generating error code correction (ECC) by Reed-Solomon procedure

            // Convert bits from output to byte array
            byte[] bytes = BinaryExtensions.BitArrayToByteArray(new BitArray(this.output.ToArray()));

            if (this.debugData != null)
            {
                this.debugData.Append(
                    "------------------ Step 7 ------------------\n- Calculating error code correction ...\n");
                this.debugData.Append(
                    "- Dividing data words into blocks: " + this.version.GetBlockCount() + " total.\n");
                this.debugData.Append("- Creating message polynomial for each block ...\n");
            }

            // Divide bytes into blocks
            QrBlock[] blocks = new QrBlock[this.version.GetBlockCount()];

            for (int x = 0; x < this.version.GetBlockCount(); x++)
            {
                // Creating message polynominal system (F(x)) for current block

                // Calculate block length and starting position
                int blockLength;
                int blockStart;

                if (x >= this.version.BlockOneCount)
                {
                    blockLength = this.version.BlockTwoSize;

                    blockStart = (this.version.BlockOneSize * this.version.BlockOneCount)
                                 + ((x - this.version.BlockOneCount) * this.version.BlockTwoSize);
                }
                else
                {
                    blockLength = this.version.BlockOneSize;

                    blockStart = this.version.BlockOneSize * x;
                }

                if (this.debugData != null)
                {
                    this.debugData.Append(
                        "----------------------------------\n- Block " + (x + 1) + ", data from: " + blockStart
                        + ", length: " + blockLength + "\n- Message polynomial:\n\n");
                }

                Poly message = new Poly();

                int messageLevel = this.version.BlockOneSize
                                   + (this.version.ErrorSize / this.version.GetBlockCount()) - 1;

                for (int i = 0; i < blockLength; i++)
                {
                    if (this.debugData != null)
                    {
                        this.debugData.Append("(" + bytes[i + blockStart] + "x ^ " + messageLevel + ")");

                        if (i != blockLength - 1)
                        {
                            this.debugData.Append(" + ");
                        }
                    }

                    Term ter = new Term(messageLevel, bytes[i + blockStart]);
                    message.Terms.Add(ter);

                    messageLevel--;
                }

                if (this.debugData != null)
                {
                    this.debugData.Append(
                        "\n\n- Calculating "
                        + ((int)Math.Floor(this.version.ErrorSize / (double)this.version.GetBlockCount()))
                        + " error codes using Reed-Solomon algorithm.\n");
                }

                // Calculate Error codes of desired block
                blocks[x] = new QrBlock {
                    MessagePoly = new Poly(message)
                };

                // Create Reed Solomon algorithm class
                QrReedSolomon ecc = new QrReedSolomon();

                // Experimental bugfix: rounding the result, so we can choose correct ECC
                blocks[x].EccCoefficients = ecc.Calculate(
                    message, (int)Math.Floor(this.version.ErrorSize / (double)this.version.GetBlockCount()));

                if (this.debugData != null)
                {
                    this.debugData.Append(
                        "- Calculated error codes: " + BinaryExtensions.ArrayToString(blocks[x].EccCoefficients)
                        + "\n\n");
                }
            }

            // Write error codes to bit stream

            // Clear current output
            this.output.Clear();

            // Writing data bits
            if (this.debugData != null)
            {
                this.debugData.Append("- Writing data bits into output:\n- ");
            }

            // Blocks might not be the same size...
            for (int i = 0; i < Math.Max(this.version.BlockOneSize, this.version.BlockTwoSize); i++)
            {
                foreach (QrBlock t in blocks)
                {
                    if (i < t.MessagePoly.Terms.Length)
                    {
                        this.ToOutput(BinaryExtensions.DecToBin(t.MessagePoly.Terms[i].Coefficient, 8));

                        if (this.debugData != null)
                        {
                            this.debugData.Append(t.MessagePoly.Terms[i].Coefficient + ", ");
                        }
                    }
                }
            }

            if (this.debugData != null)
            {
                this.debugData.Append("\n\n- Writing ECC bits to output:\n- ");
            }

            // Writting ECC bits
            for (int i = 0; i < blocks[0].EccCoefficients.Length; i++)
            {
                if (i == 17)
                {
                    if (this.debugData != null)
                    {
                        this.debugData.Append(",");
                    }
                }

                foreach (QrBlock t in blocks)
                {
                    this.ToOutput(BinaryExtensions.DecToBin(t.EccCoefficients[i], 8));

                    if (this.debugData != null)
                    {
                        this.debugData.Append(t.EccCoefficients[i] + ", ");
                    }
                }
            }

            if (this.debugData != null)
            {
                this.debugData.Append("\n\n");
            }

            // Step 8, 9, 10 - Handled by QRImage class
            if ((this.breakPoint == QrBreakPoint.ErrorCode) && (this.debugData != null))
            {
                this.debugData.Append("------- Breakpoint reached: Step 8 -------");

                return;
            }

            this.img.CreateImage(this.output);

            if (this.debugData != null)
            {
                this.debugData.Append(this.img.GetDebugData());
            }
        }
Beispiel #16
0
        /// <summary>
        /// The write version.
        /// </summary>
        /// <param name="codeVersion">
        /// The version.
        /// </param>
        private void WriteVersion(QrVersion codeVersion)
        {
            if (this.debugData != null)
            {
                this.debugData.Append("- Should we write version information bits?\n");
            }

            // Only writing version with versions higher than 6
            if (codeVersion.Version >= 7)
            {
                // Calculate BCH (18, 6) for version information
                int bchVersion = QrBoseChaudhuriHocquenghem.CalculateBch(codeVersion.Version, QrConst.GenPolyVersion);

                int versionInformation = (codeVersion.Version << 12) | bchVersion;

                List <bool> versionInfo = BinaryExtensions.DecToBin(versionInformation, 18);

                versionInfo.Reverse();

                if (this.debugData != null)
                {
                    this.debugData.Append(
                        "- Yes, writing information: " + BinaryExtensions.BinaryToString(versionInfo) + ".\n");
                }

                int iterator = 0;

                // Version bits at upper right corner
                for (int y = 0; y < 6; y++)
                {
                    for (int x = this.picture.GetLength(0) - 8 - 3, j = 0; j < 3; x++, j++)
                    {
                        this.picture[x, y] = versionInfo[iterator] ? QrPixel.Black : QrPixel.White;

                        iterator++;
                    }
                }

                iterator = 0;

                // Version bits at lower left corner
                for (int x = 0; x < 6; x++)
                {
                    for (int y = this.picture.GetLength(0) - 8 - 3, j = 0; j < 3; y++, j++)
                    {
                        this.picture[x, y] = versionInfo[iterator] ? QrPixel.Black : QrPixel.White;

                        iterator++;
                    }
                }

                if (this.debugData != null)
                {
                    this.debugData.Append("- Version information bits successfully written.\n");
                }
            }

            if ((this.debugData != null) && (codeVersion.Version < 7))
            {
                this.debugData.Append("- No, only required for versions higher than 6.\n");
            }
        }
Beispiel #17
0
        public void ToBinaryNullObjectTest()
        {
            Action Act = () => BinaryExtensions.ToBinary <SerializableObjectFake>(null);

            Act.Should().Throw <ArgumentNullException>();
        }
        public static ulong GetUnsignedLong(IDataRecord reader, int index)
        {
            var value = reader.GetValue(index);

            return(BinaryExtensions.RowVersionBytesToUInt64((byte[])value));
        }
Beispiel #19
0
 public void DeserializeData(ISerializableLE payloadType)
 {
     Data = payloadType;
     Data.Deserialize(BinaryExtensions.ReaderFromBytes(RawData));
 }
        public static INanoPacket ParsePacket(byte[] data, NanoChannelContext context)
        {
            BEReader  packetReader = new BEReader(data);
            RtpHeader header       = new RtpHeader();

            header.Deserialize(packetReader);
            NanoPayloadType payloadType = header.PayloadType;

            // It might be NanoChannel.Unknown at this point, if ChannelCreate
            // packet was not processed yet
            // It gets processed at the end of the function
            NanoChannel channel = context.GetChannel(header.ChannelId);

            BinaryReader payloadReader =
                BinaryExtensions.ReaderFromBytes(packetReader.ReadToEnd());
            INanoPacket packet = null;

            switch (payloadType)
            {
            // FIXME: Create from Attribute is broken
            case NanoPayloadType.UDPHandshake:
                packet = new UdpHandshake();
                break;

            case NanoPayloadType.ControlHandshake:
                packet = new ControlHandshake();
                break;

            case NanoPayloadType.ChannelControl:
                // Read type to pinpoint exact payload
                ChannelControlType cct =
                    (ChannelControlType)payloadReader.ReadUInt32();
                packet = CreateFromChannelControlType(cct);
                break;

            case NanoPayloadType.Streamer:
                packet = CreateFromStreamerHeader(payloadReader, channel);
                break;

            default:
                throw new NanoPackingException(
                          $"Unknown packet type received: {payloadType}");
            }

            if (packet == null)
            {
                throw new NanoPackingException("Failed to find matching body for packet");
            }

            payloadReader.Seek(0, SeekOrigin.Begin);
            packet.Deserialize(payloadReader);
            packet.Header = header;

            if (packet as ChannelCreate != null)
            {
                string channelName = ((ChannelCreate)packet).Name;
                channel = NanoChannelClass.GetIdByClassName(channelName);
            }

            if (channel == NanoChannel.Unknown)
            {
                throw new NanoPackingException("ParsePacket: INanoPacket.Channel is UNKNOWN");
            }

            packet.Channel = channel;
            return(packet);
        }