Exemplo n.º 1
0
        private static object Deserialize(string xml, Type type, XmlDictionaryReaderQuotas quotas)
        {
            try
            {
#if WINDOWS_PHONE
                StringReader stringReader = new StringReader(xml);
                using (var reader = XmlDictionaryReader.Create(stringReader))
                {
                    var serializer = new DataContractSerializer(type);
                    return(serializer.ReadObject(reader));
                }
#else
                var bytes = Encoding.UTF8.GetBytes(xml);
                using (var reader = XmlDictionaryReader.CreateTextReader(bytes, quotas))
                {
                    var serializer = new DataContractSerializer(type);
                    return(serializer.ReadObject(reader));
                }
#endif
            }
            catch (Exception ex)
            {
                throw new SerializationException("DeserializeDataContract: Error converting type: " + ex.Message, ex);
            }
        }
Exemplo n.º 2
0
        public void Deserialize(object o, Type rootType, object rootInstance, DataContractResolver resolver)
        {
            var deserializer = new DataContractSerializer(rootType, null, Int16.MaxValue, false, false, null, resolver);
            var reader       = XmlDictionaryReader.Create(new StringReader(Serialized));

            Deserialized = deserializer.ReadObject(reader);
        }
Exemplo n.º 3
0
        public void Deserialize(object o, Type rootType)
        {
            var deserializer = new DataContractSerializer(rootType);
            var reader       = XmlDictionaryReader.Create(new StringReader(Serialized));

            Deserialized = deserializer.ReadObject(reader);
        }
Exemplo n.º 4
0
        public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
        {
            writer.WriteStartElement("XMLSerializer");

            string xml = WriteObject(graph);

            using (var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xml)))
            {
                var settings = new System.Xml.XmlReaderSettings();
                settings.IgnoreWhitespace = true;
                var w = XmlDictionaryReader.Create(ms, settings);
                writer.WriteNode(w, true);
            }

            writer.WriteEndElement();
        }
Exemplo n.º 5
0
        private Message BuildMessage(string messageBody, Message originalMessage)
        {
            // change the message body
            //messageBodyString = messageBodyString.Replace("<HelloWorldResult>Hello World 1337</HelloWorldResult>", "<HelloWorldResult>Hello World HIJACKED!</HelloWorldResult>");

            //messageBody.

            Encoding     encoding   = Encoding.UTF8;
            MemoryStream ms         = new MemoryStream(encoding.GetBytes(messageBody));
            var          dictReader = XmlDictionaryReader.Create(ms);

            var message = System.ServiceModel.Channels.Message.CreateMessage(dictReader, int.MaxValue, originalMessage.Version);

            //message.Headers.CopyHeadersFrom(originalMessage);

            return(message);
        }
Exemplo n.º 6
0
        public static void SnippetReadFrom()
        {
            AddressHeader addressHeader1 = AddressHeader.CreateAddressHeader("specialservice1", "http://localhost:8000/service", 1);
            AddressHeader addressHeader2 = AddressHeader.CreateAddressHeader("specialservice2", "http://localhost:8000/service", 2);

            AddressHeader[] addressHeaders = new AddressHeader[2] {
                addressHeader1, addressHeader2
            };
            AddressHeaderCollection headers = new AddressHeaderCollection(addressHeaders);

            EndpointAddress endpointAddress = new EndpointAddress(
                new Uri("http://localhost:8003/servicemodelsamples/service/incode/identity"), addressHeaders);

            XmlDictionaryWriter writer = (XmlDictionaryWriter)XmlDictionaryWriter.Create("addressdata.xml");

            endpointAddress.WriteTo(AddressingVersion.WSAddressing10, writer);
            writer.Close();

            // <Snippet24>
            XmlDictionaryReader reader    = (XmlDictionaryReader)XmlDictionaryReader.Create("addressdata.xml");
            EndpointAddress     createdEA = EndpointAddress.ReadFrom(reader);
            // </Snippet24>
        }
Exemplo n.º 7
0
        static void Method(string json, TypeNameHandling param)
        {
            //Unsafe 2
            var data = JsonConvert.DeserializeObject <Model>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects
            });
            var serializeSettings = new JsonSerializerSettings();

            serializeSettings.TypeNameHandling = TypeNameHandling.All;
            serializeSettings.TypeNameHandling = (TypeNameHandling)2;
            serializeSettings = new JsonSerializerSettings
            {
                TypeNameHandling = param
            };
            serializeSettings.TypeNameHandling = GetHandling("");

            // Unsafe 5
            BinaryMessageFormatter binaryMessage = new System.Messaging.BinaryMessageFormatter();

            binaryMessage.Read(new Message());


            // Unsafe 7
            System.Web.UI.ObjectStateFormatter formatter = new System.Web.UI.ObjectStateFormatter();
            formatter.Deserialize("");
            formatter.Deserialize(new MemoryStream());

            // Unsafe 8
            XmlObjectSerializer xmlObjectSerializer = null;

            xmlObjectSerializer.ReadObject(new MemoryStream());

            // Unsafe 11
            DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(InsecureDeserialize));

            dataContractJsonSerializer.ReadObject(new MemoryStream());
            dataContractJsonSerializer.ReadObject(XmlDictionaryReader.Create(""));
            dataContractJsonSerializer.ReadObject(XmlDictionaryReader.Create(""), false);
            dataContractJsonSerializer.ReadObject(XmlReader.Create(""));
            dataContractJsonSerializer.ReadObject(XmlReader.Create(""), false);

            // Unsafe 12
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(InsecureDeserialize));

            xmlSerializer.Deserialize(new MemoryStream());
            xmlSerializer.Deserialize(TextReader.Null);
            xmlSerializer.Deserialize(XmlReader.Create(""));
            xmlSerializer.Deserialize(XmlReader.Create(""), "\"");
            xmlSerializer.Deserialize(XmlReader.Create(""), new System.Xml.Serialization.XmlDeserializationEvents());
            xmlSerializer.Deserialize(XmlReader.Create(""), "\"", new System.Xml.Serialization.XmlDeserializationEvents());

            // Unsafe 13
            System.Messaging.XmlMessageFormatter xmlMessageFormatter = new XmlMessageFormatter();
            xmlMessageFormatter.Read(new System.Messaging.Message());

            // Unsafe 14
            System.Resources.ResourceReader resourceReader = new System.Resources.ResourceReader("");
            resourceReader = new System.Resources.ResourceReader(new MemoryStream());

            // Unsafe 15
            fastJSON.JSON.ToObject("");

            // Unsafe 16
            ServiceStack.Text.JsonSerializer.DeserializeFromString("", typeof(InsecureDeserialize));
            ServiceStack.Text.JsonSerializer.DeserializeFromReader(TextReader.Null, typeof(InsecureDeserialize));
            ServiceStack.Text.JsonSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());

            ServiceStack.Text.TypeSerializer.DeserializeFromString("", typeof(InsecureDeserialize));
            ServiceStack.Text.TypeSerializer.DeserializeFromReader(TextReader.Null, typeof(InsecureDeserialize));
            ServiceStack.Text.TypeSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());

            ServiceStack.Text.CsvSerializer.DeserializeFromString(typeof(InsecureDeserialize), "");
            ServiceStack.Text.CsvSerializer.DeserializeFromReader <InsecureDeserialize>(TextReader.Null);
            ServiceStack.Text.CsvSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());

            ServiceStack.Text.XmlSerializer.DeserializeFromString("", typeof(InsecureDeserialize));
            ServiceStack.Text.XmlSerializer.DeserializeFromReader <InsecureDeserialize>(TextReader.Null);
            ServiceStack.Text.XmlSerializer.DeserializeFromStream(typeof(InsecureDeserialize), new MemoryStream());
        }
Exemplo n.º 8
0
        /// <summary>
        /// Serialize the reply
        /// </summary>
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            try
            {
                // Outbound control
                var     format  = WebContentFormat.Raw;
                Message request = OperationContext.Current.RequestContext.RequestMessage;
                HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
                string accepts     = httpRequest.Headers[HttpRequestHeader.Accept],
                       contentType = httpRequest.Headers[HttpRequestHeader.ContentType];
                Message reply      = null;

                // Result is serializable
                if (result?.GetType().GetCustomAttribute <XmlTypeAttribute>() != null ||
                    result?.GetType().GetCustomAttribute <JsonObjectAttribute>() != null)
                {
                    // The request was in JSON or the accept is JSON
                    if (accepts?.StartsWith("application/json") == true ||
                        contentType?.StartsWith("application/json") == true)
                    {
                        // Prepare the serializer
                        JsonSerializer jsz = new JsonSerializer();
                        jsz.Converters.Add(new StringEnumConverter());

                        // Write json data
                        byte[] body = null;
                        using (MemoryStream ms = new MemoryStream())
                            using (StreamWriter sw = new StreamWriter(ms, Encoding.UTF8))
                                using (JsonWriter jsw = new JsonTextWriter(sw))
                                {
                                    jsz.DateFormatHandling    = DateFormatHandling.IsoDateFormat;
                                    jsz.NullValueHandling     = NullValueHandling.Ignore;
                                    jsz.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                                    jsz.TypeNameHandling      = TypeNameHandling.Auto;
                                    jsz.Converters.Add(new StringEnumConverter());
                                    jsz.Serialize(jsw, result);
                                    sw.Flush();
                                    body = ms.ToArray();
                                }

                        // Prepare reply for the WCF pipeline
                        format      = WebContentFormat.Raw;
                        contentType = "application/json";
                        reply       = Message.CreateMessage(messageVersion, this.m_operationDescription?.Messages[1]?.Action, new RawBodyWriter(body));
                    }
                    // The request was in XML and/or the accept is JSON
                    else
                    {
                        if (!s_serializers.ContainsKey(result.GetType()))
                        {
                            throw new KeyNotFoundException($"{result.GetType().Name} serializer not found");
                        }

                        XmlSerializer xsz = s_serializers[result.GetType()];
                        MemoryStream  ms  = new MemoryStream();
                        xsz.Serialize(ms, result);
                        format      = WebContentFormat.Xml;
                        contentType = "application/xml";
                        ms.Seek(0, SeekOrigin.Begin);

                        reply = Message.CreateMessage(messageVersion, this.m_operationDescription?.Messages[1]?.Action, XmlDictionaryReader.Create(ms));
                    }
                }
                else if (result is XmlSchema)
                {
                    MemoryStream ms = new MemoryStream();
                    (result as XmlSchema).Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    format      = WebContentFormat.Xml;
                    contentType = "text/xml";
                    reply       = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action, XmlDictionaryReader.Create(ms));
                }
                else if (result is Stream) // TODO: This is messy, clean it up
                {
                    contentType = "application/octet-stream";
                    reply       = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action, new RawBodyWriter(result as Stream));
                }
                else
                {
                    reply = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action);
                }

                reply.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(format));
                //var responseProperty = (HttpResponseMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name];
                //var responseProperty = new HttpResponseMessageProperty();
                WebOperationContext.Current.OutgoingResponse.ContentType = contentType;
                WebOperationContext.Current.OutgoingResponse.Headers.Add("X-PoweredBy", String.Format("OpenIZ {0} ({1})", m_version, m_versionName));
                WebOperationContext.Current.OutgoingResponse.Headers.Add("X-GeneratedOn", DateTime.Now.ToString("o"));
                //reply.Properties.Add(HttpResponseMessageProperty.Name, responseProperty);
                // TODO: Determine best way to clear current authentication context
                AuthenticationContext.Current = null;
                return(reply);
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                Message reply = null;
                new WcfErrorHandler().ProvideFault(e, messageVersion, ref reply);
                return(reply);
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Serialize the reply
        /// </summary>
        public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
        {
            try
            {
                // Outbound control
                var     format  = WebContentFormat.Raw;
                Message request = OperationContext.Current.RequestContext.RequestMessage;
                HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
                string accepts     = httpRequest.Headers[HttpRequestHeader.Accept],
                       contentType = httpRequest.Headers[HttpRequestHeader.ContentType],
                       formatParm  = httpRequest.QueryString;

                Message reply = null;

                // Result is serializable
                if (result?.GetType().GetCustomAttribute <XmlTypeAttribute>() != null ||
                    result?.GetType().GetCustomAttribute <JsonObjectAttribute>() != null)
                {
                    XmlSerializer xsz = s_serializers[result.GetType()];
                    MemoryStream  ms  = new MemoryStream();
                    xsz.Serialize(ms, result);
                    format      = WebContentFormat.Xml;
                    contentType = "application/xml+fhir";
                    ms.Seek(0, SeekOrigin.Begin);

                    // The request was in JSON or the accept is JSON
                    if (accepts?.StartsWith("application/json+fhir") == true ||
                        contentType?.StartsWith("application/json+fhir") == true ||
                        formatParm.Contains("_format=json"))
                    {
                        // Parse XML object
                        Object fhirObject = null;
                        using (StreamReader sr = new StreamReader(ms))
                        {
                            String fhirContent = sr.ReadToEnd();
                            var    parser      = new FhirXmlParser();
                            parser.Settings.AllowUnrecognizedEnums = true;
                            fhirObject = parser.Parse <Resource>(fhirContent);
                        }

                        // Now we serialize to JSON
                        byte[] body = FhirSerializer.SerializeResourceToJsonBytes(fhirObject as Hl7.Fhir.Model.Resource);

                        // Prepare reply for the WCF pipeline
                        format      = WebContentFormat.Raw;
                        contentType = "application/json+fhir";
                        reply       = Message.CreateMessage(messageVersion, this.m_operationDescription?.Messages[1]?.Action, new RawBodyWriter(body));
                    }
                    // The request was in XML and/or the accept is JSON
                    else
                    {
                        reply = Message.CreateMessage(messageVersion, this.m_operationDescription?.Messages[1]?.Action, XmlDictionaryReader.Create(ms));
                    }
                }
                else if (result is XmlSchema)
                {
                    MemoryStream ms = new MemoryStream();
                    (result as XmlSchema).Write(ms);
                    ms.Seek(0, SeekOrigin.Begin);
                    format      = WebContentFormat.Xml;
                    contentType = "text/xml";
                    reply       = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action, XmlDictionaryReader.Create(ms));
                }
                else if (result is Stream) // TODO: This is messy, clean it up
                {
                    reply = Message.CreateMessage(messageVersion, this.m_operationDescription.Messages[1].Action, new RawBodyWriter(result as Stream));
                }

                reply.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(format));
                WebOperationContext.Current.OutgoingResponse.ContentType = contentType;
                WebOperationContext.Current.OutgoingResponse.Headers.Add("X-PoweredBy", String.Format("{0} v{1} ({2})", Assembly.GetEntryAssembly().GetName().Name, Assembly.GetEntryAssembly().GetName().Version, Assembly.GetEntryAssembly().GetCustomAttribute <AssemblyInformationalVersionAttribute>()?.InformationalVersion));
                WebOperationContext.Current.OutgoingResponse.Headers.Add("X-GeneratedOn", DateTime.Now.ToString("o"));

                return(reply);
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                throw;
            }
        }