public ImmutableEnvelope ReadAsEnvelopeData(byte[] buffer) { var header = EnvelopeHeaderContract.ReadHeader(buffer); if (header.MessageFormatVersion != EnvelopeHeaderContract.Schema2DataFormat) { throw new InvalidOperationException("Unexpected bytes in enveloper header"); } EnvelopeContract envelope; using (var stream = new MemoryStream(buffer, EnvelopeHeaderContract.FixedSize, (int)header.EnvelopeBytes)) { envelope = _envelopeSerializer.DeserializeEnvelope(stream); } var items = new ImmutableMessage[envelope.Messages.Length]; for (var i = 0; i < items.Length; i++) { var itemContract = envelope.Messages[i]; var attributes = EnvelopeConvert.ItemAttributesFromContract(itemContract.Attributes); Type contractType; var itemPosition = EnvelopeHeaderContract.FixedSize + (int)header.EnvelopeBytes + (int)itemContract.ContentPosition; var itemSize = (int)itemContract.ContentSize; if (_dataSerializer.TryGetContractTypeByName(itemContract.ContractName, out contractType)) { try { // we can deserialize. Convert it to a message using (var stream = new MemoryStream(buffer, itemPosition, itemSize)) { var instance = _dataSerializer.Deserialize(stream, contractType); items[i] = new ImmutableMessage(contractType, instance, attributes, i); } } catch (Exception ex) { throw new InvalidOperationException("Failed to deserialize: " + itemContract.ContractName, ex); } } else { // we can't deserialize. Keep it as buffer var bufferInstance = new byte[itemContract.ContentSize]; Buffer.BlockCopy(buffer, itemPosition, bufferInstance, 0, itemSize); items[i] = new ImmutableMessage(null, bufferInstance, attributes, i); } } var envelopeAttributes = EnvelopeConvert.EnvelopeAttributesFromContract(envelope.EnvelopeAttributes); return(new ImmutableEnvelope(envelope.EnvelopeId, envelopeAttributes, items, envelope.DeliverOnUtc, envelope.CreatedOnUtc)); }