Esempio n. 1
0
 public void Serialize_WithNullInput_ThrowsArgumentNullException()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         string result = TypeSerializer.Serialize(null);
     });
 }
        public void BuiltInType_can_be_serialized_and_deserialized()
        {
            var builtIns = new []
            {
                new BuiltInType(BuiltInTypeKind.Any),
                new BuiltInType(BuiltInTypeKind.Null),
                new BuiltInType(BuiltInTypeKind.Bool),
                new BuiltInType(BuiltInTypeKind.Int),
                new BuiltInType(BuiltInTypeKind.String),
                new BuiltInType(BuiltInTypeKind.Object),
                new BuiltInType(BuiltInTypeKind.Array),
                new BuiltInType(BuiltInTypeKind.ResourceRef),
            };

            var serialized           = TypeSerializer.Serialize(builtIns);
            var deserializedBuiltIns = TypeSerializer.Deserialize(serialized);

            for (var i = 0; i < builtIns.Length; i++)
            {
                deserializedBuiltIns[i].Should().BeOfType <BuiltInType>();
                var deserializedBuiltIn = (BuiltInType)deserializedBuiltIns[i];

                deserializedBuiltIn.Kind.Should().Be(builtIns[i].Kind);
            }
        }
Esempio n. 3
0
 public void OnBeforeSerialize()
 {
     if (parameterTypes != null)
     {
         _parameterTypes = parameterTypes.Select(type => TypeSerializer.Serialize(type)).ToArray();
     }
 }
Esempio n. 4
0
 public void TypeSerialize <valueType>(valueType value)
 {
     if (value != null)
     {
         TypeSerializer <valueType> .Serialize(this, value);
     }
 }
Esempio n. 5
0
        /// <summary>
        /// 对象转换XML字符串
        /// </summary>
        /// <typeparam name="valueType">目标数据类型</typeparam>
        /// <param name="value">数据对象</param>
        private void serialize <valueType>(valueType value)
        {
            Warning = SerializeWarning.None;
            if (checkLoopDepth != Config.CheckLoopDepth)
            {
                if (Config.CheckLoopDepth <= 0)
                {
                    checkLoopDepth = 0;
                    if (forefather == null)
                    {
                        forefather = new object[sizeof(int)];
                    }
                }
                else
                {
                    checkLoopDepth = Config.CheckLoopDepth;
                }
            }
            CharStream.Write(Config.Header);
            fixed(char *nameFixed = Config.BootNodeName)
            {
                nameStart(nameFixed, Config.BootNodeName.Length);
                TypeSerializer <valueType> .Serialize(this, value);

                nameEnd(nameFixed, Config.BootNodeName.Length);
            }
        }
Esempio n. 6
0
    protected void Serialize(WriteTarget target)
    {
        Type type = target.item.GetType();

        context = target.item;
        int id;

        if (type.IsClass)
        {
            id = GetRefId(target.item);
            outputTargets[id] = target;
        }
        else
        {
            id = -1;
        }
        //string creationType = SerializerUtil.GetCreationType(type, context);
        TypeSerializer serializer = SerializerUtil.GetTypeSerializer(type);

        builder.Length = 0;
        writeCalls     = 0;
        serializer.Serialize(target.item, this);
        target.id         = id;
        target.fieldCount = writeCalls;
        target.fields     = builder.ToString();
        target.version    = serializer.GetVersion();
    }
        public void Test_Char()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var value      = 'o';
            var expected   = new byte[] { 0x6f };
            var actual     = serializer.Serialize(value);

            Assert.AreEqual(expected, actual);
        }
        public void Test_Null()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());

            var expected = new byte[0];
            var actual   = serializer.Serialize <string>(null);

            Assert.AreEqual(expected, actual);
        }
        public void Test_Deserialize_Int()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var five       = 5;
            var bytes      = serializer.Serialize(five);
            var actual     = serializer.Deserialize <int>(bytes, 0, bytes.Length);

            Assert.AreEqual(five, actual);
        }
        public void Test_Serialize_UInt64()
        {
            var    serializer = new TypeSerializer(new ManualByteConverter());
            UInt64 data       = 9;

            var expected = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09 };
            var actual   = serializer.Serialize(data);

            Assert.AreEqual(expected, actual);
        }
        public void Test_Deserialize_String()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var value      = "astring";
            var bytes      = serializer.Serialize(value);
            var bytes1     = Encoding.UTF8.GetBytes(value);
            var actual     = serializer.Deserialize <string>(bytes, 0, bytes.Length);

            Assert.AreEqual(value, actual);
        }
        public void Test_Serialize_UInt64()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            UInt64 data = 9;

            var expected = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09 };
            var actual = serializer.Serialize(data);

            Assert.AreEqual(expected, actual);
        }
        public void Test_Serialize_String()
        {
            var    serializer = new TypeSerializer(new ManualByteConverter());
            string data       = "Hello";

            var expected = new byte[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f };
            var actual   = serializer.Serialize(data);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 14
0
 public void TypeSerialize <valueType>(valueType value)
 {
     if (value == null)
     {
         CharStream.WriteJsonNull();
     }
     else
     {
         TypeSerializer <valueType> .Serialize(this, ref value);
     }
 }
        public void Test_Poco()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var value      = new Person {
                Name = "jeff"
            };
            var bytes = serializer.Serialize(value);

            var actual = serializer.Deserialize <Person>(new ArraySegment <byte>(bytes), 0, bytes.Length);

            Assert.AreEqual(value.Name, actual.Name);
        }
Esempio n. 16
0
 protected YuzuException Error(string message, params object[] args)
 {
     for (int i = 0; i < args.Length; ++i)
     {
         if (args[i] is Type)
         {
             args[i] = TypeSerializer.Serialize((Type)args[i]);
         }
     }
     return(new YuzuException(
                String.Format(message, args),
                Options.ReportErrorPosition ? new YuzuPosition(Reader.BaseStream.Position) : null));
 }
Esempio n. 17
0
        /// <summary>
        /// 準備したデータをシリアライズします。
        /// </summary>
        private void Serialize()
        {
            if (Data == null)
            {
                throw new PbException("Dataがnullです。");
            }

            SerializedData = PbUtil.Serialize(Data, Data.GetType());

            // 型名はPbConnectionでエンコードします。
            TypeName        = TypeSerializer.Serialize(Data.GetType());
            EncodedTypeName = PbConnection.EncodeTypeName(TypeName);
            EncodedTypeData = Encoding.UTF8.GetBytes(EncodedTypeName);
        }
Esempio n. 18
0
        protected object FromReaderIntGenerated(object obj)
        {
            KillBuf();
            Require('{');
            var    expectedType = obj.GetType();
            string name         = GetNextName(first: true);

            if (name == JsonOptions.ClassTag)
            {
                CheckExpectedType(RequireUnescapedString(), expectedType);
                name = GetNextName(first: false);
            }
            return(name == null ? obj :
                   MakeDeserializer(TypeSerializer.Serialize(obj.GetType())).ReadFields(obj, name));
        }
Esempio n. 19
0
        private ClassDef WriteClassId(object obj)
        {
            var      t = obj.GetType();
            ClassDef result;

            if (classIdCache.TryGetValue(t, out result))
            {
                writer.Write(result.Id);
                var g = result.Meta.GetUnknownStorage;
                if (g == null)
                {
                    return(result);
                }
                var i = g(obj).Internal;
                // If we have unknown fields, their definition must be present in the first serialized object,
                // but not necessariliy in subsequent ones.
                if (i != null && i != result.ReaderDef)
                {
                    throw new YuzuException("Conflictiing reader class definitions for unknown storage of " + t.Name);
                }
                return(result);
            }

            result = new ClassDef {
                Id = (short)(classIdCache.Count + unknownClassIdCache.Count + 1)
            };
            result.Meta     = Meta.Get(t, Options);
            classIdCache[t] = result;
            if (result.Meta.GetUnknownStorage == null)
            {
                PrepareClassDefFields(result);
            }
            else
            {
                result.ReaderDef = result.Meta.GetUnknownStorage(obj).Internal as ReaderClassDef;
                if (result.ReaderDef == null)
                {
                    PrepareClassDefFields(result);
                }
                else
                {
                    PrepareClassDefFieldsUnknown(result);
                }
            }
            WriteClassDefFields(result, result.Meta.WriteAlias ?? TypeSerializer.Serialize(result.Meta.Type));
            return(result);
        }
Esempio n. 20
0
        private Surrogate GetSurrogate <T>(Type actualType)
        {
            var sg = Meta.Get(typeof(T), Options).Surrogate;

            if (sg.FuncFrom == null)
            {
                throw Error(
                          "Expected type '{0}', but got '{1}'",
                          typeof(T), actualType == null ? "number" : TypeSerializer.Serialize(actualType));
            }
            if (actualType != null && !sg.SurrogateType.IsAssignableFrom(actualType))
            {
                throw Error(
                          "Expected type '{0}' or '{1}', but got '{2}'",
                          typeof(T), sg.SurrogateType.Name, actualType);
            }
            return(sg);
        }
Esempio n. 21
0
        /// <summary>
        /// Assign the parameter types to their underlying properties
        /// </summary>
        public static void SerializeParameterTypes(SerializedProperty parameterTypesProperty, Type[] parameterTypes)
        {
            if (parameterTypes == null)
            {
                parameterTypesProperty.arraySize = 0;
            }
            else
            {
                parameterTypesProperty.arraySize = parameterTypes.Length;

                for (int i = 0; i < parameterTypesProperty.arraySize; i++)
                {
                    SerializedProperty parameterTypeProperty = parameterTypesProperty.GetArrayElementAtIndex(i);

                    parameterTypeProperty.stringValue = TypeSerializer.Serialize(parameterTypes[i]);
                }
            }
        }
Esempio n. 22
0
        public void Serialize_WithAllProperties_ReturnsCorrectlySequencedFields()
        {
            Address hl7Type = new()
            {
                StreetAddress              = "1",
                OtherDesignation           = "2",
                City                       = "3",
                StateOrProvince            = "4",
                ZipOrPostalCode            = "5",
                Country                    = "6",
                AddressType                = "7",
                OtherGeographicDesignation = "8"
            };

            string expected = "1^2^3^4^5^6^7^8";
            string actual   = TypeSerializer.Serialize(hl7Type);

            Assert.Equal(expected, actual);
        }
        public override void Serialize(StreamElement value, IDataOutputView target)
        {
            if (value.IsRecord)
            {
                var record = value.AsRecord <T>();

                if (record.HasTimestamp)
                {
                    target.Write(TagRecWithTimestamp);
                    target.WriteLong(record.Timestamp);
                }
                else
                {
                    target.Write(TagRecWithoutTimestamp);
                }

                ContainedTypeSerializer.Serialize(record.Value, target);
            }
            else if (value.IsWatermark)
            {
                target.Write(TagWatermark);
                target.WriteLong(value.AsWatermark().Timestamp);
            }
            else if (value.IsStreamStatus)
            {
                target.Write(TagStreamStatus);
                target.WriteInt(value.AsStreamStatus().Status);
            }
            else if (value.IsLatencyMarker)
            {
                target.Write(TagLatencyMarker);
                target.WriteLong(value.AsLatencyMarker().MarkedTime);
                target.WriteLong(value.AsLatencyMarker().OperatorId.LowerPart);
                target.WriteLong(value.AsLatencyMarker().OperatorId.UpperPart);
                target.WriteInt(value.AsLatencyMarker().SubTaskIndex);
            }
            else
            {
                throw new RuntimeException();
            }
        }
        public override async Task Generate(CodeModel serviceClient)
        {
            var apiVersions = serviceClient.Methods
                              .SelectMany(method => method.XMsMetadata.apiVersions)
                              .Concat(new [] { serviceClient.ApiVersion })
                              .Where(each => each != null)
                              .Distinct().ToArray();

            foreach (var version in apiVersions)
            {
                var results = CodeModelProcessor.GenerateTypes(serviceClient, version);

                foreach (var result in results)
                {
                    var generatedTypes = result.TypeFactory.GetTypes();

                    var typesJson = TypeSerializer.Serialize(generatedTypes);
                    await Write(typesJson, Path.Combine(result.ProviderNamespace, result.ApiVersion, "types.json"), true);
                }
            }
        }
Esempio n. 25
0
        /// <inheritdoc />
        protected override void SetValue(UnityMethod value)
        {
            base.SetValue(value);

            // Assign the parameter types to their underlying properties

            if (value == null || value.parameterTypes == null)
            {
                parameterTypesProperty.arraySize = 0;
            }
            else
            {
                parameterTypesProperty.arraySize = value.parameterTypes.Length;

                for (int i = 0; i < parameterTypesProperty.arraySize; i++)
                {
                    SerializedProperty parameterTypeProperty = parameterTypesProperty.GetArrayElementAtIndex(i);

                    parameterTypeProperty.stringValue = TypeSerializer.Serialize(value.parameterTypes[i]);
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Recursive method, serializing every object in my objects graph
        /// </summary>
        internal void Serialize(object obj, Type objType)
        {
            // If it's Object, we get the underlying type
            if (objType == typeof(Object) && obj != null)
            {
                var baseType = obj.GetType().GetBaseType();
                // var s = TypeSerializer.GetSerializer(baseType);
                Serialize(obj, baseType);
                return;
            }
            TypeSerializer serializer = null;

            if (!typeSerializers.ContainsKey(objType))
            {
                serializer = TypeSerializer.GetSerializer(objType);
                typeSerializers.Add(objType, serializer);
            }

            serializer = typeSerializers[objType];

            // Write object type
            this.Writer.Write(objType.GetAssemblyQualifiedName());

            // Check if it's not a reference
            int     refIndex = 0;
            DmState state    = this.GetState(obj, objType, ref refIndex);

            // Write state
            this.Writer.Write((byte)state);

            // Write index;
            this.Writer.Write(refIndex);

            // if not null or ref
            if (state == DmState.IsAloneOrValue)
            {
                serializer.Serialize(this, obj, objType);
            }
        }
        public FromElementsFunction(TypeSerializer <T> serializer, IEnumerable <T> elements)
        {
            var stream = new MemoryStream();
            var output = new DataOutputViewStreamWrapper(stream);

            var count = 0;

            try
            {
                foreach (var element in elements)
                {
                    _serializer.Serialize(element, output);
                    count++;
                }
            }
            catch (Exception e)
            {
                throw new IOException("Serializing the source elements failed.", e);
            }

            _numElements        = count;
            _serializer         = serializer;
            _elementsSerialized = stream.ToArray();
        }
        public void Test_Null()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());

            var expected = new byte[0];
            var actual = serializer.Serialize<string>(null);

            Assert.AreEqual(expected, actual);
        }
Esempio n. 29
0
 internal static void SerializeObject <valueType>(JsonSerializer jsonSerializer, object value)
 {
     TypeSerializer <valueType> .Serialize(jsonSerializer, (valueType)value);
 }
Esempio n. 30
0
        /// <summary>
        /// 对象转换JSON字符串
        /// </summary>
        /// <typeparam name="valueType">目标数据类型</typeparam>
        /// <param name="value">数据对象</param>
        private void serialize <valueType>(ref valueType value)
        {
#if AutoCSer
            if (Config.GetLoopObject == null || Config.SetLoopObject == null)
            {
                if (Config.GetLoopObject != null)
                {
                    Warning = SerializeWarning.LessSetLoop;
                }
                else if (Config.SetLoopObject != null)
                {
                    Warning = SerializeWarning.LessGetLoop;
                }
                else
                {
                    Warning = SerializeWarning.None;
                }
                if (checkLoopDepth != Config.CheckLoopDepth || isLoopObject)
                {
                    if (Config.CheckLoopDepth <= 0)
                    {
                        checkLoopDepth = 0;
                        if (forefather == null)
                        {
                            forefather = new object[sizeof(int)];
                        }
                    }
                    else
                    {
                        checkLoopDepth = Config.CheckLoopDepth;
                    }
                }
                isLoopObject = false;
            }
            else
            {
                if (!isLoopObject)
                {
                    isLoopObject = true;
                    if (objectIndexs == null)
                    {
                        objectIndexs = ReusableDictionary <ObjectReference> .Create <int>();
                    }
                }
                Warning        = SerializeWarning.None;
                checkLoopDepth = Config.CheckLoopDepth <= 0 ? SerializeConfig.DefaultCheckLoopDepth : Config.CheckLoopDepth;
            }
#else
            Warning = SerializeWarning.None;
            if (checkLoopDepth != Config.CheckLoopDepth)
            {
                if (Config.CheckLoopDepth <= 0)
                {
                    checkLoopDepth = 0;
                    if (forefather == null)
                    {
                        forefather = new object[sizeof(int)];
                    }
                }
                else
                {
                    checkLoopDepth = Config.CheckLoopDepth;
                }
            }
#endif
            TypeSerializer <valueType> .Serialize(this, ref value);
        }
Esempio n. 31
0
File: Main.cs Progetto: rotanov/Yuzu
 private void TestTypeSerializerHelper(Type t, string s)
 {
     Assert.AreEqual(s, TypeSerializer.Serialize(t));
     Assert.AreEqual(t, TypeSerializer.Deserialize(s));
 }
        public void Test_Char()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var value = 'o';
            var expected = new byte[] { 0x6f };
            var actual = serializer.Serialize(value);

            Assert.AreEqual(expected, actual);
        }
        public void Test_Poco()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var value = new Person {Name = "jeff"};
            var bytes = serializer.Serialize(value);

            var actual = serializer.Deserialize<Person>(new ArraySegment<byte>(bytes), 0, bytes.Length);

            Assert.AreEqual(value.Name, actual.Name);
        }
Esempio n. 34
0
        /// <summary>
        /// シリアライズandデシリアライズで同じ型に戻るか調べます。
        /// </summary>
        private void TypeTest(Type type)
        {
            var selialized = TypeSerializer.Serialize(type);

            Assert.AreEqual(type, TypeSerializer.Deserialize(selialized));
        }
        public void Test_Serialize_String()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            string data = "Hello";

            var expected = new byte[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f };
            var actual = serializer.Serialize(data);

            Assert.AreEqual(expected, actual);
        }
        public void Test_Deserialize_Int()
        {
            var serializer = new TypeSerializer(new ManualByteConverter());
            var five = 5;
            var bytes = serializer.Serialize(five);
            var actual = serializer.Deserialize<int>(bytes, 0, bytes.Length);
            Assert.AreEqual(five, actual);

        }
 public void Test_Deserialize_String()
 {
     var serializer = new TypeSerializer(new ManualByteConverter());
     var value = "astring";
     var bytes = serializer.Serialize(value);
     var bytes1 = Encoding.UTF8.GetBytes(value);
     var actual = serializer.Deserialize<string>(bytes, 0, bytes.Length);
     Assert.AreEqual(value, actual);
 }