public void EndAfterDeserialize(DataSerializer s, string name) { try { if (managers.Contains(name)) { counter++; } if (!fixesApplied && counter == managers.Length - 1) { try { RepairSave(); } catch { // ignored } fixesApplied = true; } } finally { var events = (FastList<LoadingProfiler.Event>) typeof(LoadingProfiler).GetField("m_events", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this); events.Add(new LoadingProfiler.Event(LoadingProfiler.Type.EndAfterDeserialize, (string)null, 0)); } }
public void InvalidXml_ThowsSerializationException() { //Arrange var serializer = new DataSerializer<DataContractTestClass>(); //Act+Assert ActionAssert.Throws<SerializationException>(() => serializer.Deserialize("<int val=\"1\"/>")); }
public void ValidXml_DeserializedCorrectly() { //Arrange var serializer = new DataSerializer<DataContractTestClass>(); //Act DataContractTestClass obj = serializer.Deserialize("<DataContractTestClass xmlns=\"http://schemas.datacontract.org/2004/07/JohnsonControls.Serialization.Xml\"><Value>TestValue</Value></DataContractTestClass>"); //Note that DataSerializer is very picky about the xmlns being present //Assert Assert.AreEqual("TestValue",obj.Value); }
public void DataContractSerialization_RoundTrip() { //Arrange var serializer = new DataSerializer<DataContractTestClass>(); var obj = new DataContractTestClass { Value = "DemoValue" }; //Act string xml = serializer.Serialize(obj); DataContractTestClass obj2 = serializer.Deserialize(xml); //Assert Assert.AreEqual(obj.Value, obj2.Value, "Round trip with DataSerializer failed"); }
public void ValidObject_SerializesCorrectly() { //Arrange var serializer = new DataSerializer<DataContractTestClass>(); var validObject = new DataContractTestClass {Value = "So Meta"}; //Act string xml = serializer.Serialize(validObject); //Assert StringAssert.Contains(xml, "<DataContractTestClass "); StringAssert.Contains(xml, "<Value>So Meta</Value>"); }
public void Serialize(DataSerializer s) { var districtGrid = FakeDistrictManager.districtGrid; int num2 = districtGrid.Length; EncodedArray.Byte @byte = EncodedArray.Byte.BeginWrite(s); for (int num19 = 0; num19 < num2; num19++) { @byte.Write(districtGrid[num19].m_district1); } for (int num20 = 0; num20 < num2; num20++) { @byte.Write(districtGrid[num20].m_district2); } for (int num21 = 0; num21 < num2; num21++) { @byte.Write(districtGrid[num21].m_district3); } for (int num22 = 0; num22 < num2; num22++) { @byte.Write(districtGrid[num22].m_district4); } for (int num23 = 0; num23 < num2; num23++) { @byte.Write(districtGrid[num23].m_alpha1); } for (int num24 = 0; num24 < num2; num24++) { @byte.Write(districtGrid[num24].m_alpha2); } for (int num25 = 0; num25 < num2; num25++) { @byte.Write(districtGrid[num25].m_alpha3); } for (int num26 = 0; num26 < num2; num26++) { @byte.Write(districtGrid[num26].m_alpha4); } @byte.EndWrite(); }
/// <summary> /// 現在実行している同名のプロセスが1回目かどうかを判定 /// </summary> /// <param name="processName"></param> /// <returns>1回目であればtrue</returns> public static bool Check(string processName) { bool retVal = false; // 現在のセッション情報 BootAndLogonSession session = new BootAndLogonSession(processName); // 前回セッション情報を確認 string tempDir = Path.Combine( Environment.ExpandEnvironmentVariables("%TEMP%"), Item.APPLICATION_NAME); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } string sessionFile = Path.Combine(tempDir, Item.SESSION_FILE); Dictionary <string, BootAndLogonSession> sessionData = DataSerializer.Deserialize <Dictionary <string, BootAndLogonSession> >(sessionFile); if (sessionData == null) { sessionData = new Dictionary <string, BootAndLogonSession>(); } if (sessionData.ContainsKey(processName)) { retVal = sessionData[processName].BootUpTime != session.BootUpTime && !sessionData[processName].LogonIdList.SequenceEqual(session.LogonIdList); } else { retVal = true; } // 現在のセッションを保存 sessionData[processName] = session; DataSerializer.Serialize <Dictionary <string, BootAndLogonSession> >(sessionData, sessionFile); return(retVal); }
public void Deserialize(DataSerializer s) { Singleton <LoadingManager> .instance.m_loadingProfilerSimulation.BeginDeserialize(s, "GameAreaManager"); GameAreaManager instance = Singleton <GameAreaManager> .instance; //begin mod instance.m_areaGrid = new int[AREAGRID_RESOLUTION * AREAGRID_RESOLUTION]; //end mod int[] numArray = instance.m_areaGrid; int length = numArray.Length; instance.m_areaCount = (int)s.ReadUInt8(); //begin mod instance.m_maxAreaCount = AREAGRID_RESOLUTION * AREAGRID_RESOLUTION; //end mod _startTileField.SetValue(instance, s.version < 137U ? 12 : (int)s.ReadUInt8()); EncodedArray.Byte @byte = EncodedArray.Byte.BeginRead(s); for (int index = 0; index < length; ++index) { numArray[index] = (int)@byte.Read(); } @byte.EndRead(); instance.m_areaNotUnlocked = s.version < 87U ? (GenericGuide)null : s.ReadObject <GenericGuide>(); if (s.version >= 199U) { _fieldInfo1.SetValue(instance, s.ReadFloat()); _fieldInfo2.SetValue(instance, s.ReadFloat()); _fieldInfo3.SetValue(instance, s.ReadFloat()); _fieldInfo4.SetValue(instance, s.ReadFloat()); } else { _fieldInfo1.SetValue(instance, -1f); _fieldInfo2.SetValue(instance, -1f); _fieldInfo3.SetValue(instance, -1f); _fieldInfo4.SetValue(instance, -1f); } Singleton <LoadingManager> .instance.m_loadingProfilerSimulation.EndDeserialize(s, "GameAreaManager"); }
public void Serialize(DataSerializer s) { Singleton <LoadingManager> .instance.m_loadingProfilerSimulation.BeginSerialize(s, "GameAreaManager"); GameAreaManager instance = Singleton <GameAreaManager> .instance; //begin mod int[] numArray = new int[AREAGRID_RESOLUTION * AREAGRID_RESOLUTION]; int length = numArray.Length; int areaCount = 0; for (var i = 0; i < 5; i += 1) { for (var j = 0; j < 5; j += 1) { var grid = GameAreaManager.instance.m_areaGrid[(j + 2) * GRID + (i + 2)]; numArray[j * AREAGRID_RESOLUTION + i] = grid; if (grid != 0) { areaCount += 1; } } } s.WriteUInt8((uint)areaCount); //end mod s.WriteUInt8((uint)(int)_startTileField.GetValue(instance)); EncodedArray.Byte @byte = EncodedArray.Byte.BeginWrite(s); for (int index = 0; index < length; ++index) { @byte.Write((byte)numArray[index]); } @byte.EndWrite(); s.WriteObject <GenericGuide>(instance.m_areaNotUnlocked); s.WriteFloat((float)_fieldInfo1.GetValue(instance)); s.WriteFloat((float)_fieldInfo2.GetValue(instance)); s.WriteFloat((float)_fieldInfo3.GetValue(instance)); s.WriteFloat((float)_fieldInfo4.GetValue(instance)); Singleton <LoadingManager> .instance.m_loadingProfilerSimulation.EndSerialize(s, "GameAreaManager"); }
protected override void ProcessRecord() { if (Range == null && !string.IsNullOrEmpty(Name)) { Range[] ranges = _setting.GetRange(Name); if (ranges != null && ranges.Length > 0) { // すでに同じ名前のRangeがある為、追加不可 return; } else { // 名前を指定留守場合は1つずつ追加 _setting.Ranges.Add(new Range() { Name = this.Name, StartNumber = this.StartNumber, EndNumber = this.EndNumber }); } } else if (Range != null) { foreach (Range range in Range) { if (_setting.Ranges.Any(x => x.Name.Equals(range.Name, StringComparison.OrdinalIgnoreCase))) { // すでに同じ名前のRangeがある為、追加不可 return; } else { _setting.Ranges.Add(range); } } } DataSerializer.Serialize <EnumRunSetting>(_setting, SettingPath); WriteObject(_setting); }
public async Task <IEnumerable <Coinddelta> > CoinDelta() { Init(false); var koinTicker = tickers.FirstOrDefault(x => x.id == 2); if ((DateTime.UtcNow - koinTicker.time).Minutes <= 5) { return(DataSerializer.JsonDeserializerFromFile <IEnumerable <Coinddelta> >( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data//coindelta-ticker.json"))); } var client = new RestClient("https://api.coindelta.com/api/v1/public/getticker"); var response = client.Execute(new RestRequest()); var tickerContent = DataSerializer.JsonDeserializer <IEnumerable <Coinddelta> >(response.Content).Where(x => x.MarketName.Split('-').LastOrDefault() == "inr"); // tickerContent.lind = ""; DataSerializer.JsonSerializerSaveAsFile <IEnumerable <Coinddelta> >(tickerContent, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data//coindelta-ticker.json")); koinTicker.time = DateTime.UtcNow; DataSerializer.JsonSerializerSaveAsFile <IEnumerable <Ticker> >(tickers, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data//tickers.json")); Init(false); return(DataSerializer.JsonDeserializerFromFile <IEnumerable <Coinddelta> >( Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data//coindelta-ticker.json"))); }
/// <summary> /// Write <see cref="SaveFile"/> (if savefile doesn't exist - create one) to the savefiles path. /// </summary> /// <param name="save">Savefile to write</param> /// <param name="createJsonFile">Do we need to create json file with savefile data? (Useful when debugging)</param> public void WriteSave(SaveFile save, bool createJsonFile = false) { if (save == null) { Debug.LogWarning("Savefile can't be null."); OnFileWritingFail?.Invoke("Savefile can't be null."); return; } string data = DataSerializer.SerializeObject(save); if (!Directory.Exists(SaveFilesPath)) { Directory.CreateDirectory(SaveFilesPath); } File.WriteAllText(SaveFilesPath + save.Name + ".txt", data); OnFileWritingComplete?.Invoke("File was successfuly writen."); if (createJsonFile) { File.WriteAllText(SaveFilesPath + save.Name + "Json" + ".json", save.ToJson(false)); } }
public void Serialize(ContentSerializerContext context, SerializationStream stream, T obj) { // Get serializer // Note: Currently registered serializer is the content reference one // However, we would like to serialize the actual type here if (dataSerializer == null) { var dataSerializerType = DataSerializerFactory.GetSerializer("Default", typeof(T)).SerializerType; if (dataSerializerType == null) { throw new InvalidOperationException(string.Format("Could not find a serializer for type {0}", typeof(T))); } dataSerializer = (DataSerializer <T>)Activator.CreateInstance(dataSerializerType); if (dataSerializer is IDataSerializerInitializer) { ((IDataSerializerInitializer)dataSerializer).Initialize(stream.Context.SerializerSelector); } } // Serialize object stream.SerializeExtended(ref obj, context.Mode, dataSerializer); }
/// <summary> /// Нажатие на пункт меню Отрыть проект. /// </summary> /// <param name="sender">Истончик события.</param> /// <param name="e">Параметры события.</param> private void OpenProjectToolStripMenuItemClick(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { try { DataSerializer.DeserializeBin(openFileDialog.FileName, ref _project); } catch (Exception exception) { MessageBox.Show(exception.Message); _project = new Project { Circuits = new List <IComponent>(), Frequencies = new List <double>() }; } iComponentBindingSource.DataSource = _project.Circuits; _calculatorZ.Frequencies = _project.Frequencies; _calculatorZ.Circuit = null; } }
public override void OnSaveData() { base.OnSaveData(); // serialize data to bytes[] var data = BuildingDataManager.Data.Values .ToArray(); data = FilterData(data); byte[] bytes; using (var stream = new MemoryStream()) { DataSerializer.SerializeArray(stream, DataSerializer.Mode.Memory, DataVersion, data); bytes = stream.ToArray(); } // save bytes in savegame serializableDataManager.SaveData(DataId, bytes); Logger.Log("data saved ({0} bytes)", bytes.Length); }
public void Deserialize(DataSerializer s) { try { options = null; data = null; int count = s.ReadInt32(); data = new VehicleData[count]; for (int i = 0; i < count; i++) { data[i] = new VehicleData(); data[i].name = s.ReadUniqueString(); data[i].enabled = s.ReadBool(); data[i].addBackEngine = s.ReadBool(); data[i].maxSpeed = s.ReadFloat(); data[i].acceleration = s.ReadFloat(); data[i].braking = s.ReadFloat(); data[i].turning = s.ReadFloat(); data[i].springs = s.ReadFloat(); data[i].dampers = s.ReadFloat(); data[i].leanMultiplier = s.ReadFloat(); data[i].nodMultiplier = s.ReadFloat(); data[i].useColorVariations = s.ReadBool(); data[i].color0 = new HexaColor(s.ReadUniqueString()); data[i].color1 = new HexaColor(s.ReadUniqueString()); data[i].color2 = new HexaColor(s.ReadUniqueString()); data[i].color3 = new HexaColor(s.ReadUniqueString()); data[i].capacity = s.ReadInt32(); } } catch (Exception e) { // Couldn't Deserialize DebugUtils.Warning("Couldn't deserialize"); DebugUtils.LogException(e); } }
public void DataSerializer_Json_JsonReaderAndWriter() { var p = new Person { Name = "Bart", Age = 21 }; var ser = (JsonDataSerializer)DataSerializer.Create(); var sw = new StringWriter(); var jw = new JsonTextWriter(sw); ser.SerializeTo(p, jw); var json = sw.ToString(); var sr = new StringReader(json); var jr = new JsonTextReader(sr); var res = ser.DeserializeFrom <Person>(jr); Assert.AreEqual(p.Name, res.Name); Assert.AreEqual(p.Age, res.Age); }
public void DataSerializer_Create_ArgumentChecks() { #pragma warning disable IDE0034 // Simplify 'default' expression (illustrative of method signature) var tries = new Action[] { () => DataSerializer.Create(default(IExpressionSerializer)), () => DataSerializer.Create(default(Func <Expression, string>), _ => null), () => DataSerializer.Create(e => null, default(Func <string, Expression>)), #pragma warning disable 618 // Deprecated () => DataSerializer.Create(default(IExpressionSerializer), includePrivate: false), () => DataSerializer.Create(default(Func <Expression, string>), _ => null, includePrivate: false), () => DataSerializer.Create(e => null, default(Func <string, Expression>), includePrivate: false), #pragma warning restore 618 // Deprecated }; #pragma warning restore IDE0034 // Simplify 'default' expression foreach (var t in tries) { Assert.ThrowsException <ArgumentNullException>(t); } }
public void ShouldSerializeDataTableUsingOptions() { // Arrange var stream = new MemoryStream(); var options = new ProtoDataWriterOptions() { SerializeEmptyArraysAsNull = true }; // Act DataSerializer.Serialize(stream, this.CreateTable(new char[0]), options); // Assert stream.Position = 0; var dataReader = new ProtoDataReader(stream); dataReader.Read(); Assert.True(dataReader.IsDBNull(0)); }
// The given DataSerializer is the dummy one that writes to Stream.Null. public void Serialize(DataSerializer s) { if (OptionsWrapper <Configuration> .Options.IsLoggingEnabled() && OptionsWrapper <Configuration> .Options.DebugLoggingLevel > 1) { Logger.dbgLog("Fake serialize from " + startIndex.ToString() + " to " + idxList.Count.ToString()); } // Setup a dummy PrefabCollection<TreeInfo>.m_encodedArray so that we can continue refcounting. FieldInfo encoderField = typeof(PrefabCollection <TreeInfo>).GetField("m_encodedArray", BindingFlags.NonPublic | BindingFlags.Static); EncodedArray.UShort original = (EncodedArray.UShort)encoderField.GetValue(null); try { EncodedArray.UShort dummy = EncodedArray.UShort.BeginWrite(s); encoderField.SetValue(null, dummy); // Now that the do-nothing m_encodedArray has been set, we can safely continue refcounting. TreeInstance[] mBuffer = Singleton <TreeManager> .instance.m_trees.m_buffer; int limit = idxList.Count; for (int j = startIndex; j < limit; j++) { if (mBuffer[idxList[j]].m_flags != 0) { PrefabCollection <TreeInfo> .Serialize(mBuffer[idxList[j]].m_infoIndex); } } } catch (Exception ex) { Logger.dbgLog("", ex, true); } finally { encoderField.SetValue(null, original); } }
// Validates that all building ids are active public void AfterDeserialize(DataSerializer s) { if (!BuildingManager.exists) { return; } List <ushort> validatedBuildingIds = new List <ushort>(); Building[] buildingInstances = BuildingManager.instance.m_buildings.m_buffer; // itertate through all building ids, filter active ids foreach (ushort buildingId in HistoricalBuildingIds) { if (buildingInstances[buildingId].m_flags != Building.Flags.None) { validatedBuildingIds.Add(buildingId); } } HistoricalBuildingIds = validatedBuildingIds; }
public void Deserialize(DataSerializer s) { data.Clear(); var arraySize = s.ReadInt32(); for (int i = 0; i < arraySize; i++) { uint tree = (uint)s.ReadUInt32(); Data value = new Data(); value.x = (ushort)s.ReadUInt16(); value.z = (ushort)s.ReadUInt16(); try { if ((TreeManager.instance.m_trees.m_buffer[tree].m_flags & (ushort)TreeInstance.Flags.Created) == (ushort)TreeInstance.Flags.Created) { data[tree] = value; } } catch (Exception e) { Debug.LogException(e); continue; } } }
private void InitConnection() { string serverAddress; DataSerializer dataSerializer = DPSManager.GetDataSerializer <ProtobufSerializer>(); List <DataProcessor> dataProcessors = new List <DataProcessor>(); Dictionary <string, string> dataProcessorOptions = new Dictionary <string, string>(); dataProcessors.Add(DPSManager.GetDataProcessor <QuickLZCompressor.QuickLZ>()); NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions); NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = true; NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority = QueueItemPriority.AboveNormal; NetworkComms.AppendGlobalIncomingPacketHandler <VRCommand>("Command", HandleIncomingCommand); SystemConfigs.TryGetValue("ServerIPPort", out serverAddress); // get IP:Port IPEndPoint ip = IPTools.ParseEndPointFromString(serverAddress); targetServerConnectionInfo = new ConnectionInfo(ip, ApplicationLayerProtocolStatus.Enabled); }
public void Deserialize(DataSerializer s) { EnhancedEarthquake d = Singleton <EnhancedDisastersManager> .instance.container.Earthquake; deserializeCommonParameters(s, d); d.WarmupYears = s.ReadFloat(); if (s.version >= 3) { d.NoCracks = s.ReadBool(); } d.aftershocksCount = (byte)s.ReadInt8(); d.aftershockMaxIntensity = (byte)s.ReadInt8(); if (s.version >= 2) { d.mainStrikeIntensity = (byte)s.ReadInt8(); } d.lastTargetPosition = new Vector3(s.ReadFloat(), s.ReadFloat(), s.ReadFloat()); d.lastAngle = s.ReadFloat(); }
object ReadProjectFile(FilePath fileName, IProgressMonitor monitor) { XmlTextReader reader = null; try { reader = new XmlTextReader(new StreamReader(fileName)); reader.MoveToContent(); string version = reader.GetAttribute("version"); if (version == null) { version = reader.GetAttribute("fileversion"); } DataSerializer serializer = new DataSerializer(MD1ProjectService.DataContext, fileName); IProjectReader projectReader = null; monitor.BeginTask(GettextCatalog.GetString("Loading project: {0}", fileName), 1); if (version == "2.0" || version == "2.1") { projectReader = new ProjectReaderV2(serializer); return(projectReader.ReadProject(reader)); } else { throw new MD1UnknownProjectVersion(fileName, version); } } catch (Exception ex) { monitor.ReportError(GettextCatalog.GetString("Could not load project: {0}", fileName), ex); throw; } finally { monitor.EndTask(); if (reader != null) { reader.Close(); } } }
public override void OnLoadData() { if (ToolManager.instance.m_properties.m_mode != ItemClass.Availability.Game) { return; } // Storing default values ASAP (before any mods have the time to change values) DefaultOptions.StoreAll(); if (!serializableDataManager.EnumerateData().Contains(ID)) { return; } var data = serializableDataManager.LoadData(ID); using (var ms = new MemoryStream(data)) { AdvancedVehicleOptionsUID.config.data = DataSerializer.Deserialize <Configuration>(ms, DataSerializer.Mode.Memory).data; } }
public void Deserialize(DataSerializer s) { AutobudgetWater d = Singleton <AutobudgetManager> .instance.container.AutobudgetWater; if (s.version == 0) { d.Enabled = s.ReadBool(); d.AutobudgetBuffer = s.ReadInt32(); d.BudgetMaxValue = s.ReadInt32(); d.PauseWhenBudgetTooHigh = s.ReadBool(); d.TargetWaterStorageRatio = s.ReadInt32(); if (d.TargetWaterStorageRatio == 95) { d.TargetWaterStorageRatio = 50; // Change the default value } } else if (s.version == 1) { d.Enabled = s.ReadBool(); d.AutobudgetBuffer = s.ReadInt32(); d.BudgetMaxValue = s.ReadInt32(); d.PauseWhenBudgetTooHigh = s.ReadBool(); d.TargetWaterStorageRatio = s.ReadInt32(); bool tmp = s.ReadBool(); } else { // Revert to the version 0 d.Enabled = s.ReadBool(); d.AutobudgetBuffer = s.ReadInt32(); d.BudgetMaxValue = s.ReadInt32(); d.PauseWhenBudgetTooHigh = s.ReadBool(); d.TargetWaterStorageRatio = s.ReadInt32(); } }
internal static void WriteExternalProjectProperties(this MSBuildProject project, object ob, Type typeToScan, bool includeBaseMembers = false) { DataSerializer ser = new DataSerializer(Services.ProjectService.DataContext); var props = Services.ProjectService.DataContext.GetProperties(ser.SerializationContext, ob); XmlConfigurationWriter writer = null; foreach (var prop in props) { if (!prop.IsExternal) { continue; } var val = prop.GetValue(ob); if (val != null) { var data = prop.Serialize(ser.SerializationContext, ob, val); if (data != null) { data.Name = prop.Name; if (writer == null) { writer = new XmlConfigurationWriter { Namespace = MSBuildProject.Schema } } ; XmlDocument doc = new XmlDocument(); var elem = writer.Write(doc, data); // TODO NPM project.SetMonoDevelopProjectExtension(prop.Name, elem); continue; } } project.RemoveMonoDevelopProjectExtension(prop.Name); } }
public AccountRepository(string user) { _saveDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data", $"{user}.acc"); Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Data")); string serializedData = Encryptor.DecryptFile(_saveDirectory); if (serializedData != null) { List <Account> accounts = DataSerializer.DeserializeFromXml <List <Account> >(serializedData); int i = 0; foreach (Account account in accounts) { account.Id = ++i; } AccountCollection = new ObservableCollection <Account>(accounts); //AccountCollection = new ObservableCollection<Account>(DataSerializer.DeserializeFromXml<List<Account>>(serializedData)); } else { AccountCollection = new ObservableCollection <Account>(); } AccountCollection.CollectionChanged += OnCollectionChanged; }
private void InitNetworkComms() { int port = (INTERNAL_TEST) ? 20015 : 20018; // This is for internal middle ware testing. For Game Selector UI testing port should be 20015 DataSerializer dataSerializer = DPSManager.GetDataSerializer <ProtobufSerializer>(); List <DataProcessor> dataProcessors = new List <DataProcessor>(); Dictionary <string, string> dataProcessorOptions = new Dictionary <string, string>(); dataProcessors.Add(DPSManager.GetDataProcessor <SharpZipLibCompressor.SharpZipLibGzipCompressor>()); NetworkComms.DefaultSendReceiveOptions = new SendReceiveOptions(dataSerializer, dataProcessors, dataProcessorOptions); NetworkComms.DefaultSendReceiveOptions.IncludePacketConstructionTime = true; NetworkComms.DefaultSendReceiveOptions.ReceiveHandlePriority = QueueItemPriority.AboveNormal; NetworkComms.AppendGlobalIncomingPacketHandler <VRCommand>("Command", HandleIncomingCommand); Connection.StartListening(ConnectionType.TCP, new IPEndPoint(IPAddress.Any, port)); foreach (IPEndPoint localEndPoint in Connection.ExistingLocalListenEndPoints(ConnectionType.TCP)) { infoText += localEndPoint.Address.ToString() + ":" + localEndPoint.Port.ToString() + Environment.NewLine; } }
private void CreateModules() { SerializeType serializeType = CheckModule.ReadConfigurationFile(); if (serializeType == SerializeType.Bin) { BinaryModulesFactory binFactory = new BinaryModulesFactory(); readModule = binFactory.CreateDeserializer(); writeModule = binFactory.CreateSerializer(); } else if (serializeType == SerializeType.Xml) { XmlModulesFactory xmlFactory = new XmlModulesFactory(); readModule = xmlFactory.CreateDeserializer(); writeModule = xmlFactory.CreateSerializer(); } else { throw new IncorrectSerializeType("Serialize type is incorrect. Data won't be save."); } }
public static void Main(string[] args) { var dataSet = CreateDataSet(); var dataReader = dataSet.CreateDataReader(); var assembly = GetAssembly(); var assemblyVersion = FileVersionInfo.GetVersionInfo(assembly.Location).ProductVersion; using (var stream = File.Create($"{assemblyVersion}.proto")) { DataSerializer.Serialize(stream, dataReader); } using (var stream = File.Create($"{assemblyVersion}.xsd")) { dataSet.WriteXmlSchema(stream, type => type.FullName); } using (var stream = File.Create($"{assemblyVersion}.xml")) { dataSet.WriteXml(stream); } }
public void DataSerializer_Create_Simple() { var sh = new SerializationHelper(); var es = sh.ExpressionSerializer; var sers = new[] { DataSerializer.Create(), DataSerializer.Create(es), DataSerializer.Create(e => null, _ => null), #pragma warning disable 618 // Deprecated DataSerializer.Create(es, includePrivate: false), DataSerializer.Create(e => null, _ => null, includePrivate: false), #pragma warning restore 618 // Deprecated }; foreach (var ser in sers) { AssertRoundtrips(ser); } }
//SERVER ACTIONS private void CreateNewPlayer(ServerData data) { Payload payload = DatagramToPayload(data.datagram); currentGame = GetAvailableGame(); if (payload != null && string.IsNullOrEmpty(payload.clientID)) { Player player = new Player(data.endPoint); currentGame.AddPlayer(player); playerList.Add(player.endPoint, currentGame.index - 1); payload.clientID = player.clientID; data.datagram = DataSerializer.SerializePayload(payload); listener.Send(data.datagram, data.datagram.Length, data.endPoint.Address.ToString(), data.endPoint.Port); } if (currentGame.isReady) { RecycleCurrentGame(); } }
public static byte[] DataSerialization(DataTable dt) { if (dt == null) { return(null); //If Data Table is null return Null } try { using (MemoryStream ms = new MemoryStream()) { using (IDataReader dr = dt.CreateDataReader()) { DataSerializer.Serialize(ms, dr); //Stream & Dataset } return(ms.ToArray()); //Converts it to ByteArray } } catch { throw; //Add Error Handling Later on } }
public void AfterDeserialize(DataSerializer s) { }
public void AfterDeserialize(DataSerializer s) { Singleton<LoadingManager>.instance.WaitUntilEssentialScenesLoaded(); DistrictManager instance = Singleton<DistrictManager>.instance; District[] buffer = instance.m_districts.m_buffer; DistrictManager.Cell[] districtGrid = FakeDistrictManager.m_districtGrid; int num = districtGrid.Length; for (int i = 0; i < num; i++) { DistrictManager.Cell cell = districtGrid[i]; District[] expr_60_cp_0 = buffer; byte expr_60_cp_1 = cell.m_district1; expr_60_cp_0[(int)expr_60_cp_1].m_totalAlpha = expr_60_cp_0[(int)expr_60_cp_1].m_totalAlpha + (uint)cell.m_alpha1; District[] expr_80_cp_0 = buffer; byte expr_80_cp_1 = cell.m_district2; expr_80_cp_0[(int)expr_80_cp_1].m_totalAlpha = expr_80_cp_0[(int)expr_80_cp_1].m_totalAlpha + (uint)cell.m_alpha2; District[] expr_A0_cp_0 = buffer; byte expr_A0_cp_1 = cell.m_district3; expr_A0_cp_0[(int)expr_A0_cp_1].m_totalAlpha = expr_A0_cp_0[(int)expr_A0_cp_1].m_totalAlpha + (uint)cell.m_alpha3; District[] expr_C0_cp_0 = buffer; byte expr_C0_cp_1 = cell.m_district4; expr_C0_cp_0[(int)expr_C0_cp_1].m_totalAlpha = expr_C0_cp_0[(int)expr_C0_cp_1].m_totalAlpha + (uint)cell.m_alpha4; } instance.m_districtCount = (int)(instance.m_districts.ItemCount() - 1u); instance.AreaModified(0, 0, 511, 511, true); instance.NamesModified(); }
public void Deserialize(DataSerializer s) { var districtGrid = new DistrictManager.Cell[GRID * GRID]; EncodedArray.Byte @byte = EncodedArray.Byte.BeginRead(s); int num2 = districtGrid.Length; for (int num21 = 0; num21 < num2; num21++) { districtGrid[num21].m_district1 = @byte.Read(); } for (int num22 = 0; num22 < num2; num22++) { districtGrid[num22].m_district2 = @byte.Read(); } for (int num23 = 0; num23 < num2; num23++) { districtGrid[num23].m_district3 = @byte.Read(); } for (int num24 = 0; num24 < num2; num24++) { districtGrid[num24].m_district4 = @byte.Read(); } for (int num25 = 0; num25 < num2; num25++) { districtGrid[num25].m_alpha1 = @byte.Read(); } for (int num26 = 0; num26 < num2; num26++) { districtGrid[num26].m_alpha2 = @byte.Read(); } for (int num27 = 0; num27 < num2; num27++) { districtGrid[num27].m_alpha3 = @byte.Read(); } for (int num28 = 0; num28 < num2; num28++) { districtGrid[num28].m_alpha4 = @byte.Read(); } @byte.EndRead(); FakeDistrictManager.m_districtGrid = districtGrid; }
public void Serialize(DataSerializer s) { Cell[] electricityGrid = FakeElectricityManager.electricityGrid; int num = electricityGrid.Length; EncodedArray.Byte @byte = EncodedArray.Byte.BeginWrite(s); for (int i = 0; i < num; i++) { @byte.Write(electricityGrid[i].m_conductivity); } @byte.EndWrite(); EncodedArray.Short @short = EncodedArray.Short.BeginWrite(s); for (int j = 0; j < num; j++) { if (electricityGrid[j].m_conductivity != 0) { @short.Write(electricityGrid[j].m_currentCharge); } } @short.EndWrite(); EncodedArray.UShort uShort = EncodedArray.UShort.BeginWrite(s); for (int k = 0; k < num; k++) { if (electricityGrid[k].m_conductivity != 0) { uShort.Write(electricityGrid[k].m_extraCharge); } } uShort.EndWrite(); EncodedArray.UShort uShort2 = EncodedArray.UShort.BeginWrite(s); for (int l = 0; l < num; l++) { if (electricityGrid[l].m_conductivity != 0) { uShort2.Write(electricityGrid[l].m_pulseGroup); } } uShort2.EndWrite(); EncodedArray.Bool @bool = EncodedArray.Bool.BeginWrite(s); for (int m = 0; m < num; m++) { if (electricityGrid[m].m_conductivity != 0) { @bool.Write(electricityGrid[m].m_electrified); } } @bool.EndWrite(); EncodedArray.Bool bool2 = EncodedArray.Bool.BeginWrite(s); for (int n = 0; n < num; n++) { if (electricityGrid[n].m_conductivity != 0) { bool2.Write(electricityGrid[n].m_tmpElectrified); } } bool2.EndWrite(); s.WriteUInt16((uint)FakeElectricityManager.m_pulseGroupCount); for (int num2 = 0; num2 < FakeElectricityManager.m_pulseGroupCount; num2++) { s.WriteUInt32(FakeElectricityManager.m_pulseGroups[num2].m_origCharge); s.WriteUInt32(FakeElectricityManager.m_pulseGroups[num2].m_curCharge); s.WriteUInt16((uint)FakeElectricityManager.m_pulseGroups[num2].m_mergeIndex); s.WriteUInt16((uint)FakeElectricityManager.m_pulseGroups[num2].m_mergeCount); s.WriteUInt16((uint)FakeElectricityManager.m_pulseGroups[num2].m_x); s.WriteUInt16((uint)FakeElectricityManager.m_pulseGroups[num2].m_z); } int num3 = FakeElectricityManager.m_pulseUnitEnd - FakeElectricityManager.m_pulseUnitStart; if (num3 < 0) { num3 += FakeElectricityManager.m_pulseUnits.Length; } s.WriteUInt16((uint)num3); int num4 = FakeElectricityManager.m_pulseUnitStart; while (num4 != FakeElectricityManager.m_pulseUnitEnd) { s.WriteUInt16((uint)FakeElectricityManager.m_pulseUnits[num4].m_group); s.WriteUInt16((uint)FakeElectricityManager.m_pulseUnits[num4].m_node); s.WriteUInt16((uint)FakeElectricityManager.m_pulseUnits[num4].m_x); s.WriteUInt16((uint)FakeElectricityManager.m_pulseUnits[num4].m_z); if (++num4 >= FakeElectricityManager.m_pulseUnits.Length) { num4 = 0; } } EncodedArray.UShort uShort3 = EncodedArray.UShort.BeginWrite(s); for (int num5 = 0; num5 < 32768; num5++) { uShort3.Write(FakeElectricityManager.m_nodeGroups[num5]); } uShort3.EndWrite(); s.WriteInt32(FakeElectricityManager.m_processedCells); s.WriteInt32(FakeElectricityManager.m_conductiveCells); s.WriteBool(FakeElectricityManager.m_canContinue); }
public void AfterDeserialize(DataSerializer s) { CheckDataIntegrity(zones3, 5); CheckDataIntegrity(zones4, 7); }
public void Serialize(DataSerializer s) { SerializeZoneMasks(s, zones3); SerializeZoneMasks(s, zones4); }
/// <summary> /// Initializes a new instance of the <see cref="SendReceiveOptions"/> class with a specified <see cref="DPSBase.DataSerializer"/>, set of <see cref="DPSBase.DataProcessor"/>s and and other options /// </summary> /// <param name="serializer">The <see cref="DPSBase.DataSerializer"/> to use</param> /// <param name="dataProcessors">The set of <see cref="DPSBase.DataProcessor"/>s to use. The order in the list determines the order the <see cref="DPSBase.DataProcessor"/>s will be applied</param> /// <param name="options">Allows additional options to be passed to the <see cref="DPSBase.DataSerializer"/> and <see cref="DPSBase.DataProcessor"/>s</param> public SendReceiveOptions(DataSerializer serializer, List<DataProcessor> dataProcessors, Dictionary<string, string> options) { if (serializer == null) throw new ArgumentNullException("serializer", "The serializer argument when creating a sendReceiveOptions object should never be null."); this.DataSerializer = serializer; this.DataProcessors = dataProcessors; if (options != null) this.options = options; else this.options = new Dictionary<string, string>(); }
public void Deserialize(DataSerializer s) { areaGrid = new int[GRID * GRID]; int num = areaGrid.Length; EncodedArray.Byte @byte = EncodedArray.Byte.BeginRead(s); for (int i = 0; i < num; i++) { areaGrid[i] = (int)@byte.Read(); } @byte.EndRead(); }
public void Deserialize(DataSerializer s) { Cell[] electricityGrid = new Cell[GRID * GRID]; int num = electricityGrid.Length; EncodedArray.Byte @byte = EncodedArray.Byte.BeginRead(s); for (int i = 0; i < num; i++) { electricityGrid[i].m_conductivity = @byte.Read(); } @byte.EndRead(); EncodedArray.Short @short = EncodedArray.Short.BeginRead(s); for (int l = 0; l < num; l++) { if (electricityGrid[l].m_conductivity != 0) { electricityGrid[l].m_currentCharge = @short.Read(); } else { electricityGrid[l].m_currentCharge = 0; } } @short.EndRead(); EncodedArray.UShort uShort = EncodedArray.UShort.BeginRead(s); for (int m = 0; m < num; m++) { if (electricityGrid[m].m_conductivity != 0) { electricityGrid[m].m_extraCharge = uShort.Read(); } else { electricityGrid[m].m_extraCharge = 0; } } uShort.EndRead(); EncodedArray.UShort uShort2 = EncodedArray.UShort.BeginRead(s); for (int n = 0; n < num; n++) { if (electricityGrid[n].m_conductivity != 0) { electricityGrid[n].m_pulseGroup = uShort2.Read(); } else { electricityGrid[n].m_pulseGroup = 65535; } } uShort2.EndRead(); EncodedArray.Bool @bool = EncodedArray.Bool.BeginRead(s); for (int num3 = 0; num3 < num; num3++) { if (electricityGrid[num3].m_conductivity != 0 ) { electricityGrid[num3].m_electrified = @bool.Read(); } else { electricityGrid[num3].m_electrified = false; } } @bool.EndRead(); EncodedArray.Bool bool2 = EncodedArray.Bool.BeginRead(s); for (int num4 = 0; num4 < num; num4++) { if (electricityGrid[num4].m_conductivity != 0 ) { electricityGrid[num4].m_tmpElectrified = bool2.Read(); } else { electricityGrid[num4].m_tmpElectrified = false; } } bool2.EndRead(); FakeElectricityManager.electricityGrid = electricityGrid; FakeElectricityManager.m_pulseGroups = new PulseGroup[1024]; FakeElectricityManager.m_pulseGroupCount = (int)s.ReadUInt16(); for (int num5 = 0; num5 < FakeElectricityManager.m_pulseGroupCount; num5++) { FakeElectricityManager.m_pulseGroups[num5].m_origCharge = s.ReadUInt32(); FakeElectricityManager.m_pulseGroups[num5].m_curCharge = s.ReadUInt32(); FakeElectricityManager.m_pulseGroups[num5].m_mergeIndex = (ushort)s.ReadUInt16(); FakeElectricityManager.m_pulseGroups[num5].m_mergeCount = (ushort)s.ReadUInt16(); FakeElectricityManager.m_pulseGroups[num5].m_x = (byte)s.ReadUInt16(); FakeElectricityManager.m_pulseGroups[num5].m_z = (byte)s.ReadUInt16(); } FakeElectricityManager.m_pulseUnits = new PulseUnit[32768]; int num6 = (int)s.ReadUInt16(); FakeElectricityManager.m_pulseUnitStart = 0; FakeElectricityManager.m_pulseUnitEnd = num6 % FakeElectricityManager.m_pulseUnits.Length; for (int num7 = 0; num7 < num6; num7++) { FakeElectricityManager.m_pulseUnits[num7].m_group = (ushort)s.ReadUInt16(); FakeElectricityManager.m_pulseUnits[num7].m_node = (ushort)s.ReadUInt16(); FakeElectricityManager.m_pulseUnits[num7].m_x = (byte)s.ReadUInt16(); FakeElectricityManager.m_pulseUnits[num7].m_z = (byte)s.ReadUInt16(); } FakeElectricityManager.m_nodeGroups = new ushort[32768]; EncodedArray.UShort uShort4 = EncodedArray.UShort.BeginRead(s); for (int num8 = 0; num8 < 32768; num8++) { FakeElectricityManager.m_nodeGroups[num8] = uShort4.Read(); } uShort4.EndRead(); FakeElectricityManager.m_processedCells = s.ReadInt32(); FakeElectricityManager.m_conductiveCells = s.ReadInt32(); FakeElectricityManager.m_canContinue = s.ReadBool(); }
public void AfterDeserialize(DataSerializer s) { Singleton<LoadingManager>.instance.WaitUntilEssentialScenesLoaded(); ElectricityManager.instance.AreaModified(0, 0, GRID, GRID); }
public void Deserialize(DataSerializer s) { var count = s.ReadInt32(); #if DEBUG Debug.Log($"Deserializing {count} active options"); #endif for (var i = 0; i < count; i++) { var prefabName = s.ReadUniqueString(); var prefab = PrefabCollection<NetInfo>.FindLoaded(prefabName); if (prefab == null) continue; var options = new SegmentData(); options.Deserialize(s); #if DEBUG Debug.Log($"{prefabName} --> {options.ToString()}"); #endif SegmentDataManager.Instance.SetActiveOptions(prefab, options); } }
public void Serialize(DataSerializer s) { var count = SegmentDataManager.Instance._selectedSegmentOptions.Count; s.WriteInt32(count); #if DEBUG Debug.Log($"Serializing {count} active options"); #endif foreach (var selectedOption in SegmentDataManager.Instance._selectedSegmentOptions) { #if DEBUG Debug.Log($"{selectedOption.Key.name} --> {selectedOption.Value.ToString()}"); #endif s.WriteUniqueString(selectedOption.Key.name); selectedOption.Value.Serialize(s); } }
public void Deserialize(DataSerializer s) { DeserializeZoneMasks(s, zones3); DeserializeZoneMasks(s, zones4); }
private static void SerializeZoneMasks(DataSerializer s, ulong[] array) { s.WriteInt32(array.Length); foreach (var zoneMask in array) { s.WriteULong64(zoneMask); } }
public void Serialize(DataSerializer s) { var districtGrid = FakeDistrictManager.m_districtGrid; int num2 = districtGrid.Length; EncodedArray.Byte @byte = EncodedArray.Byte.BeginWrite(s); for (int num19 = 0; num19 < num2; num19++) { @byte.Write(districtGrid[num19].m_district1); } for (int num20 = 0; num20 < num2; num20++) { @byte.Write(districtGrid[num20].m_district2); } for (int num21 = 0; num21 < num2; num21++) { @byte.Write(districtGrid[num21].m_district3); } for (int num22 = 0; num22 < num2; num22++) { @byte.Write(districtGrid[num22].m_district4); } for (int num23 = 0; num23 < num2; num23++) { @byte.Write(districtGrid[num23].m_alpha1); } for (int num24 = 0; num24 < num2; num24++) { @byte.Write(districtGrid[num24].m_alpha2); } for (int num25 = 0; num25 < num2; num25++) { @byte.Write(districtGrid[num25].m_alpha3); } for (int num26 = 0; num26 < num2; num26++) { @byte.Write(districtGrid[num26].m_alpha4); } @byte.EndWrite(); }
public void AfterDeserialize(DataSerializer s) { typeof(GameAreaManager).GetField("m_areasUpdated", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(GameAreaManager.instance,true); }
private static void DeserializeZoneMasks(DataSerializer s, ulong[] array) { var serializedLength = s.ReadInt32(); for (var i = 0; i < serializedLength; i++) { var zoneMask = s.ReadULong64(); if (i < array.Length) { array[i] = zoneMask; } } }
public void Serialize(DataSerializer s) { int num = areaGrid.Length; EncodedArray.Byte @byte = EncodedArray.Byte.BeginWrite(s); for (int i = 0; i < num; i++) { @byte.Write((byte)areaGrid[i]); } @byte.EndWrite(); }
/// <summary> /// Allows to choose different serializers /// </summary> private static void SelectDataSerializer(out DataSerializer dataSerializer) { Console.WriteLine("\nPlease select a serializer:\n" + "1 - Protobuf (High Performance, Versatile)\n" + "2 - BinaryFormatter (Quick to Implement, Very Inefficient)\n" + "3 - NullSerializer (High performance pass through serializer for sending byte[] only)\n" + "4 - JSON serializer (serializer objects to JSON)"); int selectedSerializer; while (true) { bool parseSucces = int.TryParse(Console.ReadKey(true).KeyChar.ToString(), out selectedSerializer); if (parseSucces && selectedSerializer <= 4 && selectedSerializer > 0) break; Console.WriteLine("Invalid serializer choice. Please try again."); } if (selectedSerializer == 1) { Console.WriteLine(" ... selected protobuf serializer.\n"); dataSerializer = DPSManager.GetDataSerializer<ProtobufSerializer>(); } else if (selectedSerializer == 2) { Console.WriteLine(" ... selected binary formatter serializer.\n"); dataSerializer = DPSManager.GetDataSerializer<BinaryFormaterSerializer>(); } else if (selectedSerializer == 3) { Console.WriteLine(" ... selected null serializer.\n"); dataSerializer = DPSManager.GetDataSerializer<NullSerializer>(); } else if(selectedSerializer == 4) { Console.WriteLine(" ... selected JSON serializer.\n"); dataSerializer = DPSManager.GetDataSerializer<JSONSerializer>(); } else throw new Exception("Unable to determine selected serializer."); }