コード例 #1
0
        public void T2000_TypeRegistry()
        {
            using (var ms = new MemoryStream())
            {
                var s   = new SlimSerializer();
                var tr1 = new TypeRegistry();

                Assert.IsTrue(tr1.Add(typeof(List <S3>)));
                Assert.IsTrue(tr1.Add(typeof(S3[])));
                Assert.IsTrue(tr1.Add(typeof(Tuple <string, S3>)));


                s.Serialize(ms, tr1);

                ms.Position = 0;

                var tr2 = s.Deserialize(ms) as TypeRegistry;

                Assert.IsNotNull(tr2);

                Assert.AreEqual(7, tr2.Count);//including system types
                Assert.AreEqual(typeof(Tuple <string, S3>), tr2["$6"]);
                Assert.AreEqual(typeof(S3[]), tr2["$5"]);
                Assert.AreEqual(typeof(List <S3>), tr2["$4"]);
            }
        }
コード例 #2
0
ファイル: SerializerForm.cs プロジェクト: rioka/nfx
        private void button2_Click(object sender, EventArgs e)
        {
            var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                      TypeRegistry.CommonCollectionTypes,
                                      TypeRegistry.BoxedCommonTypes,
                                      TypeRegistry.BoxedCommonNullableTypes);

            tr.Add(typeof(PatientRecord));
            tr.Add(typeof(Person2));
            tr.Add(typeof(System.Drawing.Point));
            tr.Add(typeof(TimeSpan));
            tr.Add(typeof(Kozel));

            var p1 = PatientRecord.Make <PatientRecord>(); // make();



            using (var ms = new FileStream(@"c:\NFX\PERSON2.slim", FileMode.Create))   //new MemoryStream())
            {
                var s = new SlimSerializer(tr);

                s.Serialize(ms, p1);

                var clk = Stopwatch.StartNew();

                for (var i = 1; i < 4000; i++)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    var p2 = s.Deserialize(ms);
                }
                Text = clk.ElapsedMilliseconds.ToString();

                //Text = p2.Name;
            }

            //BINARY formatterr

            using (var ms = new FileStream(@"c:\NFX\PERSON2.bin", FileMode.Create))    //new MemoryStream())
            {
                var s = new BinaryFormatter();

                s.Serialize(ms, p1);

                var clk = Stopwatch.StartNew();

                for (var i = 1; i < 4000; i++)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    var p2 = s.Deserialize(ms);
                }
                Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
            }
        }
コード例 #3
0
ファイル: SerializerForm.cs プロジェクト: wangchengqun/azos
        private void button3_Click(object sender, EventArgs e)
        {
            const int CNT = 1000;

            var lst = new TwitterMsg[CNT];

            for (var i = 0; i < CNT; i++)
            {
                lst[i] = (new TwitterMsg
                {
                    ID = new GDID(0, (ulong)i),
                    AuthorID = new GDID(0, (ulong)i * 251),
                    Banned = i % 45 == 0,
                    Rating = i % 5,
                    ResponseToMsg = new GDID(0, (ulong)i),
                    MsgText = Azos.Text.NaturalTextGenerator.Generate(0),
                    When = DateTime.Now,
                    ri_Deleted = false,
                    ri_Host = "Zukini1234",
                    ri_Version = DateTime.Now
                });
            }

            var tr = new TypeRegistry(
                TypeRegistry.CommonCollectionTypes,
                TypeRegistry.BoxedCommonTypes,
                TypeRegistry.BoxedCommonNullableTypes);

            tr.Add(typeof(GDID));
            tr.Add(typeof(TwitterMsg));


            var clk = Stopwatch.StartNew();

            using (var fs = new FileStream(@"c:\Azos\SLIM.slim", FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024))
            {
                var s = new SlimSerializer(tr);

                s.Serialize(fs, lst);
            }
            Text = "SLIM took {0} ms ".Args(clk.ElapsedMilliseconds);

            clk.Restart();
            using (var fs = new FileStream(@"c:\Azos\FORMATTER.bin", FileMode.Create, FileAccess.Write, FileShare.None, 1024 * 1024))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(fs, lst);
            }
            Text += "        Binary formatter took {0}ms ".Args(clk.ElapsedMilliseconds);
        }
コード例 #4
0
        private ISerializer getSerializer()
        {
            if (m_Format != FileObjectFormat.Slim)
            {
                return(new MSBinaryFormatter());
            }


            var treg = new TypeRegistry(TypeRegistry.CommonCollectionTypes,
                                        TypeRegistry.BoxedCommonTypes,
                                        TypeRegistry.BoxedCommonNullableTypes);

            foreach (var tn in m_KnownTypes)
            {
                var t = Type.GetType(tn, false);
                if (t != null)
                {
                    treg.Add(t);
                }
                else
                {
                    WriteLog(MessageType.Warning, "Specified known type could not be found: " + tn, tn, "getSerializer(slim)");
                }
            }
            return(new SlimSerializer(treg));
        }
コード例 #5
0
        private CerificationResult perform_certify(string orchestration)
        {
            CertifierOrchestrationParser parser = new CertifierOrchestrationParser();

            //parser.readOrchestrationXML(CertifierConstants.ORCHESTRATION_FILE_TEST);
            parser.readOrchestrationXML(Orchestration);
            CertifierConsoleLogger.write(parser.getOrchestration().toString());

            variables.Add("formal_properties", formal_properties);


            parser.getOrchestration().run();             //


            Console.WriteLine("iterating remaining start threads");
            foreach (KeyValuePair <String, LogicActionInstantiate> entry in InstantiateActions)
            {
                if (entry.Value._thread != null)
                {
                    entry.Value._thread.Join();
                }
            }
            foreach (KeyValuePair <String, LogicActionCompute> entry in ComputeActions)
            {
                if (entry.Value._thread != null)
                {
                    entry.Value._thread.Join();
                }
            }

            throw new Exception("TODO perform_certify");
        }
コード例 #6
0
        public void ParseAssemblyAndRegisterRosServices(Assembly assembly)
        {
            foreach (Type type in assembly.GetTypes())
            {
                var typeInfo = type.GetTypeInfo();
                if (type == typeof(RosService) || !typeInfo.IsSubclassOf(typeof(RosService)))
                {
                    continue;
                }

                RosService service = Activator.CreateInstance(type) as RosService;
                if (service.ServiceType == "undefined/unknown")
                {
                    throw new Exception("Invalid servive type. Service type field (srvtype) was not initialized correctly.");
                }

                var packageName = service.ServiceType.Split('/')[0];
                if (!PackageNames.Contains(packageName))
                {
                    PackageNames.Add(packageName);
                }

                Logger.LogDebug($"Register {service.ServiceType}");
                if (!TypeRegistry.ContainsKey(service.ServiceType))
                {
                    TypeRegistry.Add(service.ServiceType, service.GetType());
                }
            }
        }
コード例 #7
0
ファイル: ClassTests.cs プロジェクト: plioi/rook
        public void CanCreateFullyTypedInstance()
        {
            var @class = @"class Foo
                           {
                              bool Even(int n) { if (n==0) true else Odd(n-1) }
                              bool Odd(int n) { if (n==0) false else Even(n-1) }
                              int Test() { if (Even(4)) 0 else 1 }
                           }".ParseClass();

            var constructorReturningFoo = NamedType.Constructor(new NamedType(@class));

            @class.Methods.ShouldList(
                even =>
            {
                even.Name.Identifier.ShouldEqual("Even");
                even.Type.ShouldEqual(Unknown);
                even.Body.Type.ShouldEqual(Unknown);
            },
                odd =>
            {
                odd.Name.Identifier.ShouldEqual("Odd");
                odd.Type.ShouldEqual(Unknown);
                odd.Body.Type.ShouldEqual(Unknown);
            },
                test =>
            {
                test.Name.Identifier.ShouldEqual("Test");
                test.Type.ShouldEqual(Unknown);
                test.Body.Type.ShouldEqual(Unknown);
            });
            @class.Type.ShouldEqual(Unknown);

            var typeRegistry = new TypeRegistry();

            typeRegistry.Add(@class);
            var typeChecker = new TypeChecker(typeRegistry);
            var typedClass  = typeChecker.TypeCheck(@class, Scope());

            typedClass.Methods.ShouldList(
                even =>
            {
                even.Name.Identifier.ShouldEqual("Even");
                even.Type.ToString().ShouldEqual("System.Func<int, bool>");
                even.Body.Type.ShouldEqual(Boolean);
            },
                odd =>
            {
                odd.Name.Identifier.ShouldEqual("Odd");
                odd.Type.ToString().ShouldEqual("System.Func<int, bool>");
                odd.Body.Type.ShouldEqual(Boolean);
            },
                test =>
            {
                test.Name.Identifier.ShouldEqual("Test");
                test.Type.ToString().ShouldEqual("System.Func<int>");
                test.Body.Type.ShouldEqual(Integer);
            });
            typedClass.Type.ShouldEqual(constructorReturningFoo);
        }
コード例 #8
0
ファイル: ClassTests.cs プロジェクト: plioi/rook
        public void PassesTypeCheckingEvenWhenMethodNamesAreTheSameAsNamesInTheSurroundingScope()
        {
            var fooClass = "class Foo { int A() {0} int B() {2} }".ParseClass();

            var typeRegistry            = new TypeRegistry();
            var constructorReturningFoo = NamedType.Constructor(new NamedType(fooClass));

            typeRegistry.Add(fooClass);

            var typeChecker = new TypeChecker(typeRegistry);

            typeChecker.TypeCheck(fooClass, Scope(B => NamedType.Function(NamedType.Boolean))).Type.ShouldEqual(constructorReturningFoo);
            typeChecker.HasErrors.ShouldBeFalse();
        }
コード例 #9
0
ファイル: ClassTests.cs プロジェクト: plioi/rook
        public void HasATypeCorrespondingWithTheDefaultConstructor()
        {
            var fooClass = "class Foo { }".ParseClass();

            var typeRegistry            = new TypeRegistry();
            var constructorReturningFoo = NamedType.Constructor(new NamedType(fooClass));

            typeRegistry.Add(fooClass);

            var typeChecker = new TypeChecker(typeRegistry);

            typeChecker.TypeCheck(fooClass, Scope()).Type.ShouldEqual(constructorReturningFoo);
            typeChecker.HasErrors.ShouldBeFalse();
        }
コード例 #10
0
        public CompilationUnit TypeCheck(CompilationUnit compilationUnit)
        {
            var position  = compilationUnit.Position;
            var classes   = compilationUnit.Classes;
            var functions = compilationUnit.Functions;

            foreach (var @class in classes)//TODO: Test coverage.
            {
                typeRegistry.Add(@class);
            }

            var scope = CreateGlobalScope(classes, functions);

            return(new CompilationUnit(position, TypeCheck(classes, scope), TypeCheck(functions, scope)));
        }
コード例 #11
0
ファイル: MethodInvocationTests.cs プロジェクト: plioi/rook
        public MethodInvocationTests()
        {
            mathClass = @"class Math
            {
                int Zero() { 0 }
                int Square(int x) { x*x }
                bool Even(int n) { if (n==0) true else Odd(n-1) }
                bool Odd(int n) { if (n==0) false else Even(n-1) }
                int Max(int a, int b) { if (a > b) a else b }
            }".ParseClass();

            typeRegistry = new TypeRegistry();
            typeRegistry.Add(mathClass);
            mathType = new NamedType(mathClass);
        }
コード例 #12
0
        /// <summary>
        /// Adds the given type to the type registry.
        /// </summary>
        /// <param name="type">Type of the type register.</param>
        /// <remarks>
        /// After plugins are loaded, any type that inherits or implements the given Type can be easily found.
        /// If the type is already in the type registry, nothing will be done.
        /// </remarks>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="type"/> is null.</exception>
        public void RegisterTypeRegister(TypeInfo type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (!TypeRegistry.ContainsKey(type))
            {
                TypeRegistry.Add(type, new List <TypeInfo>());

                // Add the type to its own registry.
                // The function will only add it if an instance can be created.
                // This will happen automatically if assembly searching is enabled,
                // but it needs to happen now to avoid issues where it doesn't exist until later, despite some things expecting it now.
                RegisterType(type, type);
            }
        }
コード例 #13
0
ファイル: DefaultPile.cs プロジェクト: Vadimyan/nfx
          private byte[] serialize(object payload, out int payloadSize, out byte serVersion)
          {
            var stream = getTLWriteStream();
            var serializer = ts_WriteSerializer;
            if (serializer==null || serializer.Owner != this)
            {
                serializer = new SlimSerializer(m_CurrentTypeRegistry, SlimFormat.Instance);
                serializer.Owner = this;
                serializer.TypeMode = TypeRegistryMode.Batch;
                ts_WriteSerializer = serializer;
            }
            
            while(Running)
            {
              stream.Position = 0;
              serializer.Serialize(stream, payload);
              if (!serializer.BatchTypesAdded) break;
              
              TypeRegistry newReg;
              lock(m_CurrentTypeRegistryLock)
              {
                newReg = new TypeRegistry( m_CurrentTypeRegistry );
                foreach(var t in serializer.BatchTypeRegistry)
                  newReg.Add( t );

                m_CurrentTypeRegistry = newReg;
              }
              //re-allocate serializer with the new type registry
              serializer = new SlimSerializer(newReg, SlimFormat.Instance);
              serializer.Owner = this;
              serializer.TypeMode = TypeRegistryMode.Batch;
              ts_WriteSerializer = serializer;
            }//while

            payloadSize = (int)stream.Position;
            serVersion = 0;//not used for now
            return stream.GetBuffer();
          }
コード例 #14
0
ファイル: SerializerForm.cs プロジェクト: wangchengqun/azos
        private void button1_Click(object sender, EventArgs e)
        {
            var Frank = new Person
            {
                Name         = "Frank Frankfurter",
                Age          = 99,
                IsHappy      = true,
                MarriageDate = App.LocalizedTime,

                Father = new Person {
                    Name = "Zaxar Mai", Age = 44
                },

                Type = typeof(System.Reflection.Assembly)
            };

            var Marry = new Person
            {
                Name         = "Marry Morra",
                Age          = 44,
                IsHappy      = false,
                MarriageDate = App.LocalizedTime,

                Father = Frank.Father,

                Type = typeof(System.Diagnostics.Stopwatch)
                       //Buffer = new byte[] {10,13,65,65,65,65,65,65,65,65,66,66,66,66,66,66,66,66},
                       //Chars = new char[] {'i', ' ', 'a', 'm', ' ','!'}
            };


            var Dodik = new Person
            {
                Name         = "Dodik Kutzhenbukher",
                Age          = 12,
                IsHappy      = true,
                MarriageDate = App.LocalizedTime.AddDays(-100),
                Father       = Frank,
                Mother       = Marry
            };

            Marry.Mother = Dodik;//Cycle



            //Frank.Father.Items["Absukov"] = 123;
            //Frank.Father.Items["Bosurxevich"] = true;
            //Frank.Father.Items["Corshunovich"] = "ya est tot kto mojet byt";
            //Frank.Father.Items["Zmejukka"] = " do svazi!";


            //Dodik.IntArray = new int[10,10,10];

            //Dodik.IntArray[5,3,4] = 67;
            //Dodik.IntArray[9,9,9] = 65;


            //Dodik.ObjArray = new object[10];
            //for(int i=0; i<Dodik.ObjArray.Length; i++)
            // Dodik.ObjArray[i] = new Person{ Name = "Chelovek-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow};

            //for(int i=0; i<10; i++)
            // Dodik.Relatives.Add( new Person{ Name = "Solovei-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow} );

            //for(int i=0; i<1000; i++)
            // Dodik.Numbers.Add( 10000-i );


            var tr = new TypeRegistry(TypeRegistry.CommonCollectionTypes,
                                      TypeRegistry.BoxedCommonTypes,
                                      TypeRegistry.BoxedCommonNullableTypes);

            tr.Add(typeof(Person));
            tr.Add(typeof(Person2));
            tr.Add(typeof(Person[]));
            tr.Add(typeof(System.Collections.Generic.List <Person>));
            tr.Add(typeof(System.Drawing.Point));
            tr.Add(typeof(int[]));
            tr.Add(typeof(int[, , ]));



            var data = make();

            var clk = Stopwatch.StartNew();

            // for(var i=1; i<1000; i++)
            using (var fs = new FileStream(@"c:\Azos\SLIM.slim", FileMode.Create))
            {
                var s = new SlimSerializer(tr);

                for (var i = 1; i < 1000; i++)
                {
                    s.Serialize(fs, data);//Dodik);
                }
            }
            Text = clk.ElapsedMilliseconds.ToString();

            clk.Restart();
            using (var fs = new FileStream(@"c:\Azos\FORMATTER.bin", FileMode.Create))
            {
                var bf = new BinaryFormatter();

                for (var i = 1; i < 1000; i++)
                {
                    bf.Serialize(fs, data);//Dodik);
                }
            }
            Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
        }
コード例 #15
0
        public void ParseAssemblyAndRegisterRosMessages(Assembly assembly)
        {
            foreach (Type othertype in assembly.GetTypes())
            {
                var messageInfo = othertype.GetTypeInfo();
                if (othertype == typeof(RosMessage) || !messageInfo.IsSubclassOf(typeof(RosMessage)) || othertype == typeof(InnerActionMessage))
                {
                    continue;
                }

                var        goalAttribute     = messageInfo.GetCustomAttribute <ActionGoalMessageAttribute>();
                var        resultAttribute   = messageInfo.GetCustomAttribute <ActionResultMessageAttribute>();
                var        feedbackAttribute = messageInfo.GetCustomAttribute <ActionFeedbackMessageAttribute>();
                var        ignoreAttribute   = messageInfo.GetCustomAttribute <IgnoreRosMessageAttribute>();
                RosMessage message;
                if (goalAttribute != null || resultAttribute != null || feedbackAttribute != null || ignoreAttribute != null)
                {
                    Type actionType;
                    if (goalAttribute != null)
                    {
                        actionType = typeof(GoalActionMessage <>);
                    }
                    else if (resultAttribute != null)
                    {
                        actionType = typeof(ResultActionMessage <>);
                    }
                    else if (feedbackAttribute != null)
                    {
                        actionType = typeof(FeedbackActionMessage <>);
                    }
                    else if (ignoreAttribute != null)
                    {
                        continue;
                    }
                    else
                    {
                        throw new InvalidOperationException($"Could create Action Message for {othertype}");
                    }

                    Type[] innerType       = { othertype };
                    var    goalMessageType = actionType.MakeGenericType(innerType);
                    message = (Activator.CreateInstance(goalMessageType)) as RosMessage;
                }
                else
                {
                    message = Activator.CreateInstance(othertype) as RosMessage;
                    if ((message != null) && (message.MessageType == "undefined/unknown"))
                    {
                        throw new Exception("Invalid message type. Message type field (msgtype) was not initialized correctly.");
                    }
                }

                var packageName = message.MessageType.Split('/')[0];
                if (!PackageNames.Contains(packageName))
                {
                    PackageNames.Add(packageName);
                }

                Logger.LogDebug($"Register {message.MessageType}");
                if (!TypeRegistry.ContainsKey(message.MessageType))
                {
                    TypeRegistry.Add(message.MessageType, message.GetType());
                }
                else
                {
                    var messageFromRegistry = CreateMessage(message.MessageType);
                    if (messageFromRegistry.MD5Sum() != message.MD5Sum())
                    {
                        throw new InvalidOperationException($"The message of type {message.MessageType} has already been " +
                                                            $"registered and the MD5 sums do not match. Already registered: {messageFromRegistry.MD5Sum()} " +
                                                            $"new message: {message.MD5Sum()}.");
                    }
                    else
                    {
                        Logger.LogDebug($"The message of type {message.MessageType} has already been registered. Since the" +
                                        "MD5 sums do match, the new message is ignored.");
                    }
                }
            }
        }
コード例 #16
0
        private ISerializer getSerializer()
        {
          if (m_Format!=FileObjectFormat.Slim)
          {
            return new MSBinaryFormatter();
          }


          var treg = new TypeRegistry(TypeRegistry.CommonCollectionTypes,
                                                TypeRegistry.RecordModelTypes,
                                                TypeRegistry.BoxedCommonTypes,
                                                TypeRegistry.BoxedCommonNullableTypes);
          
          foreach(var tn in m_KnownTypes)
          {
            var t = Type.GetType(tn, false);
            if (t!=null) 
             treg.Add(t);
            else
             WriteLog(MessageType.Warning, "Specified known type could not be found: " + tn, tn, "getSerializer(slim)"); 
          }
          return  new SlimSerializer(treg); 
        }
コード例 #17
0
ファイル: SerializerForm.cs プロジェクト: vlapchenko/nfx
        private void button3_Click(object sender, EventArgs e)
        {
            const int CNT = 1000;

              var lst = new TwitterMsg[CNT];
              for(var i=0; i<CNT; i++)
               lst[i] = ( new TwitterMsg
               {
             ID = new GDID(0, (ulong)i),
             AuthorID = new GDID(0, (ulong)i*251),
             Banned = i%45==0,
             Rating = i%5,
             ResponseToMsg = new GDID(0, (ulong)i),
             MsgText = NFX.Parsing.NaturalTextGenerator.Generate(0),
             When = DateTime.Now,
             ri_Deleted = false,
             ri_Host = "Zukini1234",
             ri_Version = DateTime.Now
               });

               var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                  TypeRegistry.CommonCollectionTypes,
                                  TypeRegistry.BoxedCommonTypes,
                                  TypeRegistry.BoxedCommonNullableTypes);
               tr.Add( typeof(GDID));
               tr.Add( typeof(TwitterMsg));

               var clk = Stopwatch.StartNew();
               using (var fs = new FileStream(@"c:\NFX\SLIM.slim", FileMode.Create, FileAccess.Write, FileShare.None, 1024*1024))
               {
                var s = new SlimSerializer(tr);

                s.Serialize(fs,  lst);
               }
               Text = "SLIM took {0} ms ".Args(clk.ElapsedMilliseconds);

              clk.Restart();
               using (var fs = new FileStream(@"c:\NFX\FORMATTER.bin", FileMode.Create, FileAccess.Write, FileShare.None, 1024*1024))
               {
             var bf = new BinaryFormatter();
             bf.Serialize(fs,  lst);
               }
               Text += "        Binary formatter took {0}ms ".Args(clk.ElapsedMilliseconds);
        }
コード例 #18
0
ファイル: SerializerForm.cs プロジェクト: vlapchenko/nfx
        private void button2_Click(object sender, EventArgs e)
        {
            var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                  TypeRegistry.CommonCollectionTypes,
                                  TypeRegistry.BoxedCommonTypes,
                                  TypeRegistry.BoxedCommonNullableTypes);
             tr.Add(typeof(PatientRecord));
             tr.Add(typeof(Person2));
             tr.Add(typeof(System.Drawing.Point));
             tr.Add(typeof(TimeSpan));
             tr.Add(typeof(Kozel));

              var p1 = PatientRecord.Make<PatientRecord>();// make();

              using (var ms = new FileStream(@"c:\NFX\PERSON2.slim", FileMode.Create) )//new MemoryStream())
              {
                var s = new SlimSerializer(tr);

                s.Serialize(ms, p1);

                var clk = Stopwatch.StartNew();

                for(var i=1; i<4000; i++)
                {
                  ms.Seek(0, SeekOrigin.Begin);
                  var p2 = s.Deserialize(ms);
                }
                Text = clk.ElapsedMilliseconds.ToString();

                //Text = p2.Name;
              }

              //BINARY formatterr

              using (var ms = new FileStream(@"c:\NFX\PERSON2.bin", FileMode.Create) ) //new MemoryStream())
              {
                var s = new BinaryFormatter();

                s.Serialize(ms, p1);

                var clk = Stopwatch.StartNew();

                for(var i=1; i<4000; i++)
                {
                  ms.Seek(0, SeekOrigin.Begin);
                  var p2 = s.Deserialize(ms);
                }
                Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
              }
        }
コード例 #19
0
ファイル: SerializerForm.cs プロジェクト: vlapchenko/nfx
        private void button1_Click(object sender, EventArgs e)
        {
            var Frank = new Person
                          {
                            Name = "Frank Frankfurter",
                            Age = 99,
                            IsHappy = true,
                            MarriageDate = App.LocalizedTime,

                            Father = new Person { Name = "Zaxar Mai", Age = 44},

                            Type = typeof(System.Reflection.Assembly)
                          };

               var Marry = new Person
                          {
                            Name = "Marry Morra",
                            Age = 44,
                            IsHappy = false,
                            MarriageDate = App.LocalizedTime,

                            Father = Frank.Father,

                            Type = typeof(System.Diagnostics.Stopwatch)
                            //Buffer = new byte[] {10,13,65,65,65,65,65,65,65,65,66,66,66,66,66,66,66,66},
                            //Chars = new char[] {'i', ' ', 'a', 'm', ' ','!'}
                          };

               var Dodik = new Person
                          {
                            Name = "Dodik Kutzhenbukher",
                            Age = 12,
                            IsHappy = true,
                            MarriageDate = App.LocalizedTime.AddDays(-100),
                            Father = Frank,
                            Mother = Marry
                          };

              Marry.Mother = Dodik;//Cycle

              var rec = PatientRecord.Make<PatientRecord>();

            //Frank.Father.Items["Absukov"] = 123;
            //Frank.Father.Items["Bosurxevich"] = true;
            //Frank.Father.Items["Corshunovich"] = "ya est tot kto mojet byt";
            //Frank.Father.Items["Zmejukka"] = " do svazi!";

            //Dodik.IntArray = new int[10,10,10];

            //Dodik.IntArray[5,3,4] = 67;
            //Dodik.IntArray[9,9,9] = 65;

            //Dodik.ObjArray = new object[10];
            //for(int i=0; i<Dodik.ObjArray.Length; i++)
            // Dodik.ObjArray[i] = new Person{ Name = "Chelovek-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow};

            //for(int i=0; i<10; i++)
            // Dodik.Relatives.Add( new Person{ Name = "Solovei-"+(i%4).ToString(), Age = 1, Father = Dodik, IsHappy = true, MarriageDate = App.TimeSource.UTCNow} );

            //for(int i=0; i<1000; i++)
            // Dodik.Numbers.Add( 10000-i );

            var tr = new TypeRegistry(TypeRegistry.RecordModelTypes,
                                  TypeRegistry.CommonCollectionTypes,
                                  TypeRegistry.BoxedCommonTypes,
                                  TypeRegistry.BoxedCommonNullableTypes);

            tr.Add(typeof(PatientRecord));
            tr.Add(typeof(Person));
            tr.Add(typeof(Person2));
            tr.Add(typeof(Person[]));
            tr.Add(typeof(System.Collections.Generic.List<Person>));
            tr.Add(typeof(System.Drawing.Point));
            tr.Add(typeof(int[]));
            tr.Add(typeof(int[,,]));

            var data = PatientRecord.Make<PatientRecord>();// make();

             var clk = Stopwatch.StartNew();
            // for(var i=1; i<1000; i++)
               using (var fs = new FileStream(@"c:\NFX\SLIM.slim", FileMode.Create))
              {
                var s = new SlimSerializer(tr);

                for(var i=1; i<1000; i++)
                {
                  s.Serialize(fs,  data);//Dodik);
                }
              }
             Text = clk.ElapsedMilliseconds.ToString();

             clk.Restart();
               using (var fs = new FileStream(@"c:\NFX\FORMATTER.bin", FileMode.Create))
              {
                var bf = new BinaryFormatter();

                for(var i=1; i<1000; i++)
                {
                 bf.Serialize(fs, data);//Dodik);
                }
              }
             Text += "        Binary formatter: " + clk.ElapsedMilliseconds.ToString();
        }