示例#1
0
        public Serializers()
        {
            // order matters here
            NamedTypeSerializer = new ObjectSerializer(this, types);

            serializers.Add(KeyValuePair.New(
                typeof(byte[]), (ISerializer)new ByteArraySerializer(this)));
            serializers.Add(KeyValuePair.New(
                typeof(string), (ISerializer)new StringSerializer(this)));
            serializers.Add(KeyValuePair.New(
                typeof(int), (ISerializer)new Int32Serializer(this)));
            //serializers.Add(KeyValuePair.New(
            //    typeof(IRpcMail), (ISerializer)new RpcMailSerializer(this, types)));
            serializers.Add(KeyValuePair.New(
                typeof(object[]), (ISerializer)new ObjectArraySerializer(this)));
            serializers.Add(KeyValuePair.New(
                typeof(Expression), (ISerializer)new ExprSerializer(this)));
            serializers.Add(KeyValuePair.New(
                typeof(object), NamedTypeSerializer));
            serializers.Add(KeyValuePair.New(
                (Type)null, (ISerializer)new JsonSerializer()));

            serializerMap = serializers.Take(serializers.Count()-1)
                .ToDictionary(n=>n.Key, n=>n.Value);
        }
示例#2
0
    // Use this for initialization
    void Start()
    {
        List<AnotatedAnimation> aList = new List<AnotatedAnimation>();
        AnotatedAnimation anotatedAnimation = new AnotatedAnimation();
        anotatedAnimation.angle = 0.1F;
        anotatedAnimation.distance = 1.0F;
        anotatedAnimation.LeftFoot = new JointState[2];
        JointState js = new JointState();
        js.angle = 0.1F;
        js.orientation = new Vector3(1.0F,1.0F,1.0F);
        anotatedAnimation.LeftFoot[0] = js;
        anotatedAnimation.LeftFoot[1] = js;
        aList.Add(anotatedAnimation);
        aList.Add(anotatedAnimation);

        // writing an object to file
        ObjectSerializer os = new ObjectSerializer();
        os.serializedObject = aList;
        os.writeObjectToFile("test.xml");

        //reading an object from file
        ObjectSerializer os1 = new ObjectSerializer();
        os1.serializedObject = new List<AnotatedAnimation>();
        os1.readObjectFromFile("test.xml");
        List<AnotatedAnimation> objectThatNeedsToBeReadFromFile = (List<AnotatedAnimation>) os1.serializedObject;
        Debug.Log("after read " + objectThatNeedsToBeReadFromFile[1].LeftFoot[1].orientation);
    }
示例#3
0
 /// <summary>
 /// Writes this object's state to a YAML emitter.
 /// </summary>
 void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
 {
     foreach (var item in events)
     {
         emitter.Emit(item);
     }
 }
        public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor, IEnumerable<IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer)
            : base(nextVisitor)
        {
            this.typeConverters = typeConverters != null
                ? typeConverters.ToList()
                : Enumerable.Empty<IYamlTypeConverter>();

            this.nestedObjectSerializer = nestedObjectSerializer;
        }
示例#5
0
 public void read(POxOPrimitiveDecoder decoder, ObjectSerializer serializer, Object obj)
 {
     try
     {
         FieldSerializerUtil[] fieldsSerializerList = objectSerializer.getFieldsSerializers(type);
         for (int i = 0, n = fieldsSerializerList.Length; i < n; i++)
             fieldsSerializerList[i].Field.SetValue(obj,
                 fieldsSerializerList[i].Serializer.read(decoder));
     }
     catch (Exception e)
     {
         throw new POxOSerializerException("Error during fields deserializing. ", e);
     }
 }
示例#6
0
 public void write(POxOPrimitiveEncoder encoder, ObjectSerializer serializer, Object obj)
 {
     try
     {
         FieldSerializerUtil[] fieldsSerializerList = objectSerializer.getFieldsSerializers(type);
         for (int i = 0, n = fieldsSerializerList.Length; i < n; i++)
             fieldsSerializerList[i].Serializer.write(encoder,
                 fieldsSerializerList[i].Field.GetValue(obj));
     }
     catch (Exception e)
     {
         throw new POxOSerializerException("Error during fields serializing. ", e);
     }
 }
示例#7
0
 public NeighborForm()
 {
     InitializeComponent();
     ObjectSerializer<Neighbor> objSerializer = new ObjectSerializer<Neighbor>();
     Neighbor yourObjectFromFile = objSerializer.GetSerializedObject("Neighbor.bin");
     if (yourObjectFromFile != null)
     {
         neighbor = yourObjectFromFile;
     }
     else
     {
         MessageBox.Show("Not reasy");
     }
 }
示例#8
0
        public void CreateAdminUser(string aUserName, string aPassword)
        {
            if (String.IsNullOrEmpty(aUserName))
                throw new ArgumentException("aUserName cannot be null nor empty");
            if (String.IsNullOrEmpty(aPassword))
                throw new ArgumentException("aPassword cannot be null nor empty");

            SetConfigValue("admins", aUserName, aPassword, new Result()).Wait();
            BasePlug.WithCredentials(aUserName, aPassword);// Logon(username, password, new Result<bool>()).Wait();
            CouchUser user = new CouchUser {Name = aUserName};

            ObjectSerializer<CouchUser> serializer = new ObjectSerializer<CouchUser>();
            BasePlug.At("_users", HttpUtility.UrlEncode("org.couchdb.user:" + aUserName)).Put(DreamMessage.Ok(MimeType.JSON, serializer.Serialize(user)), new Result<DreamMessage>()).Wait();
        }
 public PerceptronViewer()
 {
     InitializeComponent();
     lform.FormClosing += Lform_FormClosing;
     ObjectSerializer<Perceptron> objSerializer = new ObjectSerializer<Perceptron>();
     Perceptron yourObjectFromFile = objSerializer.GetSerializedObject(PathObjectSerializer);
     if (yourObjectFromFile != null)
     {
         per = yourObjectFromFile;
     }
     else
     {
         per = new Perceptron(6400, 3200);
     }
     Load += PerceptronViewer_Load;
 }
示例#10
0
        public override void ExposeData(ObjectSerializer serializer)
        {
            base.ExposeData(serializer);

            serializer.DataField(this, l => l.Speed, "speed", 2.6f);
        }
示例#11
0
        public override void ExposeData(ObjectSerializer serializer)
        {
            base.ExposeData(serializer);

            serializer.DataField(ref refillAmmo, "refillAmmo", 5);
        }
示例#12
0
 /// <summary>
 /// Provides a cursor into a set of a single object.
 /// </summary>
 /// <param name="Value">Singleton value.</param>
 /// <param name="Serializer">Serializer of <paramref name="Value"/>.</param>
 ///	<param name="ObjectId">Object ID.</param>
 internal SingletonCursor(T Value, ObjectSerializer Serializer, Guid ObjectId)
 {
     this.value      = Value;
     this.serializer = Serializer;
     this.objectId   = ObjectId;
 }
 public override void ExposeData(ObjectSerializer serializer)
 {
     base.ExposeData(serializer);
     serializer.DataField(ref _outputTile, "output", "floor_steel");
 }
示例#14
0
 /// <summary>
 /// Saves the plugin settings
 /// </summary>
 public void SaveSettings()
 {
     ObjectSerializer.Serialize(this.settingFilename, this.settingObject);
 }
示例#15
0
 void IExposeData.ExposeData(ObjectSerializer serializer)
 {
     serializer.DataField(ref _temperatureMultiplier, "temperatureMultiplier", 1.15f);
 }
 public DotNetSerializableSerializer(ITypeResolver typeResolver)
 {
     _typeResolver               = typeResolver;
     _objectSerializer           = new ObjectSerializer(_constructorFactory, _serializationCallbacks, _formatterConverter);
     _valueTypeSerializerFactory = new ValueTypeSerializerFactory(_constructorFactory, _serializationCallbacks, _formatterConverter);
 }
 public RequestGenerator()
 {
     _objectSerializer = new ObjectSerializer();
 }
 public override void ExposeData(ObjectSerializer serializer) => throw new NotSupportedException();
 public void ExposeData(ObjectSerializer serializer)
 {
     serializer.DataField(this, x => x.Anchored, "anchored", true);
 }
示例#20
0
        public override void ExposeData(ObjectSerializer serializer)
        {
            base.ExposeData(serializer);

            serializer.DataField(ref _equippedPrefix, "HeldPrefix", null);
        }
 public override void ExposeData(ObjectSerializer serializer)
 {
     base.ExposeData(serializer);
     serializer.DataField(ref _wirePrototypeID, "wirePrototypeID", "HVWire");
     serializer.DataField(ref _blockingWireType, "blockingWireType", WireType.HighVoltage);
 }
示例#22
0
 public void ExposeData(ObjectSerializer serializer)
 {
     UiKey      = serializer.ReadStringEnumKey("key");
     ClientType = serializer.ReadDataField <string>("type");
 }
示例#23
0
 void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
 {
     Emit(emitter, new EmitterState());
 }
示例#24
0
 public void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
 {
     nestedObjectSerializer(new TransformTemplate(this));
 }
示例#25
0
 //save collection image
 private void DividedIntoImageButton_Click(object sender, EventArgs e)
 {
     ObjectSerializer<Perceptron> objSerializer = new ObjectSerializer<Perceptron>();
     Perceptron yourObjectFromFile = objSerializer.GetSerializedObject(PathObjectSerializer);
     if (yourObjectFromFile != null)
     {
         per = yourObjectFromFile;
     }
     else
     {
         MessageBox.Show("Perceptron not trained");
     }
     Segmentation segment = new Segmentation(null, null);
     numberImageCollection = segment.GetCollectionofImage(DividedImageList, DividedImage);
     ImageFormat format = ImageFormat.Bmp;
     SaveFileDialog saveFileDialog = new SaveFileDialog();
     if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         int x = 0;
         DividedimageList1.ImageSize = new Size(50, 50);
         foreach (var item in numberImageCollection)
         {
             item.bitmap.Save(saveFileDialog.FileName + item.Name + ".bmp", format);
             DividedimageList1.Images.Add(Image.FromFile(saveFileDialog.FileName + item.Name + ".bmp"));
             DividedListView.Items.Add("image", x++);
         }
         DividedListView.LargeImageList = DividedimageList1;
     }
 }
示例#26
0
        public SucceedAPIsMockModule()
        {
            Post[BasePath + "objects"] = x => {
                TestUtils.AssertObjectEquals(TestUtils.CreateTestObject(), ObjectSerializer.DeserializeObject(NancyUtils.BodyAsString(this.Request)));
                return(201);
            };

            Put[BasePath + "objects"] = x => {
                List <SmartObject> objects = TestUtils.DeserializeObjects(NancyUtils.BodyAsString(this.Request));
                TestUtils.AssertObjectsEqual(TestUtils.CreateObjects(objects.Count <SmartObject>()), objects);

                List <Result> results = new List <Result>();
                foreach (SmartObject anObject in objects)
                {
                    results.Add(new Result(anObject.DeviceId, Result.ResultStates.Success, null));
                }

                return(JsonConvert.SerializeObject(results));
            };

            Put[BasePath + "objects/{deviceId}"] = x => {
                TestUtils.AssertObjectEquals(TestUtils.CreateObjectUpdateAttribute(), ObjectSerializer.DeserializeObject(NancyUtils.BodyAsString(this.Request)));
                Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId);
                return(200);
            };

            Delete[BasePath + "objects/{deviceId}"] = x => {
                Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId);
                return(200);
            };

            Get[BasePath + "objects/exists/{deviceId}"] = x => {
                var deviceId = (string)x.deviceId;
                Assert.AreEqual(TestUtils.DeviceId, deviceId);
                IDictionary <string, bool> result = new Dictionary <string, bool>()
                {
                    { deviceId, true }
                };
                return(JsonConvert.SerializeObject(result));
            };

            Post[BasePath + "owners"] = x => {
                TestUtils.AssertOwnerEquals(TestUtils.CreateTestOwner(), OwnerSerializer.DeserializeOwner(NancyUtils.BodyAsString(this.Request)));
                return(201);
            };

            Put[BasePath + "owners"] = x => {
                List <Owner> owners = TestUtils.DeserializeOwners(NancyUtils.BodyAsString(this.Request));
                TestUtils.AssertOwnersEqual(TestUtils.CreateOwners(owners.Count <Owner>()), owners);

                List <Result> results = new List <Result>();
                foreach (Owner owner in owners)
                {
                    results.Add(new Result(owner.Username, Result.ResultStates.Success, null));
                }

                return(JsonConvert.SerializeObject(results));
            };

            Put[BasePath + "owners/{username}"] = x => {
                TestUtils.AssertOwnerEquals(TestUtils.CreateOwnerUpdateAttribute(), OwnerSerializer.DeserializeOwner(NancyUtils.BodyAsString(this.Request)));
                Assert.AreEqual(TestUtils.Username, (string)x.username);
                return(200);
            };

            Put[BasePath + "owners/{username}/password"] = x => {
                Dictionary <string, string> body = JsonConvert.DeserializeObject <Dictionary <string, string> >(NancyUtils.BodyAsString(this.Request));
                Assert.IsTrue(body.ContainsKey("x_password"));
                String password = "";
                body.TryGetValue("x_password", out password);
                Assert.AreEqual(TestUtils.Password, password);
                Assert.AreEqual(TestUtils.Username, (string)x.username);
                return(200);
            };

            Post[BasePath + "owners/{username}/objects/{deviceId}/claim"] = x => {
                Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId);
                Assert.AreEqual(TestUtils.Username, (string)x.username);
                return(200);
            };

            Post[BasePath + "owners/{username}/objects/{deviceId}/unclaim"] = x => {
                Assert.AreEqual(TestUtils.DeviceId, (string)x.deviceId);
                Assert.AreEqual(TestUtils.Username, (string)x.username);
                return(200);
            };

            Delete[BasePath + "owners/{username}"] = x => {
                Assert.AreEqual(TestUtils.Username, (string)x.username);
                return(200);
            };

            Get[BasePath + "owners/exists/{username}"] = x => {
                string username = (string)x.username;
                Assert.AreEqual(TestUtils.Username, username);
                IDictionary <string, bool> result = new Dictionary <string, bool>()
                {
                    { username, true }
                };
                return(JsonConvert.SerializeObject(result));
            };

            Post[BasePath + "events"] = x => {
                bool reportResults = (bool)this.Request.Query["report_results"];

                Assert.AreEqual(true, reportResults);
                List <EventResult> results = TestUtils.EventsToSuccesfullResults(NancyUtils.BodyAsString(this.Request));
                return(JsonConvert.SerializeObject(results));
            };

            Get[BasePath + "events/exists/{eventId}"] = x => {
                IDictionary <string, bool> result = new Dictionary <string, bool>()
                {
                    { (string)x.eventId, true }
                };
                return(JsonConvert.SerializeObject(result));
            };

            Get[BasePath + "search/datasets"] = x => {
                return(JsonConvert.SerializeObject(TestUtils.CreateDatasets()));
            };

            Post[BasePath + "search/basic"] = x => {
                Assert.AreEqual(TestUtils.CreateQuery(), NancyUtils.BodyAsString(this.Request));
                return(TestUtils.CreateExpectedSearchResult());
            };

            // test HttpClient itself
            Post[BasePath + "compressed"] = x => {
                if (!NancyUtils.IsGzipCompressed(this.Request))
                {
                    return(FailedAPIsMockModule.badRequest());
                }

                if (!this.Request.Headers.AcceptEncoding.Contains("gzip"))
                {
                    return(FailedAPIsMockModule.badRequest());
                }

                var body = NancyUtils.BodyAsString(this.Request);
                if (body != TestJsonString)
                {
                    return(FailedAPIsMockModule.badRequest());
                }

                var data     = Encoding.UTF8.GetBytes(body);
                var response = new Response();
                response.Headers.Add("Content-Encoding", "gzip");
                response.Headers.Add("Content-Type", "application/json");
                response.Contents = stream =>
                {
                    using (var gz = new GZipStream(stream, CompressionMode.Compress))
                    {
                        gz.Write(data, 0, data.Length);
                        gz.Flush();
                    }
                };
                return(response);
            };

            Post[BasePath + "decompressed"] = x => {
                if (NancyUtils.IsGzipCompressed(this.Request))
                {
                    return(FailedAPIsMockModule.badRequest());
                }

                var body = NancyUtils.BodyAsString(this.Request);
                if (body != TestJsonString)
                {
                    return(FailedAPIsMockModule.badRequest());
                }

                return(TestJsonString);
            };
        }
示例#27
0
 /// <summary>
 /// Loads the plugin settings
 /// </summary>
 public void LoadSettings()
 {
     this.settingObject = new Settings();
     if (!File.Exists(this.settingFilename))
     {
         this.SaveSettings();
     }
     else
     {
         Object obj = ObjectSerializer.Deserialize(this.settingFilename, this.settingObject);
         this.settingObject = (Settings)obj;
     }
     // Recheck after installer update if auto config is not disabled
     if (!this.settingObject.DisableAutoConfig && PluginBase.MainForm.RefreshConfig)
     {
         this.settingObject.PlayerPath = null;
     }
     // Try to find player path from: Tools/flexlibs/
     if (String.IsNullOrEmpty(this.settingObject.PlayerPath))
     {
         String playerPath11  = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.0\win\FlashPlayerDebugger.exe");
         String playerPath111 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.1\win\FlashPlayerDebugger.exe");
         String playerPath112 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.2\win\FlashPlayerDebugger.exe");
         String playerPath113 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.3\win\FlashPlayerDebugger.exe");
         String playerPath114 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.4\win\FlashPlayerDebugger.exe");
         String playerPath115 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.5\win\FlashPlayerDebugger.exe");
         String playerPath116 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.6\win\FlashPlayerDebugger.exe");
         String playerPath117 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.7\win\FlashPlayerDebugger.exe");
         String playerPath118 = Path.Combine(PathHelper.ToolDir, @"flexlibs\runtimes\player\11.8\win\FlashPlayerDebugger.exe");
         if (File.Exists(playerPath118))
         {
             this.settingObject.PlayerPath = playerPath118;
         }
         else if (File.Exists(playerPath117))
         {
             this.settingObject.PlayerPath = playerPath117;
         }
         else if (File.Exists(playerPath116))
         {
             this.settingObject.PlayerPath = playerPath116;
         }
         else if (File.Exists(playerPath115))
         {
             this.settingObject.PlayerPath = playerPath115;
         }
         else if (File.Exists(playerPath114))
         {
             this.settingObject.PlayerPath = playerPath114;
         }
         else if (File.Exists(playerPath113))
         {
             this.settingObject.PlayerPath = playerPath113;
         }
         else if (File.Exists(playerPath112))
         {
             this.settingObject.PlayerPath = playerPath112;
         }
         else if (File.Exists(playerPath111))
         {
             this.settingObject.PlayerPath = playerPath111;
         }
         else if (File.Exists(playerPath11))
         {
             this.settingObject.PlayerPath = playerPath11;
         }
     }
     // Try to find player path from: Tools/flexsdk/
     if (String.IsNullOrEmpty(this.settingObject.PlayerPath))
     {
         String playerPath10  = Path.Combine(PathHelper.ToolDir, @"flexsdk\runtimes\player\10\win\FlashPlayer.exe");
         String playerPath101 = Path.Combine(PathHelper.ToolDir, @"flexsdk\runtimes\player\10.1\win\FlashPlayerDebugger.exe");
         String playerPath102 = Path.Combine(PathHelper.ToolDir, @"flexsdk\runtimes\player\10.2\win\FlashPlayerDebugger.exe");
         if (File.Exists(playerPath102))
         {
             this.settingObject.PlayerPath = playerPath102;
         }
         else if (File.Exists(playerPath101))
         {
             this.settingObject.PlayerPath = playerPath101;
         }
         else if (File.Exists(playerPath10))
         {
             this.settingObject.PlayerPath = playerPath10;
         }
     }
     // Try to find player path from: FlexSDK
     if (!this.settingObject.DisableAutoConfig && String.IsNullOrEmpty(this.settingObject.PlayerPath))
     {
         String compiler      = PluginBase.MainForm.ProcessArgString("$(CompilerPath)");
         String playerPath10  = Path.Combine(compiler, @"runtimes\player\10\win\FlashPlayer.exe");
         String playerPath101 = Path.Combine(compiler, @"runtimes\player\10.1\win\FlashPlayerDebugger.exe");
         String playerPath102 = Path.Combine(compiler, @"runtimes\player\10.2\win\FlashPlayerDebugger.exe");
         if (File.Exists(playerPath102))
         {
             this.settingObject.PlayerPath = playerPath102;
         }
         else if (File.Exists(playerPath101))
         {
             this.settingObject.PlayerPath = playerPath101;
         }
         else if (File.Exists(playerPath10))
         {
             this.settingObject.PlayerPath = playerPath10;
         }
     }
     // After detection, if the path is incorrect clear it
     if (this.settingObject.PlayerPath == null || !File.Exists(this.settingObject.PlayerPath))
     {
         this.settingObject.PlayerPath = String.Empty;
     }
 }
示例#28
0
 public override void ExposeData(ObjectSerializer serializer)
 {
     base.ExposeData(serializer);
     serializer.DataField(ref _wireDroppedOnCutPrototype, "wireDroppedOnCutPrototype", "HVWireStack1");
     serializer.DataField(ref _wireType, "wireType", WireType.HighVoltage);
 }
示例#29
0
 /// <summary>
 /// Provides a cursor into an empty set.
 /// </summary>
 internal EmptyCursor(ObjectSerializer Serializer)
 {
 }
示例#30
0
        public override void ExposeData(ObjectSerializer serializer)
        {
            base.ExposeData(serializer);

            serializer.DataField(ref _templateName, "Template", "HumanInventory");
        }
 public override void ExposeData(ObjectSerializer serializer)
 {
     base.ExposeData(serializer);
     serializer.DataField(ref _tools, "tools", new List <ToolEntry>());
 }
示例#32
0
        public static void Test()
        {
            try
            {
                //获取Redis操作接口
                IRedisClient Redis = RedisManager.GetClient();
                //Hash表操作
                HashOperator operators = new HashOperator();

                //移除某个缓存数据
                bool isTrue = Redis.Remove("additemtolist");

                //将字符串列表添加到redis
                List <string> storeMembers = new List <string>()
                {
                    "韩梅梅", "李雷", "露西"
                };
                storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x));

                //得到指定的key所对应的value集合
                Console.WriteLine("得到指定的key所对应的value集合:");
                var members = Redis.GetAllItemsFromList("additemtolist");
                members.ForEach(s => Console.WriteLine("additemtolist :" + s));
                Console.WriteLine("");

                // 获取指定索引位置数据
                Console.WriteLine("获取指定索引位置数据:");
                var item = Redis.GetItemFromList("additemtolist", 2);
                Console.WriteLine(item);

                Console.WriteLine("");

                //将数据存入Hash表中
                Console.WriteLine("Hash表数据存储:");
                UserInfo userInfos = new UserInfo()
                {
                    UserName = "******", Age = 45
                };
                var    ser     = new ObjectSerializer(); //位于namespace ServiceStack.Redis.Support;
                bool   results = operators.Set <byte[]>("userInfosHash", "userInfos", ser.Serialize(userInfos));
                byte[] infos   = operators.Get <byte[]>("userInfosHash", "userInfos");
                userInfos = ser.Deserialize(infos) as UserInfo;
                Console.WriteLine("name=" + userInfos.UserName + "   age=" + userInfos.Age);

                Console.WriteLine("");

                //object序列化方式存储
                Console.WriteLine("object序列化方式存储:");
                UserInfo uInfo = new UserInfo()
                {
                    UserName = "******", Age = 12
                };
                bool     result    = Redis.Set <byte[]>("uInfo", ser.Serialize(uInfo));
                UserInfo userinfo2 = ser.Deserialize(Redis.Get <byte[]>("uInfo")) as UserInfo;
                Console.WriteLine("name=" + userinfo2.UserName + "   age=" + userinfo2.Age);

                Console.WriteLine("");

                //存储值类型数据
                Console.WriteLine("存储值类型数据:");
                Redis.Set <int>("my_age", 12);//或Redis.Set("my_age", 12);
                int age = Redis.Get <int>("my_age");
                Console.WriteLine("age=" + age);

                Console.WriteLine("");

                //序列化列表数据
                Console.WriteLine("列表数据:");
                List <UserInfo> userinfoList = new List <UserInfo> {
                    new UserInfo {
                        UserName = "******", Age = 1, Id = 1
                    },
                    new UserInfo {
                        UserName = "******", Age = 3, Id = 2
                    },
                };
                Redis.Set <byte[]>("userinfolist_serialize", ser.Serialize(userinfoList));
                List <UserInfo> userList = ser.Deserialize(Redis.Get <byte[]>("userinfolist_serialize")) as List <UserInfo>;
                userList.ForEach(i =>
                {
                    Console.WriteLine("name=" + i.UserName + "   age=" + i.Age);
                });
                //释放内存
                Redis.Dispose();
                operators.Dispose();
                Console.Read();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                Console.WriteLine("Please open the redis-server.exe ");
                Console.ReadKey();
            }
        }
示例#33
0
 public void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer)
 {
     throw new NotImplementedException();
 }
        public override Result DoWork()
        {
            var serializedNotification = InputData.GetString(NotificationCenter.ExtraReturnNotification);

            if (string.IsNullOrWhiteSpace(serializedNotification))
            {
                return(Result.InvokeFailure());
            }

            var serializedNotificationAndroid = InputData.GetString($"{NotificationCenter.ExtraReturnNotification}_Android");

            Task.Run(() =>
            {
                try
                {
                    Log.Info(Application.Context.PackageName, $"ScheduledNotificationWorker.DoWork: SerializedNotification [{serializedNotification}]");
                    var notification = ObjectSerializer.DeserializeObject <NotificationRequest>(serializedNotification);
                    if (string.IsNullOrWhiteSpace(serializedNotificationAndroid) == false)
                    {
                        var notificationAndroid =
                            ObjectSerializer.DeserializeObject <AndroidOptions>(serializedNotificationAndroid);
                        if (notificationAndroid != null)
                        {
                            notification.Android = notificationAndroid;
                        }
                    }

                    if (notification.NotifyTime.HasValue && notification.Repeats != NotificationRepeat.No)
                    {
                        switch (notification.Repeats)
                        {
                        case NotificationRepeat.Daily:
                            // To be consistent with iOS, Schedule notification next day same time.
                            notification.NotifyTime = notification.NotifyTime.Value.AddDays(1);
                            while (notification.NotifyTime <= DateTime.Now)
                            {
                                notification.NotifyTime = notification.NotifyTime.Value.AddDays(1);
                            }

                            break;

                        case NotificationRepeat.Weekly:
                            // To be consistent with iOS, Schedule notification next week same day same time.
                            notification.NotifyTime = notification.NotifyTime.Value.AddDays(7);
                            while (notification.NotifyTime <= DateTime.Now)
                            {
                                notification.NotifyTime = notification.NotifyTime.Value.AddDays(7);
                            }

                            break;
                        }

                        NotificationCenter.Current.Show(notification);
                    }

                    // To be consistent with iOS, Do not show notification if NotifyTime is earlier than DateTime.Now
                    if (notification.NotifyTime != null && notification.NotifyTime.Value <= DateTime.Now.AddMinutes(-1))
                    {
                        System.Diagnostics.Debug.WriteLine("NotifyTime is earlier than DateTime.Now, notification ignored");
                        return;
                    }

                    notification.NotifyTime = null;
                    NotificationCenter.Current.Show(notification);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                }
            });

            return(Result.InvokeSuccess());
        }
示例#35
0
 void IExposeData.ExposeData(ObjectSerializer serializer)
 {
     serializer.DataField(this, x => x.Container, "container", null);
 }
 public void ExposeData(ObjectSerializer serializer)
 {
     serializer.DataField(this, x => x.Open, "open", true);
 }
示例#37
0
 public FieldsSerializer(Type classToSerialize, ObjectSerializer objectSerializer)
 {
     this.objectSerializer = objectSerializer;
     this.type = classToSerialize;
 }
示例#38
0
 private void SavePerceptron()
 {
     ObjectSerializer<Perceptron> objSerializer = new ObjectSerializer<Perceptron>();
     objSerializer.SaveSerializedObject(per, PathObjectSerializer);
 }
示例#39
0
 private void button1_Click(object sender, EventArgs e)
 {
     neighbor = new Neighbor(bitList);
     ObjectSerializer<Neighbor> objSerializer = new ObjectSerializer<Neighbor>();
     objSerializer.SaveSerializedObject(neighbor, "Neighbor.bin");
 }
示例#40
0
    public void ReadAnalysisFromFile(string fileName)
    {
        //reading an object from file
        ObjectSerializer os1 = new ObjectSerializer();
        os1.serializedObject = new SerializableDictionary<string,AnotatedAnimation>();
        os1.readObjectFromFile(fileName);
        analyzedAnimations = (SerializableDictionary<string,AnotatedAnimation>) os1.serializedObject;

        foreach (KeyValuePair<string,AnotatedAnimation> anim in analyzedAnimations)
        {
            updateGlobalInfo(anim.Value);
        }
        UpdateGlobalInfo();

        if (log)
        {
            foreach (KeyValuePair<string,AnotatedAnimation> anim in analyzedAnimations)
            {
                anim.Value.LogAnotations();
            }

            Debug.Log("Mean duration: " + meanActionDuration);
            Debug.Log("Mean step size: " + meanStepSize);
        }
    }
示例#41
0
 private void button3_Click(object sender, EventArgs e)
 {
     if (numberImageCollection != null)
     {
         NeighbLable.Text = "";
         Neighbor neir = new Neighbor();
         ObjectSerializer<Neighbor> objSerializer = new ObjectSerializer<Neighbor>();
         Neighbor yourObjectFromFile = objSerializer.GetSerializedObject("Neighbor.bin");
         if (yourObjectFromFile != null)
         {
             neir = yourObjectFromFile;
         }
         else
         {
             MessageBox.Show("Neighbor not trained");
         }
         foreach (var item in numberImageCollection)
         {
             NeighbLable.Text = NeighbLable.Text + neir.NameClass(item.bitmap);
         }
     }
     else
     {
         MessageBox.Show("Collection image empty");
     }
 }
示例#42
0
 public void ItShouldDeserializeResponse()
 {
     ObjectSerializer.Verify(x => x.DeserializeJson <TweetCollection>(_webResponse.Object));
 }
示例#43
0
 private void MainForm_Load(object sender, EventArgs e)
 {
     ObjectSerializer<Perceptron> objSerializer = new ObjectSerializer<Perceptron>();
     Perceptron yourObjectFromFile = objSerializer.GetSerializedObject(PathObjectSerializer);
     if (yourObjectFromFile != null)
     {
         per = yourObjectFromFile;
     }
     else
     {
         MessageBox.Show("Perceptron not trained");
     }
 }
 private async Task SendNoticeToClientsAsync(IEnumerable <ClientConnection> clients, Notice notice)
 {
     try
     {
         if (clients.IsNullOrEmpty())
         {
             return;
         }
         foreach (var client in clients)
         {
             try
             {
                 if (client.IsProxiedClientConnection && client.ClientSocket == null && client.ProxyNodeWebSocket != null)
                 {
                     NodeConnection nodeConnection = connectionsService.GetNodeConnections().FirstOrDefault(opt => opt.NodeWebSocket == client.ProxyNodeWebSocket);
                     byte[]         noticeData     = ObjectSerializer.CommunicationObjectToBytes(notice);
                     if (client.IsEncryptedConnection)
                     {
                         noticeData = Encryptor.SymmetricDataEncrypt(
                             noticeData,
                             NodeData.Instance.NodeKeys.SignPrivateKey,
                             client.SymmetricKey,
                             MessageDataType.Notice,
                             NodeData.Instance.NodeKeys.Password);
                     }
                     nodeNoticeService.SendProxyUsersNotificationsNodeNoticeAsync(
                         noticeData,
                         client.UserId.GetValueOrDefault(),
                         client.PublicKey,
                         nodeConnection);
                 }
                 else if (client.ClientSocket != null)
                 {
                     byte[] noticeData = ObjectSerializer.NoticeToBytes(notice);
                     if (client.IsEncryptedConnection)
                     {
                         noticeData = Encryptor.SymmetricDataEncrypt(
                             noticeData,
                             NodeData.Instance.NodeKeys.SignPrivateKey,
                             client.SymmetricKey,
                             MessageDataType.Binary,
                             NodeData.Instance.NodeKeys.Password);
                     }
                     await client.ClientSocket.SendAsync(
                         noticeData,
                         WebSocketMessageType.Binary,
                         true,
                         CancellationToken.None)
                     .ConfigureAwait(false);
                 }
             }
             catch (WebSocketException)
             {
                 continue;
             }
         }
     }
     catch (Exception ex)
     {
         Logger.WriteLog(ex, notice.ToString());
     }
 }
示例#45
0
 void IExposeData.ExposeData(ObjectSerializer serializer)
 {
 }
示例#46
0
 public override void ExposeData(ObjectSerializer serializer)
 {
     base.ExposeData(serializer);
     serializer.DataField(ref _transferAmount, "transferAmount", ReagentUnit.New(0.5));
 }
 public TheSerializeMethod()
 {
     _serializer = new ObjectSerializer();
 }
示例#48
0
 void IExposeData.ExposeData(ObjectSerializer serializer)
 {
     serializer.DataField(this, x => x.Type, "type", null);
     serializer.DataField(this, x => x.Damage, "damage", 0);
 }
        public override void ExposeData(ObjectSerializer serializer)
        {
            base.ExposeData(serializer);

            serializer.DataField(ref _storageLimit, "StorageLimit", -1);
        }
示例#50
0
    void LateUpdate()
    {
        if (stored)
            return;

        // If analysis done remove all animations
        if (currentAnimationIndex == animationNames.Length)
        {
            if (analyzer != null)
            {
                // Stop and remove animations from the character
                analyzer.RemoveAnimations(animation);

                // Update global information
                analyzer.UpdateGlobalInfo();

                // Store analysis
                // writing an object to file
                ObjectSerializer os = new ObjectSerializer();
                os.serializedObject = analyzer.analyzedAnimations;
                os.writeObjectToFile(fileName);

                stored = true;

                if (analyzer.log)
                    analyzer.ReadAnalysisFromFile(fileName);
            }

            // End execution
            return;
        }

        //if (currentAnimation != null
        //    && Mathf.Abs(currentAnimation.time) < currentActionTime
        //)
            // We compute the root displacement
            //rootMotion.ComputeRootMotion();

        if (changed && currentAnimationName != null)
        {
            //currentAnimation.time = 0;
            //agent.animation.Sample();
            //rootMotion.ComputeRootMotion();

            AnotatedAnimation animInfo = analyzer.GetAnotatedAnimation(currentAnimationName);

            // analyze initial state
            analyzer.analyzeInitState(animInfo);

            currentSample = 1;
        }

        // If its the first animation or the current animation ended,
        if (currentAnimation == null
            || Mathf.Abs(currentAnimation.time) >= currentActionTime
            )
        {
            if (currentAnimationName != null)
            {
                Debug.Log("Time difference = " + (currentAnimation.time - currentActionTime));

                // We correct the pose to the one we really want to analyze
                //currentAnimation.time = currentActionTime;
                //agent.animation.Sample();
                //rootMotion.ComputeRootMotion();

                AnotatedAnimation endedAnimInfo = analyzer.GetAnotatedAnimation(currentAnimationName);

                // Analyze end state
                analyzer.analyzeState(endedAnimInfo,analyzer.samples-1,currentAnimation.normalizedTime);

                // Analyze the movement
                analyzer.analyzeMovement(endedAnimInfo);

                // Update global values
                analyzer.updateGlobalInfo(endedAnimInfo);
            }

            // Get new animation
            currentAnimationIndex++;

            // If there is no more animations we stop
            if (currentAnimationIndex == animationNames.Length)
                return;

            string animationName = animationNames[currentAnimationIndex];

            if (blending)
            {
                // We blend out the previous animation
                // if it exists and it is not the first one
                if (currentAnimation != null)
                {
                    if (currentAnimationIndex > 0)
                        agent.animation.Blend(currentAnimation.name,0.0f,currentBlendingTime);
                    else
                    {
                        agent.animation.Stop();
                        agent.animation.Sample();
                    }
                }
            }

            // We set up the speed of the new animation
            AnimationState newAnimationState =  agent.animation[animationName];
            newAnimationState.speed = 1.0f;
            // We set the animation at the beginning
            newAnimationState.time = 0;
            newAnimationState.enabled = true;

            // We save the new animation
            currentAnimation = newAnimationState;
            currentAnimationName = animationName;

            // We get the info of the new animation
            AnotatedAnimation animInfo = analyzer.GetAnotatedAnimation(animationName);

            // We compute the time of the action and the time of the blending
            float newActionTime = animInfo.time * animInfo.totalLength;

            float newBlendingTime = animInfo.totalLength * animInfo.footPlantLenght;
            if (animInfo.type != LocomotionMode.Walk)
                newBlendingTime = 0.5f;

            currentActionTime = newActionTime;

            if (previousBlendingTime < newBlendingTime)
                currentBlendingTime = previousBlendingTime;
            else
                currentBlendingTime = newBlendingTime;

            previousBlendingTime = newBlendingTime;

            if (blending)
            {
                //We play/blend in the new animation if it's not the first one
                if (currentAnimationIndex > 0)
                    agent.animation.Blend(currentAnimation.name,1.0f,currentBlendingTime);
                else
                {
                    agent.animation.Play(currentAnimation.name);
                    agent.animation.Sample();
                }
            }
            else
                agent.animation.Play(currentAnimation.name);

            changed = true;

            currentSample = 0;

        }
        else
        {
            changed = false;

            if (currentAnimationName != null)
            {
                AnotatedAnimation animInfo = analyzer.GetAnotatedAnimation(currentAnimationName);

                float previousSampleTime = (currentSample-1)*animInfo.time/(analyzer.samples-1);
                previousSampleTime *= animInfo.totalLength;

                float timeBetweenSamples = animInfo.time/(analyzer.samples-1);

                float timeDifference = Mathf.Abs(currentAnimation.time) - previousSampleTime;

                if (timeDifference >= timeBetweenSamples)
                {
                    // We correct the pose to the one we really want to analyze
                    //currentAnimation.time = currentSample*animInfo.time/(analyzer.samples-1);
                    //agent.animation.Sample();

                    analyzer.analyzeState(animInfo,currentSample,currentAnimation.normalizedTime);

                    currentSample++;
                }
            }
        }
    }