Ejemplo n.º 1
0
        public override void Serialize(DmSerializer dmSerializer, object obj, Type objType)
        {
            IEnumerable list = obj as IEnumerable;

            if (list == null)
            {
                return;
            }

            var valueType = GetArrayItemValueType(objType);

            IEnumerator e = list.GetEnumerator();

            PropertyInfo pi = objType.GetProperties().Where(p => p.Name == "Count" || p.Name == "Length").FirstOrDefault();

            if (pi == null)
            {
                throw new ArgumentException("an array should have a Count / Length property");
            }

            int count = (int)pi.GetValue(obj);

            // write length
            dmSerializer.Writer.Write(count);

            // Iterate through the dictionary
            while (e.MoveNext())
            {
                object value = e.Current;
                dmSerializer.Serialize(value, valueType);
            }
        }
Ejemplo n.º 2
0
        public override object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            Object instance = objType.CreateInstance();

            var currentType = objType;

            while (currentType != null && currentType != typeof(Object))

            {
                List <MemberInfo> members = DmUtils.GetMembers(currentType);

                var membersValue = new object[members.Count];

                for (int i = 0; i < members.Count; i++)
                {
                    var member      = members[i];
                    var memberValue = dmSerializer.GetObject(isDebugMode);

                    if (memberValue != null)
                    {
                        member.SetValue(instance, memberValue);
                    }
                }
                currentType = currentType.GetTypeInfo().BaseType;
            }

            return(instance);
        }
Ejemplo n.º 3
0
        public override void Serialize(DmSerializer dmSerializer, object obj, Type objType)
        {
            IDictionary dictionary = obj as IDictionary;

            if (dictionary == null)
            {
                return;
            }

            var  args            = objType.GetGenericArguments();
            Type keyType         = args[0].GetBaseType();
            Type valueType       = args[1].GetBaseType();
            var  keySerializer   = TypeSerializer.GetSerializer(keyType);
            var  valueSerializer = TypeSerializer.GetSerializer(valueType);

            // write length
            dmSerializer.Writer.Write(dictionary.Count);

            // Iterate through the dictionary
            foreach (DictionaryEntry entry in dictionary)
            {
                object value = entry.Value;
                object key   = entry.Key;

                dmSerializer.Serialize(key, keyType);
                dmSerializer.Serialize(value, valueType);
            }
        }
Ejemplo n.º 4
0
    private async static Task TestWebPostStream()
    {
        var dmTable = GetATestTable();
        var dmSet   = new DmSet();

        dmSet.Tables.Add(dmTable);
        var surrgotabeTable = new DmSetSurrogate(dmSet);

        DmSerializer serializer = new DmSerializer();
        var          binaryData = serializer.Serialize(surrgotabeTable);

        Uri target = new Uri("http://localhost:5000/api/sync");

        var client = new HttpClient();

        ByteArrayContent arrayContent = new ByteArrayContent(binaryData);
        var response = await client.PostAsync(target, arrayContent);

        if (response.IsSuccessStatusCode)
        {
            using (var stream = await response.Content.ReadAsStreamAsync())
            {
                var ds = serializer.Deserialize <DmSetSurrogate>(stream);

                var newDs = ds.ConvertToDmSet();
            }
        }
    }
Ejemplo n.º 5
0
        public void TestCases()
        {
            DmSerializer serializer = new DmSerializer();

            foreach (var obj in SerializableObjects.GetObjects())
            {
                try
                {
                    var cliByte = serializer.Serialize(obj);
                    var ob2     = serializer.Deserialize(cliByte);

                    bool areEqual = false;


                    if (EqualityHelpers.IsDictionary(obj.GetType()))
                    {
                        areEqual = EqualityHelpers.DictionariesAreEqual((IDictionary)obj, (IDictionary)ob2);
                    }
                    else if (EqualityHelpers.IsEnumerable(obj.GetType()))
                    {
                        areEqual = EqualityHelpers.ArraysAreEqual((IEnumerable)obj, (IEnumerable)ob2);
                    }
                    else
                    {
                        areEqual = obj.Equals(ob2);
                    }

                    Assert.True(areEqual, $"Type: {obj.GetType()}: Instance 1 is not equal to deserialized instance.");
                }
                catch (Exception ex)
                {
                    Assert.True(false, ($"Object 1 Type : {obj.GetType()} - is not serializable. ({ex.Message})"));
                }
            }
        }
Ejemplo n.º 6
0
        public override object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            var writer = dmSerializer.DebugWriter;
            var br     = dmSerializer.Reader;

            // Get key / value base type
            var    args            = objType.GetGenericArguments();
            Type   keyType         = args[0].GetBaseType();
            Type   valueType       = args[1].GetBaseType();
            String keyName         = keyType.Name;
            String valueName       = valueType.Name;
            var    keySerializer   = TypeSerializer.GetSerializer(keyType);
            var    valueSerializer = TypeSerializer.GetSerializer(valueType);

            // Create instance
            var arrayInstance = objType.CreateInstance() as IDictionary;

            var count = br.ReadInt32();

            for (int i = 0; i < count; i++)
            {
                var keyValue  = dmSerializer.GetObject(isDebugMode);
                var itemValue = dmSerializer.GetObject(isDebugMode);

                if (keyValue != null)
                {
                    arrayInstance.Add(keyValue, itemValue);
                }
            }

            return(arrayInstance);
        }
Ejemplo n.º 7
0
        public override void Serialize(DmSerializer dmSerializer, object obj, Type objType)
        {
            // write primitive
            var objTypeString = typeof(string);
            var objConverterd = this.converter.ConvertToString(obj);

            dmSerializer.Writer.Write(objConverterd, objTypeString);
        }
        public override void Serialize(DmSerializer dmSerializer, object obj, Type objType)
        {
            Type baseType = null;

            // Get the base type if Nullable<>
            baseType = objType.GetBaseType();

            // write primitive
            dmSerializer.Writer.Write(obj, baseType);
        }
Ejemplo n.º 9
0
        public override object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            var objTypeString = typeof(string);

            // Get the value
            var typeString = dmSerializer.Reader.ReadString();

            var obj = this.converter.ConvertFromString(typeString);

            if (isDebugMode)
            {
                dmSerializer.DebugWriter.Write(obj);
            }

            return(obj);
        }
Ejemplo n.º 10
0
        public static void Serialize(DmSetSurrogate set, string fileName)
        {
            DmSerializer serializer = new DmSerializer();

            FileInfo fi = new FileInfo(fileName);

            if (!Directory.Exists(fi.Directory.FullName))
            {
                Directory.CreateDirectory(fi.Directory.FullName);
            }

            // Serialize on disk.
            using (var f = new FileStream(fileName, FileMode.CreateNew, FileAccess.ReadWrite))
            {
                serializer.Serialize(set, f);
            }
        }
        public override Object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            Type baseType = null;

            // Get the base type if Nullable<>
            baseType = objType.GetBaseType();

            // Get the value
            var value = dmSerializer.Reader.Read(baseType);

            if (isDebugMode)
            {
                dmSerializer.DebugWriter.Write(value);
            }

            return(value);
        }
Ejemplo n.º 12
0
        public override void Serialize(DmSerializer dmSerializer, object obj, Type objType)
        {
            // Get the serialized members
            var members = DmUtils.GetMembers(objType);

            //var ctorParameters = objType.GetConstructorParameters(true);
            //if (ctorParameters != null)
            //    members = DmUtils.GetMembersOrderedByParametersForConstructor(members, ctorParameters);

            foreach (MemberInfo member in members)
            {
                object memberValue = member.GetValue(obj);
                var    memberType  = member.GetMemberType();

                dmSerializer.Serialize(memberValue, memberType);
            }
        }
Ejemplo n.º 13
0
        public void AddingAConverter()
        {
            ClassWithAConverter cc = new ClassWithAConverter();

            cc.ID       = 12;
            cc.LastName = "Pertus";
            cc.Ptr      = new IntPtr(12222);


            DmSerializer serializer = new DmSerializer();

            serializer.RegisterConverter(typeof(ClassWithAConverter), new ClassConverterForClassWithAConverter());

            var b = serializer.Serialize(cc);

            var cc2 = serializer.Deserialize <ClassWithAConverter>(b);

            Assert.Equal(cc, cc2);
        }
Ejemplo n.º 14
0
        public override void Serialize(DmSerializer dmSerializer, object obj, Type objType)
        {
            var context = new StreamingContext();
            var value   = obj as ISerializable;
            SerializationInfo serializationInfo = new SerializationInfo(objType, new FormatterConverter());

            value.GetObjectData(serializationInfo, context);

            // write length
            dmSerializer.Writer.Write(serializationInfo.MemberCount);

            foreach (SerializationEntry serializationEntry in serializationInfo)
            {
                var entryName  = serializationEntry.Name;
                var entryValue = serializationEntry.Value;

                dmSerializer.Serialize(entryName, entryName.GetType());
                dmSerializer.Serialize(entryValue, entryValue.GetType());
            }
        }
Ejemplo n.º 15
0
        public override object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            Object            instance = objType.CreateInstance();
            List <MemberInfo> members  = DmUtils.GetMembers(objType);

            var membersValue = new object[members.Count];

            for (int i = 0; i < members.Count; i++)
            {
                var member      = members[i];
                var memberValue = dmSerializer.GetObject(isDebugMode);

                if (memberValue != null)
                {
                    member.SetValue(instance, memberValue);
                }
            }


            return(instance);
        }
Ejemplo n.º 16
0
        public static BatchPart Deserialize(string fileName)
        {
            if (String.IsNullOrEmpty(fileName))
            {
                throw new ArgumentException("Cant get a Batch part if fileName doesn't exist");
            }

            if (!File.Exists(fileName))
            {
                throw new ArgumentException($"file {fileName} doesn't exist");
            }

            BatchPart bp = new BatchPart();

            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                DmSerializer serializer = new DmSerializer();
                bp.DmSetSurrogate = serializer.Deserialize <DmSetSurrogate>(fs);
            }

            return(bp);
        }
Ejemplo n.º 17
0
        public override object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            var             br = dmSerializer.Reader;
            ConstructorInfo constructorInfo = objType.GetISerializableConstructor();

            var context = new StreamingContext();
            SerializationInfo serializationInfo = new SerializationInfo(objType, new FormatterConverter());

            var count = br.ReadInt32();


            for (int i = 0; i < count; i++)
            {
                var entryName  = (string)dmSerializer.GetObject(isDebugMode);
                var entryValue = dmSerializer.GetObject(isDebugMode);

                serializationInfo.AddValue(entryName, entryValue, entryValue.GetType());
            }

            var obj = constructorInfo.Invoke(new object[] { serializationInfo, context });

            return(obj);
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            Address clientAddress = new Address
            {
                City       = "Toulouse",
                PostalCode = "31620"
            };
            Client cli = new Client
            {
                Address     = clientAddress,
                Birthday    = new DateTime(1976, 10, 23),
                ClientId    = Guid.NewGuid(),
                FirstName   = "Sebastien",
                LastName    = "Pertus",
                IsAvailable = true,
                Money       = 10,
                Id          = 1,
            };

            Client deserializedClient = null;

            // ----------------------------------------------------------------------------
            // We are on .NET 4.6.2, so using version .Net Standard 1.3 (to 1.5)
            // ----------------------------------------------------------------------------
            DmSerializer serializer = new DmSerializer();

            using (FileStream fs = new FileStream("client.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                serializer.Serialize(cli, fs);
            }

            using (FileStream fs = new FileStream("client.bin", FileMode.Open, FileAccess.ReadWrite))
            {
                deserializedClient = serializer.Deserialize <Client>(fs);
            }
        }
Ejemplo n.º 19
0
        internal static void SerializeInDmSet(DmSet set, SyncConfiguration configuration)
        {
            if (set == null)
            {
                return;
            }

            DmTable dmTableConfiguration    = null;
            DmTable dmTableFilterParameters = null;
            DmTable dmTableTables           = null;

            if (!set.Tables.Contains("DotmimSync__ServiceConfiguration"))
            {
                dmTableConfiguration = new DmTable("DotmimSync__ServiceConfiguration");
                set.Tables.Add(dmTableConfiguration);
            }

            dmTableConfiguration = set.Tables["DotmimSync__ServiceConfiguration"];

            dmTableConfiguration.Clear();
            dmTableConfiguration.Columns.Clear();

            dmTableConfiguration.Columns.Add <String>("BatchDirectory");
            dmTableConfiguration.Columns.Add <Int32>("ConflictResolutionPolicy");
            dmTableConfiguration.Columns.Add <Int32>("DownloadBatchSizeInKB");
            dmTableConfiguration.Columns.Add <Boolean>("EnableDiagnosticPage");
            dmTableConfiguration.Columns.Add <Boolean>("UseBulkOperations");
            dmTableConfiguration.Columns.Add <Boolean>("UseVerboseErrors");
            dmTableConfiguration.Columns.Add <Boolean>("OverwriteConfiguration");
            dmTableConfiguration.Columns.Add <Int32>("SerializationConverter");

            var dmRowConfiguration = dmTableConfiguration.NewRow();

            dmRowConfiguration["BatchDirectory"]           = configuration.BatchDirectory;
            dmRowConfiguration["ConflictResolutionPolicy"] = configuration.ConflictResolutionPolicy;
            dmRowConfiguration["DownloadBatchSizeInKB"]    = configuration.DownloadBatchSizeInKB;
            dmRowConfiguration["UseBulkOperations"]        = configuration.UseBulkOperations;
            dmRowConfiguration["UseVerboseErrors"]         = configuration.UseVerboseErrors;
            dmRowConfiguration["OverwriteConfiguration"]   = configuration.OverwriteConfiguration;
            dmRowConfiguration["SerializationConverter"]   = configuration.SerializationFormat;
            dmTableConfiguration.Rows.Add(dmRowConfiguration);

            if (configuration.ScopeSet != null && configuration.ScopeSet.Tables.Count > 0)
            {
                foreach (var dmTable in configuration.ScopeSet.Tables)
                {
                    var dmTableConf = dmTable.Clone();
                    set.Tables.Add(dmTableConf);
                }

                foreach (var dmRelation in configuration.ScopeSet.Relations)
                {
                    var dmRelationConf = dmRelation.Clone(set);
                    set.Relations.Add(dmRelationConf);
                }
            }

            if (configuration.Filters.Count > 0)
            {
                if (!set.Tables.Contains("DotmimSync__Filters"))
                {
                    dmTableFilterParameters = new DmTable("DotmimSync__Filters");
                    set.Tables.Add(dmTableFilterParameters);
                }

                dmTableFilterParameters = set.Tables["DotmimSync__Filters"];
                dmTableFilterParameters.Columns.Add <String>("TableName");
                dmTableFilterParameters.Columns.Add <String>("ColumnName");

                DmSerializer serializer = new DmSerializer();

                foreach (var p in configuration.Filters)
                {
                    var dmRowFilter = dmTableFilterParameters.NewRow();
                    dmRowFilter["TableName"]  = p.TableName;
                    dmRowFilter["ColumnName"] = p.ColumnName;

                    //var objType = p.Value.GetType();
                    //var converter = objType.GetConverter();
                    //dmRowFilter["Value"] = converter.ConvertToInvariantString(p.Value);
                    //dmRowFilter["ValueType"] = objType.GetAssemblyQualifiedName();

                    dmTableFilterParameters.Rows.Add(dmRowFilter);
                }
            }

            if (configuration.Tables != null && configuration.Tables.Length > 0)
            {
                if (!set.Tables.Contains("DotmimSync__Table"))
                {
                    dmTableTables = new DmTable("DotmimSync__Table");
                    set.Tables.Add(dmTableTables);
                }

                dmTableTables = set.Tables["DotmimSync__Table"];
                dmTableTables.Columns.Add <String>("Name");

                foreach (var p in configuration.Tables)
                {
                    var dmRowTable = dmTableTables.NewRow();
                    dmRowTable["Name"] = p;
                    dmTableTables.Rows.Add(dmRowTable);
                }
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes in memory cache class.
 /// </summary>
 public SessionCache(HttpContext context)
 {
     this.serializer = new DmSerializer();
     this.context    = context;
 }
Ejemplo n.º 21
0
    private static void TestSerializerSize()
    {
        DmTable  dtClient    = new DmTable("Client");
        DmColumn dcId        = new DmColumn <int>("Id");
        DmColumn dcName      = new DmColumn <string>("Name");
        DmColumn dcBirthdate = new DmColumn <DateTime>("Date");
        DmColumn dcMoney     = new DmColumn <Double>("Money");
        DmColumn dcInt       = new DmColumn <Int64>("i64");
        DmColumn dcJob       = new DmColumn <String>("Job");

        dtClient.Columns.AddRange(new[] { dcId, dcName, dcBirthdate, dcMoney, dcInt, dcJob });


        long rowsSize = 0;

        foreach (var c in dtClient.Columns)
        {
            DmColumnSurrogate dcs = new DmColumnSurrogate(c);
            Console.WriteLine($"Column {dcs.ColumnName} Surrogate length : " + dcs.GetBytesLength());
            rowsSize += dcs.GetBytesLength();
        }

        var dmTableS       = new DmTableSurrogate(dtClient);
        var dmTableSLength = dmTableS.GetEmptyBytesLength();

        Console.WriteLine("DmTableSurrogate length = " + dmTableSLength);

        rowsSize += dmTableSLength;


        for (int i = 0; i < 50000; i++)
        {
            var newRow = dtClient.NewRow();

            Random r    = new Random(DateTime.Now.Second);
            var    l    = r.NextDouble() * 100;
            string name = "";
            for (int j = 0; j < l; j++)
            {
                name += "a";
            }

            newRow["Id"]    = 12;
            newRow["Name"]  = name;
            newRow["Date"]  = DateTime.Now;
            newRow["Money"] = l;

            var    l2  = r.NextDouble() * 100;
            string job = "";
            for (int j = 0; j < l2; j++)
            {
                job += "b";
            }
            newRow["Job"] = job;
            newRow["i64"] = l2;

            rowsSize += DmTableSurrogate.GetRowSizeFromDataRow(newRow);

            dtClient.Rows.Add(newRow);
        }


        var serializer = new DmSerializer();

        long dtSize = 0;

        if (File.Exists("dt.bin"))
        {
            File.Delete("dt.bin");
        }


        using (var fs = new FileStream("dt.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
        {
            serializer.Serialize(new DmTableSurrogate(dtClient), fs);
            dtSize = fs.Length;
        }

        //using (var fs = new FileStream("dt.bin", FileMode.Open, FileAccess.Read))
        //{
        //    var ds = serializer.Deserialize<DmTableSurrogate>(fs);

        //}

        Console.WriteLine("Rows Size : " + rowsSize);
        Console.WriteLine("Table Size : " + dtSize);
    }
Ejemplo n.º 22
0
 public DmBinaryConverter()
 {
     serializer = new DmSerializer();
 }
Ejemplo n.º 23
0
        public override object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false)
        {
            var br = dmSerializer.Reader;

            // DOnt try to get an ICollection (coz ICollection<T> doesn't inherit from it)
            object arrayInstance;

            // Create instance
            if (objType.IsArray)
            {
                arrayInstance = new ArrayList();
            }
            else
            {
                arrayInstance = objType.CreateInstance();
            }

            var count = br.ReadInt32();

            // Get the Add method if exist
            // Since ICollection<T> is not accessible
            var valueType = GetArrayItemValueType(objType);

            Func <object, int> addFunction = null;

            if (objType.IsArray)
            {
                addFunction = ((ArrayList)arrayInstance).Add;
            }
            else
            {
                MethodInfo mi = objType.GetMethod("Add", new Type[] { valueType });

                if (mi == null)
                {
                    throw new ArgumentException("Deserializing an array must have a Add<T> method");
                }

                addFunction = new Func <object, int>((value) =>
                {
                    mi.Invoke(arrayInstance, new object[] { value });
                    return(0);
                });
            }


            for (int i = 0; i < count; i++)
            {
                var item = dmSerializer.GetObject(isDebugMode);

                addFunction(item);
            }

            if (objType.IsArray)
            {
                return(((ArrayList)arrayInstance).ToArray(objType.GetTypeInfo().GetElementType()));
            }
            else
            {
                return(arrayInstance);
            }
        }
Ejemplo n.º 24
0
 public abstract Object Deserialize(DmSerializer dmSerializer, Type objType, bool isDebugMode = false);
Ejemplo n.º 25
0
 public abstract void Serialize(DmSerializer dmSerializer, object obj, Type objType);