public Entity Deserialize(Stream input, Encoding encoding) { bool forceHypermedia; using (var reader = CreateReader(input, encoding, out forceHypermedia)) { GraphWriter graphWriter = null; using (var writer = new DelayedWriter()) { writer.Intercept += (o, e) => { if (e.Node.Type.HasFlag(NodeType.Property)) { var isPayload = "form".EqualsIgnoreCase(e.Node.Value as string) || "record".EqualsIgnoreCase(e.Node.Value as string) || "records".EqualsIgnoreCase(e.Node.Value as string); graphWriter = isPayload ? new GraphWriter(typeof(Payload)) : new GraphWriter(typeof(Entity)); writer.SetWriter(graphWriter); } }; reader.CopyTo(writer); } var graph = graphWriter?.Graphs.Cast <object>().FirstOrDefault(); var entity = graph as Entity ?? throw new NotImplementedException(); //var entity = graph is Payload payload ? payload.ToEntity() : (Entity)graph; return(entity); } }
public async Task WriteAsync_SemaphoreIncludesWriteCoreAsync_Task() { var handler = new DelayedWriter(this.sendingStream, this.receivingStream, new MessagePackFormatter()); var writeTask = handler.WriteAsync(CreateRequestMessage(), CancellationToken.None).AsTask(); var write2Task = handler.WriteAsync(CreateRequestMessage(), CancellationToken.None).AsTask(); // Give the library extra time to do the wrong thing asynchronously. await Task.Delay(ExpectedTimeout); Assert.Equal(1, handler.WriteCoreCallCount); handler.WriteBlock.Set(); await Task.WhenAll(writeTask, write2Task).WithTimeout(UnexpectedTimeout); Assert.Equal(2, handler.WriteCoreCallCount); }
public async Task WriteAsync_PreferOperationCanceledException_MidExecution() { var handler = new DelayedWriter(this.sendingStream, this.receivingStream, new MessagePackFormatter()); var cts = new CancellationTokenSource(); var writeTask = handler.WriteAsync(CreateRequestMessage(), cts.Token); cts.Cancel(); handler.Dispose(); // Unblock writer. It should not throw anything as it is to emulate not recognizing the // CancellationToken before completing its work. handler.WriteBlock.Set(); await Assert.ThrowsAnyAsync <OperationCanceledException>(() => writeTask.AsTask()); }
public void Write_UpdatesBuffer(int shadowBufferSize, int repCount) { int totBytes = repCount * shadowBufferSize; var config = GetConfig(shadowBufferSize, delayedWriter: true); byte[] sourceBuffer = Enumerable.Range(1, totBytes).Select(f => (byte)f).ToArray(); byte[] destBuffer = new byte[totBytes]; IWriter writer = new DelayedWriter(new MemoryStream(destBuffer), config); for (int ix = 0, f = 0; f < repCount; ix += shadowBufferSize, f++) { using (ShadowBufferData buf = writer.RequestBuffer()) { buf.byteCount = shadowBufferSize; Buffer.BlockCopy(sourceBuffer, ix, buf.buffer, 0, shadowBufferSize); writer.ReturnBufferAndWrite(buf); } } writer.Flush(); Assert.AreEqual(sourceBuffer, destBuffer); }