Beispiel #1
0
 private byte[] SerializeEvent(AuditEvent auditEvent)
 {
     if (CustomSerializer != null)
     {
         return(CustomSerializer.Invoke(auditEvent));
     }
     return(Encoding.UTF8.GetBytes(auditEvent.ToJson()));
 }
        public void Add_Resolve_Success()
        {
            var mySerializer = new CustomSerializer(typeof(int), null, 1, null);

            var serializerCollection = (SerializerCollection)SerializerCollection.New.Add(mySerializer);

            serializerCollection.ResolveSerializer(typeof(int)).Should().Be(mySerializer);
        }
        public virtual void Write(System.Xml.XmlElement xElement, string name, TestSerializeData obj)
        {
            var node = xElement.OwnerDocument.CreateElement(name);

            xElement.AppendChild(node);
            ReXmlSerializer.Write(xElement, "helloInt", obj.helloInt);
            CustomSerializer.GetSerializer <TestSerializeData>().Write(xElement, "testData", obj.testData);
        }
Beispiel #4
0
        public void Save <T>(string filename, List <T> objects)
        {
            CustomSerializer customSerializer = new CustomSerializer(typeof(List <T>));

            using (FileStream fs = new FileStream(filename, FileMode.Create))
            {
                customSerializer.Serialize(fs, objects);
            }
        }
Beispiel #5
0
        public void SetTestsFromFile(string filePath)
        {
            var tests = CustomSerializer.GetObject <IList <Test> >(filePath);

            foreach (var test in tests)
            {
                _tests.Enqueue(test);
            }
        }
Beispiel #6
0
        public override object Deserialize(XmlTextReader r, Type type)
        {
            var col          = type.Assembly.CreateInstance(type.FullName);
            var instanceName = r.Name;

            if (r.IsEmptyElement)
            {
                return(col);
            }
            var addToColl = type.GetMethod("Add");

            r.Read();

            // Loop until end of collection
            while (!(r.NodeType == XmlNodeType.EndElement && r.Name == instanceName))
            {
                // Skip the end element node
                if (r.NodeType == XmlNodeType.EndElement)
                {
                    r.Read();
                }

                // Skip over white space or comments
                while (r.NodeType == XmlNodeType.Whitespace ||
                       r.NodeType == XmlNodeType.Comment)
                {
                    r.Read();
                }

                if (r.NodeType != XmlNodeType.Element)
                {
                    continue;
                }
                var childType = addToColl.GetParameters()[0].ParameterType;

                object   child = CustomSerializer.DeserializeObject(r, childType);
                object[] args  = { child };
                addToColl.Invoke(col, args);

                // break the endless loop if the object is an 'empty' object.
                if (r.IsEmptyElement)
                {
                    r.Read();
                }

                //else if (r.NodeType != XmlNodeType.EndElement)
                //{
                //    // Only an Element or EndElement is valid so throw an exception
                //    //throw new FrameworkException(
                //        //string.Format("CollectionSerializer expects all Xml nodes but found {0} node: {1}",
                //        //r.NodeType.ToString(), r.Value));
                //}
            }

            return(col);
        }
Beispiel #7
0
        public void JSON_SerializationAndDeserialization_ForACollection_Test(CatsCollection <Cat> cats, string filepath)
        {
            CustomSerializer <CatsCollection <Cat> > serializer = new CustomSerializer <CatsCollection <Cat> >();

            serializer.SerializeToJson(cats, filepath);

            CatsCollection <Cat> t_cats = serializer.DeserializeFromJson(filepath);

            Assert.Equal(cats, t_cats);
        }
Beispiel #8
0
 public CustomSerializer[] GetSerializers()
 {
     CustomSerializer[] jsonConverters = new CustomSerializer[]
     {
         new AbstractTypeSerializer <IAsymmetricPublicKey, BouncyCastlePublicKey>(),
         new AbstractTypeSerializer <IAsymmetricPrivateKey, BouncyCastlePrivateKey>(),
         new AbstractTypeSerializer <IAsymmetricKeyPair, BouncyCastleKeyPair>(),
     };
     return(jsonConverters);
 }
Beispiel #9
0
        public void JSON_SerializationAndDeserialization_ForAClassObject_Test(Cat cat, string filepath)
        {
            CustomSerializer <Cat> serializer = new CustomSerializer <Cat>();

            serializer.SerializeToJson(cat, filepath);

            Cat t_cat = serializer.DeserializeFromJson(filepath);

            Assert.Equal(cat, t_cat);
        }
Beispiel #10
0
        public void XmlAttributeDeserializesIntoProperty()
        {
            var xml = @"<AttributeContainer SomeValue=""abc""></AttributeContainer>";

            var serializer = new CustomSerializer<AttributeContainer>(null, TestXmlSerializerOptions.Empty);

            var container = (AttributeContainer)serializer.DeserializeObject(xml);

            Assert.That(container.SomeValue, Is.EqualTo("abc"));
        }
Beispiel #11
0
        public UserAccount ValidateUser(string userName, string password)
        {
            var users = new List <UserAccount>();

            users = CustomSerializer <UserAccount> .Read(xmlFileName);

            var user = users.FirstOrDefault(p => p.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase));

            return(user);
        }
Beispiel #12
0
        public void XmlAttributeDeserializesIntoProperty()
        {
            var xml = @"<AttributeContainer SomeValue=""abc""></AttributeContainer>";

            var serializer = new CustomSerializer <AttributeContainer>(null, TestXmlSerializerOptions.Empty);

            var container = (AttributeContainer)serializer.DeserializeObject(xml);

            Assert.That(container.SomeValue, Is.EqualTo("abc"));
        }
Beispiel #13
0
        public void XmlAttributeDeserializesIntoProperty()
        {
            var xml = @"<AttributeContainer SomeValue=""abc""></AttributeContainer>";

            var serializer = new CustomSerializer<AttributeContainer>(null, null, null);

            var container = serializer.Deserialize(xml);

            Assert.That(container.SomeValue, Is.EqualTo("abc"));
        }
Beispiel #14
0
        public void EnumAttributeDeserializesCorrectlyWhenExtraTypesArePassedIn()
        {
            var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<EnumAttributeContainer xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" MyEnum=""Value2"" />";

            var serializer = new CustomSerializer<EnumAttributeContainer>(null, TestXmlSerializerOptions.WithExtraTypes(typeof(IFoo)));

            var container = (EnumAttributeContainer)serializer.DeserializeObject(xml);

            Assert.That(container.MyEnum, Is.EqualTo(MyEnum.Value2));
        }
Beispiel #15
0
    public static void Test()
    {
        var obj = new CustomString {
            Value = "Random string!"
        };
        var serializer = new CustomSerializer();
        var xml        = serializer.Serialize(obj);

        Console.WriteLine(xml);
        var obj2 = serializer.Deserialize <CustomString>(xml);
    }
Beispiel #16
0
        public void EnumAttributeDeserializesCorrectlyWhenExtraTypesArePassedIn()
        {
            var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<EnumAttributeContainer xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" MyEnum=""Value2"" />";

            var serializer = new CustomSerializer <EnumAttributeContainer>(null, TestXmlSerializerOptions.WithExtraTypes(typeof(IFoo)));

            var container = (EnumAttributeContainer)serializer.DeserializeObject(xml);

            Assert.That(container.MyEnum, Is.EqualTo(MyEnum.Value2));
        }
Beispiel #17
0
        public List <T> Open <T>(string filename)
        {
            CustomSerializer customSerializer = new CustomSerializer(typeof(List <T>));
            List <T>         objects          = new List <T>();

            using (FileStream fs = new FileStream(filename, FileMode.Open))
            {
                objects = customSerializer.Deserialize(fs) as List <T>;
            }

            return(objects);
        }
        private ICommand GetCommandFromMessage(ReceivedTransportMessage message)
        {
            if (UseCustomSerializer)
            {
                var deserializedMessage = CustomSerializer.Deserialize(message);
                if (deserializedMessage != null && deserializedMessage.Messages.Length > 0)
                {
                    var command = deserializedMessage.Messages[0] as ICommand;
                    if (command != null)
                    {
                        return(command);
                    }
                }
            }

            string body;

            switch (message.Headers["rebus-encoding"].ToString().ToLowerInvariant())
            {
            case "utf-7":
                body = Encoding.UTF7.GetString(message.Body);
                break;

            case "utf-8":
                body = Encoding.UTF8.GetString(message.Body);
                break;

            case "utf-32":
                body = Encoding.UTF32.GetString(message.Body);
                break;

            case "ascii":
                body = Encoding.ASCII.GetString(message.Body);
                break;

            case "unicode":
                body = Encoding.Unicode.GetString(message.Body);
                break;

            default:
                return(null);
            }

            var msg   = JsonConvert.DeserializeObject(body, _jsonSerializerSettings);
            var array = msg as Object[];

            if (array != null)
            {
                return(array[0] as ICommand);
            }

            return(null);
        }
Beispiel #19
0
        private static ConcurrentDictionary <CommandCode, CustomSerializer> commandCustomSerializer = new ConcurrentDictionary <CommandCode, CustomSerializer>(); // command code

        /// <summary>
        /// Register custom serializer for class name.
        /// </summary>
        /// <param name="className"> </param>
        /// <param name="serializer">
        /// @return </param>
        public static void registerCustomSerializer(Type className, CustomSerializer serializer)
        {
            if (classCustomSerializer.ContainsKey(className))
            {
                classCustomSerializer.TryGetValue(className, out var prevSerializer);
                throw new Exception("CustomSerializer has been registered for class: " + className + ", the custom serializer is: " + prevSerializer.GetType().FullName);
            }
            else
            {
                classCustomSerializer.TryAdd(className, serializer);
            }
        }
 public void Setup()
 {
     _serializer = new CustomSerializer();
     _broadcast  = new Broadcast(1, "Broadcast Name", BroadcastStatus.ARCHIVED,
                                 new DateTime(2014, 1, 1, 3, 0, 0), BroadcastType.TEXT,
                                 new TextBroadcastConfig(new CfTextBroadcastConfig(2, new DateTime(2014, 1, 1, 3, 0, 0),
                                                                                   "111", null, new CfBroadcastConfigRetryConfig(1, 1, new [] { CfResult.Busy }, new [] { CfRetryPhoneType.HomePhone }), "message", new CfBigMessageStrategy())))
     {
         idSpecified           = true,
         LastModifiedSpecified = true
     };
 }
Beispiel #21
0
        public void EnumElementDeserializesCorrectlyWhenIgnoreCaseForEnumIsPassedIn()
        {
            var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<EnumElementContainer xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
  <MyEnum>vALUE1</MyEnum>
</EnumElementContainer>";

            var serializer = new CustomSerializer<EnumElementContainer>(null, TestXmlSerializerOptions.WithExtraTypes());

            var container = (EnumElementContainer)serializer.DeserializeObject(xml, new TestSerializeOptions { ShouldIgnoreCaseForEnum = true });

            Assert.That(container.MyEnum, Is.EqualTo(MyEnum.Value1));
        }
Beispiel #22
0
        public void EnumElementDeserializesCorrectlyWhenExtraTypesArePassedIn()
        {
            var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <EnumElementContainer xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
              <MyEnum>Value2</MyEnum>
            </EnumElementContainer>";

            var serializer = new CustomSerializer<EnumElementContainer>(null, new[] { typeof(IFoo) }, null);

            var container = serializer.Deserialize(xml);

            Assert.That(container.MyEnum, Is.EqualTo(MyEnum.Value2));
        }
Beispiel #23
0
        public void EnumElementSerializesCorrectlyWhenExtraTypesArePassedIn()
        {
            var container = new EnumElementContainer
            {
                MyEnum = MyEnum.Value2
            };

            var serializer = new CustomSerializer<EnumElementContainer>(null, new[] { typeof(IFoo) }, null);

            var xml = serializer.Serialize(container, new XmlSerializerNamespaces(), Encoding.UTF8, Formatting.Indented);

            Assert.That(xml, Contains.Substring("Value2"));
        }
Beispiel #24
0
        public void EnumAttributeDeserializesCorrectlyWhenIgnoreCaseForEnumIsPassedIn()
        {
            var xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<EnumAttributeContainer xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" MyEnum=""vALUE1"" />";

            var serializer = new CustomSerializer <EnumAttributeContainer>(null, TestXmlSerializerOptions.WithExtraTypes());

            var container = (EnumAttributeContainer)serializer.DeserializeObject(xml, new TestSerializeOptions {
                ShouldIgnoreCaseForEnum = true
            });

            Assert.That(container.MyEnum, Is.EqualTo(MyEnum.Value1));
        }
        public bool SaveUser(UserAccount userAccount)
        {
            var userlist = new List <UserAccount>();

            if (System.IO.File.Exists(xmlFileName))
            {
                userlist = CustomSerializer <UserAccount> .Read(xmlFileName);
            }
            userlist.Add(userAccount);
            CustomSerializer <UserAccount> .Save(userlist, xmlFileName);

            return(true);
        }
Beispiel #26
0
        public void EnumAttributeSerializesCorrectlyWhenExtraTypesArePassedIn()
        {
            var container = new EnumAttributeContainer
            {
                MyEnum = MyEnum.Value2
            };

            var serializer = new CustomSerializer<EnumAttributeContainer>(null, TestXmlSerializerOptions.WithExtraTypes(typeof(IFoo)));

            var xml = serializer.SerializeObject(container, Encoding.UTF8, Formatting.Indented, new TestSerializeOptions());

            Assert.That(xml, Contains.Substring("Value2"));
        }
Beispiel #27
0
        public void EnumAttributeSerializesCorrectlyWhenExtraTypesArePassedIn()
        {
            var container = new EnumAttributeContainer
            {
                MyEnum = MyEnum.Value2
            };

            var serializer = new CustomSerializer <EnumAttributeContainer>(null, TestXmlSerializerOptions.WithExtraTypes(typeof(IFoo)));

            var xml = serializer.SerializeObject(container, Encoding.UTF8, Formatting.Indented, new TestSerializeOptions());

            Assert.That(xml, Contains.Substring("Value2"));
        }
        public void AddTwoCustomSerializers_Throws()
        {
            var myCustomSerializer1 = new CustomSerializer(typeof(int), null, 1, null);
            var myCustomSerializer2 = new CustomSerializer(typeof(int), null, 1, null);

            Action action = () =>
            {
                var serializerCollection = (SerializerCollection)SerializerCollection.New
                                           .Add(myCustomSerializer1)
                                           .Add(myCustomSerializer2);
            };

            action.ShouldThrow <ShapeshifterException>().Where(i => i.Id == Exceptions.SerializerAlreadyExistsId);
        }
Beispiel #29
0
        public void SerializeClassBObjectTest()
        {
            string           filePath   = Directory.GetCurrentDirectory() + "\\customSerialized.txt";
            CustomSerializer serializer = new CustomSerializer();

            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                serializer.Serialize(fileStream, classB);
            }
            FileInfo info = new FileInfo(filePath);

            Assert.IsTrue(info.Exists);
            Assert.IsTrue(info.Length >= 300);
        }
Beispiel #30
0
        internal override void WriteBytes(ByteWriter writer)
        {
            if (keySerializer == null)
            {
                keySerializer = CustomSerializer.Get <K>();
            }

            writer.WriteInt(Count);
            foreach (var pair in nodes)
            {
                keySerializer.WriteBytes(pair.Key, writer);
                pair.Value.WriteBytes(writer);
            }
        }
Beispiel #31
0
        static int port = 8005; // порт для приема входящих запросов
        public void ServerStart()
        {
            // получаем адреса для запуска сокета
            IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

            // создаем сокет
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                // связываем сокет с локальной точкой, по которой будем принимать данные
                listenSocket.Bind(ipPoint);

                // начинаем прослушивание
                listenSocket.Listen(10);

                Console.WriteLine("Сервер запущен. Ожидание подключений...");

                while (true)
                {
                    Socket handler = listenSocket.Accept();
                    // получаем сообщение
                    StringBuilder builder = new StringBuilder();
                    int           bytes   = 0;             // количество полученных байтов
                    byte[]        data    = new byte[256]; // буфер для получаемых данных

                    do
                    {
                        bytes = handler.Receive(data);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }while (handler.Available > 0);

                    Console.WriteLine(DateTime.Now.ToShortTimeString() + ": " + builder.ToString());

                    // отправляем ответ
                    CustomSerializer customSerializer = new CustomSerializer();
                    string           message          = customSerializer.MyJSONToServerSerializer(militaryPlane);
                    data = Encoding.Unicode.GetBytes(message);
                    handler.Send(data);
                    // закрываем сокет
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public void RoundTripsCorrectly(object instance, Type type)
        {
            var customSerializer  = CustomSerializer.GetSerializer(type, null, TestXmlSerializerOptions.Empty);
            var defaultSerializer = new System.Xml.Serialization.XmlSerializer(type);

            var customXml  = customSerializer.SerializeObject(instance, Encoding.UTF8, Formatting.Indented, new TestSerializeOptions(shouldAlwaysEmitTypes: AlwaysEmitTypes)).StripXsiXsdDeclarations();
            var defaultXml = defaultSerializer.SerializeObject(instance, Encoding.UTF8, Formatting.Indented, new TestSerializeOptions(shouldAlwaysEmitTypes: AlwaysEmitTypes)).StripXsiXsdDeclarations();

            Console.WriteLine("Default XML:");
            Console.WriteLine(defaultXml);
            Console.WriteLine();
            Console.WriteLine("Custom XML:");
            Console.WriteLine(customXml);

            Assert.That(customXml, Is.EqualTo(defaultXml));
        }
Beispiel #33
0
        public async Task SaveSerializedDataAsync()
        {
            var path       = GetProjectsContentPath(SavePath.Value);
            var rootType   = Root.Value.Type;
            var serializer = rootType.GetMethods()
                             .FirstOrDefault(x => x.GetCustomAttribute <PwSerializerAttribute>() != null);

            if (serializer != null)
            {
                await CustomSerializer.SaveDataAsync(serializer, Root.Value, path);
            }
            else
            {
                await JsonSerializer.SaveDataAsync(Root.Value, path);
            }
        }
Beispiel #34
0
        public string GetUserId(XDocument xml)
        {
            var logins  = CustomSerializer.Deserializ <SysAdminUnit>(new MemoryStream(Encoding.UTF8.GetBytes(xml.ToString() ?? "")));
            var respond = new SysAdminUnitResponed();

            foreach (var login in logins.items)
            {
                respond.items.Add(new ItemRespond()
                {
                    ErrorCode = 1, ErrorDescription = "error1", IsSuccess = true, UserOneCGuid = Guid.NewGuid()
                });
            }
            var stream       = CustomSerializer.Serializ(respond);
            var srteamReader = new StreamReader(stream);

            return(srteamReader.ReadToEnd());
        }
Beispiel #35
0
        internal override void ReadBytes(ByteReader reader)
        {
            if (keySerializer == null)
            {
                keySerializer = CustomSerializer.Get <K>();
            }

            Clear();
            int count = reader.ReadInt();

            for (int i = 0; i < count; ++i)
            {
                var key   = (K)keySerializer.ReadBytes(reader);
                var value = Add(key, false);
                value.ReadBytes(reader);
            }
        }
        public void Benchmark()
        {
            const int Iterations = 50000;

            var xmlSerializer    = new System.Xml.Serialization.XmlSerializer(typeof(ContainerWithAbstract), null, null, null, null);
            var customSerializer = CustomSerializer.GetSerializer(typeof(ContainerWithInterface), null, TestXmlSerializerOptions.Empty);

            var xmlSerializerStopwatch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                using (var stringReader = new StringReader(_xmlWithAbstract))
                {
                    using (var reader = new XmlTextReader(stringReader))
                    {
                        xmlSerializer.Deserialize(reader);
                    }
                }
            }

            xmlSerializerStopwatch.Stop();

            var options = new TestSerializeOptions();

            var customSerializerStopwatch = Stopwatch.StartNew();

            for (int i = 0; i < Iterations; i++)
            {
                using (var stringReader = new StringReader(_xmlWithInterface))
                {
                    using (var xmlReader = new XmlTextReader(stringReader))
                    {
                        using (var reader = new XSerializerXmlReader(xmlReader, options.GetEncryptionMechanism(), options.EncryptKey, options.SerializationState))
                        {
                            customSerializer.DeserializeObject(reader, options);
                        }
                    }
                }
            }

            customSerializerStopwatch.Stop();

            Console.WriteLine("XmlSerializer Elapsed Time: {0}", xmlSerializerStopwatch.Elapsed);
            Console.WriteLine("CustomSerializer Elapsed Time: {0}", customSerializerStopwatch.Elapsed);
        }
Beispiel #37
0
 //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
 //ORIGINAL LINE: @Override public void serializeHeader(InvokeContext invokeContext) throws exception.SerializationException
 public override void serializeHeader(InvokeContext invokeContext)
 {
     if (CustomSerializer != null)
     {
         try
         {
             CustomSerializer.serializeHeader(this, invokeContext);
         }
         catch (SerializationException)
         {
             throw;
         }
         catch (Exception e)
         {
             throw new SerializationException("Exception caught when serialize header of rpc request command!", e);
         }
     }
 }