public Messenger( Transporter channel, SerializerFactory serializerFactory, DeserializerFactory deserializerFactory, MessageTypeInfo[] outputMessages, MessageTypeInfo[] inputMessages) { _channel = channel; _channel.OnReceive += _channel_OnReceive; _channel.OnDisconnect += (c, e) => ChannelIsDisconnected?.Invoke(this, e); var outputSayMessageSerializes = new Dictionary <int, ISerializer>(); foreach (var messageSayInfo in outputMessages) { var serializer = serializerFactory.Create(messageSayInfo.ArgumentTypes); var hasReturnType = messageSayInfo.ReturnType != typeof(void); outputSayMessageSerializes.Add(messageSayInfo.MessageId, serializer); if (hasReturnType) { _inputSayMessageDeserializeInfos.Add( -messageSayInfo.MessageId, InputMessageDeserializeInfo.CreateForAnswer( deserializerFactory.Create(messageSayInfo.ReturnType))); } } foreach (var messageSayInfo in inputMessages) { var hasReturnType = messageSayInfo.ReturnType != typeof(void); var deserializer = deserializerFactory.Create(messageSayInfo.ArgumentTypes); _inputSayMessageDeserializeInfos.Add( messageSayInfo.MessageId, InputMessageDeserializeInfo.CreateForAsk(messageSayInfo.ArgumentTypes.Length, hasReturnType, deserializer)); if (hasReturnType) { outputSayMessageSerializes.Add(-messageSayInfo.MessageId, serializerFactory.Create(messageSayInfo.ReturnType)); } } _inputSayMessageDeserializeInfos.Add(Messenger.ExceptionMessageTypeId, InputMessageDeserializeInfo.CreateForExceptionHandling()); _sender = new Sender(_channel, outputSayMessageSerializes); }
/// <summary> /// Deserializes DeltaCache from file. /// </summary> public void Deserialize() { lock (syncLock) { ISerializer <DeltaCacheItem> iSerializer = SerializerFactory.Create <DeltaCacheItem>(SerializationFormat.XML); List <DeltaCacheItem> list = null; try { list = iSerializer.DeserializeListFromFile(DeltaCacheFileName); } catch (Exception cexc) { if (cexc.Message.Contains("Bad PKCS7 padding") || cexc.Message.Contains("Padding is invalid and cannot be removed")) { // attempt to deserialize file with no encryption. list = iSerializer.DeserializeListFromFile(DeltaCacheFileName, EncryptionMode.NoEncryption); } else { throw; } } if (list == null) { return; } foreach (DeltaCacheItem item in list) { this.Add(item, false); } } }
/// <summary> /// Sauvegarde l'instance du manager de contact en utilisant la méthode de /// sérialisation spécifiée. /// </summary> /// <param name="serialisationMethod">La méthode de sérialisation à utiliser pour la sérialisation.</param> private void SaveToFile(string serialisationMethod) { string filePath = GetFilePath(); Console.WriteLine("Ajoutez un mot de passe (Peut être vide, utilisera le SID): "); string password = Console.ReadLine(); byte[] encryptionKey = ContactManagerCryptography.GetKeyFromPassword(password); try { IContactManagerSerializer serializer = SerializerFactory.Create(serialisationMethod); using (FileStream fileStream = new FileStream(filePath, FileMode.Create)) { using (CryptoStream cryptoStream = ContactManagerCryptography.EncryptionStream(encryptionKey, fileStream)) { serializer.Serialize(cryptoStream, _contactManager); Console.WriteLine($"Contacts sauvegardés dans: \"{filePath}\""); } } } catch (SerializationException e) { Console.WriteLine($"Erreur de sauvegarde: {e.Message}"); } catch (ArgumentException) { Console.WriteLine("Type de sérialisation invalide."); } }
public void Execute() { var xml = @"<?xml version=""1.0"" ?> <Messages xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://tempuri.net/NServiceBus.Core.Tests.Serializers.XML"" xmlns:baseType=""NServiceBus.Core.Tests.Serializers.XML.IMyBusMessage""> <FirstMessage></FirstMessage> <SecondMessage></SecondMessage> <SecondMessage></SecondMessage> <SecondMessage></SecondMessage> </Messages> "; using (Stream stream = new MemoryStream()) { var writer = new StreamWriter(stream); writer.Write(xml); writer.Flush(); stream.Position = 0; var serializer = SerializerFactory.Create(typeof(IMyBusMessage), typeof(FirstMessage), typeof(SecondMessage)); var messageDeserialized = serializer.Deserialize(stream); Assert.IsInstanceOf <FirstMessage>(messageDeserialized[0]); Assert.IsInstanceOf <SecondMessage>(messageDeserialized[1]); Assert.IsInstanceOf <SecondMessage>(messageDeserialized[2]); Assert.IsInstanceOf <SecondMessage>(messageDeserialized[3]); } }
virtual public void Serialize(Stream stream, Encoding encoding) { foreach (DictionaryEntry de in m_object.Properties) { Property p = (Property)de.Value; ISerializable serializer = SerializerFactory.Create(p); if (serializer != null) { serializer.Serialize(stream, encoding); } } foreach (DictionaryEntry de in m_object.Parameters) { Parameter p = (Parameter)de.Value; ISerializable serializer = SerializerFactory.Create(p); if (serializer != null) { serializer.Serialize(stream, encoding); } } foreach (DDay.iCal.Objects.iCalObject obj in m_object.Children) { ISerializable serializer = SerializerFactory.Create(obj); if (serializer != null) { serializer.Serialize(stream, encoding); } } }
/// <summary> /// 构造函数 /// </summary> /// <param name="hostName"></param> /// <param name="userName"></param> /// <param name="port"></param> /// <param name="password"></param> /// <param name="maxQueueCount"></param> /// <param name="serializerType"></param> /// <param name="loger"></param> /// <param name="writeWorkerTaskNumber"></param> private RabbitMQClient(string hostName, string userName, string password, int?port, int maxQueueCount , SerializerType serializerType, ILoger loger = null, short writeWorkerTaskNumber = 4) { factory = new ConnectionFactory(); factory.HostName = hostName; if (!port.HasValue || port.Value < 0) { factory.Port = 5672; } else { factory.Port = port.Value; } factory.Password = password; factory.UserName = userName; serializer = SerializerFactory.Create(serializerType); _queue = new System.Collections.Concurrent.BlockingCollection <StrongBox <QueueMessage> >(); _maxQueueCount = maxQueueCount > 0 ? maxQueueCount : Options.DefaultMaxQueueCount; this.loger = loger; var scheduler = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, writeWorkerTaskNumber).ExclusiveScheduler; TaskFactory taskFactory = new TaskFactory(scheduler); for (int i = 0; i < writeWorkerTaskNumber; i++) { taskFactory.StartNew(QueueToWrite, TaskCreationOptions.LongRunning); } }
/// <summary> /// Deserializes the cache index. /// </summary> /// <param name="serializeFileName">Name of the serialize file.</param> /// <returns></returns> public static CacheIndex DeserializeCacheIndex(string serializeFileName) { lock (staticLock) { CacheIndex cacheIndex = null; ISerializer <CacheIndex> iSerializer = SerializerFactory.Create <CacheIndex>(SerializationFormat.XML); try { cacheIndex = iSerializer.DeserializeObjectFromFile(serializeFileName); if (cacheIndex != null) { cacheIndex.PreFetchIndexEnabled = true; cacheIndex.CleanIndexEnabled = true; } } catch (Exception cexc) { if (cexc.Message.Contains("Bad PKCS7 padding") || cexc.Message.Contains("Padding is invalid and cannot be removed")) { // attempt to deserialize file with no encryption. cacheIndex = iSerializer.DeserializeObjectFromFile(serializeFileName, EncryptionMode.NoEncryption); } else { throw; } } return(cacheIndex); } }
private string SerializeContent() { var serializer = SerializerFactory.Create(_contentType); var serializedContent = serializer.Serialize(this._content); return(serializedContent); }
private void Marshal(Type type, AttributeExtCollection attributes, object val, CdrOutputStream cdrOut) { Serializer ser = m_serFactory.Create(type, attributes); ser.Serialize(val, cdrOut); }
private object Unmarshal(Type type, AttributeExtCollection attributes, CdrInputStream cdrIn) { Serializer ser = m_serFactory.Create(type, attributes); return(ser.Deserialize(cdrIn)); }
public void Execute() { var xml = @"<?xml version=""1.0"" ?> <Messages xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns=""http://tempuri.net/NameSpace2"" xmlns:q1=""http://tempuri.net/NameSpace1"" xmlns:baseType=""NameSpace1.IMyBusMessage""> <FirstMessage></FirstMessage> <q1:FirstMessage></q1:FirstMessage> </Messages> "; using (Stream stream = new MemoryStream()) { var writer = new StreamWriter(stream); writer.Write(xml); writer.Flush(); stream.Position = 0; var serializer = SerializerFactory.Create(typeof(IMyBusMessage), typeof(NameSpace1.FirstMessage), typeof(NameSpace2.FirstMessage)); var messageDeserialized = serializer.Deserialize(stream); Assert.IsInstanceOf <NameSpace2.FirstMessage>(messageDeserialized[0]); Assert.IsInstanceOf <NameSpace1.FirstMessage>(messageDeserialized[1]); } }
public static (AdfItemType type, object value) Deserialize(string file) { var jsonString = File.ReadAllText(file); var serializer = factory.Create(jsonString); return(serializer.Deserialize()); }
/// <summary> /// 使用rabbitmq,针对同一服务,只允许调用一次 /// </summary> /// <param name="server"></param> /// <param name="config">rabbitmq配置</param> /// <param name="logger"></param> /// <returns></returns> public static IMissionServer UseRabbit(this IMissionServer server, RabbitMissionConfig config, ILogger logger = null) { var middleWare = new RabbitMqMiddleWare(config); var serializer = SerializerFactory.Create(config.SerializerType); server.UseMiddleWare(middleWare, serializer, logger); return(server); }
/// <summary> /// Serializes DeltaCache to file. /// </summary> public void Serialize() { lock (syncLock) { ISerializer <DeltaCacheItem> iSerializer = SerializerFactory.Create <DeltaCacheItem>(SerializationFormat.XML); iSerializer.SerializeListToFile(this.ToList(), DeltaCacheFileName); } }
public static IServiceCollection AddSerialization(this IServiceCollection serviceCollection, SerializerType type = SerializerType.SystemTextJson) { var serializer = SerializerFactory.Create(type); serviceCollection.AddSingleton <ISerializer>(serializer); return(serviceCollection); }
internal CodecImplEncap(GiopVersion version, SerializerFactory serFactory) { m_version = version; m_serFactory = serFactory; m_serializerForAnyType = m_serFactory.Create(ReflectionHelper.ObjectType, AttributeExtCollection.EmptyCollection); }
internal RabbitMqMiddleWare(RabbitMissionConfig config) { _serializer = SerializerFactory.Create(config.SerializerType); _config = config; _factory = new ConnectionFactory { Uri = new Uri(config.Uri) }; }
private void GenericFactoryTest(Type createFor, Type expectedSerType) { SerializerFactory factory = m_serFactory; Serializer ser = factory.Create(createFor, AttributeExtCollection.EmptyCollection); Assert.AreEqual(expectedSerType, ser.GetType(), "wrong serializer type"); }
/// <summary> /// Parses a xml into a StatusNotification object. /// </summary> /// <param name="notificationXml"></param> /// <returns></returns> public StatusNotification ParseNotification(string notificationXml) { // Gets a xml serializer. ISerializer serializer = SerializerFactory.Create("xml"); // Parses the xml into a StatusNotification object. StatusNotification statusNotification = serializer.DeserializeObject <StatusNotification>(notificationXml); return(statusNotification); }
/// <summary> /// 使用rabbitmq,针对同一客户端,只允许调用一次 /// </summary> /// <param name="client"></param> /// <param name="config">rabbitmq配置</param> /// <param name="logger"></param> /// <returns></returns> public static IMissionClient UseRabbit(this IMissionClient client, RabbitMissionConfig config, ILogger logger = null) { var middleWare = new RabbitMqMiddleWare(config); var serializer = SerializerFactory.Create(config.SerializerType); client.UseMiddleWare(middleWare, serializer, logger); client.UseHttpClient(config.ServerHost); client.StartSubscribe(); return(client); }
/// <summary> /// Serializa um objeto para uma string Json ou Xml /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="httpContentType"></param> /// <returns></returns> private string SerializeObject <T>(T obj, HttpContentTypeEnum httpContentType) { // Obtém um serializador para o content type definido. ISerializer serializer = SerializerFactory.Create(httpContentType.ToString()); // Recupera a string correspondente ao objeto serializado string serializedString = serializer.SerializeObject <T>(obj); return(serializedString); }
/// <summary> /// Realiza a deserialização de uma string Json ou Xml para um objeto /// </summary> /// <typeparam name="T"></typeparam> /// <param name="serializedObject"></param> /// <param name="httpContentType"></param> /// <returns></returns> private T DeserializeObject <T>(string serializedObject, HttpContentTypeEnum httpContentType) { // Obtém um serializador para o content type definido. ISerializer serializer = SerializerFactory.Create(httpContentType.ToString()); // Realiza a deserialização da string para o objeto informado T obj = serializer.DeserializeObject <T>(serializedObject); return(obj); }
public void Serialize(System.Xml.XmlTextWriter xtw) { foreach (object obj in m_Array) { IXCalSerializable serializer = SerializerFactory.Create(obj); if (serializer != null) { serializer.Serialize(xtw); } } }
virtual public void Serialize(Stream stream, Encoding encoding) { foreach (object obj in m_Array) { ISerializable serializer = SerializerFactory.Create(obj); if (serializer != null) { serializer.Serialize(stream, encoding); } } }
public override string SerializeToString() { if (m_Binary.Uri != null) { ISerializable serializer = SerializerFactory.Create(m_Binary.Uri); return(serializer.SerializeToString()); } else { return(Convert.ToBase64String(m_Binary.Data)); } }
public override string SerializeToString() { if (m_Binary.Uri != null) { IXCalSerializable serializer = SerializerFactory.Create(m_Binary.Uri); return serializer.SerializeToString(); } else { UTF8Encoding encoding = new UTF8Encoding(); return Encode(encoding.GetString(m_Binary.Data)); } }
virtual public void Serialize(XmlTextWriter xtw) { if (Object.Name != null) { // Serialize "VERSION" before any other properties if (Object.Properties.ContainsKey("VERSION")) { Property p = (Property)Object.Properties["VERSION"]; IXCalSerializable serializer = SerializerFactory.Create(p); if (serializer != null) { serializer.Serialize(xtw); } } foreach (DictionaryEntry de in Object.Properties) { // Don't serialize "VERSION" again, we've already done it above. if (de.Key.Equals("VERSION")) { continue; } Property p = (Property)de.Value; IXCalSerializable serializer = SerializerFactory.Create(p); if (serializer != null) { serializer.Serialize(xtw); } } foreach (DictionaryEntry de in Object.Parameters) { Parameter p = (Parameter)de.Value; IXCalSerializable serializer = SerializerFactory.Create(p); if (serializer != null) { serializer.Serialize(xtw); } } } foreach (DDay.iCal.Components.iCalObject obj in Object.Children) { IXCalSerializable serializer = SerializerFactory.Create(obj); if (serializer != null) { serializer.Serialize(xtw); } } }
public byte[] encode_value(object data) { CdrEncapsulationOutputStream outputStream = new CdrEncapsulationOutputStream(m_version); if (!(data is Any)) { Serializer ser = m_serFactory.Create(data.GetType(), AttributeExtCollection.EmptyCollection); ser.Serialize(data, outputStream); } else { Type marshalAs = ((TypeCodeImpl)((Any)data).Type).GetClsForTypeCode(); AttributeExtCollection marshalAsAttrs = ((TypeCodeImpl)((Any)data).Type).GetClsAttributesForTypeCode(); Serializer ser = m_serFactory.Create(marshalAs, marshalAsAttrs); ser.Serialize(data, outputStream); } return(outputStream.GetEncapsulationData()); }
public override string SerializeToString() { List <string> values = new List <string>(); foreach (object obj in m_RDate.Items) { ISerializable serializer = SerializerFactory.Create(obj); if (serializer != null) { values.Add(serializer.SerializeToString()); } } return(string.Join(",", values.ToArray())); }
public override string SerializeToString() { if (m_Binary.Uri != null) { ISerializable serializer = SerializerFactory.Create(m_Binary.Uri); return(serializer.SerializeToString()); } else { // NOTE: fixed a bug pointed out by Tony Dubey that caused binary data // to be converted to a UTF8 string before being serialized into // a BASE64 char array (which caused data loss). return(Encode(m_Binary.Data)); } }