コード例 #1
0
        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);
        }
コード例 #2
0
ファイル: DeltaCache.cs プロジェクト: BenButzer/iFactr-Data
        /// <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);
                }
            }
        }
コード例 #3
0
        /// <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.");
            }
        }
コード例 #4
0
        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]);
            }
        }
コード例 #5
0
        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);
                }
            }
        }
コード例 #6
0
        /// <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);
            }
        }
コード例 #7
0
ファイル: CacheIndex.cs プロジェクト: BenButzer/iFactr-Data
 /// <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);
     }
 }
コード例 #8
0
        private string SerializeContent()
        {
            var serializer        = SerializerFactory.Create(_contentType);
            var serializedContent = serializer.Serialize(this._content);

            return(serializedContent);
        }
コード例 #9
0
        private void Marshal(Type type, AttributeExtCollection attributes,
                             object val, CdrOutputStream cdrOut)
        {
            Serializer ser = m_serFactory.Create(type, attributes);

            ser.Serialize(val, cdrOut);
        }
コード例 #10
0
        private object Unmarshal(Type type, AttributeExtCollection attributes,
                                 CdrInputStream cdrIn)
        {
            Serializer ser = m_serFactory.Create(type, attributes);

            return(ser.Deserialize(cdrIn));
        }
コード例 #11
0
        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]);
            }
        }
コード例 #12
0
        public static (AdfItemType type, object value) Deserialize(string file)
        {
            var jsonString = File.ReadAllText(file);

            var serializer = factory.Create(jsonString);

            return(serializer.Deserialize());
        }
コード例 #13
0
        /// <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);
        }
コード例 #14
0
ファイル: DeltaCache.cs プロジェクト: BenButzer/iFactr-Data
 /// <summary>
 /// Serializes DeltaCache to file.
 /// </summary>
 public void Serialize()
 {
     lock (syncLock)
     {
         ISerializer <DeltaCacheItem> iSerializer = SerializerFactory.Create <DeltaCacheItem>(SerializationFormat.XML);
         iSerializer.SerializeListToFile(this.ToList(), DeltaCacheFileName);
     }
 }
コード例 #15
0
    public static IServiceCollection AddSerialization(this IServiceCollection serviceCollection, SerializerType type = SerializerType.SystemTextJson)
    {
        var serializer = SerializerFactory.Create(type);

        serviceCollection.AddSingleton <ISerializer>(serializer);

        return(serviceCollection);
    }
コード例 #16
0
ファイル: Codec.cs プロジェクト: divyang4481/IIOPNet
 internal CodecImplEncap(GiopVersion version, SerializerFactory serFactory)
 {
     m_version              = version;
     m_serFactory           = serFactory;
     m_serializerForAnyType =
         m_serFactory.Create(ReflectionHelper.ObjectType,
                             AttributeExtCollection.EmptyCollection);
 }
コード例 #17
0
 internal RabbitMqMiddleWare(RabbitMissionConfig config)
 {
     _serializer = SerializerFactory.Create(config.SerializerType);
     _config     = config;
     _factory    = new ConnectionFactory {
         Uri = new Uri(config.Uri)
     };
 }
コード例 #18
0
        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");
        }
コード例 #19
0
        /// <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);
        }
コード例 #20
0
        /// <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);
        }
コード例 #21
0
        /// <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);
        }
コード例 #22
0
        /// <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);
        }
コード例 #23
0
 public void Serialize(System.Xml.XmlTextWriter xtw)
 {
     foreach (object obj in m_Array)
     {
         IXCalSerializable serializer = SerializerFactory.Create(obj);
         if (serializer != null)
         {
             serializer.Serialize(xtw);
         }
     }
 }
コード例 #24
0
 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);
         }
     }
 }
コード例 #25
0
 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));
     }
 }
コード例 #26
0
 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));
     }
 }        
コード例 #27
0
        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);
                }
            }
        }
コード例 #28
0
ファイル: Codec.cs プロジェクト: divyang4481/IIOPNet
        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());
        }
コード例 #29
0
        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()));
        }
コード例 #30
0
 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));
     }
 }