Beispiel #1
0
        public void Serialize <T>(Stream stream, SendContext <T> context)
            where T : class
        {
            try
            {
                context.ContentType = JsonContentType;

                context.SetNServiceBusHeaders();

                using var writer     = new StreamWriter(stream, _encoding.Value, 1024, true);
                using var jsonWriter = new JsonTextWriter(writer)
                      {
                          Formatting = Formatting.Indented
                      };

                JsonMessageSerializer.Serializer.Serialize(jsonWriter, context.Message, typeof(T));

                jsonWriter.Flush();
                writer.Flush();
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }
Beispiel #2
0
        public void Serialize <T>(Stream stream, SendContext <T> context)
            where T : class
        {
            try
            {
                context.ContentType = XmlContentType;

                context.SetNServiceBusHeaders();

                var json = new StringBuilder(1024);

                using (var stringWriter = new StringWriter(json, CultureInfo.InvariantCulture))
                    using (var jsonWriter = new JsonTextWriter(stringWriter)
                    {
                        Formatting = Newtonsoft.Json.Formatting.None
                    })
                    {
                        _serializer.Value.Serialize(jsonWriter, context.Message, typeof(T));

                        jsonWriter.Flush();
                        stringWriter.Flush();
                    }

                using (var stringReader = new StringReader(json.ToString()))
                    using (var jsonReader = new JsonTextReader(stringReader))
                    {
                        var document = (XDocument)XmlSerializer.Value.Deserialize(jsonReader, typeof(XDocument));

                        if (document.Root != null)
                        {
                            document.Root.Name = typeof(T).Name;
                        }

                        using (var writer = new StreamWriter(stream, Encoding.Value, 1024, true))
                            using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings {
                                CheckCharacters = false
                            }))
                            {
                                document.WriteTo(xmlWriter);
                            }
                    }
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("Failed to serialize message", ex);
            }
        }