当前位置: 首页>>代码示例>>C#>>正文


C# ByteString.ToByteArray方法代码示例

本文整理汇总了C#中ByteString.ToByteArray方法的典型用法代码示例。如果您正苦于以下问题:C# ByteString.ToByteArray方法的具体用法?C# ByteString.ToByteArray怎么用?C# ByteString.ToByteArray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ByteString的用法示例。


在下文中一共展示了ByteString.ToByteArray方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetKeyStartingFrom

        public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
        {
            byte[] from = prefix.ToByteArray();
            byte[] to = prefix.ToByteArray();
            to[to.Length - 1]++;

            return await ExecuteQuery<Record>(
                "EXEC [Openchain].[GetRecordRange] @instance, @from, @to;",
                reader => new Record(new ByteString((byte[])reader[0]), new ByteString((byte[])reader[1]), new ByteString((byte[])reader[2])),
                new Dictionary<string, object>()
                {
                    ["instance"] = this.instanceId,
                    ["from"] = from,
                    ["to"] = to
                });
        }
开发者ID:juanfranblanco,项目名称:openchain,代码行数:16,代码来源:SqlServerLedger.cs

示例2: PostTransaction

        public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
        {
            Mutation mutation;
            try
            {
                // Verify that the mutation can be deserialized
                mutation = MessageSerializer.DeserializeMutation(rawMutation);
            }
            catch (InvalidProtocolBufferException)
            {
                throw new TransactionInvalidException("InvalidMutation");
            }

            if (!mutation.Namespace.Equals(this.ledgerId))
                throw new TransactionInvalidException("InvalidNamespace");

            if (mutation.Records.Count == 0)
                throw new TransactionInvalidException("InvalidMutation");

            if (mutation.Records.Any(record => record.Key.Value.Count > MaxKeySize))
                throw new TransactionInvalidException("InvalidMutation");

            ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));

            ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);

            // All assets must have an overall zero balance

            IReadOnlyDictionary<AccountKey, AccountStatus> accounts =
                await this.store.GetAccounts(parsedMutation.AccountMutations.Select(entry => entry.AccountKey));

            var groups = parsedMutation.AccountMutations
                .GroupBy(account => account.AccountKey.Asset.FullPath)
                .Select(group => group.Sum(entry => entry.Balance - accounts[entry.AccountKey].Balance));

            if (groups.Any(group => group != 0))
                throw new TransactionInvalidException("UnbalancedTransaction");

            DateTime date = DateTime.UtcNow;

            await this.validator.Validate(parsedMutation, authentication, accounts);

            TransactionMetadata metadata = new TransactionMetadata(authentication);

            byte[] rawMetadata = SerializeMetadata(metadata);

            Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
            byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);

            try
            {
                await this.store.AddTransactions(new[] { new ByteString(serializedTransaction) });
            }
            catch (ConcurrentMutationException)
            {
                throw new TransactionInvalidException("OptimisticConcurrency");
            }

            return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
        }
开发者ID:packetlost,项目名称:openchain,代码行数:60,代码来源:TransactionValidator.cs

示例3: ToArray_Success

        public void ToArray_Success()
        {
            byte[] sourceArray = new byte[] { 18, 178, 255, 70, 0 };
            ByteString result = new ByteString(sourceArray);

            Assert.Equal<byte>(new byte[] { 18, 178, 255, 70, 0 }, result.ToByteArray());
        }
开发者ID:hellwolf,项目名称:openchain,代码行数:7,代码来源:ByteStringTests.cs

示例4: GetRecordMutations

 public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
 {
     var key = recordKey.ToByteArray();
     var res = await TransactionCollection.Find(Builders<MongoDbTransaction>.Filter.AnyEq(x=>x.Records, key))
         .Project(x=>x.MutationHash)
         .SortBy(x=>x.Timestamp)
         .ToListAsync();
     return res.Select(x=>new ByteString(x)).ToList().AsReadOnly();
 }
开发者ID:Flavien,项目名称:mongodb-storage,代码行数:9,代码来源:MongoDbLedger.cs

示例5: ToData

 /// <summary>
 /// Converts a <see cref="ByteString"/> structure into a Helios <see cref="NetworkData"/> structure
 /// </summary>
 /// <param name="byteString">The data to send over the network</param>
 /// <param name="address">The address that we received data from / are sending data to</param>
 /// <returns>a new <see cref="NetworkData"/> struct</returns>
 public static NetworkData ToData(ByteString byteString, Address address)
 {
     var data = new NetworkData()
     {
         Buffer = byteString.ToByteArray(),
         RemoteHost = HeliosTransport.AddressToNode(address)
     };
     data.Length = data.Buffer.Length;
     return data;
 }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:16,代码来源:HeliosHelpers.cs

示例6: GetRecordMutations

 public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
 {
     return await ExecuteQuery<ByteString>(
         "EXEC [Openchain].[GetRecordMutations] @instance, @recordKey;",
         reader => new ByteString((byte[])reader[0]),
         new Dictionary<string, object>()
         {
             ["instance"] = this.instanceId,
             ["recordKey"] = recordKey.ToByteArray()
         });
 }
开发者ID:juanfranblanco,项目名称:openchain,代码行数:11,代码来源:SqlServerLedger.cs

示例7: GetRecordMutations

 public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
 {
     return await ExecuteAsync(@"
             SELECT  MutationHash
             FROM    RecordMutations
             WHERE   RecordKey = @recordKey",
         reader => new ByteString((byte[])reader.GetValue(0)),
         new Dictionary<string, object>()
         {
             ["@recordKey"] = recordKey.ToByteArray()
         });
 }
开发者ID:juanfranblanco,项目名称:openchain,代码行数:12,代码来源:SqliteLedger.cs

示例8: GetPubKeyHash

        public string GetPubKeyHash(ByteString pubKey)
        {
            Org.BouncyCastle.Crypto.Digests.RipeMD160Digest ripe = new Org.BouncyCastle.Crypto.Digests.RipeMD160Digest();

            using (SHA256 sha256 = SHA256.Create())
            {
                byte[] shaResult = sha256.ComputeHash(pubKey.ToByteArray());
                ripe.BlockUpdate(shaResult, 0, shaResult.Length);
                byte[] hash = new byte[20];
                ripe.DoFinal(hash, 0);
                return Base58CheckEncoding.Encode(new byte[] { versionByte }.Concat(hash).ToArray());
            }
        }
开发者ID:hellwolf,项目名称:openchain,代码行数:13,代码来源:KeyEncoder.cs

示例9: GetKeyStartingFrom

        public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
        {
            byte[] from = prefix.ToByteArray();
            byte[] to = prefix.ToByteArray();

            if (to[to.Length - 1] < 255)
                to[to.Length - 1] += 1;

            return await ExecuteAsync(@"
                    SELECT  Key, Value, Version
                    FROM    Records
                    WHERE   Key >= @from AND Key < @to",
                reader => new Record(
                    new ByteString((byte[])reader.GetValue(0)),
                    reader.GetValue(1) == null ? ByteString.Empty : new ByteString((byte[])reader.GetValue(1)),
                    new ByteString((byte[])reader.GetValue(2))),
                new Dictionary<string, object>()
                {
                    ["@from"] = from,
                    ["@to"] = to
                });
        }
开发者ID:juanfranblanco,项目名称:openchain,代码行数:22,代码来源:SqliteLedger.cs

示例10: GetKeyStartingFrom

        public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
        {
            var prefixS = Encoding.UTF8.GetString(prefix.ToByteArray());
            var list = new List<Record>();
            var res = await RecordCollection.FindAsync(x => x.KeyS.StartsWith(prefixS));
            await res.ForEachAsync(r =>
            {
                list.Add(new Record(new ByteString(r.Key), new ByteString(r.Value), new ByteString(r.Version)));
            }

            );
            return list.AsReadOnly();
        }
开发者ID:Flavien,项目名称:mongodb-storage,代码行数:13,代码来源:MongoDbLedger.cs

示例11: GetTransaction

        public async Task<ByteString> GetTransaction(ByteString mutationHash)
        {
            IEnumerable<ByteString> transactions = await ExecuteAsync(@"
                    SELECT  RawData
                    FROM    Transactions
                    WHERE   MutationHash = @mutationHash",
               reader => new ByteString((byte[])reader.GetValue(0)),
               new Dictionary<string, object>()
               {
                   ["@mutationHash"] = mutationHash.ToByteArray()
               });

            return transactions.FirstOrDefault();
        }
开发者ID:juanfranblanco,项目名称:openchain,代码行数:14,代码来源:SqliteLedger.cs

示例12: Decode

 /// <summary>
 /// Decode a value of the given type.
 /// Should not be called directly. This interface is used by service client stubs.
 /// </summary>
 public static object Decode(ByteString value, Type type, Connection client)
 {
     var stream = new CodedInputStream (value.ToByteArray ());
     if (type == typeof(double))
         return stream.ReadDouble ();
     else if (type == typeof(float))
         return stream.ReadFloat ();
     else if (type == typeof(int))
         return stream.ReadInt32 ();
     else if (type == typeof(long))
         return stream.ReadInt64 ();
     else if (type == typeof(uint))
         return stream.ReadUInt32 ();
     else if (type == typeof(ulong))
         return stream.ReadUInt64 ();
     else if (type == typeof(bool))
         return stream.ReadBool ();
     else if (type == typeof(string))
         return stream.ReadString ();
     else if (type == typeof(byte[]))
         return stream.ReadBytes ().ToByteArray ();
     else if (type.IsEnum)
         return stream.ReadInt32 ();
     else if (typeof(RemoteObject).IsAssignableFrom (type)) {
         if (client == null)
             throw new ArgumentException ("Client not passed when decoding remote object");
         var id = stream.ReadUInt64 ();
         if (id == 0)
             return null;
         return (RemoteObject)Activator.CreateInstance (type, client, id);
     } else if (typeof(IMessage).IsAssignableFrom (type)) {
         IMessage message = (IMessage)Activator.CreateInstance (type);
         message.MergeFrom (stream);
         return message;
     } else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IList<>))
         return DecodeList (value, type, client);
     else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(IDictionary<,>))
         return DecodeDictionary (value, type, client);
     else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof(ISet<>))
         return DecodeSet (value, type, client);
     else if (type.IsGenericType &&
              (type.GetGenericTypeDefinition () == typeof(Tuple<>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,,>) ||
              type.GetGenericTypeDefinition () == typeof(Tuple<,,,,,>)))
         return DecodeTuple (value, type, client); // TODO: ugly handing of tuple types
     throw new ArgumentException (type + " is not a serializable type");
 }
开发者ID:artwhaley,项目名称:krpc,代码行数:54,代码来源:Encoder.cs

示例13: PostTransaction

        public async Task<ByteString> PostTransaction(ByteString rawMutation, IReadOnlyList<SignatureEvidence> authentication)
        {
            Mutation mutation;
            try
            {
                // Verify that the mutation can be deserialized
                mutation = MessageSerializer.DeserializeMutation(rawMutation);
            }
            catch (InvalidProtocolBufferException)
            {
                throw new TransactionInvalidException("InvalidMutation");
            }

            ParsedMutation parsedMutation = ParsedMutation.Parse(mutation);

            IReadOnlyDictionary<AccountKey, AccountStatus> accounts = await ValidateMutation(mutation, parsedMutation);

            ValidateAuthentication(authentication, MessageSerializer.ComputeHash(rawMutation.ToByteArray()));

            DateTime date = DateTime.UtcNow;

            IList<Mutation> generatedMutations = await this.validator.Validate(parsedMutation, authentication, accounts);

            TransactionMetadata metadata = new TransactionMetadata(authentication);

            byte[] rawMetadata = SerializeMetadata(metadata);

            Transaction transaction = new Transaction(rawMutation, date, new ByteString(rawMetadata));
            byte[] serializedTransaction = MessageSerializer.SerializeTransaction(transaction);

            List<ByteString> transactions = new List<ByteString>() { new ByteString(serializedTransaction) };

            transactions.AddRange(await Task.WhenAll(generatedMutations.Select(async generatedMutation =>
            {
                await ValidateMutation(generatedMutation, ParsedMutation.Parse(generatedMutation));
                Transaction generatedTransaction = new Transaction(new ByteString(MessageSerializer.SerializeMutation(generatedMutation)), date, ByteString.Empty);
                return new ByteString(MessageSerializer.SerializeTransaction(generatedTransaction));
            })));

            try
            {
                await this.store.AddTransactions(transactions);
            }
            catch (ConcurrentMutationException)
            {
                throw new TransactionInvalidException("OptimisticConcurrency");
            }

            return new ByteString(MessageSerializer.ComputeHash(serializedTransaction));
        }
开发者ID:openchain,项目名称:openchain,代码行数:50,代码来源:TransactionValidator.cs

示例14: GetTransaction

        public async Task<ByteString> GetTransaction(ByteString mutationHash)
        {
            IReadOnlyList<ByteString> result = await ExecuteQuery<ByteString>(
                "EXEC [Openchain].[GetTransaction] @instance, @mutationHash;",
                reader => new ByteString((byte[])reader[0]),
                new Dictionary<string, object>()
                {
                    ["instance"] = this.instanceId,
                    ["mutationHash"] = mutationHash.ToByteArray()
                });

            if (result.Count > 0)
                return result[0];
            else
                return null;
        }
开发者ID:juanfranblanco,项目名称:openchain,代码行数:16,代码来源:SqlServerLedger.cs

示例15: Subscribe

        public async Task Subscribe(CancellationToken cancel)
        {
            byte[] buffer = new byte[1024 * 1024];
            ArraySegment<byte> segment = new ArraySegment<byte>(buffer);

            ByteString currentRecord = await this.store.GetLastTransaction();

            while (!cancel.IsCancellationRequested)
            {
                try
                {
                    ClientWebSocket socket = new ClientWebSocket();

                    this.endpoint.Query = string.Format("from={0}", currentRecord.ToString());

                    logger.LogInformation("Connecting to {0}", this.endpoint.Uri);

                    await socket.ConnectAsync(this.endpoint.Uri, cancel);

                    while (true)
                    {
                        WebSocketReceiveResult result = await socket.ReceiveAsync(segment, cancel);
                        if (result.MessageType == WebSocketMessageType.Close)
                            break;

                        ByteString record = new ByteString(buffer.Take(result.Count));
                        await store.AddTransactions(new[] { record });

                        currentRecord = new ByteString(MessageSerializer.ComputeHash(record.ToByteArray()));
                    }
                }
                catch (Exception exception)
                {
                    logger.LogError("Error in the stream subscriber: {0}", exception.ToString());
                }

                await Task.Delay(TimeSpan.FromMinutes(1));
            }
        }
开发者ID:packetlost,项目名称:openchain,代码行数:39,代码来源:StreamSubscriber.cs


注:本文中的ByteString.ToByteArray方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。