public SaveData ConstructSaveData(string LevelSaveKey) { float Seconds = SimpleSerializer.LoadFloat(LevelSaveKey); Vector2 Offset = SimpleSerializer.LoadVector(LevelSaveKey); return(new SaveData(Seconds, Offset)); }
static TypeSerializer() { Type type = typeof(valueType); int memberCountVerify; BinarySerialize.Fields <BinarySerialize.FieldSize> fields = BinarySerialize.SerializeMethodCache.GetFields(MemberIndexGroup <valueType> .GetFields(MemberFilters.PublicInstanceField), false, out memberCountVerify); #if NOJIT fixedFillSize = -fields.FixedSize & 3; fixedSize = (fields.FixedSize + fields.FieldArray.Length * sizeof(int) + 3) & (int.MaxValue - 3); fixedSerializer = new FieldFerializer(ref fields.FixedFields).Serialize; if (fields.FieldArray.Length != 0) { serializer = new FieldFerializer(ref fields.FieldArray).Serialize; } #else SerializeDynamicMethod dynamicMethod = new SerializeDynamicMethod(type, (fields.FixedSize + fields.FieldArray.Length * sizeof(int) + 3) & (int.MaxValue - 3)); foreach (BinarySerialize.FieldSize member in fields.FixedFields) { dynamicMethod.Push(member); } dynamicMethod.FixedFill(-fields.FixedSize & 3); foreach (BinarySerialize.FieldSize member in fields.FieldArray) { dynamicMethod.Push(member); } Serializer = (SimpleSerializer)dynamicMethod.Create <SimpleSerializer>(); #endif }
/// <summary> /// /// </summary> /// <param name="e"></param> protected virtual void OnValueChanged(object sender, PropertyChangedEventArgs e) { switch (sender) { case RegisterFlag rf: { SimpleSerializer.DeserializeProps(Target, rf.Value ? "1" : "0", rf.ItemName); break; } case RegisterValue rc: if (rc.IsNullable) { if (rc.NullableValue == null) { SimpleSerializer.DeserializeProps(Target, "", rc.ItemName); } else { SimpleSerializer.DeserializeProps(Target, rc.Value.ToString((IFormatProvider)null), rc.ItemName); } } else { SimpleSerializer.DeserializeProps(Target, rc.Value.ToString((IFormatProvider)null), rc.ItemName); } break; } ValueChanged?.Invoke(sender, e); ignoreTextChange = true; textBoxSR.Text = SerializeData; ignoreTextChange = false; }
private void SaveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) { if (scenLoaded) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "劇本檔 (*.json)|*.json"; saveFileDialog.InitialDirectory = @"Content\Data\Scenario"; if (saveFileDialog.ShowDialog() == true) { String filename = saveFileDialog.FileName; String scenName = filename.Substring(filename.LastIndexOf(@"\") + 1, filename.LastIndexOf(".") - filename.LastIndexOf(@"\") - 1); String scenPath = filename.Substring(0, filename.LastIndexOf(@"\")); scen.SaveGameScenario(filename, true, false, false, false, true, true); // GameCommonData.json String commonPath = @"Content\Data\Common\CommonData.json"; saveGameCommonData(commonPath); // Scenarios.json String scenariosPath = scenPath + @"\Scenarios.json"; List <GameManager.Scenario> scesList = null; if (File.Exists(scenariosPath)) { scesList = SimpleSerializer.DeserializeJsonFile <List <GameManager.Scenario> >(scenariosPath, false).NullToEmptyList(); } if (scesList == null) { scesList = new List <GameManager.Scenario>(); } GameManager.Scenario s1 = createScenarioObject(scen, scenName); if (s1 != null) { int index = scesList.FindIndex(x => x.Name == scenName); if (index >= 0) { scesList[index] = s1; } else { scesList.Add(s1); } } string s2 = Newtonsoft.Json.JsonConvert.SerializeObject(scesList, Newtonsoft.Json.Formatting.Indented); File.WriteAllText(scenariosPath, s2); MessageBox.Show("劇本已儲存為" + filename); } } else { // GameCommonData.json String commonPath = @"Content\Data\Common\CommonData.json"; saveGameCommonData(commonPath); MessageBox.Show("CommonData已儲存為" + commonPath); } }
public void TestTypeSerialization() { var type = typeof(Expression <Func <int, bool> >); var bytes = SimpleSerializer.Binary().Serialize(type); var type2 = (Type)SimpleSerializer.Binary().Deserialize(bytes); type2.Should().Be(type); }
public void FieldWrapperIsSerializable() { var prop = typeof(Sample).GetField("TestField").ToSettable(); var result = SimpleSerializer.Binary().RoundTrip(prop); result.Name.Should().Be.Equals(prop.Name); }
public void TestItInternal <T, TRet>(Expression <T> expr, Func <T, TRet> howToCall) { TestItInternalInternal <T, TRet>(expr, howToCall, SimpleSerializer.Binary()); TestItInternalInternal <T, TRet>(expr, howToCall, SimpleSerializer.NetDataContract()); }
public void TestMethodSerialization() { var method = typeof(Queryable).GetMember("Where").OfType <MethodInfo>().Where(x => x.GetParameters().Length == 2).First(); var bytes = SimpleSerializer.Binary().Serialize(method); var method2 = (MethodInfo)SimpleSerializer.Binary().Deserialize(bytes); method2.Should().Be(method); }
public void ShouldBeSerializable() { var expr = ExprTyped(x => x.TestProp).ToSettable(); var expr2 = SimpleSerializer.Binary().RoundTrip(expr); expr2.Expression.ToString().Should().Be(expr.Expression.ToString()); }
/// <summary> /// Inserts a record into a table using Cmd /// </summary> /// <param name="Cmd">The Sql Command object to execute.</param> /// <param name="PaymentId">The payment id to which to assign the record.</param> /// <param name="Record">The record to insert.</param> private void Insert_Record(SqlCommand Cmd, int PaymentId, SimpleSerializer Record) { if (Record == null) { throw new Exception("Missing data for: " + Cmd.CommandText); } Record.CopyTo(Cmd); Cmd.Parameters["@PaymentId"].Value = PaymentId; Cmd.ExecuteNonQuery(); }
public void SerializeDoesNothingIfContentIsNull() { var dataPath = Path.Combine(_tempPath, DatacardConstants.DataFolder); var serializer = new SimpleSerializer <Catalog>(DatacardConstants.CatalogFile); serializer.Serialize(_baseSerializerMock.Object, null, dataPath); _baseSerializerMock.Verify(x => x.Serialize(It.IsAny <Catalog>(), It.IsAny <string>()), Times.Never()); }
private List <DeviceForXml> ReadXml(string path) { using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read)) { StreamReader sReader = new StreamReader(fsWrite); string xmlStr = sReader.ReadToEnd(); Type type = typeof(List <DeviceForXml>); return((List <DeviceForXml>)SimpleSerializer.Deserialize(type, xmlStr)); } }
public void WhenTheValueIsNullItDoesntSerializeTheProxy() { var serializable = new SerializeAsString(null); var newSerializable = SimpleSerializer.Binary().RoundTrip(serializable); newSerializable.IsProxyActivated.Should().Be.False(); newSerializable.IsRealActivated.Should().Be.False(); newSerializable.Real.Should().Be.Null(); newSerializable.IsRealActivated.Should().Be.True(); }
public void TestGeneratedQuoteSerialization() { Expression <Func <int, int> > original = x => x * 2; var expr1 = EditableExpression.Create(Expression.Quote(original)); var bytes = SimpleSerializer.Binary().Serialize(expr1); var expr2 = (EditableExpression)SimpleSerializer.Binary().Deserialize(bytes); expr2.Should().Not.Be.Null(); }
public void Unpack(BinaryReader reader) { this.Name = reader.ReadString(); this.InnerObject = (ObjectField)SimpleSerializer.UnpackObject(reader); //int parametersLength = reader.ReadInt32(); this.Parameters = SerializationTools.DeserializeDict(reader.BaseStream); //this.Parameters = (Dictionary<string, object>)SerializationTools.DeserializeFromBytes(test); }
static void Main() { Settings settings; var serializer = new SimpleSerializer<Settings>(SettingsPath); if (!File.Exists(SettingsPath)) { settings = new Settings { WatchPath = " ", TargetPath = " ", Patterns = new[] { " " }, Overwrite = false, ActivityTimeout = 1000 }; serializer.Serialize(settings); } else { settings = serializer.Deserialize(); } LiveSync liveSync = null; if (settings == null || string.IsNullOrWhiteSpace(settings.WatchPath) || string.IsNullOrWhiteSpace(settings.TargetPath) || settings.Patterns == null) { Console.Title = "LiveSync"; Console.WriteLine("Please create a {0} file first!", SettingsPath); } else { Console.Title = string.Format("LiveSync - {0}", string.IsNullOrWhiteSpace(settings.Title) ? settings.WatchPath : Environment.ExpandEnvironmentVariables(settings.Title)); liveSync = new LiveSync( Environment.ExpandEnvironmentVariables(settings.WatchPath), Environment.ExpandEnvironmentVariables(settings.TargetPath), settings.Patterns, settings.Overwrite, settings.ActivityTimeout); liveSync.Start(); } Console.WriteLine("Press Q to quit!"); var isRunning = true; while (isRunning) { var key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.Q: isRunning = false; break; } } if (liveSync != null) { liveSync.Stop(); } }
public void TestSerializeLambda() { var ser = SimpleSerializer.Binary(new ExpressionSurrogateSelector()); Expression <Func <int, int> > expr = x => x * 2; var newExpr = (Expression <Func <int, int> >)ser.Deserialize(ser.Serialize(expr)); newExpr.Should().Not.Be(expr); newExpr.Compile()(21).Should().Be(42); }
public void SerializeCallsBaseSerializerIfContentIsNotNull() { var dataPath = Path.Combine(_tempPath, DatacardConstants.DataFolder); var catalog = new Catalog(); var serializer = new SimpleSerializer <Catalog>(DatacardConstants.CatalogFile); serializer.Serialize(_baseSerializerMock.Object, catalog, dataPath); _baseSerializerMock.Verify(x => x.Serialize(catalog, Path.Combine(dataPath, DatacardConstants.CatalogFile)), Times.Once()); }
public void CompositeWrapperIsSerializable() { var outer = typeof(Sample).GetProperty("TestInner"); var inner = typeof(Inner).GetProperty("TestInt"); var props = new[] { outer, inner }.Select(x => x.ToSettable()); var set = props.ToSettable(); var result = SimpleSerializer.Binary().RoundTrip(set); result.Name.Should().Be.Equals(set.Name); }
public void DeserializeDoesNothingIfFileDoesNotExist() { var dataPath = Path.Combine(_tempPath, DatacardConstants.DataFolder); Directory.CreateDirectory(dataPath); var serializer = new SimpleSerializer <Catalog>(DatacardConstants.CatalogFile); serializer.Deserialize(_baseSerializerMock.Object, dataPath); _baseSerializerMock.Verify(x => x.Deserialize <Catalog>(It.IsAny <string>()), Times.Never()); }
//TODO: Move this shit somewhere else. SRP is a scared pact public void SaveGame() { Debug.Log("Saved"); if (GameManager.ins.LevelTimer.IsStarted) { Vector2 PlayerOffset = ((Vector2)PlayerCopy.transform.position) - spawnPos; float LastTime = GameManager.ins.LevelTimer.GetCurrentTime(); SimpleSerializer.SaveVector(currentLevel.SaveKey, PlayerOffset); SimpleSerializer.SaveFloat(currentLevel.SaveKey, LastTime); } }
public override void OnInspectorGUI() { base.OnInspectorGUI(); if (GUILayout.Button("Generate key")) { ((LevelAsset)target).SaveKey = RandomKey(); } if (GUILayout.Button("Reset level save")) { SimpleSerializer.ClearKey(((LevelAsset)target).SaveKey); } }
public PresetVoiLutConfiguration GetConfiguration() { Validate(); PresetVoiLutConfiguration configuration = PresetVoiLutConfiguration.FromFactory(_sourceFactory); foreach (KeyValuePair <string, string> pair in SimpleSerializer.Deserialize <PresetVoiLutConfigurationAttribute>(this)) { configuration[pair.Key] = pair.Value; } return(configuration); }
public void TestSerializeLambdaWithAnonymousTypes() { var ser = SimpleSerializer.Binary(new ExpressionSurrogateSelector()); var expr = Expr(x => new { asd = x * 2 }); var newExpr = (LambdaExpression)ser.Deserialize(ser.Serialize(expr)); newExpr.Should().Not.Be(expr); var obj = newExpr.Compile().DynamicInvoke(21); obj.GetType().GetProperty("asd").GetValue(obj, null).Should().Be(42); }
public static void ReadCallback(IAsyncResult ar) { // Retrieve the state object and the handler socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); state.messageSize = bytesRead; if (bytesRead > 0) { if (bytesRead + state.totalBytesRead > state.messageSize) { bytesRead = (int)state.messageSize - (int)state.totalBytesRead; state.totalBytesRead = state.messageSize; } else { state.totalBytesRead += bytesRead; } if (state.totalBytesRead >= state.messageSize) { IBinarySerializable serializable; using (MemoryStream ms = new MemoryStream(state.buffer, 0, bytesRead)) { using (BinaryReader reader = new BinaryReader(ms, Encoding.ASCII)) { serializable = SimpleSerializer.UnpackObject(reader); } } if (serializable is ICommandBase) { ((ICommandBase)serializable).Execute(); } else { throw new Exception("Попытка использовать объект вместо команды"); } } else { handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } }
public void Pack(BinaryWriter writer) { writer.Write(this.GetType().Name); writer.Write(this.Name); SimpleSerializer.PackObject(writer, this.InnerObject); SerializationTools.SerializeDict(this.Parameters, writer.BaseStream); //byte[] parametersData = SerializationTools.SerializeToBytes(this.Parameters); //writer.Write(parametersData.Length); //writer.Write(parametersData); }
private void SaveObject(object sender, EventArgs e) { if (treeViewContainer.flag == false) { MessageBox.Show("当前没有设备,无需保存工程!"); return; } SaveFileDialog sFD = new SaveFileDialog(); sFD.Title = "保存文件"; sFD.ShowHelp = true; sFD.Filter = "工程文件(*.cfg)|*.cfg"; //过滤格式 sFD.FilterIndex = 1; //格式索引 sFD.RestoreDirectory = false; sFD.InitialDirectory = "c:\\"; //默认路径 if (sFD.ShowDialog() == DialogResult.OK) { //获得保存文件的路径 string filePath = sFD.FileName; string xmlResult = string.Empty; DeviceForXml deviceForXml = new DeviceForXml(); List <DeviceForXml> list = new List <DeviceForXml>(); //遍历整个tree获取device foreach (var item in treeViewContainer.treeView.Nodes) { TreeNode treeNode = (TreeNode)item; foreach (var A429Dev in treeNode.Nodes) { TreeNode treeNodeA429Dev = (TreeNode)A429Dev; foreach (var treeNodes in treeNodeA429Dev.Nodes) { TreeNode treeNodes429 = (TreeNode)treeNodes; //string[] pathParts = treeNodes429.Name.Split('_'); Device429 _device429 = App.Instance.FlightBusManager.Bus429.GetSpecificItem(treeNodes429.Name); TopMenuVM topMenuVM = new TopMenuVM(_device429); topMenuVM.SaveSetting(); deviceForXml = topMenuVM._deviceInfo; list.Add(deviceForXml); } } } xmlResult = SimpleSerializer.Serialize <List <DeviceForXml> >(list); //保存 using (FileStream fsWrite = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)) { byte[] buffer = Encoding.Default.GetBytes(xmlResult); fsWrite.Write(buffer, 0, buffer.Length); } } }
private void CommandRecieved(Mas3CommandType command, string[] args) { if (!_enabled) { return; } switch (command) { case Mas3CommandType.Configuration: if (_sleeping) { StopSleep(); return; } ApplyConfig(SimpleSerializer.FromJason <Configuration>(args[0])); break; case Mas3CommandType.RequestBotStrings: _commandHandlerServer.SendCommand(Mas3CommandType.ResponseBotStrings, new[] { SimpleSerializer.ToJason(Bot.GetProfiles()), SimpleSerializer.ToJason(Bot.GetMulliganProfiles()), SimpleSerializer.ToJason(Bot.GetDiscoverProfiles()), SimpleSerializer.ToJason(Bot.GetArenaProfiles()) }); break; case Mas3CommandType.RequestDecks: if (!_gettingDecks) { _gettingDecks = true; Bot.RefreshDecks(); WaitNewDecks(); } break; case Mas3CommandType.StartSleep: StartSleep(); break; case Mas3CommandType.StartBot: Bot.StartBot(); Bot.SuspendBot(); _commandHandlerServer.SendCommand(Mas3CommandType.EnterAccount, new[] { "" }); break; case Mas3CommandType.StopBot: Bot.StopBot(); break; } }
public void DeserializeCallsBaseSerializerIfFileExists() { var dataPath = Path.Combine(_tempPath, DatacardConstants.DataFolder); Directory.CreateDirectory(dataPath); var filePath = Path.Combine(dataPath, DatacardConstants.CatalogFile); File.WriteAllText(filePath, string.Empty); var serializer = new SimpleSerializer <Catalog>(DatacardConstants.CatalogFile); serializer.Deserialize(_baseSerializerMock.Object, dataPath); _baseSerializerMock.Verify(x => x.Deserialize <Catalog>(filePath), Times.Once()); }
public IPresetVoiLutOperationComponent GetEditComponent(PresetVoiLutConfiguration configuration) { PresetVoiLutOperationComponentType component = new PresetVoiLutOperationComponentType(); component.SourceFactory = this; if (configuration != null) { ValidateFactoryName(configuration); Dictionary <string, string> dictionary = new Dictionary <string, string>(); configuration.CopyTo(dictionary); SimpleSerializer.Serialize <PresetVoiLutConfigurationAttribute>(component, dictionary); } return(component); }
public IPresetVoiLutOperation Create(PresetVoiLutConfiguration configuration) { Platform.CheckForNullReference(configuration, "configuration"); ValidateFactoryName(configuration); Dictionary <string, string> dictionary = new Dictionary <string, string>(); configuration.CopyTo(dictionary); PresetVoiLutOperationComponentType component = new PresetVoiLutOperationComponentType(); component.SourceFactory = this; SimpleSerializer.Serialize <PresetVoiLutConfigurationAttribute>(component, dictionary); component.Validate(); return(component); }