public virtual void CancelEdit() { if ((this.savedData != null) && (this.serializer != null)) { var ms = new MemoryStream(this.savedData); using (XmlDictionaryReader w = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max)) { var values = (List <object>)(serializer.ReadObject(w)); int index = 0; foreach (var prop in GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (Attribute.IsDefined(prop, typeof(EditableAttribute))) { if (prop.CanRead && prop.CanWrite) { prop.SetValue(this, values[index++], null); } } } foreach (var prop in GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) { if (Attribute.IsDefined(prop, typeof(EditableAttribute))) { prop.SetValue(this, values[index++]); } } } this.savedData = null; this.serializer = null; } }
public void Issue22_DataContractSerializerCausesInvalidDataException_Binary() { var obj = new TestClass { Test1 = "1" }; var serializer = new DataContractSerializer(typeof(TestClass)); byte[] bytes; using (var ms = new MemoryStream()) { using (var compressionStream = LZ4Stream.Encode(ms)) using (var writer = XmlDictionaryWriter.CreateBinaryWriter(compressionStream)) { serializer.WriteObject(writer, obj); } bytes = ms.ToArray(); } using (var ms = new MemoryStream(bytes)) using (var decompressionStream = LZ4Stream.Decode(ms)) using (var reader = XmlDictionaryReader.CreateBinaryReader( decompressionStream, XmlDictionaryReaderQuotas.Max)) { var o = serializer.ReadObject(reader) as TestClass; Assert.Equal(obj.Test1, o.Test1); } }
internal async Task ListenForResponses() { var receiver = connections.ListenForResponses(responsePartition); while (true) { IEnumerable <EventData> eventData = await receiver.ReceiveAsync(configuration.MaxReceiveBatchSize, TimeSpan.FromMinutes(1)); if (eventData != null) { foreach (var ed in eventData) { MemoryStream stream = new MemoryStream(ed.Body.Array); using (var binaryDictionaryReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { var rsps = (List <IResponseMessage>)responseSerializer.ReadObject(binaryDictionaryReader); foreach (var rsp in rsps) { rsp.Process(this); } } } } } }
public EnvelopeContract DeserializeEnvelope(Stream stream) { using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { return((EnvelopeContract)_serializer.ReadObject(reader)); } }
private string ReadRawBody(ref Message message) { XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); byte[] bodyBytes = bodyReader.ReadContentAsBase64(); //MemoryStream ms1 = new MemoryStream(bodyBytes); //StreamReader sr = new StreamReader(ms1); //JsonSerializer serializer = JsonHelper.GetJsonSerializer(); //var obj = serializer.Deserialize(sr, typeof(ReturnMessage<object>)); string messageBody = Encoding.UTF8.GetString(bodyBytes); // Now to recreate the message MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms); writer.WriteStartElement("Binary"); writer.WriteBase64(bodyBytes, 0, bodyBytes.Length); writer.WriteEndElement(); writer.Flush(); ms.Position = 0; XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max); Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version); newMessage.Properties.CopyProperties(message.Properties); newMessage.Headers.CopyHeadersFrom(message); message = newMessage; return(messageBody); }
public XDocument Unprotect(Stream data, X509Certificate2 encryptionCertificate, X509Certificate2 signingCertificate, X509Certificate2 legacyEncryptionCertificate) { if (data == null) { throw new ArgumentNullException(nameof(data)); } try { return(XDocument.Load(data)); } catch (XmlException) { // some parties have chose to use string instead of stream when sending unecrypted XML (soap faults) // since the GetBody<Stream>() always returns a valid stream, it causes a problem if the original data was string // the general XDocument.Load() fails, then we try a fallback to a manually deserialize the content try { data.Position = 0; var serializer = new DataContractSerializer(typeof(string)); var dictionary = XmlDictionaryReader.CreateBinaryReader(data, XmlDictionaryReaderQuotas.Max); var xmlContent = serializer.ReadObject(dictionary); return(XDocument.Parse(xmlContent as string)); } catch (Exception ex) { throw new PayloadDeserializationException("Could not deserialize payload", ex); } } }
public void WriteTo(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (this.IsReadOnly) { // cache the serialized bytes to ensure repeatability if (this.cachedWriteBuffer == null) { MemoryStream stream = new MemoryStream(); using (XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary)) { this.OnWriteTo(binaryWriter); binaryWriter.Flush(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); this.cachedWriteBuffer = stream.GetBuffer(); this.cachedWriteBufferLength = (int)stream.Length; } } writer.WriteNode(XmlDictionaryReader.CreateBinaryReader(this.cachedWriteBuffer, 0, this.cachedWriteBufferLength, XD.Dictionary, XmlDictionaryReaderQuotas.Max), false); } else { this.OnWriteTo(writer); } }
public void WriteTo(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (this.IsReadOnly) { // cache the serialized bytes to ensure repeatability if (_cachedWriteBuffer.Array == null) { MemoryStream stream = new MemoryStream(); using (XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary)) { this.OnWriteTo(binaryWriter); binaryWriter.Flush(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); bool gotBuffer = stream.TryGetBuffer(out _cachedWriteBuffer); if (!gotBuffer) { throw new UnauthorizedAccessException(SRServiceModel.UnauthorizedAccess_MemStreamBuffer); } _cachedWriteBufferLength = (int)stream.Length; } } writer.WriteNode(XmlDictionaryReader.CreateBinaryReader(_cachedWriteBuffer.Array, 0, _cachedWriteBufferLength, XD.Dictionary, XmlDictionaryReaderQuotas.Max), false); } else { this.OnWriteTo(writer); } }
public static string GetBody(Message message) { string body = null; // Get the body if (message.Body is string) { body = message.Body as string; } else if (message.Body is byte[]) { using (var reader = XmlDictionaryReader.CreateBinaryReader( new MemoryStream(message.Body as byte[]), null, XmlDictionaryReaderQuotas.Max)) { var doc = new XmlDocument(); doc.Load(reader); body = doc.InnerText; } } else { throw new ArgumentException($"Message {message.Properties.MessageId} has body with an invalid type {message.Body.GetType()}"); } return(body); }
public void Send(uint processId, IMessage message) { var destinationprocess = processes[processId]; if (configuration.RoundTripMessages) // for debugging message serialization { var stream = new MemoryStream(); using (var binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream)) { _serializer.WriteObject(binaryDictionaryWriter, message); stream.Flush(); } var bytes = stream.ToArray(); stream = new MemoryStream(bytes); using (var binaryDictionaryReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { message = (IMessage)_serializer.ReadObject(binaryDictionaryReader); } } // need lock since ephemeral sends can execute on threadpool lock (destinationprocess) { destinationprocess.Inbox.Add(message); } }
public object DeserializeFromString(string xml, Type type) { try { var bytes = Encoding.UTF8.GetBytes(xml); #if MONOTOUCH using (var reader = XmlDictionaryReader.CreateTextReader(bytes, null)) #elif SILVERLIGHT && !WINDOWS_PHONE using (var reader = XmlDictionaryReader.CreateTextReader(bytes, XmlDictionaryReaderQuotas.Max)) #elif WINDOWS_PHONE using (var reader = XmlDictionaryReader.CreateBinaryReader(bytes, XmlDictionaryReaderQuotas.Max)) #else using (var reader = XmlDictionaryReader.CreateTextReader(bytes, this.quotas)) #endif { var serializer = new System.Runtime.Serialization.DataContractSerializer(type); return(serializer.ReadObject(reader)); } } catch (Exception ex) { throw new SerializationException("DeserializeDataContract: Error converting type: " + ex.Message, ex); } }
public XmlDictionaryReader GetReaderAtContent() { if (writer_extension != null) { // It is messy, but it somehow returns an XmlReader that has wrapper "content" element for non-XmlReader extension... XmlReader r = extension.GetReader(); if (!(r is XmlDictionaryReader)) { r = XmlDictionaryReader.CreateDictionaryReader(r); } var ms = new MemoryStream(); var xw = XmlDictionaryWriter.CreateBinaryWriter(ms); xw.WriteStartElement("content", Namespaces.Atom10); xw.WriteAttributeString("type", "text/xml"); while (!r.EOF) { xw.WriteNode(r, false); } xw.WriteEndElement(); xw.Close(); ms.Position = 0; var xr = XmlDictionaryReader.CreateBinaryReader(ms, new XmlDictionaryReaderQuotas()); xr.MoveToContent(); return(xr); } else { XmlReader r = extension.GetReader(); if (!(r is XmlDictionaryReader)) { r = XmlDictionaryReader.CreateDictionaryReader(r); } return((XmlDictionaryReader)r); } }
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) { if (contentType != null && contentType != ContentType) { throw new ProtocolException("Only content type 'application/soap+msbin1' is allowed."); } // FIXME: remove this extraneous buffering. It is somehow required for HTTP + binary encoding binding. The culprit is probably in binary xml reader or writer, but not sure. if (!stream.CanSeek) { var tmpms = new MemoryStream(); var bytes = new byte [4096]; int len; do { len = stream.Read(bytes, 0, bytes.Length); tmpms.Write(bytes, 0, len); } while (len > 0); tmpms.Seek(0, SeekOrigin.Begin); stream = tmpms; } return(Message.CreateMessage( XmlDictionaryReader.CreateBinaryReader(stream, Constants.SoapDictionary, owner != null ? owner.Owner.ReaderQuotas : new XmlDictionaryReaderQuotas(), session ? CurrentReaderSession : null), maxSizeOfHeaders, MessageVersion)); }
/// <summary> /// Decode a bytestream that was encoded by WCF's BinaryEncodingBindingElement. Will throw if the bytestream does /// not decode properly or the result is not valid XML. I/O streams are flushed but not closed. /// </summary> /// <param name="explodeNewlines">if true, the returned string will be nicely indented according to /// element depth, and each attribute will be placed on its own line</param> /// <returns></returns> public void DecodeBinaryXML(Stream binaryInput, Stream xmlOutput, bool?explodeNewlines) { // defaults var explode = explodeNewlines ?? false; // parse bytestream into the XML DOM var doc = new XmlDocument(); using (var binaryReader = XmlDictionaryReader.CreateBinaryReader(binaryInput, WcfDictionaryBuilder.Dict, XmlDictionaryReaderQuotas.Max)) { doc.Load(binaryReader); } // write document to the output stream with customized settings var settings = new XmlWriterSettings() { CheckCharacters = false, CloseOutput = false, ConformanceLevel = ConformanceLevel.Auto, Encoding = m_encoding, Indent = explode, //IndentChars = "\t", //NewLineChars = Environment.NewLine, //NewLineHandling = explode ? NewLineHandling.Replace : NewLineHandling.None, //NewLineOnAttributes = explode DoNotEscapeUriAttributes = false }; using (var writer = XmlWriter.Create(xmlOutput, settings)) { doc.Save(writer); writer.Flush(); xmlOutput.Flush(); } }
T DeserializeBinaryXml(MemoryStream stream) { var binaryReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max); T deserialized = (T)Formatter.ReadObject(binaryReader); return(deserialized); }
void InspectMessageBody_msdn(ref Message message, bool isRequest) { if (!message.IsFault) { XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas(); XmlReader bodyReader = message.GetReaderAtBodyContents().ReadSubtree(); XmlReaderSettings wrapperSettings = new XmlReaderSettings(); wrapperSettings.CloseInput = true; wrapperSettings.Schemas = null; wrapperSettings.ValidationFlags = XmlSchemaValidationFlags.None; wrapperSettings.ValidationType = ValidationType.None; XmlReader wrappedReader = XmlReader.Create(bodyReader, wrapperSettings); // pull body into a memory backed writer to validate this.isRequest = isRequest; MemoryStream memStream = new MemoryStream(); XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateBinaryWriter(memStream); xdw.WriteNode(wrappedReader, false); xdw.Flush(); memStream.Position = 0; XmlDictionaryReader xdr = XmlDictionaryReader.CreateBinaryReader(memStream, quotas); // reconstruct the message with the validated body Message replacedMessage = Message.CreateMessage(message.Version, null, xdr); replacedMessage.Headers.CopyHeadersFrom(message.Headers); replacedMessage.Properties.CopyProperties(message.Properties); message = replacedMessage; // string content = xdr.ReadOuterXml(); } }
/// <summary> /// Creates an event. /// /// NOTE: Assumes the payload is a JSON string!!! /// </summary> /// <param name="message">message with a JSON string payload</param> /// <param name="eventType">event type. Normally the topic queue name</param> /// <param name="queueName">Fulle queue name</param> /// <returns>event</returns> public static Event ToEvent(this Message message, string eventType, string queueName) { string body = null; if (message.Body[0] == Convert.ToChar('@')) // this is from previous version of ServiceBus which serialises { var ms = new MemoryStream(message.Body); var reader = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max); body = (string)_oldSerialiser.ReadObject(reader); } else { body = Encoding.UTF8.GetString(message.Body); } return (new Event() { Body = body, ContentType = message.ContentType, EventType = eventType, QueueName = queueName, UnderlyingMessage = message }); }
public Task <IDictionary <string, object> > DeserializePropertiesAsync() { // Deserialize property dictionary to local storage // Make sure to use Internal return(Task.Run(() => { using (var store = IsolatedStorageFile.GetUserStoreForApplication()) using (var stream = store.OpenFile(PropertyStoreFile, System.IO.FileMode.OpenOrCreate)) using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { if (stream.Length == 0) { return null; } try { var dcs = new DataContractSerializer(typeof(Dictionary <string, object>)); return (IDictionary <string, object>)dcs.ReadObject(reader); } catch (Exception e) { Debug.WriteLine("Could not deserialize properties: " + e.Message); Log.Warning("Xamarin.Forms PropertyStore", $"Exception while reading Application properties: {e}"); } } return null; })); }
public static void ReadElementContentAsStringDataExceedsMaxBytesPerReadQuota() { XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas(); quotas.MaxBytesPerRead = 4096; int contentLength = 8176; string testString = new string('a', contentLength); string returnedString; XmlDictionary dict = new XmlDictionary(); XmlDictionaryString dictEntry = dict.Add("Value"); using (var ms = new MemoryStream()) { XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateBinaryWriter(ms, dict); xmlWriter.WriteElementString(dictEntry, XmlDictionaryString.Empty, testString); xmlWriter.Flush(); ms.Position = 0; XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateBinaryReader(ms, dict, quotas); xmlReader.Read(); returnedString = xmlReader.ReadElementContentAsString(); } Assert.Equal(testString, returnedString); }
private string ReadRawBody(ref Message message) { XmlDictionaryReader bodyReader = message.GetReaderAtBodyContents(); bodyReader.ReadStartElement("Binary"); byte[] bodyBytes = bodyReader.ReadContentAsBase64(); string messageBody = Encoding.UTF8.GetString(bodyBytes); // Now to recreate the message MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(ms); writer.WriteStartElement("Binary"); writer.WriteBase64(bodyBytes, 0, bodyBytes.Length); writer.WriteEndElement(); writer.Flush(); ms.Position = 0; XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(ms, XmlDictionaryReaderQuotas.Max); Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version); newMessage.Properties.CopyProperties(message.Properties); message = newMessage; return(messageBody); }
public static string DeserializeServiceBusMessage(Message message) { string deserializedBody; try { // TODO: this custom serialization nonsense is supposed to be fixed with an upcoming SB nuget package version XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(new MemoryStream(message.Body), null, XmlDictionaryReaderQuotas.Max); var doc = new XmlDocument(); doc.Load(reader); deserializedBody = HttpUtility.JavaScriptStringEncode(doc.InnerText.Replace("\r\n", ""), false).Replace("\"", "'") .Replace("\\", ""); } catch (XmlException) { string converted = Encoding.UTF8.GetString(message.Body, 0, message.Body.Length); deserializedBody = HttpUtility.JavaScriptStringEncode(converted.Replace("\r\n", ""), false).Replace("\"", "'") .Replace("\\", ""); } return(deserializedBody); }
// Deserializes a stream to a graph using the NetDataContractSerializer (binary mode) private static object DeserializeGraph(Stream rawBytes) { using (XmlDictionaryReader dr = XmlDictionaryReader.CreateBinaryReader(rawBytes, XmlDictionaryReaderQuotas.Max)) { object deserialized = new NetDataContractSerializer().ReadObject(dr); return(deserialized); } }
internal static object?Deserialize(ReadOnlySequence <byte> input, DataContractSerializer serializer) { using var stream = input.AsStream(); using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { return(serializer.ReadObject(reader)); } }
public override object ReadObject(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } return(ReadObject(XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))); }
private string GetString(MemoryStream stream) { using (XmlDictionaryReader reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { XDocument xDocument = XDocument.Load(reader); return(xDocument.ToString()); } }
/// <summary>Deserializes the object from specified source stream.</summary> /// <param name="source">The source stream.</param> /// <param name="type">The type of the object to deserialize.</param> /// <returns>deserialized object</returns> public object Deserialize(Stream source, Type type) { var serializer = GetXmlSerializer(type); using (var decompressed = Decompress(source, true)) using (var reader = XmlDictionaryReader.CreateBinaryReader(decompressed, XmlDictionaryReaderQuotas.Max)) return(serializer.ReadObject(reader)); }
public override object ReadObject(Stream stream) { if (stream == null) { throw Microsoft.ServiceBus.Messaging.FxTrace.Exception.ArgumentNull("stream"); } return(this.ReadObject(XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max))); }
public static T Deserialize <T>(byte[] data) { var serializer = new DataContractSerializer(typeof(T)); using (var stream = new MemoryStream(data)) using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) return((T)serializer.ReadObject(reader)); }
public IModuleDataModel GetEffectData() { DataContractSerializer ds = new DataContractSerializer(_moduleDataClass); MemoryStream effectDataIn = new MemoryStream(_effectData.ToArray()); using (XmlDictionaryReader r = XmlDictionaryReader.CreateBinaryReader(effectDataIn, XmlDictionaryReaderQuotas.Max)) return((IModuleDataModel)ds.ReadObject(r)); }
/// <remarks></remarks> public XElement UnpackXml(Stream source) { using (var decompressed = Decompress(source, true)) using (var reader = XmlDictionaryReader.CreateBinaryReader(decompressed, XmlDictionaryReaderQuotas.Max)) { return(XElement.Load(reader)); } }