Ejemplo n.º 1
0
 //string strss = "";
 void StartHandleData(string[] msg)
 {
     if (msg[0] == null)
     {
         return;
     }
     if (msg.Length == 6 || msg.Length == 7)
     {
         if (zoomId != "" && zoomId != "0")
         {
             NormalData(msg);
         }
     }
     else if (msg.Length == 8)
     {
         if (msg[0] == "FF" && msg[1] == "0C" && msg[2] == "02")
         {
             string zid = Hexadecimal.ConvertBase(msg[3], 16, 10);
             if (zid != "0" && !string.IsNullOrWhiteSpace(zid))
             {
                 if (int.Parse(oldId) < zCount * dNo && int.Parse(oldId) >= int.Parse(zid))
                 {
                     ExceptionData();
                 }
             }
             zoomId = Hexadecimal.ConvertBase(msg[3], 16, 10);
         }
     }
 }
Ejemplo n.º 2
0
        public void Write_UInt64_Throws_When_Buffer_Is_Too_Small()
        {
            var chars = new char[1];
            var ex    = Assert.Throws <ArgumentException>(() => Hexadecimal.Write(0UL, chars));

            Assert.Equal("output", ex.ParamName);
        }
Ejemplo n.º 3
0
        private static ArrayLease <char> TranslateBytesToHex(ArraySegment <byte> bytes, out int charCount)
        {
            byte[] buffer = bytes.Array;
            int    offset = bytes.Offset;

            charCount = bytes.Count * 2;
            var lease = ArrayPool <char> .Shared.Lease(charCount);

            try
            {
                var chars = lease.Array;

                int  j = 0;
                char left, right;

                for (int i = 0; i < bytes.Count; i++)
                {
                    byte b = buffer[offset + i];
                    Hexadecimal.FromByte(b, out left, out right);
                    chars[j]     = left;
                    chars[j + 1] = right;
                    j           += 2;
                }

                Debug.Assert(j == charCount);
            }
            catch
            {
                lease.Dispose();
                throw;
            }

            return(lease);
        }
Ejemplo n.º 4
0
        public void Write_Throws_When_Buffer_Is_Too_Small(int byteCount, int charCount, char?separator)
        {
            var chars = new char[charCount];
            var ex    = Assert.Throws <ArgumentException>(() => Hexadecimal.Write(new byte[byteCount], chars, separator));

            Assert.Equal("output", ex.ParamName);
        }
Ejemplo n.º 5
0
        public void Write_UInt64(ulong input, LetterCase letterCase, string expected)
        {
            var chars = new char[16];

            Hexadecimal.Write(input, chars, letterCase);
            Assert.Equal(expected, new string(chars));
        }
Ejemplo n.º 6
0
        public static void DecodeAndValidateUserInputTest(string seed, string pgpSeed)
        {
            var decodedSeed    = WalletSeed.DecodeAndValidateUserInput(pgpSeed, PgpWordList);
            var decodedSeedHex = Hexadecimal.Decode(seed);

            Assert.Equal(decodedSeedHex, decodedSeed);
        }
Ejemplo n.º 7
0
        public void Write_Byte(byte input, LetterCase letterCase, string expected)
        {
            var chars = new char[2];

            Hexadecimal.Write(input, chars, letterCase);
            Assert.Equal(expected, new string(chars));
        }
        private async Task ManageStakePoolsActionAsync()
        {
            var prevConfiguredStakepoolCount = ConfiguredStakePools.Count;

            // Open dialog that downloads stakepool listing and lets user enter their api key.
            var shell  = (ShellViewModel)ViewModelLocator.ShellViewModel;
            var dialog = new ManageStakePoolsDialogViewModel(shell);

            shell.ShowDialog(dialog);
            await dialog.NotifyCompletionSource.Task; // Wait until dialog is hidden

            await App.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var configuredPool in dialog.ConfiguredPools)
                {
                    var poolInfo       = configuredPool.Item1;
                    var poolUserConfig = configuredPool.Item2;

                    if (!ConfiguredStakePools.OfType <StakePoolSelection>().Where(p => p.PoolInfo.Uri.Host == poolInfo.Uri.Host).Any())
                    {
                        var stakePoolSelection = new StakePoolSelection(poolInfo, poolUserConfig.ApiKey,
                                                                        Hexadecimal.Decode(poolUserConfig.MultisigVoteScript));
                        ConfiguredStakePools.Add(stakePoolSelection);
                        RaisePropertyChanged(nameof(VotePreferencesVisibility));
                        SelectedStakePool = stakePoolSelection;
                    }
                }
            });

            if (prevConfiguredStakepoolCount != ConfiguredStakePools.Count)
            {
                await UpdateStakepoolVotePreferences();
            }
        }
Ejemplo n.º 9
0
        private async Task<byte[]> GetData()
        {

            switch (DecodeContentType)
            {
                case DecodeContentTypeEnum.Hexa:
                    Hexadecimal = Compact(Hexadecimal).Replace("-", "").Trim();

                    int len = Hexadecimal.Length / 2;

                    var tmp = new byte[len];
                    for (int i = 0; i < len; i++)
                    {
                        tmp[i] = Convert.ToByte(Hexadecimal.Substring(i * 2, 2), 16);
                    }
                    return tmp;
                case DecodeContentTypeEnum.Base64:
                    return Convert.FromBase64String(Compact(Base64));
                case DecodeContentTypeEnum.File:
                    var ms = new System.IO.MemoryStream();
                    await File.Data.CopyToAsync(ms);
                    return ms.ToArray();

                default:
                    throw new ArgumentOutOfRangeException($"Decode content type not implemented {DecodeContentType}");

            }
        }
Ejemplo n.º 10
0
        public static Numeric_Base Decode(char choise)
        {
            Numeric_Base numeric_Base;

            switch (choise)
            {
            case 'b': numeric_Base = new Binary();
                break;

            case 'o':
                numeric_Base = new Octal();
                break;

            case 'd':
                numeric_Base = new Decimal();
                break;

            case 'x':
                numeric_Base = new Hexadecimal();
                break;

            default:
                numeric_Base = null;
                break;
            }
            return(numeric_Base);
        }
Ejemplo n.º 11
0
 private void UpdateColor(string answerValue)
 {
     if (answerValue != string.Empty)
     {
         _colorDialog.Color = Hexadecimal.FromString(answerValue).ToColor();
     }
 }
        private static string FormatHexadecimal(ReadOnlyMemory <byte> bytes)
        {
            var charLength = bytes.Length * 2;
            var chars      = charLength <= 64 ? stackalloc char[charLength] : new char[charLength];

            Hexadecimal.Write(bytes.Span, chars);
            return(new string(chars));
        }
Ejemplo n.º 13
0
        private void SendHex(TextBox textBox)
        {
            var bytes = Hexadecimal.Parse(textBox.Text);

            textBox.Text = Hexadecimal.ToString(bytes);
            buffer.Output(bytes, false);
            ior.Run(() => iom.Write(bytes));
        }
Ejemplo n.º 14
0
        public void TryParse_With_Valid_Input(string input, char?separator, byte[] expected)
        {
            var actual    = new byte[expected.Length];
            var succeeded = Hexadecimal.TryParse(input, actual, separator);

            Assert.True(succeeded);
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 15
0
        public static void ValidDecodings(string hexEncoding, string pgpWordListEncoding)
        {
            var words         = pgpWordListEncoding.Split();
            var expectedBytes = Hexadecimal.Decode(hexEncoding);

            var decodedBytes = PgpWordList.Decode(words);

            Assert.Equal(expectedBytes, decodedBytes);
        }
Ejemplo n.º 16
0
        public void Write(byte[] input, LetterCase @case, char?separator, string expected)
        {
            var chars = new char[expected.Length];

            Hexadecimal.Write(input, chars, separator, @case);
            var actual = new string(chars);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 17
0
        public void ToHexChars_Regularly_ShouldReturnExpectedOutput(string text, string hexString)
        {
            var         bytes       = System.Text.Encoding.UTF8.GetBytes(text);
            Span <byte> outputChars = stackalloc byte[hexString.Length];

            Hexadecimal.ToHexChars(bytes, outputChars);
            var outputString = System.Text.Encoding.UTF8.GetString(outputChars);

            Assert.Equal(hexString, outputString);
        }
Ejemplo n.º 18
0
        public void FromHexChars_Regularly_ShouldReturnExpectedOutput(string text, string hexString)
        {
            var         chars       = System.Text.Encoding.UTF8.GetBytes(hexString);
            Span <byte> outputBytes = stackalloc byte[text.Length];

            Hexadecimal.FromHexChars(chars, outputBytes);
            var originalString = System.Text.Encoding.UTF8.GetString(outputBytes);

            Assert.Equal(text, originalString);
        }
Ejemplo n.º 19
0
        public static void PositiveHexTests(string decodedAsHexString, string encoded)
        {
            var decoded = Hexadecimal.Decode(decodedAsHexString);

            var encodeResult = Base58.Encode(decoded);

            Assert.Equal(encoded, encodeResult);

            var decodeResult = Base58.Decode(encoded);

            Assert.Equal(decoded, decodeResult);
        }
Ejemplo n.º 20
0
        public void FromHexChars_AfterToHexChars_ShouldReturnOriginalInput(string text, string hexString)
        {
            var         bytes       = System.Text.Encoding.UTF8.GetBytes(text);
            Span <byte> outputChars = stackalloc byte[hexString.Length];

            Hexadecimal.ToHexChars(bytes, outputChars);
            Span <byte> decodedBytes = stackalloc byte[bytes.Length];

            Hexadecimal.FromHexChars(outputChars, decodedBytes);
            var originalString = System.Text.Encoding.UTF8.GetString(decodedBytes);

            Assert.Equal(text, originalString);
        }
Ejemplo n.º 21
0
        public void Write_Succeeds(string stationId6, string muxs, string routerDataEndpoint, string expected)
        {
            var stationEui = stationId6.Contains(':', StringComparison.Ordinal)
                ? Id6.TryParse(stationId6, out var id6) ? new StationEui(id6) : throw new JsonException()
                : Hexadecimal.TryParse(stationId6, out ulong hhd, '-')
                    ? new StationEui(hhd)
                    : throw new JsonException();

            var computed = Json.Stringify(w =>
                                          LnsDiscovery.WriteResponse(w, stationEui, muxs, new Uri(routerDataEndpoint)));

            Assert.Equal(expected, computed);
        }
Ejemplo n.º 22
0
        public static void DecodeIsCaseInsensitive(string hexEncoding, string pgpWordListEncoding)
        {
            var expectedBytes = Hexadecimal.Decode(hexEncoding);

            var upperCaseWords   = pgpWordListEncoding.ToUpper().Split();
            var decodedUpperCase = PgpWordList.Decode(upperCaseWords);

            Assert.Equal(expectedBytes, decodedUpperCase);

            var lowerCaseWords   = pgpWordListEncoding.ToLower().Split();
            var decodedLowerCase = PgpWordList.Decode(lowerCaseWords);

            Assert.Equal(expectedBytes, decodedLowerCase);
        }
Ejemplo n.º 23
0
            public OutputScript BuildOutputScript()
            {
                switch (OutputType)
                {
                case Kind.Address:
                    var address = Address.Decode(Destination);
                    return(address.BuildScript());

                case Kind.Script:
                    return(new OutputScript.Unrecognized(Hexadecimal.Decode(Destination)));

                default:
                    throw new Exception($"Unknown pending output kind {OutputType}");
                }
            }
 private void DataBind()
 {
     this.cmbColors.Items.Clear();
     foreach (int argb in this.colors)
     {
         Color c = Color.FromArgb(argb);
         this.cmbColors.Items.Add("#" + Hexadecimal.ToString(c.R, 2) + Hexadecimal.ToString(c.G, 2) + Hexadecimal.ToString(c.B, 2));
     }
     if (this.currentColor != null && this.currentColor.HasValue)
     {
         this.cmbColors.Text = "#" + Hexadecimal.ToString(this.currentColor.Value.R, 2) + Hexadecimal.ToString(this.currentColor.Value.G, 2) + Hexadecimal.ToString(this.currentColor.Value.B, 2);
     }
     else
     {
         this.cmbColors.Text = "";
     }
 }
Ejemplo n.º 25
0
        public static string ToString(ref Blake256HashBuffer buffer)
        {
            var reverseCopy = new byte[Length];

            unsafe
            {
                fixed(byte *p = buffer._data)
                {
                    for (int i = 0, j = Length - 1; i < Length; ++i, --j)
                    {
                        reverseCopy[i] = p[j];
                    }
                }
            }

            return(Hexadecimal.Encode(reverseCopy));
        }
Ejemplo n.º 26
0
        private static byte[] DecodeUserInput(string userInput, PgpWordList pgpWordList)
        {
            byte[] seed;
            if (Hexadecimal.TryDecode(userInput, out seed))
            {
                return(seed);
            }

            var splitInput = userInput.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);

            if (splitInput.Length == 1)
            {
                // Hex decoding failed, but it's not a multi-word mneumonic either.
                // Assume the user intended hex.
                throw new HexadecimalEncodingException();
            }
            return(pgpWordList.Decode(splitInput));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 正常数据
        /// </summary>
        void  NormalData(string[] msg)
        {
            //if (zoomId == oldId)
            //    return;

            string statusNo = Hexadecimal.ConvertBase(msg[0], 16, 10);

            if (string.IsNullOrWhiteSpace(statusNo))
            {
                return;
            }
            string status = Enum.GetName(typeof(H3CMsgType), int.Parse(statusNo));

            if (string.IsNullOrWhiteSpace(status))
            {
                return;
            }
            oldId = zoomId;
            string dianya = Hexadecimal.ConvertBase(msg[1] + msg[2], 16, 10);

            StringHelper.RepairZero(dianya, 4);
            string dianliu = (double.Parse(Hexadecimal.ConvertBase(msg[3], 16, 10)) / 10).ToString("#0.0");

            if (dianliu == "0.0" && dianya == "0" && status == "正常")
            {
                //checkTime = DateTime.Now;
                // return;
                status   = "异常";
                statusNo = "7";
            }
            H3CPowerGridData data = new H3CPowerGridData()
            {
                DeviceIp       = powerIp,
                EventType      = (H3CMsgType)Enum.Parse(typeof(H3CMsgType), statusNo),
                PowerFlow      = dianliu,
                PowerGridState = int.Parse(statusNo),
                Voltage        = dianya,
                ZoomId         = int.Parse(zoomId)
            };

            SendZoomData(data);
        }
Ejemplo n.º 28
0
        public static ArrayLease <byte> DecryptHexToBytes(string ciphertext, ArraySegment <byte> key, out int count)
        {
            // Throw if the string isn't divisible by 2, since bytes are 2 hex digits
            if ((ciphertext.Length & 1) != 0) // ciphertext.Length % 2 != 0
            {
                // TODO: Strings.resx if it's worth it (see notes above)
                throw new ArgumentException(
                          message: "The ciphertext needs to be hex-encoded and have a length divisible by 2.",
                          paramName: nameof(ciphertext));
            }

            int bufferLength = ciphertext.Length / 2;
            var rented       = ArrayPool <byte> .Shared.Rent(bufferLength);

            try
            {
                Debug.Assert(bufferLength <= rented.Length);

                // Do the translation via Hexadecimal.ToByte
                int i = 0, j = 0;
                while (i < bufferLength)
                {
                    rented[i] = Hexadecimal.ToByte(ciphertext[j], ciphertext[j + 1]);

                    i += 1;
                    j += 2;
                }

                Debug.Assert(i == bufferLength && j == i * 2);

                // Now call DecryptBytes with the key/encrypted buffer
                var encryptedBytes = new ArraySegment <byte>(rented, 0, bufferLength);
                return(DecryptBytes(encryptedBytes, key, out count));
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(rented);
            }
        }
Ejemplo n.º 29
0
        private static ExitCode RunDecodeOptionsAndReturnExitCode(DecodeOptions decodeOptions)
        {
            string decodedString = null;
            string errorMsg      = null;

            switch (decodeOptions.DecodeType.ToLower())
            {
            case "base64":
            {
                decodedString = Base64.ToString(decodeOptions.InputToDecode);
            }
            break;

            case "hex":
            {
                decodedString = Hexadecimal.ToString(decodeOptions.InputToDecode);
            }
            break;

            default:
                errorMsg = $"Unknown decode type \"{decodeOptions.DecodeType}\".";
                break;
            }

            if (string.IsNullOrWhiteSpace(errorMsg))
            {
                Console.WriteLine(decodedString);

                return(ExitCode.Sucess);
            }
            else
            {
                Console.WriteLine(errorMsg);

                return(ExitCode.Error);
            }
        }
        /// <summary>
        /// 电网数据解析
        /// </summary>
        /// <param name="sender">数据</param>
        private void MyEvent(object sender)
        {
            try
            {
                XFPowerGridData pg     = new XFPowerGridData();
                byte[]          date   = sender as byte[];
                string          strMsg = Encoding.Default.GetString(date, 0, date.Length);// 将接受到的字节数据转化成字符串;
                strMsg = strMsg.Trim('\0');
                int    x = 0;
                string w = "";
                foreach (char item in strMsg)
                {
                    if (x == 1)
                    {
                        w += item + " ";
                        x  = 0;
                    }
                    else
                    {
                        w += item;
                        x++;
                    }
                }
                w = w.Substring(0, w.Length - " ".Length);
                string[] msg = w.Split(' ');
                if (msg.Length == 18)
                {
                    if (msg[0] == "3A" && msg[16] == "0A")
                    {
                        pg.LowerComputerId        = int.Parse(Hexadecimal.ConvertBase(msg[1], 16, 10));
                        pg.IsClearAlarm           = int.Parse(Hexadecimal.ConvertBase(msg[14], 16, 10));
                        pg.LowerComputerIsPowerOn = int.Parse(Hexadecimal.ConvertBase(msg[15], 16, 10));
                        pg.ExtensionComputerId    = int.Parse(Hexadecimal.ConvertBase(msg[17], 16, 10));
                        pg.PowerGridState         = int.Parse(Hexadecimal.ConvertBase(msg[2], 16, 10));
                        if (pg.ExtensionComputerId == 0 && pg.PowerGridState == 0)
                        {
                            return;
                        }
                        pg.CombatPower      = int.Parse(Hexadecimal.ConvertBase(msg[3], 16, 10));
                        pg.Triggerthreshold = int.Parse(Hexadecimal.ConvertBase(msg[4], 16, 10));
                        pg.ExtensionState   = int.Parse(Hexadecimal.ConvertBase(msg[5], 16, 10));
                        ////下位机状态
                        //if (pg.PowerGridState == 0)
                        state = pg.ExtensionState;
                        //else if (pg.PowerGridState == 4 || pg.PowerGridState == 1 || pg.PowerGridState == 3) //主机状态
                        //    state = pg.ExtensionState = 5;
                        pg.PowerFlow = int.Parse(Hexadecimal.ConvertBase(msg[8], 16, 10)) * 256 + int.Parse(Hexadecimal.ConvertBase(msg[9], 16, 10));
                        if (pg.ExtensionComputerId == 0 || (pg.PowerFlow == 0 && pg.Voltage == 0))
                        {
                            return;
                        }

                        if (int.Parse(Hexadecimal.ConvertBase(msg[10], 16, 10)) * 256 + int.Parse(Hexadecimal.ConvertBase(msg[11], 16, 10)) == 0)
                        {
                            pg.Voltage = (int.Parse(Hexadecimal.ConvertBase(msg[6], 16, 10)) * 256 + int.Parse(Hexadecimal.ConvertBase(msg[7], 16, 10))) % 1000 + 4700;
                        }
                        else
                        {
                            pg.Voltage = (int.Parse(Hexadecimal.ConvertBase(msg[6], 16, 10)) * 256 + int.Parse(Hexadecimal.ConvertBase(msg[7], 16, 10))) % 1000 + 10000;
                        }

                        pg.DeviceIp  = powerIp;
                        pg.EventType = (XFPowerState)Enum.Parse(typeof(XFPowerState), state.ToString());
                        XFZoomStatus?.Invoke(pg);
                        checkTime      = DateTime.Now;
                        isSendNetState = false;
                    }
                }
                else
                {
                    return;
                }
                string status = Enum.GetName(typeof(XFPowerState), state);
                w = string.Format("{0}:电压{1} {4} 电流{2} {5} 状态 {3};", pg.ExtensionComputerId, pg.Voltage, pg.PowerFlow, status, "V", "mA");
                ShowMsg(w);
                if (pg.ExtensionComputerId <= ZoomCount)
                {
                    allZoomData.Add(pg);
                }
                stateCount += state;
                if (pg.ExtensionComputerId == ZoomCount)
                {
                    if (allZoomData.Count == ZoomCount)
                    {
                        XFPowerGridFormatStatus?.Invoke((XFPowerState)Enum.Parse(typeof(XFPowerState), stateCount == 0 ? "0" : "7"), allZoomData);
                    }
                    allZoomData.Clear();
                }
                // checkTime = DateTime.Now;
            }
            catch (Exception) { }
        }