/// <summary>
 /// Read a signed long from the stream (little endian)
 /// </summary>
 /// <returns></returns>
 public long ReadS8le()
 {
     return(BitConverter.ToInt64(ReadBytesNormalisedLittleEndian(8), 0));
 }
    public Windows7(byte[] rawBytes, bool is32Bit, int controlSet)
    {
        Entries = new List <CacheEntry>();

        var index = 4;

        ControlSet = controlSet;

        EntryCount = BitConverter.ToInt32(rawBytes, index);

        index = 128;

        var position = 0;

        if (EntryCount == 0)
        {
            return;;
        }

        if (is32Bit)
        {
            while (index < rawBytes.Length)
            {
                try
                {
                    var ce = new CacheEntry();

                    ce.PathSize = BitConverter.ToUInt16(rawBytes, index);
                    index      += 2;

                    var maxPathSize = BitConverter.ToUInt16(rawBytes, index);
                    index += 2;


                    var pathOffset = BitConverter.ToInt32(rawBytes, index);
                    index += 4;

                    ce.LastModifiedTimeUTC =
                        DateTimeOffset.FromFileTime(BitConverter.ToInt64(rawBytes, index)).ToUniversalTime();

                    if (ce.LastModifiedTimeUTC.Value.Year == 1601)
                    {
                        ce.LastModifiedTimeUTC = null;
                    }
                    index += 8;

                    // skip 4 unknown (insertion flags?)
                    ce.InsertFlags = (AppCompatCache.InsertFlag)BitConverter.ToInt32(rawBytes, index);
                    index         += 4;

                    // skip 4 unknown (shim flags?)
                    index += 4;

                    var ceDataSize = BitConverter.ToUInt32(rawBytes, index);
                    index += 4;

                    var dataOffset = BitConverter.ToUInt32(rawBytes, index);
                    index += 4;

                    ce.Path = Encoding.Unicode.GetString(rawBytes, pathOffset, ce.PathSize).Replace(@"\??\", "");

                    if ((ce.InsertFlags & AppCompatCache.InsertFlag.Executed) == AppCompatCache.InsertFlag.Executed)
                    {
                        ce.Executed = AppCompatCache.Execute.Yes;
                    }
                    else
                    {
                        ce.Executed = AppCompatCache.Execute.No;
                    }

                    ce.CacheEntryPosition = position;
                    ce.ControlSet         = controlSet;
                    Entries.Add(ce);
                    position += 1;

                    if (Entries.Count == EntryCount)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex,
                              "Error parsing cache entry. Position: {Position} Index: {Index}, Error: {Message} ", position, index, ex.Message);

                    if (Entries.Count < EntryCount)
                    {
                        throw;
                    }

                    //TODO Report this
                    Debug.WriteLine(ex.Message);
                    //take what we can get
                    break;
                }
            }
        }
        else
        {
            while (index < rawBytes.Length)
            {
                try
                {
                    var ce1 = new CacheEntry();

                    ce1.PathSize = BitConverter.ToUInt16(rawBytes, index);
                    index       += 2;

                    var maxPathSize = BitConverter.ToUInt16(rawBytes, index);
                    index += 2;

                    // skip 4 unknown (padding)
                    index += 4;

                    var pathOffset = BitConverter.ToInt64(rawBytes, index);
                    index += 8;

                    ce1.LastModifiedTimeUTC =
                        DateTimeOffset.FromFileTime(BitConverter.ToInt64(rawBytes, index)).ToUniversalTime();
                    index += 8;

                    // skip 4 unknown (insertion flags?)
                    ce1.InsertFlags = (AppCompatCache.InsertFlag)BitConverter.ToInt32(rawBytes, index);
                    index          += 4;

                    // skip 4 unknown (shim flags?)
                    index += 4;

                    var ceDataSize = BitConverter.ToUInt64(rawBytes, index);
                    index += 8;

                    var dataOffset = BitConverter.ToUInt64(rawBytes, index);
                    index += 8;

                    ce1.Path = Encoding.Unicode.GetString(rawBytes, (int)pathOffset, ce1.PathSize).Replace(@"\??\", "");

                    if ((ce1.InsertFlags & AppCompatCache.InsertFlag.Executed) == AppCompatCache.InsertFlag.Executed)
                    {
                        ce1.Executed = AppCompatCache.Execute.Yes;
                    }
                    else
                    {
                        ce1.Executed = AppCompatCache.Execute.No;
                    }

                    ce1.CacheEntryPosition = position;
                    ce1.ControlSet         = controlSet;
                    Entries.Add(ce1);
                    position += 1;

                    if (Entries.Count == EntryCount)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex,
                              "Error parsing cache entry. Position: {Position} Index: {Index}, Error: {Message} ", position, index, ex.Message);

                    //TODO Report this
                    if (Entries.Count < EntryCount)
                    {
                        throw;
                    }
                    //take what we can get
                    break;
                }
            }
        }
    }
Пример #3
0
 /// Generates a unique numeric ID. Generated off a GUID and
 /// returned as a 64 bit long value
 /// </summary>
 /// <returns></returns>
 public static long GenerateUniqueNumericId()
 {
     byte[] bytes = Guid.NewGuid().ToByteArray();
     return(BitConverter.ToInt64(bytes, 0));
 }
Пример #4
0
 public long GetInt64()
 {
     return(BitConverter.ToInt64(this.GetBytes(8), 0));
 }
        /// <summary>
        /// Compares two streams fast, will fallback to normal stream comaparison if necessary.
        /// </summary>
        internal static void AssertStreamsAreEqualFast(Stream src, Stream dst)
        {
            Assert.AreEqual(src.Length, dst.Length);

            const int bufferSize = 4 * 1024;
            var       buffer1    = new byte[bufferSize];
            var       buffer2    = new byte[bufferSize];

            long origDstPosition = dst.Position;
            long origSrcPosition = src.Position;
            long bytesRead1      = 0;
            long bytesRead2      = 0;

            while (true)
            {
                int count1 = src.Read(buffer1, 0, bufferSize);
                bytesRead1 += count1;
                int count2 = dst.Read(buffer2, 0, bufferSize);
                bytesRead2 += count2;

                if (count1 != count2 || count1 == 0)
                {
                    break;
                }

                int iterations = (int)Math.Ceiling((double)count1 / sizeof(Int64));
                for (int i = 0; i < iterations; i++)
                {
                    Assert.AreEqual(BitConverter.ToInt64(buffer1, i * sizeof(Int64)), BitConverter.ToInt64(buffer2, i * sizeof(Int64)));
                }
            }

            if (bytesRead1 == bytesRead2)
            {
                if (bytesRead1 != (src.Length - origSrcPosition))
                {
                    AssertStreamsAreEqual(src, dst);
                }
            }
            else
            {
                dst.Position = origDstPosition;
                src.Position = origSrcPosition;
                AssertStreamsAreEqual(src, dst);
            }

            dst.Position = origDstPosition;
            src.Position = origSrcPosition;
        }
        /// <summary>
        /// Configure bytes endian and data type
        /// Endian (first character):
        ///   - ! byte swap (swap pairs of two bytes: based on network order)
        ///   - < little-endian
        ///   - > big-endian
        ///
        /// Dtata type(second character)
        ///   - s string (length third character) only for string
        ///
        ///   - c chart
        ///   - b signed char
        ///
        ///   - h short
        ///   - H unsigend short
        ///   - i int
        ///   - I unsigned int
        ///   - q long long 64 bits
        ///   - Q unsigned long long
        ///
        ///   - f float
        ///   - d double
        ///
        /// Examples:
        ///
        ///   - !>i  : byte swap signed int32 big endian
        ///   - I    : unsigned int32 little indian
        ///   - f    : float (32) little endian
        ///   - !h   : signed int16 byte swap
        ///   - !s10 : byte swap string 10 elements
        ///
        /// </summary>
        /// <param name="format"></param>
        /// <param name="data"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static object Parser(this byte[] data, string format, int index)
        {
            var byteSwap    = format.Contains('!');
            var isBigEndian = format.Contains('>');

            format = format.TrimStart('!', '<', '>');
            var type         = format[0];
            var changeEndian = isBigEndian == BitConverter.IsLittleEndian;

            switch (type)
            {
            case 's':
            {
                var len = int.Parse(format.Split(type)[1]);
                var res = data.SubArray(index, len, byteSwap);
                return(UTF8Encoding.ASCII.GetString(res));
            }

            case 'b':
            {
                return((short)(sbyte)data[index]);
            }

            case 'B':
            {
                return((ushort)(byte)data[index]);
            }

            case 'h':
            {
                var res = data.SubArray(index, 2, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToInt16(res));
            }

            case 'H':
            {
                var res = data.SubArray(index, 2, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToUInt16(res));
            }

            case 'i':
            {
                var res = data.SubArray(index, 4, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToInt32(res));
            }

            case 'I':
            {
                var res = data.SubArray(index, 4, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToUInt32(res));
            }

            case 'q':
            {
                var res = data.SubArray(index, 8, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToInt64(res));
            }

            case 'Q':
            {
                var res = SubArray(data, index, 8, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToUInt64(res));
            }

            case 'f':
            {
                var res = data.SubArray(index, 4, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToSingle(res));
            }

            case 'd':
            {
                var res = data.SubArray(index, 8, byteSwap);
                if (changeEndian)
                {
                    Array.Reverse(res);
                }
                return(BitConverter.ToDouble(res));
            }
            }

            throw new ArgumentException("Bad Format parametter");
        }
Пример #7
0
        internal Midpoint[] CacheMidpointsAndVerifyHash(int depth, bool skipIndexVerify)
        {
            var buffer = new byte[4096];

            if (depth < 0 || depth > 30)
            {
                throw new ArgumentOutOfRangeException("depth");
            }
            var count = Count;

            if (count == 0 || depth == 0)
            {
                return(null);
            }

            if (skipIndexVerify)
            {
                Log.Debug("Disabling Verification of PTable");
            }

            Stream   stream   = null;
            WorkItem workItem = null;

            if (Runtime.IsUnixOrMac)
            {
                workItem = GetWorkItem();
                stream   = workItem.Stream;
            }
            else
            {
                stream = UnbufferedFileStream.Create(_filename, FileMode.Open, FileAccess.Read, FileShare.Read, false,
                                                     4096, 4096, false, 4096);
            }

            try {
                int        midpointsCount;
                Midpoint[] midpoints;
                using (MD5 md5 = MD5.Create()) {
                    try {
                        midpointsCount = (int)Math.Max(2L, Math.Min((long)1 << depth, count));
                        midpoints      = new Midpoint[midpointsCount];
                    } catch (OutOfMemoryException exc) {
                        throw new PossibleToHandleOutOfMemoryException("Failed to allocate memory for Midpoint cache.",
                                                                       exc);
                    }

                    if (skipIndexVerify && (_version >= PTableVersions.IndexV4))
                    {
                        if (_midpointsCached == midpointsCount)
                        {
                            //index verification is disabled and cached midpoints with the same depth requested are available
                            //so, we can load them directly from the PTable file
                            Log.Debug("Loading {midpointsCached} cached midpoints from PTable", _midpointsCached);
                            long startOffset = stream.Length - MD5Size - PTableFooter.GetSize(_version) -
                                               _midpointsCacheSize;
                            stream.Seek(startOffset, SeekOrigin.Begin);
                            for (uint k = 0; k < _midpointsCached; k++)
                            {
                                stream.Read(buffer, 0, _indexEntrySize);
                                IndexEntryKey key;
                                long          index;
                                if (_version == PTableVersions.IndexV4)
                                {
                                    key = new IndexEntryKey(BitConverter.ToUInt64(buffer, 8),
                                                            BitConverter.ToInt64(buffer, 0));
                                    index = BitConverter.ToInt64(buffer, 8 + 8);
                                }
                                else
                                {
                                    throw new InvalidOperationException("Unknown PTable version: " + _version);
                                }

                                midpoints[k] = new Midpoint(key, index);

                                if (k > 0)
                                {
                                    if (midpoints[k].Key.GreaterThan(midpoints[k - 1].Key))
                                    {
                                        throw new CorruptIndexException(String.Format(
                                                                            "Index entry key for midpoint {0} (stream: {1}, version: {2}) < index entry key for midpoint {3} (stream: {4}, version: {5})",
                                                                            k - 1, midpoints[k - 1].Key.Stream, midpoints[k - 1].Key.Version, k,
                                                                            midpoints[k].Key.Stream, midpoints[k].Key.Version));
                                    }
                                    else if (midpoints[k - 1].ItemIndex > midpoints[k].ItemIndex)
                                    {
                                        throw new CorruptIndexException(String.Format(
                                                                            "Item index for midpoint {0} ({1}) > Item index for midpoint {2} ({3})",
                                                                            k - 1, midpoints[k - 1].ItemIndex, k, midpoints[k].ItemIndex));
                                    }
                                }
                            }

                            return(midpoints);
                        }
                        else
                        {
                            Log.Debug(
                                "Skipping loading of cached midpoints from PTable due to count mismatch, cached midpoints: {midpointsCached} / required midpoints: {midpointsCount}",
                                _midpointsCached, midpointsCount);
                        }
                    }

                    if (!skipIndexVerify)
                    {
                        stream.Seek(0, SeekOrigin.Begin);
                        stream.Read(buffer, 0, PTableHeader.Size);
                        md5.TransformBlock(buffer, 0, PTableHeader.Size, null, 0);
                    }

                    long previousNextIndex = long.MinValue;
                    var  previousKey       = new IndexEntryKey(long.MaxValue, long.MaxValue);
                    for (long k = 0; k < midpointsCount; ++k)
                    {
                        long nextIndex = GetMidpointIndex(k, count, midpointsCount);
                        if (previousNextIndex != nextIndex)
                        {
                            if (!skipIndexVerify)
                            {
                                ReadUntilWithMd5(PTableHeader.Size + _indexEntrySize * nextIndex, stream, md5);
                                stream.Read(buffer, 0, _indexKeySize);
                                md5.TransformBlock(buffer, 0, _indexKeySize, null, 0);
                            }
                            else
                            {
                                stream.Seek(PTableHeader.Size + _indexEntrySize * nextIndex, SeekOrigin.Begin);
                                stream.Read(buffer, 0, _indexKeySize);
                            }

                            IndexEntryKey key;
                            if (_version == PTableVersions.IndexV1)
                            {
                                key = new IndexEntryKey(BitConverter.ToUInt32(buffer, 4),
                                                        BitConverter.ToInt32(buffer, 0));
                            }
                            else if (_version == PTableVersions.IndexV2)
                            {
                                key = new IndexEntryKey(BitConverter.ToUInt64(buffer, 4),
                                                        BitConverter.ToInt32(buffer, 0));
                            }
                            else
                            {
                                key = new IndexEntryKey(BitConverter.ToUInt64(buffer, 8),
                                                        BitConverter.ToInt64(buffer, 0));
                            }

                            midpoints[k]      = new Midpoint(key, nextIndex);
                            previousNextIndex = nextIndex;
                            previousKey       = key;
                        }
                        else
                        {
                            midpoints[k] = new Midpoint(previousKey, previousNextIndex);
                        }

                        if (k > 0)
                        {
                            if (midpoints[k].Key.GreaterThan(midpoints[k - 1].Key))
                            {
                                throw new CorruptIndexException(String.Format(
                                                                    "Index entry key for midpoint {0} (stream: {1}, version: {2}) < index entry key for midpoint {3} (stream: {4}, version: {5})",
                                                                    k - 1, midpoints[k - 1].Key.Stream, midpoints[k - 1].Key.Version, k,
                                                                    midpoints[k].Key.Stream, midpoints[k].Key.Version));
                            }
                            else if (midpoints[k - 1].ItemIndex > midpoints[k].ItemIndex)
                            {
                                throw new CorruptIndexException(String.Format(
                                                                    "Item index for midpoint {0} ({1}) > Item index for midpoint {2} ({3})", k - 1,
                                                                    midpoints[k - 1].ItemIndex, k, midpoints[k].ItemIndex));
                            }
                        }
                    }

                    if (!skipIndexVerify)
                    {
                        ReadUntilWithMd5(stream.Length - MD5Size, stream, md5);
                        //verify hash (should be at stream.length - MD5Size)
                        md5.TransformFinalBlock(Empty.ByteArray, 0, 0);
                        var fileHash = new byte[MD5Size];
                        stream.Read(fileHash, 0, MD5Size);
                        ValidateHash(md5.Hash, fileHash);
                    }

                    return(midpoints);
                }
            } catch {
                Dispose();
                throw;
            } finally {
                if (Runtime.IsUnixOrMac)
                {
                    if (workItem != null)
                    {
                        ReturnWorkItem(workItem);
                    }
                }
                else
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Signature scan.
        /// Read data at address which follow matched with the pattern and return it as a pointer.
        /// </summary>
        /// <param name="pattern">byte pattern signature</param>
        /// <param name="offset">offset to read</param>
        /// <param name="bRIP">x64 rip relative addressing mode if true</param>
        /// <returns>the pointer addresses</returns>
        private List <IntPtr> SigScan(string pattern, int offset = 0, bool bRIP = false)
        {
            if (pattern == null || pattern.Length % 2 != 0)
            {
                return(new List <IntPtr>());
            }

            // 1byte = 2char
            byte?[] patternByteArray = new byte?[pattern.Length / 2];

            // Convert Pattern to "Array of Byte"
            for (int i = 0; i < pattern.Length / 2; i++)
            {
                string text = pattern.Substring(i * 2, 2);
                if (text == "??")
                {
                    patternByteArray[i] = null;
                }
                else
                {
                    patternByteArray[i] = new byte?(Convert.ToByte(text, 16));
                }
            }

            int    moduleMemorySize         = _process.MainModule.ModuleMemorySize;
            IntPtr baseAddress              = _process.MainModule.BaseAddress;
            IntPtr intPtr_EndOfModuleMemory = IntPtr.Add(baseAddress, moduleMemorySize);
            IntPtr intPtr_Scannning         = baseAddress;

            int splitSizeOfMemory = 65536;

            byte[] splitMemoryArray = new byte[splitSizeOfMemory];

            List <IntPtr> list = new List <IntPtr>();

            // while loop for scan all memory
            while (intPtr_Scannning.ToInt64() < intPtr_EndOfModuleMemory.ToInt64())
            {
                IntPtr nSize = new IntPtr(splitSizeOfMemory);

                // if remaining memory size is less than splitSize, change nSize to remaining size
                if (IntPtr.Add(intPtr_Scannning, splitSizeOfMemory).ToInt64() > intPtr_EndOfModuleMemory.ToInt64())
                {
                    nSize = (IntPtr)(intPtr_EndOfModuleMemory.ToInt64() - intPtr_Scannning.ToInt64());
                }

                IntPtr intPtr_NumberOfBytesRead = IntPtr.Zero;

                // read memory
                if (NativeMethods.ReadProcessMemory(_process.Handle, intPtr_Scannning, splitMemoryArray, nSize, ref intPtr_NumberOfBytesRead))
                {
                    int num = 0;

                    // slide start point byte bu byte, check with patternByteArray
                    while ((long)num < intPtr_NumberOfBytesRead.ToInt64() - (long)patternByteArray.Length - (long)offset)
                    {
                        int matchCount = 0;
                        for (int j = 0; j < patternByteArray.Length; j++)
                        {
                            // pattern "??" have a null value. in this case, skip the check.
                            if (!patternByteArray[j].HasValue)
                            {
                                matchCount++;
                            }
                            else
                            {
                                if (patternByteArray[j].Value != splitMemoryArray[num + j])
                                {
                                    break;
                                }
                                matchCount++;
                            }
                        }

                        // if all bytes are match, it means "the pattern found"
                        if (matchCount == patternByteArray.Length)
                        {
                            IntPtr item;
                            if (bRIP)
                            {
                                item = new IntPtr(BitConverter.ToInt32(splitMemoryArray, num + patternByteArray.Length + offset));
                                item = new IntPtr(intPtr_Scannning.ToInt64() + (long)num + (long)patternByteArray.Length + 4L + item.ToInt64());
                            }
                            else if (_mode == FFXIVClientMode.FFXIV_64)
                            {
                                item = new IntPtr(BitConverter.ToInt64(splitMemoryArray, num + patternByteArray.Length + offset));
                                item = new IntPtr(item.ToInt64());
                            }
                            else
                            {
                                item = new IntPtr(BitConverter.ToInt32(splitMemoryArray, num + patternByteArray.Length + offset));
                                item = new IntPtr(item.ToInt64());
                            }

                            // add the item if not contains already
                            if (item != IntPtr.Zero && !list.Contains(item))
                            {
                                list.Add(item);
                            }
                        }
                        num++;
                    }
                }
                intPtr_Scannning = IntPtr.Add(intPtr_Scannning, splitSizeOfMemory - patternByteArray.Length - offset);
            }
            return(list);
        }
Пример #9
0
 // Token: 0x0600008D RID: 141 RVA: 0x000050D4 File Offset: 0x000032D4
 private long CVL(int startIndex, int endIndex)
 {
     checked
     {
         endIndex++;
         byte[] array = new byte[8];
         int    num   = endIndex - startIndex;
         bool   flag  = false;
         bool   flag2 = num == 0 | num > 9;
         long   result;
         if (flag2)
         {
             result = 0L;
         }
         else
         {
             flag2 = (num == 1);
             if (flag2)
             {
                 array[0] = (this.db_bytes[startIndex] & 127);
                 result   = BitConverter.ToInt64(array, 0);
             }
             else
             {
                 flag2 = (num == 9);
                 if (flag2)
                 {
                     flag = true;
                 }
                 int num2 = 1;
                 int num3 = 7;
                 int num4 = 0;
                 flag2 = flag;
                 if (flag2)
                 {
                     array[0] = this.db_bytes[endIndex - 1];
                     endIndex--;
                     num4 = 1;
                 }
                 for (int i = endIndex - 1; i >= startIndex; i += -1)
                 {
                     flag2 = (i - 1 >= startIndex);
                     if (flag2)
                     {
                         array[num4] = (byte)(unchecked (((int)((byte)((uint)this.db_bytes[i] >> (checked (num2 - 1) & 7))) & 255 >> num2) | (int)((byte)(this.db_bytes[checked (i - 1)] << (num3 & 7)))));
                         num2++;
                         num4++;
                         num3--;
                     }
                     else
                     {
                         flag2 = !flag;
                         if (flag2)
                         {
                             array[num4] = (byte)((int)(unchecked ((byte)((uint)this.db_bytes[i] >> (checked (num2 - 1) & 7)))) & 255 >> num2);
                         }
                     }
                 }
                 result = BitConverter.ToInt64(array, 0);
             }
         }
         return(result);
     }
 }
Пример #10
0
        /// <summary>
        /// クイックビューを表示
        /// </summary>
        /// <param name="startIndex"></param>
        /// <param name="type"></param>
        private void showQuickView(int startIndex, QuickViewType type)
        {
            var source     = Bytes.Skip(startIndex).ToArray();
            var showString = string.Empty;

            switch (type)
            {
            case QuickViewType.Byte:
                if (source.Length < sizeof(Byte))
                {
                    return;
                }
                hexTextBox.Select(startIndex * 3, sizeof(Byte) * 3);
                showString = string.Format("{0:#,0} (unsigned: {1:#,0})",
                                           (SByte)source[0],
                                           (Byte)source[0]);
                break;

            case QuickViewType.Int16:
                if (source.Length < sizeof(Int16))
                {
                    return;
                }
                hexTextBox.Select(startIndex * 3, sizeof(Int16) * 3);
                showString = string.Format("{0:#,0} (unsigned: {1:#,0})",
                                           BitConverter.ToInt16(source, 0),
                                           BitConverter.ToUInt16(source, 0));
                break;

            case QuickViewType.Int32:
                if (source.Length < sizeof(Int32))
                {
                    return;
                }
                hexTextBox.Select(startIndex * 3, sizeof(Int32) * 3);
                showString = string.Format("{0:#,0} (unsigned: {1:#,0})",
                                           BitConverter.ToInt32(source, 0),
                                           BitConverter.ToUInt32(source, 0));
                break;

            case QuickViewType.Int64:
                if (source.Length < sizeof(Int64))
                {
                    return;
                }
                hexTextBox.Select(startIndex * 3, sizeof(Int64) * 3);
                showString = string.Format("{0:#,0} (unsigned: {1:#,0})",
                                           BitConverter.ToInt64(source, 0),
                                           BitConverter.ToUInt64(source, 0));
                break;

            case QuickViewType.Single:
                if (source.Length < sizeof(Single))
                {
                    return;
                }
                hexTextBox.Select(startIndex * 3, sizeof(Single) * 3);
                showString = string.Format("{0}", BitConverter.ToSingle(source, 0));
                break;
            }

            var point = hexTextBox.PointToClient(Cursor.Position);

            point.Offset(0, 15);
            quickViewToolTip.Show(showString, hexTextBox, point);
        }
Пример #11
0
 private void copyAsInt64ToolStripMenuItem1_Click(object sender, EventArgs e)
 {
     Clipboard.SetText(
         BitConverter.ToInt64(getSelectedBytes(), 0).ToString()
         );
 }
 /// <summary>
 /// 从流中读取一个long数据
 /// </summary>
 /// <returns></returns>
 public long ReadLong()
 {
     byte[] arr = new byte[8];
     base.Read(arr, 0, 8);
     return(BitConverter.ToInt64(arr, 0));
 }
Пример #13
0
 internal miINT64() :
     base(buff => BitConverter.ToInt64(buff, 0), 8)
 {
 }
 /// <summary>
 /// Read a signed long from the stream (big endian)
 /// </summary>
 /// <returns></returns>
 public long ReadS8be()
 {
     return(BitConverter.ToInt64(ReadBytesNormalisedBigEndian(8), 0));
 }
Пример #15
0
        public Организации(byte[] УникальныйИдентификатор, int Глубина)
        {
            if (Глубина > 3)
            {
                return;
            }
            if (new Guid(УникальныйИдентификатор) == Guid.Empty)
            {
                return;
            }
            using (var Подключение = new SqlConnection(СтрокаСоединения))
            {
                Подключение.Open();
                using (var Команда = Подключение.CreateCommand())
                {
                    Команда.CommandText = @"Select top 1 
					_IDRRef [Ссылка]
					,_Version [Версия]
					,_Marked [ПометкаУдаления]
					,_IsMetadata [Предопределенный]
					,_Code [Код]
					,_Description [Наименование]
					,_Fld1550 [Префикс]
					,_Fld1526 [ИНН]
					,_Fld1536 [КПП]
					,_Fld1553 [РегистрационныйНомерПФР]
					,_Fld1524RRef [ГоловнаяОрганизация]
					,_Fld1543 [НаименованиеПолное]
					,_Fld1535 [КодПоОКПО]
					,_Fld1534 [КодПоОКАТО]
					,_Fld1529 [КодИМНС]
					,_Fld1551 [РайонныйКоэффициент]
					,_Fld1562RRef [ЮрФизЛицо]
					,_Fld1561RRef [ТерриториальныеУсловияПФР]
					,_Fld1549RRef [ОсновнойБанковскийСчет]
					,_Fld1523RRef [ВидСтавокЕСНиПФР]
					,_Fld1542 [НаименованиеПлательщикаПриПеречисленииНалогов]
					,_Fld1527 [ИностраннаяОрганизация]
					,_Fld1525 [ДатаРегистрации]
					,_Fld1532 [КодОКОПФ]
					,_Fld1540 [НаименованиеОКОПФ]
					,_Fld1533 [КодОКФС]
					,_Fld1541 [НаименованиеОКФС]
					,_Fld1558 [СвидетельствоСерияНомер]
					,_Fld1555 [СвидетельствоДатаВыдачи]
					,_Fld1557 [СвидетельствоНаименованиеОргана]
					,_Fld1556 [СвидетельствоКодОргана]
					,_Fld1560RRef [СтранаРегистрации]
					,_Fld1559RRef [СтранаПостоянногоМестонахождения]
					,_Fld1528 [КодВСтранеРегистрации]
					,_Fld1548 [ОГРН]
					,_Fld1538 [НаименованиеИнострОрганизации]
					,_Fld1554 [РегистрационныйНомерФСС]
					,_Fld1537 [НаименованиеИМНС]
					,_Fld1530 [КодОКВЭД]
					,_Fld1539 [НаименованиеОКВЭД]
					,_Fld1531 [КодОКОНХ]
					,_Fld1563RRef [ИндивидуальныйПредприниматель]
					,_Fld1544 [УдалитьОбменЗадействован]
					,_Fld1547 [ОбменКодАбонента]
					,_Fld1545 [ОбменКаталогОтправкиДанныхОтчетности]
					,_Fld1546 [ОбменКаталогПрограммыЭлектроннойПочты]
					,_Fld1552 [РайонныйКоэффициентРФ]
					,_Fld1564 [ОтражатьВРегламентированномУчете]
					,_Fld22976 [КодИФНСПолучателя]
					,_Fld22669 [НаименованиеТерриториальногоОрганаПФР]
					,_Fld26550 [НаименованиеСокращенное]
					,_Fld26551RRef [ВидОбменаСКонтролирующимиОрганами]
					,_Fld26552RRef [УчетнаяЗаписьОбмена]
					,_Fld26553 [КодОрганаПФР]
					,_Fld26554 [КодОрганаФСГС]
					,_Fld26555 [ДополнительныйКодФСС]
					,_Fld26556 [КодПодчиненностиФСС]
					,_Fld26557 [ЦифровойИндексОбособленногоПодразделения]
					,_Fld26558 [РегистрационныйНомерТФОМС]
					,_Fld26559 [ИПРегистрационныйНомерПФР]
					,_Fld26560 [ИПРегистрационныйНомерФСС]
					,_Fld26561 [ИПКодПодчиненностиФСС]
					,_Fld26562 [ИПРегистрационныйНомерТФОМС]
					,_Fld26563 [НаименованиеТерриториальногоОрганаФСС]
					From _Reference105(NOLOCK)
					Where _IDRRef=@УникальныйИдентификатор  "                    ;
                    Команда.Parameters.AddWithValue("УникальныйИдентификатор", УникальныйИдентификатор);
                    using (var Читалка = Команда.ExecuteReader())
                    {
                        if (Читалка.Read())
                        {
                            //ToDo: Читать нужно через GetValues()
                            Ссылка = new Guid((byte[])Читалка.GetValue(0));
                            var ПотокВерсии = ((byte[])Читалка.GetValue(1));
                            Array.Reverse(ПотокВерсии);
                            Версия           = BitConverter.ToInt64(ПотокВерсии, 0);
                            ВерсияДанных     = Convert.ToBase64String(ПотокВерсии);
                            ПометкаУдаления  = ((byte[])Читалка.GetValue(2))[0] == 1;
                            Предопределенный = ((byte[])Читалка.GetValue(3))[0] == 1;
                            Код                       = Читалка.GetString(4);
                            Наименование              = Читалка.GetString(5);
                            Префикс                   = Читалка.GetString(6);
                            ИНН                       = Читалка.GetString(7);
                            КПП                       = Читалка.GetString(8);
                            егистрационныйНомерПФР    = Читалка.GetString(9);
                            ГоловнаяОрганизация       = new V82.СправочникиСсылка.Организации((byte[])Читалка.GetValue(10), Глубина + 1);
                            НаименованиеПолное        = Читалка.GetString(11);
                            КодПоОКПО                 = Читалка.GetString(12);
                            КодПоОКАТО                = Читалка.GetString(13);
                            КодИМНС                   = Читалка.GetString(14);
                            айонныйКоэффициент        = Читалка.GetDecimal(15);
                            ЮрФизЛицо                 = V82.Перечисления /*Ссылка*/.ЮрФизЛицо.ПустаяСсылка.Получить((byte[])Читалка.GetValue(16));
                            ТерриториальныеУсловияПФР = new V82.СправочникиСсылка.ТерриториальныеУсловия((byte[])Читалка.GetValue(17), Глубина + 1);
                            ОсновнойБанковскийСчет    = new V82.СправочникиСсылка.БанковскиеСчета((byte[])Читалка.GetValue(18), Глубина + 1);
                            ВидСтавокЕСНиПФР          = V82.Перечисления /*Ссылка*/.ВидыСтавокЕСНиПФР.ПустаяСсылка.Получить((byte[])Читалка.GetValue(19));
                            НаименованиеПлательщикаПриПеречисленииНалогов = Читалка.GetString(20);
                            ИностраннаяОрганизация = ((byte[])Читалка.GetValue(21))[0] == 1;
                            ДатаРегистрации        = Читалка.GetDateTime(22);
                            КодОКОПФ                         = Читалка.GetString(23);
                            НаименованиеОКОПФ                = Читалка.GetString(24);
                            КодОКФС                          = Читалка.GetString(25);
                            НаименованиеОКФС                 = Читалка.GetString(26);
                            СвидетельствоСерияНомер          = Читалка.GetString(27);
                            СвидетельствоДатаВыдачи          = Читалка.GetDateTime(28);
                            СвидетельствоНаименованиеОргана  = Читалка.GetString(29);
                            СвидетельствоКодОргана           = Читалка.GetString(30);
                            СтранаРегистрации                = new V82.СправочникиСсылка.КлассификаторСтранМира((byte[])Читалка.GetValue(31), Глубина + 1);
                            СтранаПостоянногоМестонахождения = new V82.СправочникиСсылка.КлассификаторСтранМира((byte[])Читалка.GetValue(32), Глубина + 1);
                            КодВСтранеРегистрации            = Читалка.GetString(33);
                            ОГРН = Читалка.GetString(34);
                            НаименованиеИнострОрганизации = Читалка.GetString(35);
                            егистрационныйНомерФСС        = Читалка.GetString(36);
                            НаименованиеИМНС                         = Читалка.GetString(37);
                            КодОКВЭД                                 = Читалка.GetString(38);
                            НаименованиеОКВЭД                        = Читалка.GetString(39);
                            КодОКОНХ                                 = Читалка.GetString(40);
                            ИндивидуальныйПредприниматель            = new V82.СправочникиСсылка.ФизическиеЛица((byte[])Читалка.GetValue(41), Глубина + 1);
                            УдалитьОбменЗадействован                 = ((byte[])Читалка.GetValue(42))[0] == 1;
                            ОбменКодАбонента                         = Читалка.GetString(43);
                            ОбменКаталогОтправкиДанныхОтчетности     = Читалка.GetString(44);
                            ОбменКаталогПрограммыЭлектроннойПочты    = Читалка.GetString(45);
                            айонныйКоэффициентРФ                     = Читалка.GetDecimal(46);
                            ОтражатьВРегламентированномУчете         = ((byte[])Читалка.GetValue(47))[0] == 1;
                            КодИФНСПолучателя                        = Читалка.GetString(48);
                            НаименованиеТерриториальногоОрганаПФР    = Читалка.GetString(49);
                            НаименованиеСокращенное                  = Читалка.GetString(50);
                            ВидОбменаСКонтролирующимиОрганами        = V82.Перечисления /*Ссылка*/.ВидыОбменаСКонтролирующимиОрганами.ПустаяСсылка.Получить((byte[])Читалка.GetValue(51));
                            УчетнаяЗаписьОбмена                      = new V82.СправочникиСсылка.УчетныеЗаписиДокументооборота((byte[])Читалка.GetValue(52), Глубина + 1);
                            КодОрганаПФР                             = Читалка.GetString(53);
                            КодОрганаФСГС                            = Читалка.GetString(54);
                            ДополнительныйКодФСС                     = Читалка.GetString(55);
                            КодПодчиненностиФСС                      = Читалка.GetString(56);
                            ЦифровойИндексОбособленногоПодразделения = Читалка.GetDecimal(57);
                            егистрационныйНомерТФОМС                 = Читалка.GetString(58);
                            ИПРегистрационныйНомерПФР                = Читалка.GetString(59);
                            ИПРегистрационныйНомерФСС                = Читалка.GetString(60);
                            ИПКодПодчиненностиФСС                    = Читалка.GetString(61);
                            ИПРегистрационныйНомерТФОМС              = Читалка.GetString(62);
                            НаименованиеТерриториальногоОрганаФСС    = Читалка.GetString(63);
                            //return Ссылка;
                        }
                        else
                        {
                            //return null;
                        }
                    }
                }
            }
        }
Пример #16
0
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                if (m_configuration.m_enableUPnP)
                {
                    m_upnp = new NetUPnP(this);
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                m_handshakes.Clear();

                // bind to socket
                IPEndPoint iep = null;

                iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port);
                EndPoint ep = (EndPoint)iep;

                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize;
                m_socket.SendBufferSize    = m_configuration.SendBufferSize;
                m_socket.Blocking          = false;
                m_socket.Bind(ep);

                IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint;
                LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
                m_listenPort = boundEp.Port;

                m_receiveBuffer            = new byte[m_configuration.ReceiveBufferSize];
                m_sendBuffer               = new byte[m_configuration.SendBufferSize];
                m_readHelperMessage        = new NetIncomingMessage(NetIncomingMessageType.Error);
                m_readHelperMessage.m_data = m_receiveBuffer;

                byte[] macBytes = new byte[8];
                NetRandom.Instance.NextBytes(macBytes);

#if IS_MAC_AVAILABLE
                try
                {
                    System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress();
                    if (pa != null)
                    {
                        macBytes = pa.GetAddressBytes();
                        LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes));
                    }
                    else
                    {
                        LogWarning("Failed to get Mac address");
                    }
                }
                catch (NotSupportedException)
                {
                    // not supported; lets just keep the random bytes set above
                }
#endif
                byte[] epBytes  = BitConverter.GetBytes(boundEp.GetHashCode());
                byte[] combined = new byte[epBytes.Length + macBytes.Length];
                Array.Copy(epBytes, 0, combined, 0, epBytes.Length);
                Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length);
                m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0);

                m_status = NetPeerStatus.Running;
            }
        }
Пример #17
0
        public static IEnumerable <PingerHost> PingAll(string subNets, int timeOut = 1500)
        {
            ushort packetID = (ushort)new Random().Next(0, ushort.MaxValue);

            //Init
            using Socket rawSock = new(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);

            rawSock.Bind(new IPEndPoint(IPAddress.Any, 0));

            rawSock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, 255);
            rawSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, int.MaxValue);
            rawSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, int.MaxValue);
            rawSock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);

            HashSet <PingerHost> aliveIPs = new();

            //** Receiver **
            Task receiver = Task.Factory.StartNew(() => {
                byte[] received        = new byte[64];
                EndPoint remoteAddress = new IPEndPoint(IPAddress.Any, 0);

                while (true)
                {
                    try {
                        rawSock.ReceiveFrom(received, ref remoteAddress);
                    }
                    catch { return; }

                    ushort replyId = BitConverter.ToUInt16(received, IP_HEADER_LEN + OFFSET_ID);
                    if (received[IP_HEADER_LEN] == ICMP_ECHO_REPLY && replyId == packetID)
                    {
                        long ticksInPong = BitConverter.ToInt64(received, IP_HEADER_LEN + ICMP_HEADER_LEN);
                        int duration     = (int)((DateTime.Now.Ticks - ticksInPong) / TimeSpan.TicksPerMillisecond);
                        PingerHost host  = new(((IPEndPoint)remoteAddress).Address.ToString(), duration);

                        lock (aliveIPs) {
                            aliveIPs.Add(host);
                        }
                    }
                }
            }, TaskCreationOptions.LongRunning);

            Task.Yield();             //Give a chance to listener task to start.

            //** Sender **
            foreach (string ip in GetIPAddresses(subNets))
            {
                byte[]     packet = CreatePacket(packetID, BitConverter.GetBytes(DateTime.Now.Ticks));
                IPEndPoint dest   = new IPEndPoint(IPAddress.Parse(ip), 0);
                try {
                    rawSock.SendTo(packet, dest);
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine($"==>{ip}");
                }
            }

            Task.WaitAny(receiver, Task.Delay(timeOut));
            return(aliveIPs);
        }
Пример #18
0
 private static long Hash(long x, HashAlgorithm hashAlg)
 {
     return(BitConverter.ToInt64(hashAlg.ComputeHash(BitConverter.GetBytes(x), 0, 8), 0));
 }
Пример #19
0
        private static void ReadCentralDirectoryFooter(ZipFile zf)
        {
            Stream s = zf.ReadStream;
            int signature = Frame.Utils.Ionic.Zip.SharedUtilities.ReadSignature(s);

            byte[] block = null;
            int j = 0;
            if (signature == ZipConstants.Zip64EndOfCentralDirectoryRecordSignature)
            {
                // We have a ZIP64 EOCD
                // This data block is 4 bytes sig, 8 bytes size, 44 bytes fixed data,
                // followed by a variable-sized extension block.  We have read the sig already.
                // 8 - datasize (64 bits)
                // 2 - version made by
                // 2 - version needed to extract
                // 4 - number of this disk
                // 4 - number of the disk with the start of the CD
                // 8 - total number of entries in the CD on this disk
                // 8 - total number of entries in the CD
                // 8 - size of the CD
                // 8 - offset of the CD
                // -----------------------
                // 52 bytes

                block = new byte[8 + 44];
                s.Read(block, 0, block.Length);

                Int64 DataSize = BitConverter.ToInt64(block, 0);  // == 44 + the variable length

                if (DataSize < 44)
                    throw new ZipException("Bad size in the ZIP64 Central Directory.");

                zf._versionMadeBy = BitConverter.ToUInt16(block, j);
                j += 2;
                zf._versionNeededToExtract = BitConverter.ToUInt16(block, j);
                j += 2;
                zf._diskNumberWithCd = BitConverter.ToUInt32(block, j);
                j += 2;

                //zf._diskNumberWithCd++; // hack!!

                // read the extended block
                block = new byte[DataSize - 44];
                s.Read(block, 0, block.Length);
                // discard the result

                signature = Frame.Utils.Ionic.Zip.SharedUtilities.ReadSignature(s);
                if (signature != ZipConstants.Zip64EndOfCentralDirectoryLocatorSignature)
                    throw new ZipException("Inconsistent metadata in the ZIP64 Central Directory.");

                block = new byte[16];
                s.Read(block, 0, block.Length);
                // discard the result

                signature = Frame.Utils.Ionic.Zip.SharedUtilities.ReadSignature(s);
            }

            // Throw if this is not a signature for "end of central directory record"
            // This is a sanity check.
            if (signature != ZipConstants.EndOfCentralDirectorySignature)
            {
                s.Seek(-4, SeekOrigin.Current);
                throw new BadReadException(String.Format("Bad signature ({0:X8}) at position 0x{1:X8}",
                                                         signature, s.Position));
            }

            // read the End-of-Central-Directory-Record
            block = new byte[16];
            zf.ReadStream.Read(block, 0, block.Length);

            // off sz  data
            // -------------------------------------------------------
            //  0   4  end of central dir signature (0x06054b50)
            //  4   2  number of this disk
            //  6   2  number of the disk with start of the central directory
            //  8   2  total number of entries in the  central directory on this disk
            // 10   2  total number of entries in  the central directory
            // 12   4  size of the central directory
            // 16   4  offset of start of central directory with respect to the starting disk number
            // 20   2  ZIP file comment length
            // 22  ??  ZIP file comment

            if (zf._diskNumberWithCd == 0)
            {
                zf._diskNumberWithCd = BitConverter.ToUInt16(block, 2);
                //zf._diskNumberWithCd++; // hack!!
            }

            // read the comment here
            ReadZipFileComment(zf);
        }
Пример #20
0
 /**
  * 读取一个long数据
  */
 public long ReadLong(bool isLittleEndian = false)
 {
     return(BitConverter.ToInt64(Read(8, isLittleEndian), 0));
 }
        public static InterfaceDescriptionOption Parse(BinaryReader binaryReader, bool reverseByteOrder, Action <Exception> ActionOnException)
        {
            //Contract.Requires<ArgumentNullException>(binaryReader != null, "binaryReader cannot be null");
            InterfaceDescriptionOption            option      = new InterfaceDescriptionOption();
            List <KeyValuePair <ushort, byte[]> > optionsList = EkstractOptions(binaryReader, reverseByteOrder, ActionOnException);

            if (optionsList.Any())
            {
                foreach (var item in optionsList)
                {
                    try
                    {
                        switch (item.Key)
                        {
                        case (ushort)InterfaceDescriptionOptionCode.CommentCode:
                            option.Comment = UTF8Encoding.UTF8.GetString(item.Value);
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.NameCode:
                            option.Name = UTF8Encoding.UTF8.GetString(item.Value);
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.DescriptionCode:
                            option.Description = UTF8Encoding.UTF8.GetString(item.Value);
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.IPv4AddressCode:
                            if (item.Value.Length == 8)
                            {
                                option.IPv4Address = new IPAddress_v4(item.Value);
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] IPv4AddressCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 8));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.IPv6AddressCode:
                            if (item.Value.Length == 17)
                            {
                                option.IPv6Address = new IPAddress_v6(item.Value);
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] IPv6AddressCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 17));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.MacAddressCode:
                            if (item.Value.Length == 6)
                            {
                                option.MacAddress = new PhysicalAddress(item.Value);
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] MacAddressCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 6));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.EuiAddressCode:
                            if (item.Value.Length == 8)
                            {
                                option.EuiAddress = item.Value;
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] EuiAddressCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 8));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.SpeedCode:
                            if (item.Value.Length == 8)
                            {
                                option.Speed = (BitConverter.ToInt64(item.Value, 0)).ReverseByteOrder(reverseByteOrder);
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] SpeedCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 8));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.TimestampResolutionCode:
                            if (item.Value.Length == 1)
                            {
                                option.TimestampResolution = item.Value[0];
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] TimestampResolutionCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 1));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.TimeZoneCode:
                            if (item.Value.Length == 4)
                            {
                                option.TimeZone = (BitConverter.ToInt32(item.Value, 0)).ReverseByteOrder(reverseByteOrder);     // GMT offset
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] TimeZoneCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 4));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.FilterCode:
                            option.Filter = item.Value;
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.OperatingSystemCode:
                            option.OperatingSystem = UTF8Encoding.UTF8.GetString(item.Value);
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.FrameCheckSequenceCode:
                            if (item.Value.Length == 1)
                            {
                                option.FrameCheckSequence = item.Value[0];
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] FrameCheckSequenceCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 1));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.TimeOffsetSecondsCode:
                            if (item.Value.Length == 8)
                            {
                                option.TimeOffsetSeconds = (BitConverter.ToInt64(item.Value, 0)).ReverseByteOrder(reverseByteOrder);
                            }
                            else
                            {
                                throw new ArgumentException(string.Format("[InterfaceDescriptio.Parse] TimeOffsetSecondsCode contains invalid length. Received: {0} bytes, expected: {1}", item.Value.Length, 8));
                            }
                            break;

                        case (ushort)InterfaceDescriptionOptionCode.EndOfOptionsCode:
                        default:
                            break;
                        }
                    }
                    catch (Exception exc)
                    {
                        if (ActionOnException != null)
                        {
                            ActionOnException(exc);
                        }
                    }
                }
            }
            return(option);
        }
Пример #22
0
        /// <summary>
        /// 一些基元类型解压缩
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="byte"></param>
        /// <param name="flag"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected bool TryDecompressTargetTypeFlag <T>(byte[] @byte, byte flag, TargetTypeFlag enumFlag, out T value)
        {
            value = default(T);

            try
            {
                switch (enumFlag)
                {
                case TargetTypeFlag.@char:
                {
                    value = (T)(dynamic)BitConverter.ToChar(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@bool:
                {
                    value = (T)(dynamic)BitConverter.ToBoolean(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@byte:
                {
                    value = (T)(dynamic)((byte)BitConverter.ToInt16(@byte, 0));
                    return(true);
                }

                case TargetTypeFlag.@short:
                {
                    value = (T)(dynamic)BitConverter.ToInt16(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@ushort:
                {
                    value = (T)(dynamic)BitConverter.ToUInt16(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@int:
                {
                    value = (T)(dynamic)BitConverter.ToInt32(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@uint:
                {
                    value = (T)(dynamic)BitConverter.ToUInt32(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@long:
                {
                    value = (T)(dynamic)BitConverter.ToInt64(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@ulong:
                {
                    value = (T)(dynamic)BitConverter.ToUInt64(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@float:
                {
                    value = (T)(dynamic)BitConverter.ToSingle(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@double:
                {
                    value = (T)(dynamic)BitConverter.ToDouble(@byte, 0);
                    return(true);
                }

                case TargetTypeFlag.@decimal:
                {
                    value = (T)(dynamic)((decimal)BitConverter.ToDouble(@byte, 0));
                    return(true);
                }

                case TargetTypeFlag.@timespan:
                {
                    value = (T)(dynamic)TimeSpan.FromMilliseconds(BitConverter.ToDouble(@byte, 0));
                    return(true);
                }

                case TargetTypeFlag.@datetime:
                {
                    value = (T)(dynamic) new DateTime(BitConverter.ToInt64(@byte, 0));
                    return(true);
                }
                }
            }
            catch
            {
            }

            return(false);
        }
Пример #23
0
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="type"></param>
        /// <param name="datas"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        private static object Deserialize(Type type, byte[] datas, ref int offset)
        {
            dynamic obj = null;

            var len = 0;

            byte[] data = null;

            len     = BitConverter.ToInt32(datas, offset);
            offset += 4;
            if (len > 0)
            {
                data = new byte[len];
                Buffer.BlockCopy(datas, offset, data, 0, len);
                offset += len;

                if (type == stringType)
                {
                    obj = Encoding.UTF8.GetString(data);
                }
                else if (type == typeof(byte))
                {
                    obj = (data);
                }
                else if (type == typeof(bool))
                {
                    obj = (BitConverter.ToBoolean(data, 0));
                }
                else if (type == typeof(short))
                {
                    obj = (BitConverter.ToInt16(data, 0));
                }
                else if (type == typeof(int))
                {
                    obj = (BitConverter.ToInt32(data, 0));
                }
                else if (type == typeof(long))
                {
                    obj = (BitConverter.ToInt64(data, 0));
                }
                else if (type == typeof(float))
                {
                    obj = (BitConverter.ToSingle(data, 0));
                }
                else if (type == typeof(double))
                {
                    obj = (BitConverter.ToDouble(data, 0));
                }
                else if (type == typeof(decimal))
                {
                    obj = (BitConverter.ToDouble(data, 0));
                }
                else if (type == typeof(DateTime))
                {
                    var dstr  = Encoding.UTF8.GetString(data);
                    var ticks = long.Parse(StringHelper.Substring(dstr, 2));
                    obj = (new DateTime(ticks));
                }
                else if (type.BaseType == typeof(Enum))
                {
                    var numType = Enum.GetUnderlyingType(type);

                    if (numType == typeof(byte))
                    {
                        obj = Enum.ToObject(type, data[0]);
                    }
                    else if (numType == typeof(short))
                    {
                        obj = Enum.ToObject(type, BitConverter.ToInt16(data, 0));
                    }
                    else if (numType == typeof(int))
                    {
                        obj = Enum.ToObject(type, BitConverter.ToInt32(data, 0));
                    }
                    else
                    {
                        obj = Enum.ToObject(type, BitConverter.ToInt64(data, 0));
                    }
                }
                else if (type == typeof(byte[]))
                {
                    obj = (byte[])data;
                }
                else if (type.IsGenericType)
                {
                    if (TypeHelper.ListTypeStrs.Contains(type.Name))
                    {
                        obj = DeserializeList(type, data);
                    }
                    else if (TypeHelper.DicTypeStrs.Contains(type.Name))
                    {
                        obj = DeserializeDic(type, data);
                    }
                    else
                    {
                        obj = DeserializeClass(type, data);
                    }
                }
                else if (type.IsClass)
                {
                    obj = DeserializeClass(type, data);
                }
                else if (type.IsArray)
                {
                    obj = DeserializeArray(type, data);
                }
                else
                {
                    throw new Exception("ParamsSerializeUtil.Deserialize 未定义的类型:" + type.ToString());
                }
            }
            return(obj);
        }
 public void Read(out long value)
 {
     Align(sizeof(long));
     value   = BitConverter.ToInt64(data, offset);
     offset += sizeof(long);
 }
Пример #25
0
        public static int WriteToFile(DateTime date)//每天凌晨写入昨天的数据到文件,可以考虑用服务或计划任务;数据库只保留当天的记录;调度程序负责删除过期记录;历史数据应支持合并
        {
            int    year = date.Year; int month = date.Month; int day = date.Day;
            string path = string.Concat(m_Path, "\\", year.ToString(), "-", month.ToString(), ".bin");

            if (CreateFile(year, month))//如该月文件不存在,则创建;否则写入
            {
                using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    stream.Seek(day * 8, SeekOrigin.Begin); //先读入索引区,定位到该日期的指针
                    byte[] bits = new byte[8];
                    stream.Read(bits, 0, 8);                //如果该位置指针为>0的正数,说明该区域已有数据
                    if (BitConverter.ToInt64(bits, 0) > 0)
                    {
                        return(-1);
                    }
                }
                using (var dataReader = DataHelper.Instance.ExecuteProcedureReader("WRITEHDATA", DataHelper.CreateParam("@DATE", SqlDbType.DateTime, date)))
                {
                    if (dataReader == null)
                    {
                        return(-10);
                    }
                    else
                    {
                        dataReader.Read();
                        int cont = dataReader.GetInt32(0);//读入标签数量
                        if (cont == 0)
                        {
                            return(-2);
                        }
                        string path2 = path + ".temp";
                        try
                        {
                            File.Copy(path, path2, true);//先把原文件全部复制到临时文件
                            //Stopwatch sw = Stopwatch.StartNew();
                            using (FileStream stream = File.Open(path2, FileMode.Open))
                            {
                                //w.Seek(8 + day * 8, SeekOrigin.Begin);
                                //w.Seek(0x100, SeekOrigin.Begin);
                                long start = stream.Seek(0, SeekOrigin.End);//定位到文件末尾
                                long end   = 0;
                                using (BinaryWriter w = new BinaryWriter(stream))
                                {
                                    w.Write(new SqlDateTime(date).DayTicks); //写入日期
                                    w.Write(cont);                           ///写入标签数量
                                    int count = dataReader.GetInt32(1);
                                    w.Write(count);
                                    HDataFormat[] list = new HDataFormat[count];
                                    if (dataReader.NextResult())
                                    {
                                        int p = 0;
                                        int x = 0;
                                        while (dataReader.Read())                //写入标签元数据
                                        {
                                            short id   = dataReader.GetInt16(0); //ID号
                                            byte  type = dataReader.GetByte(1);  //数据类型
                                            int   cn   = dataReader.GetInt32(2); //标签个数
                                            //list[x].ID = id;
                                            list[x].Type  = (DataType)type;
                                            list[x].Count = cn;
                                            //list[x].Offset = p;
                                            w.Write(id);
                                            w.Write(type);
                                            w.Write(cn);
                                            w.Write(p);
                                            p += cn * dataLen[type];
                                            x++;
                                        }
                                        if (dataReader.NextResult())
                                        {
                                            for (int i = 0; i < list.Length; i++)
                                            {
                                                int len = list[i].Count;
                                                for (int j = 0; j < len; j++)
                                                {
                                                    if (dataReader.Read())
                                                    {
                                                        w.Write(dataReader.GetTimeTick(0));
                                                        switch (list[i].Type)
                                                        {
                                                        case DataType.BOOL:
                                                            w.Write(dataReader.GetFloat(1) > 0);
                                                            break;

                                                        case DataType.BYTE:
                                                            w.Write((byte)dataReader.GetFloat(1));
                                                            break;

                                                        case DataType.WORD:
                                                        case DataType.SHORT:
                                                            w.Write((short)dataReader.GetFloat(1));
                                                            break;

                                                        case DataType.INT:
                                                            w.Write((int)dataReader.GetFloat(1));
                                                            break;

                                                        case DataType.FLOAT:
                                                            w.Write(dataReader.GetFloat(1));
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    end = stream.Position;                   //文件的结尾,总长度
                                    w.Seek((day - 1) * 8, SeekOrigin.Begin); //定位到索引区
                                    w.Write(start);                          //写入当日指针
                                    w.Write(end);                            //写入下一日指针
                                    //w.Close();
                                }
                            }
                            File.Copy(path2, path, true);
                        }
                        catch (Exception err)
                        {
                            DataHelper.AddErrorLog(err);
                            return(-3);
                        }
                        finally
                        {
                            if (File.Exists(path2))
                            {
                                File.Delete(path2);
                            }
                        }
                        //dataReader.Close();
                        return(0);

                        /*写入失败,则将备份文件还原;数据库不做删除动作,保留记录,次日服务检查数据文件是否存在,不存在则合并写入
                         * 可在服务内建XML文件保存失败记录的日期列表,以便还原;用File.Mov;定时间隔、开始时间也可XML定义。
                         * 先备份二进制归档库,再加载数据库数据,写入文件;如成功,删除数据库当日记录并删除备份文件
                         * sw.Stop();
                         * if (sw.ElapsedTicks > 0) { }
                         */
                    }
                }
            }
            return(-10);
        }
Пример #26
0
 public bool FromBytes(byte[] bodyData)
 {
     Result           = BitConverter.ToInt16(bodyData, 0);
     RoomUserUniqueId = BitConverter.ToInt64(bodyData, 2);
     return(true);
 }
Пример #27
0
 /// <summary>
 ///   Read a long from the Buffer
 /// </summary>
 /// <returns></returns>
 public Int64 ReadLong()
 {
     return(BitConverter.ToInt64(ReadBigEndianBytes(8), 0));
 }
Пример #28
0
 public bool FromBytes(byte[] bodyData)
 {
     UserUniqueId = BitConverter.ToInt64(bodyData, 0);
     return(true);
 }
Пример #29
0
        /// <summary>
        ///     Converts some binary data into the form used in the CLR.
        /// </summary>
        /// <param name="type">The type of data to convert from.</param>
        /// <param name="data">The data to convert.</param>
        /// <param name="parsedData">The parsed CLR object.</param>
        /// <returns>Indication if the parsed data could be parsed correctly as the specified type. If false, data is always a byte[].</returns>
        public static bool TryConvertValueDataToObject(RegValueType type, byte[] data, out object parsedData)
        {
            parsedData = data;

            switch (type)
            {
            case RegValueType.REG_NONE:
                // NONE format shouldn't be specified, ever.
                return(false);

            case RegValueType.REG_LINK:      // This is a unicode string
            case RegValueType.REG_EXPAND_SZ: // This is a unicode string
            case RegValueType.REG_SZ:
                if (data.Length % 2 != 0)
                {
                    // UTF-16 strings are always an even number of bytes
                    return(false);
                }

                // Remove all the trailing nulls
                int toIndex = 0;
                while (data.Length > toIndex + 2 && (data[toIndex] != 0 || data[toIndex + 1] != 0))
                {
                    toIndex += 2;
                }

                parsedData = StringEncoding.GetString(data, 0, toIndex);
                return(true);

            case RegValueType.REG_BINARY:
                return(true);

            case RegValueType.REG_DWORD:
                if (data.Length != 4)
                {
                    return(false);
                }

                parsedData = BitConverter.ToInt32(data, 0);
                return(true);

            case RegValueType.REG_DWORD_BIG_ENDIAN:
                if (data.Length != 4)
                {
                    return(false);
                }

                Array.Reverse(data);
                parsedData = BitConverter.ToInt32(data, 0);
                return(true);

            case RegValueType.REG_MULTI_SZ:
                // Get string without the ending null
                if (data.Length % 2 != 0)
                {
                    // Invalid string data, must always be even in length
                    return(false);
                }

                if (data.Length == 0)
                {
                    // A badly formatted list
                    return(false);
                }

                if (data.Length == 2 && data[0] == 0 && data[1] == 0)
                {
                    // An empty list is identified by: \0
                    parsedData = new string[0];
                    return(true);
                }

                if (data[data.Length - 4] != 0 || data[data.Length - 3] != 0 || data[data.Length - 2] != 0 ||
                    data[data.Length - 1] != 0)
                {
                    // Must always end with four nulls
                    return(false);
                }

                string s2 = StringEncoding.GetString(data, 0, data.Length - 4);
                parsedData = s2.Split(new[] { '\0' });
                return(true);

            case RegValueType.REG_RESOURCE_LIST:
                return(true);

            case RegValueType.REG_FULL_RESOURCE_DESCRIPTOR:
                return(true);

            case RegValueType.REG_RESOURCE_REQUIREMENTS_LIST:
                return(true);

            case RegValueType.REG_QWORD:
                if (data.Length != 8)
                {
                    return(false);
                }

                parsedData = BitConverter.ToInt64(data, 0);
                return(true);

            default:
                throw new ArgumentOutOfRangeException("TryConvertValueDataToObject was given an invalid RegValueType: " + type);
            }
        }
Пример #30
0
 /// <summary>
 /// 生成Guid
 /// </summary>
 /// <returns></returns>
 public static long GenerateId()
 {
     byte[] buffer = Guid.NewGuid().ToByteArray();
     return(BitConverter.ToInt64(buffer, 0));
 }