Exemplo n.º 1
0
        public ResultInfo SaveIcon(List <FileInfo> fileList)
        {
            List <IconBKInfo> iconList        = new List <IconBKInfo>();
            StringBuilder     upProDTProDefSB = new StringBuilder();

            foreach (FileInfo file in fileList)
            {
                IconBKInfo sadDTIcon = new IconBKInfo();

                //1001_小吃A.jpg 取 小吃A
                int IconNameBegin = file.Name.IndexOf('_') + 1;
                int IconNameEnd   = file.Name.LastIndexOf('.');
                sadDTIcon.IconName = file.Name.Substring(IconNameBegin, IconNameEnd - IconNameBegin);
                string iconNumber       = file.Name.Substring(0, file.Name.LastIndexOf('_'));
                int    iconNumberTail   = 0;
                string upProDTProDefStr = string.Format("update proDTProDef set IconNumber={0} where ProDefNumber={1}", iconNumber + iconNumberTail, iconNumber);
                if (sadDTIcon.IconName.EndsWith("detail", StringComparison.InvariantCultureIgnoreCase))
                {
                    iconNumberTail   = 1;
                    upProDTProDefStr = string.Format("update proDTProDef set detailIconNumber={0} where ProDefNumber={1}", iconNumber + iconNumberTail, iconNumber);
                }
                else if (sadDTIcon.IconName.EndsWith("display", StringComparison.InvariantCultureIgnoreCase))
                {
                    iconNumberTail   = 2;
                    upProDTProDefStr = string.Format("update proDTProDef set displayIcon={0} where ProDefNumber={1}", iconNumber + iconNumberTail, iconNumber);
                }
                upProDTProDefSB.Append(upProDTProDefStr + "\r\n");

                sadDTIcon.IconNumber = Convert.ToInt32(iconNumber + iconNumberTail);
                sadDTIcon.IconType   = 1;
                if (file.Extension.Equals(".gif", StringComparison.InvariantCultureIgnoreCase))
                {
                    sadDTIcon.IconType = 2;
                }
                sadDTIcon.IconImage = BinaryHelper.FileToBytes(file);
                sadDTIcon.Status    = true;
                sadDTIcon.UpUser    = 1;
                sadDTIcon.UpDT      = DateTime.Now;
                iconList.Add(sadDTIcon);
            }
            try
            {
                _dal.SaveIcon(iconList, upProDTProDefSB.ToString());
            }
            catch (Exception ex)
            {
                _log.Fatal(ex);
                return(ResultInfo.Fail);
            }
            return(ResultInfo.Success);
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Fan1"></param>
        /// <param name="Fan2"></param>
        /// <param name="Fan3"></param>
        /// <param name="Fan4"></param>
        /// <param name="TimeoutValue">Timeout is in 1/8 ticks, 1 = 1/8, 2 = 1/4, 255 = 31 7/8</param>
        public void SetFanPowerFailSafe(bool Fan1, bool Fan2, bool Fan3, bool Fan4, byte TimeoutValue)
        {
            Binary _bitMask = new Binary();

            _bitMask = BinaryHelper.ToggleBit(_bitMask, 0, Fan1, true);
            _bitMask = BinaryHelper.ToggleBit(_bitMask, 1, Fan2, true);
            _bitMask = BinaryHelper.ToggleBit(_bitMask, 2, Fan3, true);
            _bitMask = BinaryHelper.ToggleBit(_bitMask, 3, Fan4, true);

            _display.SendCommand(Commands.SET_FAN_POWER_FAILSAFE, new byte[2] {
                Convert.ToByte(_bitMask),
                TimeoutValue
            });
        }
Exemplo n.º 3
0
        public ReadCompare()
        {
            int size = sizeof(int) * AMOUNT;

            m_byteBuf = new byte[size];
            m_ptrBuf  = Marshal.AllocHGlobal(size);

            for (int i = 0; i < size; i += 4)
            {
                int num = i / 4;
                BinaryHelper.Write(m_byteBuf, i, num);
                BinaryHelper.Write(m_ptrBuf, i, num);
            }
        }
Exemplo n.º 4
0
    public List <int> eventsList = new  List <int>();// 事件列表
    //////////////////////////////////////////////////////////////////////////
    // 触发事件 逻辑关系事件的 读写数据 顺序为
    // 事件ID 也是事件关系
    // 关系事件列表的数量
    // 关系事件列表内循环内 此逻辑关系事件的唯一ID
    // 关系事件列表内循环内 各个事件的逻辑关系事件的数量
    // 关系事件列表内循环内 各个事件的逻辑关系事件列表循环内  事件唯一ID

    override public void Write(BinaryHelper helper)
    {
        helper.Write(serNo);
        helper.Write(eventsList.Count);

        Debug.Log("EventsRelationship 写数据serNo:" + serNo + "eventId:" + eventId + ",eventsList.Count:" + eventsList.Count);
        for (int i = 0; i < eventsList.Count; i++)
        {
            helper.Write(eventsList[i]);


            Debug.Log("EventsRelationship eventsList[i]:" + eventsList[i]);
        }
    }
Exemplo n.º 5
0
        public override void WriteTo(System.IO.Stream stream)
        {
            if (Addresses == null || Masks == null || Addresses.Length != Masks.Length)
            {
                throw new NotSupportedException("Addresses and Masks do not have the same length");
            }
            stream.WriteByte((byte)(Addresses.Length + Masks.Length));

            for (int i = 0; i < Addresses.Length; i++)
            {
                BinaryHelper.Write(stream, Addresses[i].GetAddressBytes());
                BinaryHelper.Write(stream, Masks[i].GetAddressBytes());
            }
        }
Exemplo n.º 6
0
        public void ReadPtrByteReaderTest(int value)
        {
            byte[] dat = new byte[4];
            BinaryHelper.Write(dat, 0, value);

            ByteReader br   = new ByteReader(dat);
            IntPtr     dest = Alloc(4);

            br.ReadPtr(dest.ToPointer(), 4);

            Assert.AreEqual(4, br.Offset);
            Assert.AreEqual(value, BinaryHelper.Read <int>(dest, 0));
            Free(dest);
        }
Exemplo n.º 7
0
        public void TestDeserializeField()
        {
            // Read the serialized data
            //string filePath = TestContext.CurrentContext.TestDirectory + System.IO.Path.DirectorySeparatorChar + @"Data\DynamicSchemaBinaryField.dat";
            string filePath = Util.GetTestDirectory() + System.IO.Path.DirectorySeparatorChar + @"Data\DynamicSchemaBinaryField.dat";

            byte[] bytes = Util.ReadBinaryFile(filePath);

            // Deserialize the serialized data
            object deserialized = BinaryHelper.DeserializeField(bytes);

            // Assert that Field value is correct
            Assert.That(NUMBER_FIELD_VALUE, Is.EqualTo(deserialized));
        }
Exemplo n.º 8
0
    public void Load(byte[] bytes)
    {
        m_levelUpMap = new Dictionary <int, LevelUpInfo>();
        BinaryHelper helper = new BinaryHelper(bytes);

        int sceneCount = helper.ReadInt();

        for (int index = 0; index < sceneCount; ++index)
        {
            LevelUpInfo info = new LevelUpInfo();
            info.Load(helper);
            m_levelUpMap.Add(info.lvl, info);
        }
    }
Exemplo n.º 9
0
        private static BundleKeys DeriveBundleKeys(byte[] key, string keyInfo)
        {
            byte[] info = BinaryHelper.Kw(keyInfo);

            using (var hmac = new HMACSHA256())
            {
                HKDF   hkdf   = new HKDF(hmac, key);
                byte[] result = hkdf.Expand(info, 3 * 32);

                byte[] hmacKey = result.Take(32).ToArray();
                byte[] xorKey  = result.Skip(32).ToArray();
                return(new BundleKeys(hmacKey, xorKey));
            }
        }
Exemplo n.º 10
0
    public void Load(byte[] bytes)
    {
        m_dungeonEventMap = new Dictionary <int, DungeonEventInfo>();
        BinaryHelper helper = new BinaryHelper(bytes);

        int count = helper.ReadInt();

        for (int index = 0; index < count; ++index)
        {
            DungeonEventInfo info = new DungeonEventInfo();
            info.Load(helper);
            m_dungeonEventMap.Add(info.EventID, info);
        }
    }
Exemplo n.º 11
0
        public override void LoadFromBinaryReader(System.IO.Stream binaryReader)
        {
            base.LoadFromBinaryReader(binaryReader);
            Contents = binaryReader.ReadBytes((int)(BlockSize - 8));

            //Hack para o monkey island 2 com vozes.
            if (BinaryHelper.ConvertByteArrayToUTF8String(binaryReader.PeekBytes(4)) == "021_")
            {
                var lstBytes = new List <byte>(Contents);
                lstBytes.AddRange(binaryReader.ReadBytes(8));

                Contents = lstBytes.ToArray();
            }
        }
Exemplo n.º 12
0
    public void Load(byte[] bytes)
    {
        m_map = new Dictionary <int, QualityInfo>();
        BinaryHelper helper = new BinaryHelper(bytes);

        int sceneCount = helper.ReadInt();

        for (int index = 0; index < sceneCount; ++index)
        {
            QualityInfo info = new QualityInfo();
            info.Load(helper);
            m_map.Add(info.m_quality, info);
        }
    }
Exemplo n.º 13
0
        // FUNCTIONS

        public List <byte> toBytes()
        {
            List <byte> byteFile = new List <byte>();

            recalcCounts();
            byteFile.AddRange(BinaryWrapper.toBytes(header));

            foreach (DDD_itemdata_Entry entry in entries)
            {
                byteFile.AddRange(BinaryWrapper.toBytes(entry));
            }
            byteFile.AddRange(BinaryHelper.hexStringAsBytes(HEX_EOF));
            return(byteFile);
        }
Exemplo n.º 14
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.String)
            {
                string hex = serializer.Deserialize <string>(reader);

                if (!string.IsNullOrEmpty(hex))
                {
                    return(BinaryHelper.StringToByteArray(hex));
                }
            }

            return(Array.Empty <byte>());
        }
Exemplo n.º 15
0
    public void Load(byte[] bytes)
    {
        m_map = new Dictionary <int, PlayerAttrInfo>();
        BinaryHelper helper = new BinaryHelper(bytes);

        int sceneCount = helper.ReadInt();

        for (int index = 0; index < sceneCount; ++index)
        {
            PlayerAttrInfo info = new PlayerAttrInfo();
            info.Load(helper);
            m_map.Add(info.m_level, info);
        }
    }
Exemplo n.º 16
0
        private uint GetPreScale(PICController controller)
        {
            bool prescale_mode = controller.GetUnbankedRegisterBit(PICMemory.ADDR_OPTION, PICMemory.OPTION_BIT_PSA);

            uint scale = 0;

            scale += controller.GetUnbankedRegisterBit(PICMemory.ADDR_OPTION, PICMemory.OPTION_BIT_PS2) ? 1U : 0U;
            scale *= 2;
            scale += controller.GetUnbankedRegisterBit(PICMemory.ADDR_OPTION, PICMemory.OPTION_BIT_PS1) ? 1U : 0U;
            scale *= 2;
            scale += controller.GetUnbankedRegisterBit(PICMemory.ADDR_OPTION, PICMemory.OPTION_BIT_PS0) ? 1U : 0U;

            return(prescale_mode ? 1 : (BinaryHelper.SHL(2, scale)));
        }
Exemplo n.º 17
0
        public void TestGetType01()
        {
            //Test Procedure Call
            Type returnType = BinaryHelper.GetType(null);

            //Post Condition Check
            Assert.IsNull(returnType);

            //Test Procedure Call
            int i = 0;

            returnType = BinaryHelper.GetType(i);
            //Post Condition Check
        }
Exemplo n.º 18
0
    public void Load(byte[] bytes)
    {
        m_map = new Dictionary <int, EventItemInfo>();
        BinaryHelper helper = new BinaryHelper(bytes);

        int sceneCount = helper.ReadInt();

        for (int index = 0; index < sceneCount; ++index)
        {
            EventItemInfo info = new EventItemInfo();
            info.Load(helper);
            m_map.Add(info.itemId, info);
        }
    }
Exemplo n.º 19
0
        public async Task FileAsyncRoundtrip()
        {
            var dummy = new DummySerializable {
                Value = 1
            };
            await BinaryHelper.SaveAsync(dummy, _file).ConfigureAwait(false);

            AssertFile.Exists(true, _file);

            var read = await BinaryHelper.ReadAsync <DummySerializable>(_file).ConfigureAwait(false);

            Assert.AreEqual(dummy.Value, read.Value);
            Assert.AreNotSame(dummy, read);
        }
Exemplo n.º 20
0
    public static KMapLoop SeedLoop(int startIndex)
    {
        // Create a size-1 loop containing the index (which should represent an enabled truth-table bit).
        KMapLoop loop = new KMapLoop();

        foreach (bool bit in BinaryHelper.BinaryValueToBoolean(startIndex, Main.Instance.inputLength))
        {
            loop.Add(new List <bool>()
            {
                bit
            });
        }
        return(loop);
    }
Exemplo n.º 21
0
 public virtual void Save(BinaryHelper helper)
 {
     helper.Write(ID);
     helper.Write(DungeonID);
     helper.Write(DungeonGroupID);
     helper.Write(ConditionList.Length);
     foreach (var info in ConditionList)
     {
         foreach (var innerInfo in info.ParamList)
         {
             helper.Write(innerInfo);
         }
     }
 }
Exemplo n.º 22
0
        public void FileRoundtrip()
        {
            var dummy = new DummySerializable {
                Value = 1
            };

            BinaryHelper.Save(dummy, _file);
            AssertFile.Exists(true, _file);

            var read = BinaryHelper.Read <DummySerializable>(_file);

            Assert.AreEqual(dummy.Value, read.Value);
            Assert.AreNotSame(dummy, read);
        }
Exemplo n.º 23
0
            public void IntTest(int value)
            {
                int length = sizeof(int);

                for (int i = 0; i < 4 * 4; i += length)
                {
                    BinaryHelper.Write(m_buffer, i, value);
                }

                for (int i = 0; i < 4 * length; i += length)
                {
                    Assert.AreEqual(value, BinaryHelper.Read <int>(m_buffer, i));
                }
            }
Exemplo n.º 24
0
        /// <summary>
        /// Tries to write a value to the <see cref="ManagedStream"/>. Returns FALSE if the value couldn't be written.
        /// </summary>
        public bool TryWrite <T>(T value) where T : unmanaged
        {
            int size = sizeof(T);

            if (m_offset + size > Length)
            {
                return(false);
            }

            BinaryHelper.Write(m_buffer, m_offset, value);
            m_offset += size;

            return(true);
        }
Exemplo n.º 25
0
    public void Load(byte[] bytes)
    {
        m_map = new Dictionary <int, ComboSwordSoulInfo>();
        BinaryHelper helper = new BinaryHelper(bytes);

        int sceneCount = helper.ReadInt();

        for (int index = 0; index < sceneCount; ++index)
        {
            ComboSwordSoulInfo info = new ComboSwordSoulInfo();
            info.Load(helper);
            m_map.Add(info.m_comboValue, info);
        }
    }
Exemplo n.º 26
0
        public static SyncKeys DeriveKeys(byte[] kB)
        {
            byte[] info = BinaryHelper.Kw("oldsync");

            HMAC hmac = new HMAC("HMACSHA256");
            HKDF hkdf = new HKDF(hmac, kB);

            byte[] result = hkdf.Expand(info, 2 * 32);

            return(new SyncKeys()
            {
                EncKey = result.Take(32).ToArray(), HmacKey = result.Skip(32).ToArray()
            });
        }
Exemplo n.º 27
0
        public virtual void LoadFromBinaryReader(Stream binaryReader)
        {
            //if (binaryReader.Position == 3091223) Debugger.Break();

            BlockOffSet = binaryReader.Position;
            string typeRead = BinaryHelper.ConvertByteArrayToUTF8String(binaryReader.ReadBytes(4));

            if (BlockType != typeRead)
            {
                throw new InvalidFileFormatException(string.Format("Sequencia de caracteres não esperada. Esperado '{0}' mas veio '{1}'", BlockType, typeRead));
            }

            BlockSize = binaryReader.ReadUint32(true);
        }
Exemplo n.º 28
0
        public void TransferFundsBlockSerializerTests()
        {
            ulong syncBlockHeight = 1;
            uint  nonce           = 4;

            byte[] powHash     = BinaryHelper.GetPowHash(1234);
            ushort version     = 1;
            ulong  blockHeight = 9;

            byte[] body;

            ulong uptodateFunds = 10001;

            byte[] targetHash = BinaryHelper.GetDefaultHash(1235);

            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    bw.Write(uptodateFunds);
                    bw.Write(targetHash);
                }

                body = ms.ToArray();
            }

            byte[] expectedPacket = BinaryHelper.GetSignedPacket(PacketType.Transactional, syncBlockHeight, nonce, powHash, version,
                                                                 BlockTypes.Transaction_TransferFunds, blockHeight, null, body, _privateKey, out byte[] expectedSignature);

            TransferFundsBlock block = new TransferFundsBlock
            {
                SyncBlockHeight    = syncBlockHeight,
                Nonce              = nonce,
                PowHash            = powHash,
                BlockHeight        = blockHeight,
                UptodateFunds      = uptodateFunds,
                TargetOriginalHash = targetHash
            };

            TransferFundsBlockSerializer serializer = new TransferFundsBlockSerializer();

            serializer.Initialize(block);
            serializer.SerializeBody();
            _signingService.Sign(block);

            byte[] actualPacket = serializer.GetBytes();

            Assert.Equal(expectedPacket, actualPacket);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Асинхронное чтение из сокета
        /// </summary>
        /// <returns></returns>
        public async Task <byte[]> ReadAsync(CancellationToken cancellationToken)
        {
            _connectedEvent.WaitOne();             // ожидание подключения

            try
            {
                NetworkStream networkStream = tcpClient.GetStream();

                byte[] buffer = new byte[tcpClient.ReceiveBufferSize];

                int readed = await networkStream.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false);

                Debug.WriteLine("[Client] Recieved bytes: " + readed.ToString());
                Debug.WriteLine("[Client] readed: " + BinaryHelper.ByteToHexBitFiddle(buffer, readed));

                // data readed???
                if (readed == 0)
                {
                    if (_reconnectTries == 3)
                    {
                        throw new Exception("TOO MANY CONNECT TRIES!!!");
                    }
                    _reconnectTries++;

                    // конекшн дроппед - реконнект
                    tcpClient = new TcpClient();
                    await tcpClient.ConnectAsync(addresses, port);

                    buffer = await ReadAsync(cancellationToken);
                }

                return(buffer);
            }
            catch (System.InvalidOperationException ex)
            {
                Debug.WriteLine("[Client] InvalidOperationException: " + ex.ToString());
                //throw new Exception()
                return(new byte[] { });
            }
            catch (SocketException sex)
            {
                Debug.WriteLine("[Client] SocketException: " + sex.ToString());
                throw sex;
            }
            catch (Exception eex)
            {
                throw eex;
            }
        }
Exemplo n.º 30
0
        public override void Persist(Stream str)
        {
            base.Persist(str);

            str.WriteByte(0);
            str.WriteInteger(SpecialTag);
            str.WriteBool(AcceptsFocus);
            str.WriteInteger(SortIndex);
            str.WriteBool(IsCheckable);
            str.WriteBool(DeviceTextScaling);

            // display data
            if (StaticDisplayData != null)
            {
                str.WriteByte(1);
                StaticDisplayData.Persist(str);
            }
            else
            {
                str.WriteByte(0);
            }

            // slot hints
            if ((SlotHints != null) && (SlotHints.Length > 0))
            {
                str.WriteInteger(SlotHints.Length);

                foreach (string slotHint in SlotHints)
                {
                    BinaryHelper.WriteString(str, slotHint);
                }
            }
            else
            {
                str.WriteInteger(0);
            }

            // state data
            str.WriteShort((short)stateData.Count);

            if (stateData.Count > 0)
            {
                foreach (var state in stateData)
                {
                    str.WriteShort((short)state.Key);
                    state.Value.Persist(str);
                }
            }
        }
Exemplo n.º 31
0
        public static int New(string prefix)
        {
            string filename = prefix + "_AI.bin";

            BinaryHelper<packAI> binaryHelper = new BinaryHelper<packAI>();

            if (!binaryHelper.FileExists(filename) )
            {
               binaryHelper.SaveObject(new packAI()
               {
                   Number = 0
               }, filename);
            }
            packAI pack = binaryHelper.LoadObject(filename);

            pack.Number++;
            binaryHelper.SaveObject(pack,filename);
            return pack.Number;

        }