/// <summary> /// Encode a text stream into a binary XML stream compatible with WCF's BinaryEncodingBindingElement. Will throw if /// the input stream cannot be parsed into an XML document. I/O streams are flushed but not closed. /// </summary> /// <param name="xmlInput"></param> /// <param name="binaryOutput"></param> public void EncodeBinaryXML(Stream xmlInput, Stream binaryOutput) { // parse string into the XML DOM var doc = new XmlDocument(); doc.Load(xmlInput); // write bytestream using (var binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(binaryOutput, WcfDictionaryBuilder.Dict, null, false)) { doc.Save(binaryWriter); binaryWriter.Flush(); binaryOutput.Flush(); } }
public OutgoingMessageBody Serialize(IServiceRemotingResponseMessageBody serviceRemotingResponseMessageBody) { if (serviceRemotingResponseMessageBody == null) { return(null); } using (var stream = new Messaging.SegmentedPoolMemoryStream(this.bufferPoolManager)) { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { this.serializer.WriteObject(writer, serviceRemotingResponseMessageBody); writer.Flush(); return(new OutgoingMessageBody(stream.GetBuffers())); } } }
/// <summary>Store the column value in the database.</summary> public override void Serialize(EseCursorBase cur, JET_COLUMNID idColumn, object value, bool bNewRecord) { using (var stm = new ColumnStream(cur.idSession, cur.idTable, idColumn)) { using (XmlDictionaryWriter bw = XmlDictionaryWriter.CreateBinaryWriter(stm, this.dict)) { this.m_serializer.WriteObject(bw, value); bw.Flush(); } // TODO [low]: if the ( current size - new size < 4kb ), then append spaces/zeros instead of resizing the column. The comments inside the SetLength method suggest that shrinking the column is very inefficient for large values. if (stm.Position < stm.Length) { stm.SetLength(stm.Position); } } }
public static byte[] Serialize <T>(T obj) where T : class { if (obj == null) { return(null); } var serializer = new DataContractSerializer(typeof(T)); using (var memStream = new MemoryStream()) { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(memStream)) { serializer.WriteObject(writer, obj); } return(memStream.ToArray()); } }
/// <summary> /// Serializes the headers to a byte array /// </summary> /// <param name="serializer">Serializer</param> /// <param name="msg">Headers</param> /// <returns>The serialized byte array</returns> public static byte[] Serialize(DataContractSerializer serializer, ServiceRemotingMessageHeaders msg) { if (msg == null) { return(null); } using (var stream = new MemoryStream()) { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { serializer.WriteObject(writer, msg); writer.Flush(); return(stream.ToArray()); } } }
public Task SerializePropertiesAsync(IDictionary <string, object> properties) { properties = new Dictionary <string, object>(properties); // Serialize property dictionary to local storage // Make sure to use Internal return(Task.Run(() => { var success = false; using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) using (IsolatedStorageFileStream stream = store.OpenFile(PropertyStoreFile + ".tmp", System.IO.FileMode.OpenOrCreate)) using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { try { var dcs = new DataContractSerializer(typeof(Dictionary <string, object>)); dcs.WriteObject(writer, properties); writer.Flush(); success = true; } catch (Exception e) { Debug.WriteLine("Could not serialize properties: " + e.Message); } } if (!success) { return; } using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { try { if (store.FileExists(PropertyStoreFile)) { store.DeleteFile(PropertyStoreFile); } store.MoveFile(PropertyStoreFile + ".tmp", PropertyStoreFile); } catch (Exception e) { Debug.WriteLine("Could not move new serialized property file over old: " + e.Message); } } })); }
protected override async Task Send(List <IMessage> toSend) { // serialize payload MemoryStream stream = new MemoryStream(); using (var binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream)) { payloadSerializer.WriteObject(binaryDictionaryWriter, toSend); stream.Flush(); } var now = DateTime.UtcNow; // send message var message = new ProcessMessage() { DeploymentTimestamp = default(DateTime), Source = processId, LastClock = null, Payload = stream.ToArray() }; var messageBytes = ProcessMessage.Serialize(message); await sender.SendAsync(new EventData(messageBytes)); logger.LogTrace($"{DateTime.UtcNow:o} Sent {message}->{destination} ({messageBytes.Length / 1024}kB)"); if (lastSendOrDoorbell + configuration.ReceiveWaitTime < now) { // send doorbell message var doorbellMessage = new DoorbellMessage() { ProcessId = destination, Guid = Guid.NewGuid() }; var doorbell = connections.GetDoorbellSender(destination); await doorbell.SendAsync(new EventData(DoorbellMessage.Serialize(doorbellMessage))); logger.LogTrace($"{DateTime.UtcNow:o} Sent {doorbellMessage}"); } lastSendOrDoorbell = now; }
public virtual void WriteMessage(Stream stream) { if (stream == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream")); } Message message = this.CreateMessage(); using (message) { XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary, null, false); using (writer) { message.WriteMessage(writer); } } }
public void Test_Metadata() { foreach (var a in new DigitalSignatureAlgorithm[] { DigitalSignatureAlgorithm.Rsa2048_Sha256, DigitalSignatureAlgorithm.EcDsaP521_Sha256 }) { var id = new byte[32]; _random.NextBytes(id); var key = new Key(id, HashAlgorithm.Sha256); var tag = new Chat("oooo", new byte[32]); var miner = new Miner(CashAlgorithm.Version1, -1, TimeSpan.Zero); var digitalSignature = new DigitalSignature("123", a); var metadata = new ChatMessageMetadata(tag, DateTime.UtcNow, key, miner, digitalSignature); ChatMessageMetadata metadata2; { var ds = new DataContractSerializer(typeof(ChatMessageMetadata)); using (BufferStream stream = new BufferStream(BufferManager.Instance)) { using (WrapperStream wrapperStream = new WrapperStream(stream, true)) using (XmlDictionaryWriter xmlDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(wrapperStream)) { ds.WriteObject(xmlDictionaryWriter, metadata); } stream.Position = 0; using (XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { metadata2 = (ChatMessageMetadata)ds.ReadObject(xmlDictionaryReader); } } } Assert.AreEqual(metadata, metadata2, "Metadata #1"); ChatMessageMetadata metadata3; using (var metadataStream = metadata.Export(_bufferManager)) { metadata3 = ChatMessageMetadata.Import(metadataStream, _bufferManager); } Assert.AreEqual(metadata, metadata3, "Metadata #2"); Assert.IsTrue(metadata3.VerifyCertificate(), "Metadata #3"); } }
//public static T DeepClone<T>(this T toClone) //{ // using (var stream = new MemoryStream()) // { // var formatter = new BinaryFormatter(); // formatter.Serialize(stream, toClone); // stream.Seek(0, SeekOrigin.Begin); // return (T)formatter.Deserialize(stream); // } //} public static void BinarySerializeObject <T>(this T serializableObject, string fileName) { if (serializableObject == null) { return; } using (FileStream stream = File.Open(fileName, FileMode.Create)) { DataContractSerializer serializer = new DataContractSerializer(serializableObject.GetType()); using (XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream)) { serializer.WriteObject(binaryDictionaryWriter, serializableObject); binaryDictionaryWriter.Close(); } stream.Close(); } }
/// Saves the game and all currently set /// configurations to the game state file public void save() { if (ActiveSave != null) // TODO => param bool saveGameState { ActiveSave.SavedDate = DateTime.Now; if (!SaveStates.Contains(ActiveSave)) { SaveStates.Add(ActiveSave); } } DataContractSerializer serializer = new DataContractSerializer(typeof(GameManager)); Stream stream = File.Open(GameStateFile, FileMode.Create); using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) serializer.WriteObject(writer, this); }
private static byte[] SerializeServiceExceptionData(ServiceExceptionData msg) { if (msg == null) { return(null); } using (var stream = new MemoryStream()) { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { serviceExceptionDataSerializer.WriteObject(writer, msg); writer.Flush(); return(stream.ToArray()); } } }
private XmlDictionaryWriter GetXmlWriter(BufferManager bufferManager, int offset) { int startSize = EstimateMessageSize(); // Reuse created writer and stream if possible, they are created on first call if (_writer != null) { _stream.Reset(bufferManager, offset, startSize); } else { _stream = new BufferManagerStream(bufferManager, offset, startSize, MaxStreamAllocationSize); _writer = XmlDictionaryWriter.CreateBinaryWriter(_stream); } return(_writer); }
/// <summary> /// Gets the property bag from the current activity. /// </summary> /// <returns>Property bag as a byte array. Null if no property bag is found.</returns> public static byte[] GetBaggageFromActivity() { // We expect the baggage to not be there at all or just contain a few small items Activity currentActivity = Activity.Current; if (currentActivity.Baggage.Any()) { using (var ms = new MemoryStream()) { var dictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms); _baggageSerializer.WriteObject(dictionaryWriter, currentActivity.Baggage); dictionaryWriter.Flush(); return(ms.GetBuffer()); } } return(null); }
static void Main_1(string[] args) { DataContractSerializer ser = new DataContractSerializer(typeof(Person)); Person p = new Person { Name = "khushal", Age = 1, Addresses = new List <Address>() { new Address() { city = "Bangalore", state = "Karnataka", zipCode = "560085" }, new Address() { city = "Bangalore1", state = "Maharashtra", zipCode = "560085" } } }; using (Stream fs = File.OpenWrite("Person.xml")) { ser.WriteObject(fs, p); fs.Flush(); } using (XmlWriter writer = XmlWriter.Create("PersonUsingXml.xml", new XmlWriterSettings() { Indent = true, Encoding = Encoding.ASCII })) { ser.WriteObject(writer, p); writer.Flush(); } MemoryStream stream = new MemoryStream(); using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { ser.WriteObject(writer, p); } Console.WriteLine(Encoding.ASCII.GetString(stream.GetBuffer())); Console.ReadLine(); }
public static void IXmlBinaryReaderWriterInitializerTest() { DataContractSerializer serializer = new DataContractSerializer(typeof(TestData)); MemoryStream ms = new MemoryStream(); TestData td = new TestData(); XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms, null, null, false); IXmlBinaryWriterInitializer writerInitializer = (IXmlBinaryWriterInitializer)binaryWriter; writerInitializer.SetOutput(ms, null, null, false); serializer.WriteObject(ms, td); binaryWriter.Flush(); byte[] xmlDoc = ms.ToArray(); binaryWriter.Close(); XmlDictionaryReader binaryReader = XmlDictionaryReader.CreateBinaryReader(xmlDoc, 0, xmlDoc.Length, null, XmlDictionaryReaderQuotas.Max, null, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { })); IXmlBinaryReaderInitializer readerInitializer = (IXmlBinaryReaderInitializer)binaryReader; readerInitializer.SetInput(xmlDoc, 0, xmlDoc.Length, null, XmlDictionaryReaderQuotas.Max, null, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { })); binaryReader.ReadContentAsObject(); binaryReader.Close(); }
/// <summary> /// Сериализовать. /// </summary> /// <param name="obj">Объект.</param> /// <returns>Сериализованное медиа.</returns> private byte[] SerializeToBytes(T obj) { if (obj == null) { return(null); } var serializer = DataContractSerializerCache.GetSerializer <TBase>(); using (var str = new MemoryStream()) { using (var wr = XmlDictionaryWriter.CreateBinaryWriter(str)) { serializer.WriteObject(wr, ValidateContract(obj)); wr.Flush(); } return(str.ToArray()); } }
/// <summary> /// Сериализовать контракт данных. /// </summary> /// <typeparam name="T">Тип контракта.</typeparam> /// <param name="obj">Объект.</param> /// <returns>Байты.</returns> protected byte[] SerializeDataContract <T>(T obj) { if (obj == null) { return(null); } var serializer = DataContractSerializerCache.GetSerializer <T>(); using (var str = new MemoryStream()) { using (var wr = XmlDictionaryWriter.CreateBinaryWriter(str)) { serializer.WriteObject(wr, obj); wr.Flush(); } return(str.ToArray()); } }
public IMessageHeader SerializeRequestHeader(IServiceRemotingRequestMessageHeader serviceRemotingRequestMessageHeader) { if (serviceRemotingRequestMessageHeader == null) { return(null); } using (var stream = new SegmentedPoolMemoryStream(this.bufferPoolManager)) { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { this.requestHeaderSerializer.WriteObject(writer, serviceRemotingRequestMessageHeader); writer.Flush(); return(new OutgoingMessageHeader(stream.GetBuffers())); } } }
private static Message CreateBrokeredMessage <T>(T message) where T : class { var json = JsonConvert.SerializeObject(message); //Creates a message that is compatible with .NET 4.5 BrokeredMessage subscribers Message brokeredMessage; var ser = new DataContractSerializer(typeof(string)); using (var ms = new MemoryStream()) { var binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms); ser.WriteObject(binaryDictionaryWriter, json); binaryDictionaryWriter.Flush(); brokeredMessage = new Message(ms.ToArray()); } return(brokeredMessage); }
private static void Test2() { Employee employee = new Employee { Id = "123", Deptment = "生产", Name = "lhl", Sex = "M" }; var session = new XmlBinaryWriterSession(); XmlDictionary dictionary = new XmlDictionary(); dictionary.Add("Employee"); dictionary.Add("Id"); dictionary.Add("Name"); dictionary.Add("Gender"); WriteObject <Employee>(employee, (stream) => XmlDictionaryWriter.CreateBinaryWriter(stream, dictionary, session, false)); }
public override IModuleDataModel Clone() { using (var stream = new MemoryStream()) { var ds = new DataContractSerializer(GetType()); using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateBinaryWriter(stream)) { ds.WriteObject(w, this); } using (var effectDataIn = new MemoryStream(stream.ToArray())) { using (XmlDictionaryReader r = XmlDictionaryReader.CreateBinaryReader(effectDataIn, XmlDictionaryReaderQuotas.Max)) { return((IModuleDataModel)ds.ReadObject(r)); } } } }
public Task SerializePropertiesAsync(IDictionary <string, object> properties) { properties = (IDictionary <string, object>) new Dictionary <string, object>(properties); return(Task.Run((Action)(() => { bool flag = false; using (IsolatedStorageFile storeForApplication = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream storageFileStream = storeForApplication.OpenFile("PropertyStore.forms.tmp", System.IO.FileMode.OpenOrCreate)) { using (XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter((Stream)storageFileStream)) { try { new DataContractSerializer(typeof(Dictionary <string, object>)).WriteObject(binaryWriter, properties); binaryWriter.Flush(); flag = true; } catch (Exception ex) { } } } } if (!flag) { return; } using (IsolatedStorageFile storeForApplication = IsolatedStorageFile.GetUserStoreForApplication()) { try { if (storeForApplication.FileExists("PropertyStore.forms")) { storeForApplication.DeleteFile("PropertyStore.forms"); } storeForApplication.MoveFile("PropertyStore.forms.tmp", "PropertyStore.forms"); } catch (Exception ex) { } } }))); }
protected override Formatter PrepareFormatter(Type type) { var name = ContractEvil.GetContractReference(type); var serializer = new DataContractSerializer(type, KnownTypes); return(new Formatter(name, stream => { using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max)) { return serializer.ReadObject(reader); } }, (o, stream) => { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream, null, null, false)) { serializer.WriteObject(writer, o); } })); }
public IMessageHeader SerializeResponseHeader(IServiceRemotingResponseMessageHeader serviceRemotingResponseMessageHeader) { if (serviceRemotingResponseMessageHeader == null) { return(null); } using (var stream = new MemoryStream()) { using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream)) { this.responseHeaderSerializer.WriteObject(writer, serviceRemotingResponseMessageHeader); writer.Flush(); var buffer = stream.ToArray(); return(new OutgoingMessageHeader(new ArraySegment <byte>(buffer))); } } }
/// <summary> /// Serizlize object using <see cref="XmlDictionaryWriter.CreateBinaryWriter(Stream)"/>. /// </summary> /// <typeparam name="T"> Type of object that will be serialized.</typeparam> /// <param name="entity"> Object to be serialized.</param> /// <param name="eof"> Serialized byte array of EOF marking. </param> /// <returns>Byte array with serialized data.</returns> public static byte[] BinarySerialize <T>(T entity, byte[] eof = null) { NetDataContractSerializer dataContractSerializer = new NetDataContractSerializer(); using (MemoryStream stream = new MemoryStream()) { XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream); dataContractSerializer.WriteObject(binaryDictionaryWriter, entity); binaryDictionaryWriter.Flush(); if (eof != null) { stream.Write(eof, 0, eof.Length); } binaryDictionaryWriter.Close(); return(stream.ToArray()); } }
public XmlDictionaryWriter OpenSection(XmlDictionaryReaderQuotas quotas) { if (bufferState != BufferState.Created) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidStateException()); } bufferState = BufferState.Writing; this.quotas = new XmlDictionaryReaderQuotas(); quotas.CopyTo(this.quotas); if (this.writer == null) { this.writer = XmlDictionaryWriter.CreateBinaryWriter(stream, XD.Dictionary, null, true); } else { ((IXmlBinaryWriterInitializer)this.writer).SetOutput(stream, XD.Dictionary, null, true); } return(this.writer); }
/// <summary> /// 序列化一个datacontract属性的对象 /// </summary> /// <param name="obj">要序列化的对象</param> /// <param name="rootName">xml字典的根名称,如:MyObject</param> /// <param name="rootNameSpace">xml的根命名空间,如:http://www.lhbis.com</param> /// <param name="knownTypes">其中包含可在对象图中呈现的类型</param> /// <returns>字节数组</returns> /// <remarks>只有在程序集里同一个命名空间下的对象才能互相序列化/反序列化. 否则反序列化可能不成功</remarks> public static byte[] SerializeDataContract(object obj, string rootName, string rootNameSpace, IEnumerable <Type> knownTypes) { var dictionary = new XmlDictionary(); var rootString = dictionary.Add(rootName); var namesapceString = dictionary.Add(rootNameSpace); using (var ms = new MemoryStream()) { using (var bw = XmlDictionaryWriter.CreateBinaryWriter(ms, dictionary)) { var ser = new DataContractSerializer(obj.GetType(), rootString, namesapceString, knownTypes); ser.WriteObject(bw, obj); bw.Flush(); ms.Position = 0; return(ms.ToArray()); } } }
public static byte[] BinarySerializeXML(string xml) { if (xml.IsBlank()) { return(null); } using (var stream2 = new MemoryStream()) { XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(stream2); using (var xmlReader = XmlReader.Create(new StringReader(xml))) { binaryDictionaryWriter.WriteNode(xmlReader, false); binaryDictionaryWriter.Flush(); return(stream2.ToArray()); } } }
static void Main(string[] args) { Employee employee = new Employee { Id = "001", Name = "张三", Gender = "男", Department = "销售部" }; var session = new XmlBinaryWriterSession(); XmlDictionary dictionary = new XmlDictionary(); dictionary.Add("Employee"); dictionary.Add("Id"); dictionary.Add("Name"); dictionary.Add("Gender"); dictionary.Add("Department"); WriteObject <Employee>(employee, stream => XmlDictionaryWriter.CreateBinaryWriter(stream, dictionary, session, false)); }