public void TestIMessagePackSerializerPackTo_ObjectTreeIsNull_ReferenceType_AsNil() { IMessagePackSerializer target = CreateTarget <string>(); using (var buffer = new MemoryStream()) using (var packer = Packer.Create(buffer)) { target.PackTo(packer, null); Assert.That(buffer.ToArray(), Is.EqualTo(new byte[] { 0xC0 })); } }
public void TestIMessagePackSerializerPackTo_Valid_Success() { IMessagePackSerializer target = CreateTarget <int>(); using (var buffer = new MemoryStream()) using (var packer = Packer.Create(buffer)) { target.PackTo(packer, 1); Assert.That(buffer.ToArray(), Is.EqualTo(new byte[] { 0x1 })); } }
public FluentdEmitter(Stream stream) { this.destination = stream; // PackerCompatibilityOptions.ProhibitExtendedTypeObjects must be turned off in order to use the PackExtendedTypeValue method this.packer = Packer.Create(destination, Packer.DefaultCompatibilityOptions & ~PackerCompatibilityOptions.ProhibitExtendedTypeObjects); var embeddedContext = new SerializationContext(this.packer.CompatibilityOptions); embeddedContext.Serializers.Register(new OrdinaryDictionarySerializer(embeddedContext, null)); this.serializationContext = new SerializationContext(PackerCompatibilityOptions.PackBinaryAsRaw); this.serializationContext.Serializers.Register(new OrdinaryDictionarySerializer(this.serializationContext, embeddedContext)); }
public static string Request(string input) { // prepare Socket var nanoSock = new NanomsgSocket(Domain.SP, Protocol.REQ); string result = null; bool messageReceived = false; // prepare Listener var listener = new NanomsgListener(); listener.ReceivedMessage += (sockedId) => { using (NanomsgReadStream inStream = nanoSock.ReceiveStream()) using (var unpacker = Unpacker.Create(inStream)) { string output; if (!unpacker.ReadString(out output)) { throw new Exception("REP invalid"); } result = output; } messageReceived = true; }; // Connect and Send Request listener.AddSocket(nanoSock); nanoSock.Connect("tcp://127.0.0.1:" + reqPort); using (NanomsgWriteStream outStream = nanoSock.CreateSendStream()) using (var packer = Packer.Create(outStream)) { packer.PackString(input); nanoSock.SendStream(outStream); } var start = DateTime.Now; while (!messageReceived && start + TimeSpan.FromSeconds(30) > DateTime.Now) { listener.Listen(TimeSpan.FromMilliseconds(250)); } listener.RemoveSocket(nanoSock); nanoSock.Dispose(); if (!messageReceived) { throw new Exception("REQ timed out"); } return(result); }
public void TestDispatch_MethodExists_Success() { var svcFile = ".\\Services.svc"; File.WriteAllText( svcFile, String.Format(CultureInfo.InvariantCulture, "<% @ ServiceHost Service=\"{0}\" %>", typeof(TestService).FullName) ); try { var configuration = new RpcServerConfiguration(); configuration.ServiceTypeLocatorProvider = conf => new FileBasedServiceTypeLocator(); using (var server = new RpcServer(configuration)) using (var transportManager = new NullServerTransportManager(server)) using (var transport = new NullServerTransport(transportManager)) using (var requestContext = DispatchTestHelper.CreateRequestContext()) using (var argumentsBuffer = new MemoryStream()) using (var waitHandle = new ManualResetEventSlim()) { var message = Guid.NewGuid().ToString(); using (var argumentsPacker = Packer.Create(argumentsBuffer, false)) { argumentsPacker.PackArrayHeader(1); argumentsPacker.Pack(message); } argumentsBuffer.Position = 0; var target = new LocatorBasedDispatcher(server); MessagePackObject response = MessagePackObject.Nil; requestContext.MethodName = "Echo:TestService:1"; requestContext.MessageId = 1; requestContext.SetTransport(transport); requestContext.ArgumentsUnpacker = Unpacker.Create(argumentsBuffer); transport.Sent += (sender, e) => { response = Unpacking.UnpackString(e.Context.GetReturnValueData()).Value; waitHandle.Set(); }; target.Dispatch(transport, requestContext); Assert.That(waitHandle.Wait(TimeSpan.FromSeconds(1))); Assert.That(message == response, "{0} != {1}", message, response); } } finally { File.Delete(svcFile); } }
public byte[] Serialize(VentMessage msg) { using (var stream = new MemoryStream()) { var packer = Packer.Create(stream); packer.Pack(msg.Source); packer.Pack(msg.Name); packer.Pack(msg.MessageType); packer.Pack(msg.Timestamp); return(stream.ToArray()); } }
public static void Serialize(IRequestContext requestContext, object dto, Stream outputStream) { if (dto == null) return; try { var serializer = MessagePackSerializer.Create(dto.GetType()); serializer.PackTo(Packer.Create(outputStream), dto); } catch (Exception ex) { HandleException(ex, dto.GetType()); } }
/// <summary> /// Serializes specified object to the <see cref="T:System.IO.Stream" /> asynchronously. /// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <param name="stream"></param> /// <param name="packerCompatibilityOptions"></param> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> is <c>null</c>. /// </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException"> /// Failed to serialize object. /// </exception> /// <seealso cref="P:Capabilities" /> public static async Task PackAsync(Type type, object?value, Stream?stream, PackerCompatibilityOptions packerCompatibilityOptions = PackerCompatibilityOptions.None, CancellationToken cancellationToken = default) { if (stream is null) { return; } var packer = Packer.Create(stream, packerCompatibilityOptions); await MessagePackSerializer.Get(type).PackToAsync(packer, value, cancellationToken); stream.TrySeek(0, SeekOrigin.Begin); }
private void EndState() { _mState = _mState.Parent; if (_mState == null) { Packer packer = Packer.Create(_mStream, PackerCompatibilityOptions.None); _mDocument.Pack(packer); } }
internal override void ClearBuffers() { this._methodNameBuffer.SetLength(0); this._argumentsBuffer.SetLength(0); this.SocketContext.BufferList = null; this._argumentsPacker.Dispose(); this._argumentsPacker = Packer.Create(this._argumentsBuffer, false); this.SendingBuffer[0] = new ArraySegment <byte>(); this.SendingBuffer[1] = new ArraySegment <byte>(); this.SendingBuffer[2] = new ArraySegment <byte>(); this.SendingBuffer[3] = new ArraySegment <byte>(); base.ClearBuffers(); }
/// <summary> /// Prepares this instance to send request or notification message. /// </summary> internal void Prepare(bool canUseChunkedBuffer) { if (this._messageType == MessageType.Response) { throw new InvalidOperationException("MessageType is not set."); } Contract.Assert(this._methodName != null); using (var packer = Packer.Create(this._methodNameBuffer, false)) { packer.Pack(this._methodName); } if (this._messageType == MessageType.Request) { Contract.Assert(this.MessageId != null); Contract.Assert(this._requestCompletionCallback != null); this.SendingBuffer[0] = _requestHeader; this.SendingBuffer[1] = this.GetPackedMessageId(); this.SendingBuffer[2] = new ArraySegment <byte>(this._methodNameBuffer.GetBuffer(), 0, unchecked (( int )this._methodNameBuffer.Length)); this.SendingBuffer[3] = new ArraySegment <byte>(this._argumentsBuffer.GetBuffer(), 0, unchecked (( int )this._argumentsBuffer.Length)); } else { Contract.Assert(this._notificationCompletionCallback != null); this.SendingBuffer[0] = _notificationHeader; this.SendingBuffer[1] = new ArraySegment <byte>(this._methodNameBuffer.GetBuffer(), 0, unchecked (( int )this._methodNameBuffer.Length)); this.SendingBuffer[2] = new ArraySegment <byte>(this._argumentsBuffer.GetBuffer(), 0, unchecked (( int )this._argumentsBuffer.Length)); this.SendingBuffer[3] = _emptyBuffer; } #if MONO if (!canUseChunkedBuffer) { this._unifiedSendingBuffer.Position = 0; this._unifiedSendingBuffer.SetLength(0); this._unifiedSendingBuffer.Write(this.SendingBuffer[0].Array, this.SendingBuffer[0].Offset, this.SendingBuffer[0].Count); this._unifiedSendingBuffer.Write(this.SendingBuffer[1].Array, this.SendingBuffer[1].Offset, this.SendingBuffer[1].Count); this._unifiedSendingBuffer.Write(this.SendingBuffer[2].Array, this.SendingBuffer[2].Offset, this.SendingBuffer[2].Count); this._unifiedSendingBuffer.Write(this.SendingBuffer[3].Array, this.SendingBuffer[3].Offset, this.SendingBuffer[3].Count); this.SocketContext.SetBuffer(this._unifiedSendingBuffer.GetBuffer(), 0, unchecked (( int )this._unifiedSendingBuffer.Length)); this.SocketContext.BufferList = null; return; } #endif this.SocketContext.SetBuffer(null, 0, 0); this.SocketContext.BufferList = this.SendingBuffer; }
public void TestCreate_OwnsStreamIsTrue_StreamIsClosed() { using (var stream = new MemoryStream()) { using (var packer = Packer.Create(stream, true)) { } try { stream.ReadByte(); Assert.Fail(); } catch (ObjectDisposedException) { } } }
/// <summary> /// Initializes a new instance of the <see cref="ClientRequestContext"/> class with specified configuration. /// </summary> /// <param name="configuration"> /// An <see cref="RpcClientConfiguration"/> to tweak this instance initial state. /// </param> public ClientRequestContext(RpcClientConfiguration configuration) { this._methodNameBuffer = new MemoryStream((configuration ?? RpcClientConfiguration.Default).InitialMethodNameBufferLength); this._argumentsBuffer = new MemoryStream((configuration ?? RpcClientConfiguration.Default).InitialArgumentsBufferLength); this.SendingBuffer = new ArraySegment <byte> [4]; #if MONO this._unifiedSendingBuffer = new MemoryStream((configuration ?? RpcClientConfiguration.Default).InitialReceiveBufferLength); #endif this._argumentsPacker = Packer.Create(this._argumentsBuffer, false); this._messageType = MessageType.Response; this._stopwatch = new Stopwatch(); }
public static void Pack(this MessagePackSerializer source, Stream stream, object objectTree, PackerCompatibilityOptions packerCompatibilityOptions) { if (source == null) { throw new ArgumentNullException("source"); } if (stream == null) { throw new ArgumentNullException("stream"); } // Packer does not have finalizer, so just avoiding packer disposing prevents stream closing. source.PackTo(Packer.Create(stream, packerCompatibilityOptions), objectTree); }
protected internal override void PackToCore(Packer packer, T objectTree) { using (var buffer = new MemoryStream()) { using (var valuePacker = Packer.Create(buffer, this.PackerCompatibilityOptions, false)) { this.GetActualTypeSerializer(objectTree.GetType()).PackTo(valuePacker, objectTree); } packer.PackExtendedTypeValue( this._typeCodeMap[objectTree.GetType().TypeHandle], buffer.ToArray() ); } }
public static byte[] ObjToBytes(object obj) { if (obj == null) { return(null); } Type type = obj.GetType(); IMessagePackSerializer ser = serDic.GetOrAdd(type, MessagePackSerializer.Create(type)); MemoryStream stream = new MemoryStream(); ser.PackTo(Packer.Create(stream), obj); byte[] data = stream.ToArray(); return(data); }
/// <summary> /// Clears this instance internal buffers for reuse. /// </summary> internal sealed override void Clear() { this.ClearBuffers(); this._errorDataBuffer.SetLength(0); this._returnDataBuffer.SetLength(0); this.SocketContext.BufferList = null; this.SendingBuffer[1] = default(ArraySegment <byte>); this.SendingBuffer[2] = default(ArraySegment <byte>); this.SendingBuffer[3] = default(ArraySegment <byte>); this._returnDataPacker.Dispose(); this._returnDataPacker = Packer.Create(this._returnDataBuffer, false); this._errorDataPacker.Dispose(); this._errorDataPacker = Packer.Create(this._errorDataBuffer, false); base.Clear(); }
/// <summary> /// Initializes a new instance of the <see cref="ServerResponseContext"/> class with specified configuration. /// </summary> /// <param name="configuration"> /// An <see cref="RpcServerConfiguration"/> to tweak this instance initial state. /// </param> public ServerResponseContext(RpcServerConfiguration configuration) { this._errorDataBuffer = new MemoryStream((configuration ?? RpcServerConfiguration.Default).InitialErrorBufferLength); this._returnDataBuffer = new MemoryStream((configuration ?? RpcServerConfiguration.Default).InitialReturnValueBufferLength); this.SendingBuffer = new ArraySegment <byte> [4]; this.SendingBuffer[0] = _responseHeader; #if MONO this._unifiedSendingBuffer = new MemoryStream((configuration ?? RpcServerConfiguration.Default).InitialReceiveBufferLength); this._unifiedSendingBuffer.Write(this.SendingBuffer[0].Array, this.SendingBuffer[0].Offset, this.SendingBuffer[0].Count); #endif this._returnDataPacker = Packer.Create(this._returnDataBuffer, false); this._errorDataPacker = Packer.Create(this._errorDataBuffer, false); }
public void Can_serialize_email_dto() { using (var ms = new MemoryStream()) { var serializer = MessagePackSerializer.Get(request.GetType()); serializer.PackTo(Packer.Create(ms), request); ms.Position = 0; var unpacker = Unpacker.Create(ms); unpacker.Read(); var response = serializer.UnpackFrom(unpacker); Assert.That(response.Equals(request)); } }
private void TestEnumForByName(SerializationContext context, Type builtType, params string[] builtMembers) { var serializer = context.GetSerializer(builtType); var value = Enum.Parse(builtType, String.Join(",", builtMembers)); using (var stream = new MemoryStream()) { serializer.PackTo(Packer.Create(stream, false), value); stream.Position = 0; var deserialized = serializer.Unpack(stream); Assert.That(deserialized, Is.EqualTo(value)); stream.Position = 0; Assert.That(Unpacking.UnpackString(stream), Is.EqualTo(value.ToString())); } }
private static ClientResponseContext CreateContext(RpcErrorMessage message) { var context = new ClientResponseContext(); using (var buffer = new MemoryStream()) using (var packer = Packer.Create(buffer, false)) { packer.Pack(message.Error.Identifier); context.ErrorBuffer = new ByteArraySegmentStream(new[] { new ArraySegment <byte>(buffer.ToArray()) }); buffer.SetLength(0); packer.Pack(message.Detail); context.ResultBuffer = new ByteArraySegmentStream(new[] { new ArraySegment <byte>(buffer.ToArray()) }); } return(context); }
/// <summary> /// Unpack array header of Arguments part on request/notification message. /// </summary> /// <param name="context">Context information.</param> /// <returns> /// <c>true</c>, if the pipeline is finished; /// <c>false</c>, the pipeline is interruppted because extra data is needed. /// </returns> private bool UnpackArgumentsHeader(ServerRequestContext context) { Contract.Assert(context != null); if (!context.ReadFromHeaderUnpacker()) { MsgPackRpcServerProtocolsTrace.TraceEvent( MsgPackRpcServerProtocolsTrace.NeedArgumentsArrayHeader, "Arguments array header is needed. {{ \"SessionID\" : {0} }}", context.SessionId ); return(false); } if (!context.HeaderUnpacker.IsArrayHeader) { this.HandleDeserializationError( context, "Invalid request/notify message stream. Arguments must be array.", () => context.UnpackingBuffer.ToArray() ); return(true); } // TODO: Avoid actual unpacking to improve performance. context.ArgumentsBufferUnpacker = context.HeaderUnpacker.ReadSubtree(); if (Int32.MaxValue < context.ArgumentsBufferUnpacker.ItemsCount) { this.HandleDeserializationError( context, RpcError.MessageTooLargeError, "Too many arguments.", context.ArgumentsBufferUnpacker.ItemsCount.ToString("#,0", CultureInfo.CurrentCulture), () => context.UnpackingBuffer.ToArray() ); return(true); } context.ArgumentsCount = unchecked (( int )(context.ArgumentsBufferUnpacker.ItemsCount)); context.ArgumentsBufferPacker = Packer.Create(context.ArgumentsBuffer, false); context.ArgumentsBufferPacker.PackArrayHeader(context.ArgumentsCount); context.UnpackedArgumentsCount = 0; context.NextProcess = this.UnpackArguments; return(context.NextProcess(context)); }
public MessagePackObject ExecuteCommand(string command, object[] args, string token = null) { Dictionary <string, object> message = new Dictionary <string, object>(); message["message"] = command; message["args"] = args; if (token != null) { message["token"] = token; } byte[] packed; using (MemoryStream stream = new MemoryStream()) { Packer packer = Packer.Create(stream); packer.PackMap(message); packed = stream.ToArray(); } byte[] packedLength = BitConverter.GetBytes(packed.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(packedLength); } _stream.Write(packedLength); _stream.Write(packed); byte[] respBytes = ReadMessage(_stream); MessagePackObjectDictionary resp = null; try { resp = Unpacking.UnpackObject(respBytes).Value.AsDictionary(); } catch { byte[] decompressed = DecompressData(respBytes); resp = Unpacking.UnpackObject(decompressed).Value.AsDictionary(); } return(resp.ContainsKey("obj") ? resp["obj"] : resp["exception"]); }
private byte[] SerializeInternal(string tag, object message) { var objects = new List <MessagePackObject>(3); // [ tag, timestamp, message ] objects.Add(tag); objects.Add(DateTimeOffset.Now.GetUnixTimestamp().TotalSeconds); objects.Add(CreateMessagePackObject(message)); using (var stream = new MemoryStream()) { var packer = Packer.Create(stream); packer.Pack(new MessagePackObject(objects)); return(stream.ToArray()); } }
private static void TestNonCollectionCore( Action <NilImplicationTestTarget> adjuster, Action <Packer, MessagePackObject, MessagePackObject, MessagePackObject, MessagePackObject, MessagePackObject> packing, MessagePackObject?memberDefault = null, MessagePackObject?nullButValueType = null, MessagePackObject?nullAndNullableValueType = null, MessagePackObject?nullAndReferenceType = null, MessagePackObject?prohibitReferenceType = null ) { using (var buffer = new MemoryStream()) using (var packer = Packer.Create(buffer)) { var serializer = MessagePackSerializer.Create <NilImplicationTestTarget>(new SerializationContext()); var target = new NilImplicationTestTarget(); if (adjuster != null) { adjuster(target); } packing( packer, memberDefault ?? target.MemberDefault, nullButValueType ?? target.NullButValueType, nullAndNullableValueType ?? (target.NullAndNullableValueType == null ? MessagePackObject.Nil : target.NullAndNullableValueType.Value), nullAndReferenceType ?? target.NullAndReferenceType, prohibitReferenceType ?? target.ProhibitReferenceType ); buffer.Position = 0; var result = serializer.Unpack(buffer); Assert.That(result.MemberDefault, Is.EqualTo(target.MemberDefault)); Assert.That(result.NullButValueType, Is.EqualTo(target.NullButValueType)); Assert.That(result.NullAndNullableValueType, Is.EqualTo(target.NullAndNullableValueType)); Assert.That(result.NullAndReferenceType, Is.EqualTo(target.NullAndReferenceType)); Assert.That(result.ProhibitReferenceType, Is.EqualTo(target.ProhibitReferenceType)); var expectedBytes = buffer.ToArray(); using (var actual = new MemoryStream()) { serializer.Pack(actual, target); } } }
/// <summary> /// Makes an async request /// </summary> /// <param name="type">Type of request</param> /// <param name="method">Method name</param> /// <param name="parameters">Method parameters</param> /// <param name="returnValue">Does it return?</param> /// <returns></returns> public async Task <MessagePackObject[]> RequestAsync(int type, string method, object[] parameters, bool returnValue = true) { MemoryStream package = new MemoryStream(); Packer packer = Packer.Create(package); packer.PackArrayHeader(4); packer.Pack(type); packer.Pack(_msgId); packer.PackString(method); packer.PackArrayHeader(parameters.Length); if (parameters.Length > 0) { foreach (var param in parameters) { packer.Pack(param); } } string temp; package.Position = 0; using (StreamReader sr = new StreamReader(package, Encoding.Default)) { temp = sr.ReadToEnd(); } int id = _msgId; if (returnValue) { tcs.Add(id, new TaskCompletionSource <MessagePackObject[]>()); } _standardInput.Write(temp); _msgId++; if (!returnValue) { return(null); } MessagePackObject[] result = await tcs[id].Task.ConfigureAwait(false); tcs.Remove(id); return(result); }
private static void InitializeBuffers(ServerRequestContext target) { target.ArgumentsBuffer.WriteByte(1); target.ArgumentsBufferPacker = Packer.Create(target.ArgumentsBuffer, false); target.ArgumentsBufferUnpacker = Unpacker.Create(target.ArgumentsBuffer, false); target.ArgumentsCount = 2; target.UnpackingBuffer = new ByteArraySegmentStream(target.ReceivedData); target.UnpackedArgumentsCount = 3; target.RootUnpacker = Unpacker.Create(target.UnpackingBuffer, false); target.HeaderUnpacker = Unpacker.Create(target.UnpackingBuffer, false); target.ArgumentsUnpacker = Unpacker.Create(target.UnpackingBuffer, false); target.SetCompletedSynchronously(); target.MessageId = 123; target.MessageType = MessageType.Request; target.MethodName = "Method"; target.NextProcess = _ => true; }
public static void RunWorker(CancellationTokenSource cancellor, int workerId) { var serverThread = new Thread(() => { var nanoSock = new NanomsgSocket(Domain.SP, Protocol.REP); var nanoListener = new NanomsgListener(); nanoListener.ReceivedMessage += (socketId) => { string input; using (NanomsgReadStream inStream = nanoSock.ReceiveStream()) using (var unpacker = Unpacker.Create(inStream)) { if (!unpacker.ReadString(out input)) { throw new Exception("REQ invalid"); } Console.WriteLine(input); } using (NanomsgWriteStream outStream = nanoSock.CreateSendStream()) using (var packer = Packer.Create(outStream)) { packer.PackString("Hello " + input); nanoSock.SendStream(outStream); } }; nanoListener.AddSocket(nanoSock); nanoSock.Connect("tcp://127.0.0.1:" + repPort); while (!cancellor.IsCancellationRequested) { nanoListener.Listen(TimeSpan.FromMilliseconds(250)); } nanoListener.RemoveSocket(nanoSock); nanoSock.Dispose(); }); serverThread.Start(); serverThread.Join(TimeSpan.FromMilliseconds(40)); }
public static void Write(string filePath, Transform cameraPivot, VoxelArray voxelArray) { if (voxelArray.IsEmpty()) { Debug.Log("World is empty! File will not be written."); return; } Debug.Log("Writing MessagePack file " + filePath); var world = WriteWorld(cameraPivot, voxelArray); var worldObject = new MessagePackObject(world); using (FileStream fileStream = File.Create(filePath)) { fileStream.WriteByte((byte)'m'); var packer = Packer.Create(fileStream, PackerCompatibilityOptions.None); worldObject.PackToMessage(packer, null); } }
private static void TestExtraFieldCore(SerializationMethod method, EmitterFlavor flavor, PackerCompatibilityOptions compat) { var serializer = CreateSerializer <VersioningTestTarget>(flavor); using (var stream = new MemoryStream()) { if (method == SerializationMethod.Array) { stream.Write(new byte[] { 0x94, 0x1, 0xFF, 0xA1, ( byte )'a', 0xA1, 0xC0 }); } else { const string String10 = "1234567890"; // packed as MinimumFixedRaw or Bin8 const string String40 = "1234567890123456789012345678901234567890"; // packed as Bin8 or Str8 var packer = Packer.Create(stream, compat, false); packer.PackMapHeader(7); packer.PackString("Field1"); packer.Pack(1); packer.PackString("Extra1"); packer.PackString(String40); packer.PackString("Extra2"); packer.PackBinary(System.Text.Encoding.UTF8.GetBytes(String40)); packer.PackString("Field2"); packer.Pack(-1); packer.PackString("Extra3"); packer.PackString(String10); packer.PackString("Field3"); packer.PackString("a"); packer.PackString("Extra4"); packer.PackArrayHeader(1); packer.PackNull(); } stream.Position = 0; var result = serializer.Unpack(stream); Assert.That(result.Field1, Is.EqualTo(1)); Assert.That(result.Field2, Is.EqualTo(-1)); Assert.That(result.Field3, Is.EqualTo("a")); } }