public Pkcs8PrivateKeyInfo( Oid algorithmId, ReadOnlyMemory <byte>?algorithmParameters, ReadOnlyMemory <byte> privateKey, bool skipCopies = false) { if (algorithmId == null) { throw new ArgumentNullException(nameof(algorithmId)); } AlgorithmId = algorithmId; AlgorithmParameters = skipCopies ? algorithmParameters : algorithmParameters?.ToArray(); PrivateKeyBytes = skipCopies ? privateKey : privateKey.ToArray(); Attributes = new CryptographicAttributeObjectCollection(); }
public Pkcs8PrivateKeyInfo( Oid algorithmId, ReadOnlyMemory <byte>?algorithmParameters, ReadOnlyMemory <byte> privateKey, bool skipCopies = false) { if (algorithmId == null) { throw new ArgumentNullException(nameof(algorithmId)); } if (algorithmParameters?.Length > 0) { // Read to ensure that there is precisely one legally encoded value. PkcsHelpers.EnsureSingleBerValue(algorithmParameters.Value.Span); } AlgorithmId = algorithmId; AlgorithmParameters = skipCopies ? algorithmParameters : algorithmParameters?.ToArray(); PrivateKeyBytes = skipCopies ? privateKey : privateKey.ToArray(); Attributes = new CryptographicAttributeObjectCollection(); }
public Pkcs8PrivateKeyInfo( Oid algorithmId, ReadOnlyMemory <byte>?algorithmParameters, ReadOnlyMemory <byte> privateKey, bool skipCopies = false) { if (algorithmId == null) { throw new ArgumentNullException(nameof(algorithmId)); } if (algorithmParameters?.Length > 0) { // Read to ensure that there is precisely one legally encoded value. AsnReader reader = new AsnReader(algorithmParameters.Value, AsnEncodingRules.BER); reader.ReadEncodedValue(); reader.ThrowIfNotEmpty(); } AlgorithmId = algorithmId; AlgorithmParameters = skipCopies ? algorithmParameters : algorithmParameters?.ToArray(); PrivateKeyBytes = skipCopies ? privateKey : privateKey.ToArray(); Attributes = new CryptographicAttributeObjectCollection(); }
public byte[] GetSignature() => _signature.ToArray();
public Task SendAsync(ReadOnlyMemory <byte> payload) { incomingRequests.Add(RconPacket.FromBytes(payload.ToArray())); return(Task.CompletedTask); }
/// <summary> /// Compare this <see cref="byte"/> array to another. /// </summary> /// <param name="buffer"><see cref="ReadOnlyMemory{byte}"/> instance.</param> /// <param name="other"><see cref="byte"/> array to compare.</param> /// <returns>Returns true if both instances has equal values.</returns> public static bool Compare(this ReadOnlyMemory <byte> buffer, byte[] other) { return(buffer.ToArray().Compare(other)); }
/// <inheritdoc /> public byte[] Convert(ReadOnlyMemory <byte> input) { return(input.ToArray()); }
public async Task SendAsync(ReadOnlyMemory <byte> request, Func <SocketAsyncState, Task> callback, ErrorMap errorMap) { ExceptionDispatchInfo capturedException = null; SocketAsyncState state = null; try { var opaque = Converter.ToUInt32(request.Span.Slice(HeaderOffsets.Opaque)); state = new SocketAsyncState { Opaque = opaque, EndPoint = (IPEndPoint)EndPoint, ConnectionId = ConnectionId, LocalEndpoint = LocalEndPoint.ToString() }; if (!MemoryMarshal.TryGetArray <byte>(request, out var arraySegment)) { // Fallback in case we can't use the more efficient TryGetArray method arraySegment = new ArraySegment <byte>(request.ToArray()); } // write data to stream await _sslStream.WriteAsync(arraySegment.Array, 0, request.Length).ConfigureAwait(false); // wait for response var received = await _sslStream.ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length).ConfigureAwait(false); var responseSize = Converter.ToInt32(_receiveBuffer.AsSpan(HeaderOffsets.BodyLength)) + HeaderOffsets.HeaderLength; // create memory slice and copy first segment var response = MemoryPool <byte> .Shared.RentAndSlice(responseSize); _receiveBuffer.AsMemory(0, received).CopyTo(response.Memory); // append any further segments as required while (received < responseSize) { var segmentLength = await _sslStream.ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length).ConfigureAwait(false); _receiveBuffer.AsMemory(0, segmentLength).CopyTo(response.Memory); received += segmentLength; } // write response to state and complete callback state.SetData(response); await callback(state).ConfigureAwait(false); } catch (Exception e) { IsDead = true; capturedException = ExceptionDispatchInfo.Capture(e); } if (capturedException != null) { var sourceException = capturedException.SourceException; if (state == null) { await callback(new SocketAsyncState { Exception = capturedException.SourceException, Status = (sourceException is SocketException) ? ResponseStatus.TransportFailure : ResponseStatus.ClientFailure }).ConfigureAwait(false); } else { state.Exception = sourceException; await state.Completed(state).ConfigureAwait(false); Log.LogDebug(sourceException, ""); } } }
/// <summary> /// Convert the <see cref="ReadOnlyMemory{byte}"/> data to <see cref="int"/> representation. /// </summary> /// <param name="buffer"><see cref="ReadOnlyMemory{byte}"/> instance.</param> /// <returns>Returns the <see cref="int"/> representation.</returns> public static int GetInt(this ReadOnlyMemory <byte> buffer) { return(buffer.ToArray().GetInt()); }
protected override async ValueTask <Memory <byte> > HandleBusiness(ReadOnlyMemory <byte> input) { //var s = Encoding.UTF8.GetString(input.ToArray()); //var r = Encoding.UTF8.GetBytes(s); return(await Task.FromResult(input.ToArray())); }
public static Task WriteAsync(this Stream stream, ReadOnlyMemory <byte> source, CancellationToken cancellationToken = default(CancellationToken)) => stream.WriteAsync(source.ToArray(), 0, source.Length, cancellationToken);
// Receive from udp socket and push value to subscribers. async void RunReceiveLoop(Stream pipeStream, Func <CancellationToken, Task>?waitForConnection) { RECONNECT: var token = cancellationTokenSource.Token; if (waitForConnection != null) { try { await waitForConnection(token).ConfigureAwait(false); } catch (IOException) { return; // connection closed. } } var buffer = new byte[65536]; while (!token.IsCancellationRequested) { ReadOnlyMemory <byte> value = Array.Empty <byte>(); try { var readLen = await pipeStream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false); if (readLen == 0) { if (waitForConnection != null) { server.Value.Dispose(); server = CreateLazyServerStream(); pipeStream = server.Value; goto RECONNECT; // end of stream(disconnect, wait reconnect) } } var messageLen = MessageBuilder.FetchMessageLength(buffer); if (readLen == (messageLen + 4)) { value = buffer.AsMemory(4, messageLen); // skip length header } else { // read more if (buffer.Length < (messageLen + 4)) { Array.Resize(ref buffer, messageLen + 4); } var remain = messageLen - (readLen - 4); await ReadFullyAsync(buffer, pipeStream, readLen, remain, token).ConfigureAwait(false); value = buffer.AsMemory(4, messageLen); } } catch (IOException) { return; // connection closed. } catch (Exception ex) { if (ex is OperationCanceledException) { return; } if (token.IsCancellationRequested) { return; } // network error, terminate. options.UnhandledErrorHandler("network error, receive loop will terminate." + Environment.NewLine, ex); return; } try { var message = MessageBuilder.ReadPubSubMessage(value.ToArray()); // can avoid copy? switch (message.MessageType) { case MessageType.PubSub: publisher.Publish(message, message, CancellationToken.None); break; case MessageType.RemoteRequest: { // NOTE: should use without reflection(Expression.Compile) var header = Deserialize <RequestHeader>(message.KeyMemory, options.MessagePackSerializerOptions); var(mid, reqTypeName, resTypeName) = (header.MessageId, header.RequestType, header.ResponseType); byte[] resultBytes; try { var t = AsyncRequestHandlerRegistory.Get(reqTypeName, resTypeName); var interfaceType = t.GetInterfaces().First(x => x.IsGenericType && x.Name.StartsWith("IAsyncRequestHandler")); var coreInterfaceType = t.GetInterfaces().First(x => x.IsGenericType && x.Name.StartsWith("IAsyncRequestHandlerCore")); var service = provider.GetRequiredService(interfaceType); // IAsyncRequestHandler<TRequest,TResponse> var genericArgs = interfaceType.GetGenericArguments(); // [TRequest, TResponse] var request = MessagePackSerializer.Deserialize(genericArgs[0], message.ValueMemory, options.MessagePackSerializerOptions); var responseTask = coreInterfaceType.GetMethod("InvokeAsync") !.Invoke(service, new[] { request, CancellationToken.None }); var task = typeof(ValueTask <>).MakeGenericType(genericArgs[1]).GetMethod("AsTask") !.Invoke(responseTask, null); await((System.Threading.Tasks.Task)task !); // Task<T> -> Task var result = task.GetType().GetProperty("Result") !.GetValue(task); resultBytes = MessageBuilder.BuildRemoteResponseMessage(mid, genericArgs[1], result !, options.MessagePackSerializerOptions); } catch (Exception ex) { // NOTE: ok to send stacktrace? resultBytes = MessageBuilder.BuildRemoteResponseError(mid, ex.ToString(), options.MessagePackSerializerOptions); } await pipeStream.WriteAsync(resultBytes, 0, resultBytes.Length).ConfigureAwait(false); } break; case MessageType.RemoteResponse: case MessageType.RemoteError: { var mid = Deserialize <int>(message.KeyMemory, options.MessagePackSerializerOptions); if (responseCompletions.TryRemove(mid, out var tcs)) { if (message.MessageType == MessageType.RemoteResponse) { tcs.TrySetResult(message); // synchronous completion, use memory buffer immediately. } else { var errorMsg = MessagePackSerializer.Deserialize <string>(message.ValueMemory, options.MessagePackSerializerOptions); tcs.TrySetException(new RemoteRequestException(errorMsg)); } } } break; default: break; } } catch (IOException) { return; // connection closed. } catch (Exception ex) { if (ex is OperationCanceledException) { continue; } options.UnhandledErrorHandler("", ex); } } }
public static bool WriteBin(RegRoot root, string keyName, string valueName, ReadOnlyMemory <byte> data) { return(WriteValue(root, keyName, valueName, RegistryValueKind.Binary, data.ToArray())); }
public static Pkcs12Info Decode( ReadOnlyMemory <byte> encodedBytes, out int bytesConsumed, bool skipCopy = false) { AsnReader reader = new AsnReader(encodedBytes, AsnEncodingRules.BER); // Trim it to the first value encodedBytes = reader.PeekEncodedValue(); ReadOnlyMemory <byte> maybeCopy = skipCopy ? encodedBytes : encodedBytes.ToArray(); PfxAsn pfx = PfxAsn.Decode(maybeCopy, AsnEncodingRules.BER); // https://tools.ietf.org/html/rfc7292#section-4 only defines version 3. if (pfx.Version != 3) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } ReadOnlyMemory <byte> authSafeBytes = ReadOnlyMemory <byte> .Empty; Pkcs12IntegrityMode mode = Pkcs12IntegrityMode.Unknown; if (pfx.AuthSafe.ContentType == Oids.Pkcs7Data) { authSafeBytes = PkcsHelpers.DecodeOctetStringAsMemory(pfx.AuthSafe.Content); if (pfx.MacData.HasValue) { mode = Pkcs12IntegrityMode.Password; } else { mode = Pkcs12IntegrityMode.None; } } else if (pfx.AuthSafe.ContentType == Oids.Pkcs7Signed) { SignedDataAsn signedData = SignedDataAsn.Decode(pfx.AuthSafe.Content, AsnEncodingRules.BER); mode = Pkcs12IntegrityMode.PublicKey; if (signedData.EncapContentInfo.ContentType == Oids.Pkcs7Data) { authSafeBytes = signedData.EncapContentInfo.Content.GetValueOrDefault(); } if (pfx.MacData.HasValue) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } } if (mode == Pkcs12IntegrityMode.Unknown) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } List <ContentInfoAsn> authSafeData = new List <ContentInfoAsn>(); AsnValueReader authSafeReader = new AsnValueReader(authSafeBytes.Span, AsnEncodingRules.BER); AsnValueReader sequenceReader = authSafeReader.ReadSequence(); authSafeReader.ThrowIfNotEmpty(); while (sequenceReader.HasData) { ContentInfoAsn.Decode(ref sequenceReader, authSafeBytes, out ContentInfoAsn contentInfo); authSafeData.Add(contentInfo); } ReadOnlyCollection <Pkcs12SafeContents> authSafe; if (authSafeData.Count == 0) { authSafe = new ReadOnlyCollection <Pkcs12SafeContents>(Array.Empty <Pkcs12SafeContents>()); } else { Pkcs12SafeContents[] contentsArray = new Pkcs12SafeContents[authSafeData.Count]; for (int i = 0; i < contentsArray.Length; i++) { contentsArray[i] = new Pkcs12SafeContents(authSafeData[i]); } authSafe = new ReadOnlyCollection <Pkcs12SafeContents>(contentsArray); } bytesConsumed = encodedBytes.Length; return(new Pkcs12Info { AuthenticatedSafe = authSafe, IntegrityMode = mode, _decoded = pfx, _authSafeContents = authSafeBytes, }); }
public static ECDSAPublicKey ToPublicKey(this ReadOnlyMemory <byte> bytes) { return(bytes.ToArray().ToPublicKey()); }
public override ReadOnlyMemory <byte> Decrypt(ReadOnlyMemory <byte> cipher, KerberosKey key, KeyUsage usage) { return(cipher.ToArray()); }
protected override void DecodePacket() { _reader.Position = 0; Header = new InternalDatagramHeader(ReadByte()); Header.DatagramSequenceNumber = ReadLittle(); // End datagram, online packet starts Messages = new List <Packet>(); while (!_reader.Eof) { byte flags = ReadByte(); var header = new ReliabilityHeader(); //header.ReliableMessageNumber header.Reliability = (Reliability)((flags & 0b011100000) >> 5); header.HasSplit = (flags & 0b00010000) > 0; short dataBitLength = ReadShort(true); switch (header.Reliability) { case Reliability.Reliable: case Reliability.ReliableSequenced: case Reliability.ReliableOrdered: header.ReliableMessageNumber = ReadLittle(); break; } switch (header.Reliability) { case Reliability.UnreliableSequenced: case Reliability.ReliableSequenced: header.SequencingIndex = ReadLittle(); break; } switch (header.Reliability) { case Reliability.UnreliableSequenced: case Reliability.ReliableSequenced: case Reliability.ReliableOrdered: case Reliability.ReliableOrderedWithAckReceipt: header.OrderingIndex = ReadLittle(); header.OrderingChannel = ReadByte(); // flags break; } if (header.HasSplit) { header.PartCount = ReadInt(true); header.PartId = ReadShort(true); header.PartIndex = ReadInt(true); } // Slurp the payload int messageLength = (int)Math.Ceiling((((double)dataBitLength) / 8)); ReadOnlyMemory <byte> internalBuffer = Slice(messageLength); if (internalBuffer.Length != messageLength) { Log.Error($"Didn't get expected length {internalBuffer.Length}"); } if (internalBuffer.Length == 0) { continue; //Log.Error($"Read length {internalBuffer.Length}, expected {messageLength}"); } if (messageLength == 0) { continue; } //if(header.Reliability != Reliability.ReliableOrdered) Log.Error($"Parsing message {internalBuffer.Span[0]} with reliability={header.Reliability}"); if (header.HasSplit) { var splitPartPacket = SplitPartPacket.CreateObject(); splitPartPacket.ReliabilityHeader = header; splitPartPacket.Id = internalBuffer.Span[0]; splitPartPacket.Message = internalBuffer; Messages.Add(splitPartPacket); if (Log.IsDebugEnabled && _reader.Position < _reader.Length) { Log.Debug($"Got split message, but more to read {_reader.Length - _reader.Position}"); } } else { byte id = internalBuffer.Span[0]; Packet packet = PacketFactory.Create(id, internalBuffer, "raknet") ?? new UnknownPacket(id, internalBuffer.ToArray()); packet.ReliabilityHeader = header; Messages.Add(packet); } if (Log.IsDebugEnabled && messageLength != internalBuffer.Length) { Log.Debug("Mismatch of requested length, and actual read length"); } } }
public async ValueTask <IChunk> GetOrAddChunk(ChunkColumnManager columnManager, ChunkPosition chunkPosition) { IChunkColumn column = await ColumnProvider.GetOrAddChunkColumn(columnManager, chunkPosition.Column).Unchain(); if (column.TryGetChunk(chunkPosition.Y, out IChunk? loadedChunk)) { return(loadedChunk); } if (column is not LocalChunkColumn localColumn) { throw new InvalidOperationException(); } Dictionary <int, NbtElement>?chunksToDecode = localColumn._chunksToDecode; if (chunksToDecode != null) { NbtElement chunkElement; bool hasElement = false; lock (chunksToDecode) { hasElement = chunksToDecode.Remove(chunkPosition.Y, out chunkElement); } if (hasElement) { // TODO: move to a Anvil chunk parser LocalChunk chunk; if (chunkElement.TryGetCompoundElement("BlockStates", out NbtElement blockStatesNbt) && chunkElement.TryGetCompoundElement("Palette", out NbtElement paletteNbt)) { IndirectBlockPalette palette = ParsePalette(columnManager.GlobalBlockPalette, paletteNbt); chunk = new LocalChunk(column, chunkPosition.Y, palette, columnManager.Air); if (palette.Count == 1 && palette.BlockForId(0) == columnManager.Air) { chunk.FillBlock(columnManager.Air); } else { ReadOnlyMemory <byte> blockStateRawData = blockStatesNbt.GetArrayData(out NbtType blockStateDataType); if (blockStateDataType != NbtType.LongArray) { throw new InvalidDataException(); } SetBlocksFromData(chunk, palette, MemoryMarshal.Cast <byte, ulong>(blockStateRawData.Span)); } if (chunkElement.TryGetCompoundElement("BlockLight", out NbtElement blockLightNbt)) { ReadOnlyMemory <byte> blockLightData = blockLightNbt.GetArrayData(out NbtType blockLightDataType); if (blockLightDataType != NbtType.ByteArray) { throw new InvalidDataException(); } chunk.BlockLight = blockLightData.ToArray(); } if (chunkElement.TryGetCompoundElement("SkyLight", out NbtElement skyLightNbt)) { ReadOnlyMemory <byte> skyLightData = skyLightNbt.GetArrayData(out NbtType skyLightDataType); if (skyLightDataType != NbtType.ByteArray) { throw new InvalidDataException(); } chunk.SkyLight = skyLightData.ToArray(); } } else { chunk = new LocalChunk(column, chunkPosition.Y, columnManager.GlobalBlockPalette, columnManager.Air); chunk.FillBlock(chunk.AirBlock); chunk.SkyLight = new byte[2048]; chunk.SkyLight.AsSpan().Fill(255); } lock (chunksToDecode) { localColumn._chunksToDecodeRefCount--; if (localColumn._chunksToDecodeRefCount == 0) { // TODO: fix //localColumn._encodedColumn?.Dispose(); localColumn._encodedColumn = null; } } return(chunk); } } return(await GenerateChunk(column, chunkPosition.Y).Unchain()); }
internal static dynamic DeserializeType(ReadOnlyMemory <byte> bytes, Type type) { if (type == typeof(Fr)) { return(Fr.FromBytes(bytes.ToArray())); } if (type == typeof(G1)) { return(G1.FromBytes(bytes.ToArray())); } if (type == typeof(G2)) { return(G2.FromBytes(bytes.ToArray())); } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return(bytes.Span[0] != 0); case TypeCode.SByte: return((sbyte)bytes.Span[0]); case TypeCode.Byte: return(bytes.Span[0]); case TypeCode.UInt16: return(bytes.Span.ToUInt16()); case TypeCode.Int16: return(bytes.Span.ToInt16()); case TypeCode.UInt32: return(bytes.Span.ToUInt32()); case TypeCode.Int32: return(bytes.Span.ToInt32()); case TypeCode.UInt64: return(bytes.Span.ToUInt64()); case TypeCode.Int64: return(bytes.Span.ToInt64()); case TypeCode.Object: return(( type.GetMethod("FromBytes") ?? throw new InvalidOperationException($"Cannot deserialize type {type} without FromBytes method") ).Invoke(null, new object[] { bytes })); case TypeCode.Single: case TypeCode.String: case TypeCode.Char: case TypeCode.DateTime: case TypeCode.DBNull: case TypeCode.Decimal: case TypeCode.Double: case TypeCode.Empty: throw new ArgumentOutOfRangeException(); default: throw new ArgumentOutOfRangeException(); } }
private string DeserializeMessage(ReadOnlyMemory <byte> body, string routingKey) { var message = Encoding.UTF8.GetString(body.ToArray()); return(message); }
public override string ToBase64(ReadOnlyMemory <byte> value) { return(MemoryMarshal.TryGetArray(value, out var segment) ? Convert.ToBase64String(segment.Array, 0, segment.Count) : Convert.ToBase64String(value.ToArray())); }
private object?DoDeserialize(ReadOnlyMemory <byte> data, uint flags) { if (flags == RawDataFlag // check if unknown flag || ((flags & (FlagPrefix + 0xff)) != flags)) { return(data.ToArray()); } var code = (TypeCode)(flags & 0xff); var span = data.Span; #pragma warning disable IDE0049 // readability switch (code) { case TypeCode.Object: if (!MemoryMarshal.TryGetArray(data, out var segment)) { throw new SerializationException("Cannot deserialize object, MemoryMarshal was not able to get the byte[] of the buffer."); // TODO dump the first 16-32 bytes into the exception } using (var ms = new MemoryStream(segment.Array, segment.Offset, segment.Count, false)) return(new BinaryFormatter().Deserialize(ms)); case TypeCode.DBNull: return(null); // incrementing a non-existing key then getting it // returns as a string, but the flag will be 0 // so treat all 0 flagged items as string // this may help inter-client data management as well case TypeCode.Empty: case TypeCode.String: return(Utf8NoBom.GetString(span)); case TypeCode.SByte: return((SByte)span[0]); case TypeCode.Byte: return(span[0]); case TypeCode.Boolean: return(span[0] != FALSE); case TypeCode.Char: return((char)BinaryPrimitives.ReadUInt16LittleEndian(span)); case TypeCode.Int16: return(BinaryPrimitives.ReadInt16LittleEndian(span)); case TypeCode.Int32: return(BinaryPrimitives.ReadInt32LittleEndian(span)); case TypeCode.Int64: return(BinaryPrimitives.ReadInt64LittleEndian(span)); case TypeCode.UInt16: return(BinaryPrimitives.ReadUInt16LittleEndian(span)); case TypeCode.UInt32: return(BinaryPrimitives.ReadUInt32LittleEndian(span)); case TypeCode.UInt64: return(BinaryPrimitives.ReadUInt64LittleEndian(span)); case TypeCode.DateTime: return(DateTime.FromBinary(BinaryPrimitives.ReadInt64LittleEndian(span))); case TypeCode.Single: #if !NETSTANDARD2_0 return(BitConverter.ToSingle(span)); #else return(BitConverter.ToSingle(span.ToArray(), 0)); #endif case TypeCode.Double: #if !NETSTANDARD2_0 return(BitConverter.ToDouble(span)); #else return(BitConverter.ToDouble(span.ToArray(), 0)); #endif case TypeCode.Decimal: var bits = new int[4]; bits[0] = BinaryPrimitives.ReadInt32LittleEndian(span); bits[1] = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(sizeof(Int32))); bits[2] = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(sizeof(Int32) + sizeof(Int32))); bits[3] = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(sizeof(Int32) + sizeof(Int32) + sizeof(Int32))); return(new Decimal(bits)); } #pragma warning restore IDE0049 return(data.ToArray()); }
/// <summary> /// Convert the <see cref="ReadOnlyMemory{byte}"/> data to UTF8 string representation. /// </summary> /// <param name="buffer"><see cref="ReadOnlyMemory{byte}"/> instance.</param> /// <returns>Returns the UTF8 string representation.</returns> public static string GetString(this ReadOnlyMemory <byte> buffer) { return(ByteExtensions.GetString(buffer.ToArray())); }
public async Task SendAsync(ReadOnlyMemory <byte> memory) { await hubConnection.SendAsync("BrowserMethod", memory.ToArray()); }
/// <summary> /// Compare this <see cref="byte"/> array to another. /// </summary> /// <param name="buffer"><see cref="byte"/> array instance.</param> /// <param name="other"><see cref="ReadOnlyMemory{byte}"/> buffer to compare.</param> /// <returns>Returns true if both instances has equal values.</returns> public static bool Compare(this byte[] buffer, ReadOnlyMemory <byte> other) { return(buffer.Compare(other.ToArray())); }
public static string ToJson(ReadOnlyMemory <byte> bytes) { var byteArray = bytes.ToArray(); return(Encoding.UTF8.GetString(byteArray)); }
/// <summary> /// Converts this <see cref="ByteString"/> into a byte array. /// </summary> /// <remarks>The data is copied - changes to the returned array will not be reflected in this <c>ByteString</c>.</remarks> /// <returns>A byte array with the same data as this <c>ByteString</c>.</returns> public byte[] ToByteArray() { return(bytes.ToArray()); }
static void Main() { System.Console.WriteLine("Starting Serial service"); //Thread.Sleep(20000); // Wait 10 seconds for RabbitMQ to startup Console.WriteLine("Serial service started"); // Create RabbitMQ channel for serial service ConnectionFactory serialServiceFactory = new ConnectionFactory() { HostName = "localhost" }; //ConnectionFactory serialServiceFactory = new ConnectionFactory() { HostName = "rabbitmq", Port = 5672 }; using IConnection serialServiceConnection = serialServiceFactory.CreateConnection(); using IModel serialServiceChannel = serialServiceConnection.CreateModel(); SerialPortModel serialPortModel = new SerialPortModel(null, null); #region Events // Triggered when data is sent serialPortModel.DataSent += (data) => { string message = "serial-data-sent-###" + string.Join(",", data.Select(p => p.ToString("X"))); byte[] body = Encoding.UTF8.GetBytes(message); // Produce message serialServiceChannel.BasicPublish(exchange: "", routingKey: "serial-service-producer", basicProperties: null, body: body); }; // Triggered when data is received serialPortModel.DataReceived += (data) => { string message = "serial-data-received-###" + string.Join(",", data.Select(p => p.ToString("X"))); //string message = "serial-data-received-###" + string.Join(",", data.Select(p => p.ToString()).ToArray()); byte[] body = Encoding.UTF8.GetBytes(message); // Produce message serialServiceChannel.BasicPublish(exchange: "", routingKey: "serial-service-producer", basicProperties: null, body: body); }; // Triggered when port is opened serialPortModel.OpenedPort += () => { string message = "serial-opened"; byte[] body = Encoding.UTF8.GetBytes(message); // Produce message serialServiceChannel.BasicPublish(exchange: "", routingKey: "serial-service-producer", basicProperties: null, body: body); }; // Triggered when port is closed serialPortModel.ClosedPort += () => { string message = "serial-closed"; byte[] body = Encoding.UTF8.GetBytes(message); // Produce message serialServiceChannel.BasicPublish(exchange: "", routingKey: "serial-service-producer", basicProperties: null, body: body); }; // Triggered when there is an error on the port serialPortModel.PortError += (sender, args) => { string message = "serial-error-###xxx"; byte[] body = Encoding.UTF8.GetBytes(message); // Produce message serialServiceChannel.BasicPublish(exchange: "", routingKey: "serial-service-producer", basicProperties: null, body: body); }; #endregion #region Create RabbitMQ Producer // Creates queue serialServiceChannel.QueueDeclare(queue: "serial-service-producer", durable: false, exclusive: false, autoDelete: false, arguments: null); #endregion #region Create RabbitMQ Consumer // Create/Use serial-messages queue serialServiceChannel.QueueDeclare(queue: "serial-service-consumer", durable: false, exclusive: false, autoDelete: false, arguments: null); // Create a consumer EventingBasicConsumer serialServiceConsumer = new EventingBasicConsumer(serialServiceChannel); // Callback for received/consumed messages serialServiceConsumer.Received += (model, ea) => { ReadOnlyMemory <byte> body = ea.Body; string message = Encoding.UTF8.GetString(body.ToArray()); message = message.ToLower().Replace("server processed ", ""); if (message.StartsWith("serial-")) { // The type of message string[] commands = message.Split('-'); // Data carried by the message string parameters; switch (commands[1]) { case "open": // Open the serial port parameters = message.Split("###")[1].Replace(" ", string.Empty).Trim(); string[] arguments = parameters.Split(','); byte comPort = 0; int baudRate = 9600; Parity parity = Parity.None; int dataBits = 8; StopBits stopBits = StopBits.One; foreach (string arg in arguments) { string[] components = arg.Split(':'); switch (components[0]) { case "comport": comPort = byte.Parse(components[1]); break; case "baudrate": baudRate = int.Parse(components[1]); break; case "parity": string parityOption = components[1]; switch (parityOption.ToLower()) { case "even": parity = Parity.Even; break; case "mark": parity = Parity.Mark; break; case "none": parity = Parity.None; break; case "odd": parity = Parity.Odd; break; case "space": parity = Parity.Space; break; default: break; } break; case "databits": dataBits = int.Parse(components[1]); break; case "stopbits": string stopBitsOption = components[1]; switch (stopBitsOption) { case "none": stopBits = StopBits.None; break; case "one": stopBits = StopBits.One; break; case "onepointfive": stopBits = StopBits.OnePointFive; break; case "two": stopBits = StopBits.Two; break; default: break; } break; default: break; } } if (!serialPortModel.IsOpen) { serialPortModel.OpenPort(comPort: comPort, baudRate: baudRate, parity: parity, dataBits: dataBits, stopBits: stopBits); } System.Console.WriteLine(message); break; case "close": // Close the serial port if (serialPortModel.IsOpen) { serialPortModel.ClosePort(); } System.Console.WriteLine(message); break; case "stx": // Set the start characters of the frame parameters = message.Split("###")[1]; string[] stxStringBytes = parameters.Replace(" ", string.Empty).Trim().Split(','); byte[] stxbytes = Array.ConvertAll(stxStringBytes, element => { return(byte.Parse(element, System.Globalization.NumberStyles.HexNumber)); }); serialPortModel.STX = stxbytes; System.Console.WriteLine(message); break; case "etx": // Set the end characters of the frame parameters = message.Split("###")[1]; string[] etxStringBytes = parameters.Replace(" ", string.Empty).Trim().Split(','); byte[] etxBytes = Array.ConvertAll(etxStringBytes, element => { return(byte.Parse(element, System.Globalization.NumberStyles.HexNumber)); }); serialPortModel.ETX = etxBytes; System.Console.WriteLine(message); break; case "message": // A message to be sent parameters = message.Split("###")[1]; string[] messageStringBytes = parameters.Replace(" ", string.Empty).Trim().Split(','); byte[] messageBytes = Array.ConvertAll(messageStringBytes, element => { return(byte.Parse(element, System.Globalization.NumberStyles.HexNumber)); }); serialPortModel.WriteSerialData(messageBytes); System.Console.WriteLine(message); break; default: break; } } }; // Start consumer serialServiceChannel.BasicConsume(queue: "serial-service-consumer", autoAck: true, consumer: serialServiceConsumer); #endregion while (true) { ; } }
public static AmqpMessage SBMessageToAmqpMessage(ServiceBusMessage sbMessage) { // body var amqpMessage = sbMessage.ToAmqpMessage(); // properties amqpMessage.Properties.MessageId = sbMessage.MessageId; amqpMessage.Properties.CorrelationId = sbMessage.CorrelationId; amqpMessage.Properties.ContentType = sbMessage.ContentType; amqpMessage.Properties.ContentEncoding = sbMessage.AmqpMessage.Properties.ContentEncoding; amqpMessage.Properties.Subject = sbMessage.Subject; amqpMessage.Properties.To = sbMessage.To; amqpMessage.Properties.ReplyTo = sbMessage.ReplyTo; amqpMessage.Properties.GroupId = sbMessage.SessionId; amqpMessage.Properties.ReplyToGroupId = sbMessage.ReplyToSessionId; amqpMessage.Properties.GroupSequence = sbMessage.AmqpMessage.Properties.GroupSequence; if (sbMessage.AmqpMessage.Properties.UserId.HasValue) { ReadOnlyMemory <byte> userId = sbMessage.AmqpMessage.Properties.UserId.Value; if (MemoryMarshal.TryGetArray(userId, out ArraySegment <byte> segment)) { amqpMessage.Properties.UserId = segment; } else { amqpMessage.Properties.UserId = new ArraySegment <byte>(userId.ToArray()); } } // If TTL is set, it is used to calculate AbsoluteExpiryTime and CreationTime if (sbMessage.TimeToLive != TimeSpan.MaxValue) { amqpMessage.Header.Ttl = (uint)sbMessage.TimeToLive.TotalMilliseconds; amqpMessage.Properties.CreationTime = DateTime.UtcNow; if (AmqpConstants.MaxAbsoluteExpiryTime - amqpMessage.Properties.CreationTime.Value > sbMessage.TimeToLive) { amqpMessage.Properties.AbsoluteExpiryTime = amqpMessage.Properties.CreationTime.Value + sbMessage.TimeToLive; } else { amqpMessage.Properties.AbsoluteExpiryTime = AmqpConstants.MaxAbsoluteExpiryTime; } } else { if (sbMessage.AmqpMessage.Properties.CreationTime.HasValue) { amqpMessage.Properties.CreationTime = sbMessage.AmqpMessage.Properties.CreationTime.Value.UtcDateTime; } if (sbMessage.AmqpMessage.Properties.AbsoluteExpiryTime.HasValue) { amqpMessage.Properties.AbsoluteExpiryTime = sbMessage.AmqpMessage.Properties.AbsoluteExpiryTime.Value.UtcDateTime; } } // message annotations foreach (KeyValuePair <string, object> kvp in sbMessage.AmqpMessage.MessageAnnotations) { switch (kvp.Key) { case AmqpMessageConstants.ScheduledEnqueueTimeUtcName: if ((sbMessage.ScheduledEnqueueTime != null) && sbMessage.ScheduledEnqueueTime > DateTimeOffset.MinValue) { amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.ScheduledEnqueueTimeUtcName, sbMessage.ScheduledEnqueueTime.UtcDateTime); } break; case AmqpMessageConstants.PartitionKeyName: if (sbMessage.PartitionKey != null) { amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.PartitionKeyName, sbMessage.PartitionKey); } break; case AmqpMessageConstants.ViaPartitionKeyName: if (sbMessage.TransactionPartitionKey != null) { amqpMessage.MessageAnnotations.Map.Add(AmqpMessageConstants.ViaPartitionKeyName, sbMessage.TransactionPartitionKey); } break; default: amqpMessage.MessageAnnotations.Map.Add(kvp.Key, kvp.Value); break; } } // application properties if (sbMessage.ApplicationProperties != null && sbMessage.ApplicationProperties.Count > 0) { if (amqpMessage.ApplicationProperties == null) { amqpMessage.ApplicationProperties = new ApplicationProperties(); } foreach (KeyValuePair <string, object> pair in sbMessage.ApplicationProperties) { if (TryGetAmqpObjectFromNetObject(pair.Value, MappingType.ApplicationProperty, out var amqpObject)) { amqpMessage.ApplicationProperties.Map.Add(pair.Key, amqpObject); } else { throw new NotSupportedException(Resources.InvalidAmqpMessageProperty.FormatForUser(pair.Key.GetType())); } } } // delivery annotations foreach (KeyValuePair <string, object> kvp in sbMessage.AmqpMessage.DeliveryAnnotations) { if (TryGetAmqpObjectFromNetObject(kvp.Value, MappingType.ApplicationProperty, out var amqpObject)) { amqpMessage.DeliveryAnnotations.Map.Add(kvp.Key, amqpObject); } } // header - except for ttl which is set above with the properties if (sbMessage.AmqpMessage.Header.DeliveryCount != null) { amqpMessage.Header.DeliveryCount = sbMessage.AmqpMessage.Header.DeliveryCount; } if (sbMessage.AmqpMessage.Header.Durable != null) { amqpMessage.Header.Durable = sbMessage.AmqpMessage.Header.Durable; } if (sbMessage.AmqpMessage.Header.FirstAcquirer != null) { amqpMessage.Header.FirstAcquirer = sbMessage.AmqpMessage.Header.FirstAcquirer; } if (sbMessage.AmqpMessage.Header.Priority != null) { amqpMessage.Header.Priority = sbMessage.AmqpMessage.Header.Priority; } // footer foreach (KeyValuePair <string, object> kvp in sbMessage.AmqpMessage.Footer) { amqpMessage.Footer.Map.Add(kvp.Key, kvp.Value); } return(amqpMessage); }
public static void AsReadOnlyMemory_ToArray_Roundtrips(string input) { ReadOnlyMemory <char> m = input.AsReadOnlyMemory(); Assert.Equal(input, new string(m.ToArray())); }