public void FillPodcastFeed() { PodcastFeed.Items.Clear(); if (validate.IfFileExists(@"C:\podFeeds\poddar.txt")) { List <Podcast> podcasts = serializer.Deserialize <Podcast>(@"C:\podFeeds\poddar.txt"); foreach (Podcast pod in podcasts) { string[] listToArray = { pod.episodeCount.ToString(), pod.Title, pod.UpdateFrequency, pod.categories.CategoryName }; string[] row1 = { listToArray[0], listToArray[2], listToArray[3] }; PodcastFeed.Items.Add(listToArray[1]).SubItems.AddRange(row1); } } }
public static void Test_Can_Deserialize_SeperatedCollection_Type() { Assert.Warn("TODO You must fix and reimplement seperated collection. It's not working fully as intended."); return; //arrange SerializerService serializer = new SerializerService(); serializer.RegisterType <TestSeperatedCollection>(); serializer.Compile(); //act byte[] bytes = serializer.Serialize(new TestSeperatedCollection("Hello meep56!", 123456, new[] { 55523, 90, 2445, 63432, 6969 })); TestSeperatedCollection deserialized = serializer.Deserialize <TestSeperatedCollection>(bytes); //assert Assert.NotNull(deserialized); Assert.NotNull(deserialized.IntsChars); Assert.AreEqual(5, deserialized.Size, "Expected the size to be the original collection size"); Assert.AreEqual(5, deserialized.IntsChars.Length, $"Expected the length of the collection to be the original length"); Assert.AreEqual("Hello meep56!", deserialized.TestString); Assert.AreEqual(123456, deserialized.AnotherValue); }
public static void Test_Can_Serializer_Then_Deserialize_Most_Complex_Test_Possible() { //arrange SerializerService serializer = new SerializerService(); TestEnum[] arrayOne = new TestEnum[] { TestEnum.Zero, TestEnum.One }; TestEnum[] arrayTwo = new TestEnum[3] { TestEnum.Two, TestEnum.One, TestEnum.Zero }; BasicWireDataContract WireDataContractNested = new BasicWireDataContract(8); //act serializer.RegisterType <VeryComplexType>(); serializer.Compile(); byte[] bytes = serializer.Serialize(new VeryComplexType(6, WireDataContractNested, arrayOne, arrayTwo)); Assert.NotNull(bytes); Assert.False(bytes.Length == 0); VeryComplexType message = serializer.Deserialize <VeryComplexType>(bytes); //assert Assert.NotNull(message); //check fields for (int i = 0; i < arrayOne.Length; i++) { Assert.AreEqual(arrayOne[i], message.testEnums[i], $"Failed for index {i}."); } for (int i = 0; i < arrayTwo.Length; i++) { Assert.AreEqual(arrayTwo[i], message.testEnumsAnother[i], $"Failed for index {i}."); } }
public void Test_Can_Serialize_Then_Deserializer_AuthSessionChallengeEvent_Vanilla_Payload() { //arrange SerializerService otherService = new SerializerService(); otherService.RegisterType <SessionAuthChallengeEvent>(); SerializerService serializer = new SerializerService(); serializer.RegisterType <SessionAuthChallengeEvent_Vanilla>(); serializer.Compile(); otherService.Compile(); SerializerService lastserializer = new SerializerService(); lastserializer.RegisterType <SessionAuthChallengeEvent_Vanilla>(); lastserializer.Compile(); //act byte[] bytes = lastserializer.Serialize(new SessionAuthChallengeEvent_Vanilla(new SessionAuthChallengeEventData(55, new byte[32]))); SessionAuthChallengeEvent_Vanilla payload = serializer.Deserialize <SessionAuthChallengeEvent_Vanilla>(bytes); //assert Assert.NotNull(bytes); }
public void Test_Can_Serialize_Type_With_Complex_Array_Ignored_And_SendSize_Array_Succedding(int[] intArray) { //arrange SerializerService serializer = new SerializerService(); serializer.RegisterType <TestComplexOptionalFieldWithDisable>(); serializer.Compile(); //act byte[] bytes = serializer.Serialize(new TestComplexOptionalFieldWithDisable(intArray)); TestComplexOptionalFieldWithDisable deserializerData = serializer.Deserialize <TestComplexOptionalFieldWithDisable>(bytes); //assert Assert.NotNull(bytes); Assert.True(bytes.Length != 0); //Check it's sizeof the element * length + the sendsize Assert.True(bytes.Length == intArray.Length * sizeof(int) + sizeof(int)); Assert.NotNull(deserializerData); for (int i = 0; i < intArray.Length; i++) { Assert.AreEqual(intArray[i], deserializerData.TestInts[i]); } }
protected override T Deserialize(Stream stream) { using TextReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); return(SerializerService.Deserialize <T>(json)); }
public override async Task Initialize() { await base.Initialize(); if (!File.Exists(settingsPath)) { this.FirstTimeUser = true; this.Settings = new Settings(); Save(); } else { this.FirstTimeUser = false; try { string json = File.ReadAllText(settingsPath); this.Settings = SerializerService.Deserialize <Settings>(json); } catch (Exception) { await GenericDialog.Show("Failed to load Settings. Your settings have been reset.", "Error", MessageBoxButton.OK); this.Settings = new Settings(); Save(); } } this.Settings.PropertyChanged += this.OnSettingsChanged; this.OnSettingsChanged(null, new PropertyChangedEventArgs(null)); }
private void Generic_CanDeserialize_CaptureTest <TBasePayloadType, TOperationType>(PacketCaptureTestEntry entry) where TBasePayloadType : IOperationCodeable <TOperationType>, ITypeSerializerReadingStrategy <TBasePayloadType> where TOperationType : Enum { //arrange SerializerService serializer = Serializer; TBasePayloadType payload; //act try { payload = serializer.Deserialize <TBasePayloadType>(entry.BinaryData, 0); if (payload is IUnknownPayloadType) { Assert.Warn($"Encountered unimplemented OpCode: 0x{payload.OperationCode:X}."); return; } } catch (Exception e) { Assert.Fail($"Critical failure. Cannot deserialize File: {entry.FileName} FileSize: {entry.BinaryData.Length} \n\n Exception: {e.Message} Stack: {e.StackTrace}"); return; } finally { } //assert Assert.NotNull(payload, $"Resulting capture capture deserialization attempt null for File: {entry.FileName}"); //We should have deserialized it. We want to make sure the opcode matches Assert.AreEqual(entry.OpCode, ConvertPayloadOperationCode <TBasePayloadType, TOperationType>(payload), $"Mismatched {nameof(payload.OperationCode)} on packet capture File: {entry.FileName}. Expected: {entry.OpCode} Was: {payload.OperationCode}"); }
public static object MemoryDecompress(byte[] bytes) { AcedInflator instance = new AcedInflator(); byte[] objs = instance.Decompress(bytes, 0, 0, 0); return(SerializerService.Deserialize(objs)); }
private static async Task AsyncMain() { //While they're typing this let's build the serializer. Task serializerReady = Task.Factory.StartNew(() => { serializer.RegisterType <AdtFile>(); serializer.Compile(); }, TaskCreationOptions.LongRunning); string adtName = Console.ReadLine(); if (String.IsNullOrEmpty(adtName) || !File.Exists(adtName)) { throw new ArgumentException($"No adt file named {adtName} found in the directory."); } byte[] bytes = File.ReadAllBytes(adtName); //wait for the serializer to compile await serializerReady; AdtFile adtFile = serializer.Deserialize <AdtFile>(bytes); foreach (var chunk in adtFile) { Console.WriteLine(chunk.ToString()); } Console.ReadKey(); }
public void Test_Can_Deserialize_ReadToEnd_String_Type() { //arrange SerializerService serializer = new SerializerService(); serializer.RegisterType <ReadToEndStringType>(); serializer.Compile(); //act byte[] bytes = serializer.Serialize(new ReadToEndStringType(5, TestStrings)); ReadToEndStringType deserializer = serializer.Deserialize <ReadToEndStringType>(bytes); Assert.NotNull(deserializer); Assert.IsNotEmpty(deserializer.Strings); Assert.AreEqual(5, deserializer.I); Assert.AreEqual(TestStrings.Length, deserializer.Strings.Length); //Check that there are null terminators Assert.AreEqual(TestStrings.Length, bytes.Skip(4).Count(b => b == 0)); for (int i = 0; i < TestStrings.Length; i++) { Assert.AreEqual(TestStrings[i], deserializer.Strings[i]); } }
public override void Run() { string propsJson = File.ReadAllText(propsFilePath); Dictionary <string, string> props = SerializerService.Deserialize <Dictionary <string, string> >(propsJson); string equipmentJson = File.ReadAllText(equipmentFilePath); List <Equipment> equipment = SerializerService.Deserialize <List <Equipment> >(equipmentJson); foreach ((string key, string value) in props) { string[] parts = value.Split(';', StringSplitOptions.RemoveEmptyEntries); string name = parts[0].Trim(); string?desc = null; if (parts.Length == 2) { desc = parts[1].Trim(); } Equipment eq = new(); eq.Name = name; eq.Description = desc; eq.Id = key; eq.Slot = Equipment.FitsSlots.Weapons; equipment.Add(eq); } ///equipment.Sort((a, b) => a.Id.CompareTo(b.Id)); string json = SerializerService.Serialize(equipment); File.WriteAllText(equipmentFilePath, json); }
/// <summary> /// Gets the raw string (xml) from the broker db by URL /// </summary> /// <param name="Url">URL of the page</param> /// <returns>String with page xml or empty string if no page was found</returns> public string GetContentByUrl(string Url) { Page page = new Page(); page.Title = Randomizer.AnyString(15); page.Id = Randomizer.AnyUri(64); page.Filename = Randomizer.AnySafeString(8) + ".html"; PageTemplate pt = new PageTemplate(); pt.Title = Randomizer.AnyString(20); Field ptfieldView = new Field(); ptfieldView.Name = "view"; ptfieldView.Values.Add("Standard"); pt.MetadataFields = new FieldSet(); pt.MetadataFields.Add(ptfieldView.Name, ptfieldView); page.PageTemplate = pt; page.ComponentPresentations = new List <ComponentPresentation>(); string cpString = ComponentPresentationProvider.GetContent(""); page.ComponentPresentations.Add(SerializerService.Deserialize <ComponentPresentation>(cpString)); FieldSet metadataFields = new FieldSet(); page.MetadataFields = metadataFields; return(SerializerService.Serialize <Page>(page)); }
public List <Workout> GetAllWorkouts(string tablename) { if (!PersistentDataProvider.Current.allTableNames.Contains(tablename)) { MessageBox.Show($"Table {tablename} not found"); } try { SerializerService ser = new SerializerService(); using var con = new SQLiteConnection("Data Source=" + directory + databaseName); con.Open(); string stm = "SELECT * FROM " + tablename; using var cmd = new SQLiteCommand(stm, con); using SQLiteDataReader rdr = cmd.ExecuteReader(); List <Workout> result = new List <Workout>(); while (rdr.Read()) { Workout t = new Workout(); t.Date = Convert.ToDateTime(rdr.GetString(1)); t.ExerciseList = ser.Deserialize <ObservableCollection <ExerciseEntry> >(rdr.GetString(0)); result.Add(t); } return(result); } catch (System.Data.SQLite.SQLiteException) { MessageBox.Show("Table " + tablename + " not found!"); return(null); } }
public void Can_Deserialize_Captures_To_GamePacketPayloads(PacketCaptureTestEntry entry) { Console.WriteLine($"Entry Decompressed/Real Size: {entry.BinaryData.Length} OpCode: {entry.OpCode}"); //arrange SerializerService serializer = Serializer; GamePacketPayload payload; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //act try { payload = serializer.Deserialize <GamePacketPayload>(entry.BinaryData); } catch (Exception e) { Assert.Fail($"Critical failure. Cannot deserialize File: {entry.FileName} FileSize: {entry.BinaryData.Length} \n\n Exception: {e.Message} Stack: {e.StackTrace}"); return; } finally { stopwatch.Stop(); } Console.WriteLine($"Serialization time in ms: {stopwatch.ElapsedMilliseconds}"); //assert Assert.NotNull(payload, $"Resulting capture capture deserialization attempt null for File: {entry.FileName}"); //We should have deserialized it. We want to make sure the opcode matches Assert.AreEqual(entry.OpCode, payload.GetOperationCode(), $"Mismatched {nameof(NetworkOperationCode)} on packet capture File: {entry.FileName}. Expected: {entry.OpCode} Was: {payload.GetOperationCode()}"); }
public void Can_Serialize_DeserializedDTO_To_Same_Binary_Representation(PacketCaptureTestEntry entry) { //arrange Console.WriteLine($"Entry Size: {entry.BinaryData.Length} OpCode: {entry.OpCode}"); SerializerService serializer = Serializer; GamePacketPayload payload = serializer.Deserialize <GamePacketPayload>(entry.BinaryData); //act byte[] serializedBytes = serializer.Serialize(payload); //assert try { Assert.AreEqual(entry.BinaryData.Length, serializedBytes.Length, $"Mismatched length on OpCode: {entry.OpCode} Type: {payload.GetType().Name}"); } catch (AssertionException e) { Assert.Fail($"Failed: {e.Message} {PrintFailureBytes(entry.BinaryData, serializedBytes)}"); } for (int i = 0; i < entry.BinaryData.Length; i++) { Assert.AreEqual(entry.BinaryData[i], serializedBytes[i], $"Mismatched byte value at Index: {i} on OpCode: {entry.OpCode} Type: {payload.GetType().Name}"); } }
public async Task Search() { WebRequest req = WebRequest.Create(SearchUrl + "&json=true"); WebResponse response = await req.GetResponseAsync(); using StreamReader reader = new StreamReader(response.GetResponseStream()); string json = reader.ReadToEnd(); SearchResultWrapper result = SerializerService.Deserialize <SearchResultWrapper>(json); if (!result.Success) { throw new Exception("Did not succede"); } Application.Current.Dispatcher.Invoke(() => { this.PopularToday.Clear(); if (result.SearchResults != null) { foreach (SearchResult searchResult in result.SearchResults) { this.PopularToday.Add(searchResult); } } }); }
//TODO: Can't remember why this isn't worknig, can't remember if needs fixing? //[Test] public static void Test_Serializer_Auth_Token() { //arrange SerializerService serializer = new SerializerService(); serializer.RegisterType <AuthenticationToken>(); serializer.RegisterType <AuthRealmListPacketTest.AuthRealmListResponse>(); serializer.Compile(); //act AuthRealmListPacketTest.AuthRealmListResponse response = serializer.Deserialize <AuthRealmListPacketTest.AuthRealmListResponse>(new DefaultStreamReaderStrategy(realworldBytes)); //act AuthenticationToken token = serializer.Deserialize <AuthenticationToken>(Encoding.UTF8.GetBytes(realWorldBytestring)); Assert.AreEqual("GLADER", token.AccountName); }
public override void Transform(Engine engine, Package package) { GeneralUtils.TimedLog("started Transform"); this.Package = package; this.Engine = engine; object component; bool hasOutput = HasPackageValue(package, "Output"); if (hasOutput) { String inputValue = package.GetValue("Output"); if (ComponentPresentationRenderStyle == Base.ComponentPresentationRenderStyle.Component) { component = (Dynamic.Component)SerializerService.Deserialize <Dynamic.Component>(inputValue); } else { component = (Dynamic.ComponentPresentation)SerializerService.Deserialize <Dynamic.ComponentPresentation>(inputValue); } } else { if (ComponentPresentationRenderStyle == Base.ComponentPresentationRenderStyle.Component) { component = GetDynamicComponent(); } else { component = GetDynamicComponentPresentation(); } } try { TransformComponent(ComponentPresentationRenderStyle == Base.ComponentPresentationRenderStyle.Component ? (Dynamic.Component)component : ((Dynamic.ComponentPresentation)component).Component); } catch (StopChainException) { Log.Debug("caught stopchainexception, will not write current component back to the package"); return; } string outputValue = ComponentPresentationRenderStyle == Base.ComponentPresentationRenderStyle.Component ? SerializerService.Serialize <Dynamic.Component>((Dynamic.Component)component) : SerializerService.Serialize <Dynamic.ComponentPresentation>((Dynamic.ComponentPresentation)component); if (hasOutput) { Item outputItem = package.GetByName("Output"); outputItem.SetAsString(outputValue); } else { package.PushItem(Package.OutputName, package.CreateStringItem(SerializerService is XmlSerializerService ? ContentType.Xml : ContentType.Text, outputValue)); } GeneralUtils.TimedLog("finished Transform"); }
//NRels are from the client static void Main(string[] args) { Console.WriteLine("Enter Filename:"); string fileName = Console.ReadLine(); SerializerService serializer = new SerializerService(); serializer.RegisterType <NRelMainBlockModel>(); serializer.RegisterType <NRelTrailerModel>(); serializer.RegisterType <NRelSectionModel>(); serializer.RegisterType <NRelSectionsChunkModel>(); serializer.Compile(); byte[] bytes = File.ReadAllBytes(fileName); //Trailer is at -16 bytes from EOF. NRelTrailerModel trailer = serializer .Deserialize <NRelTrailerModel>(new DefaultStreamReaderStrategy(new MemoryStream(bytes, bytes.Length - 16, 16))); NRelMainBlockModel mainBlock = serializer .Deserialize <NRelMainBlockModel>(new DefaultStreamReaderStrategy(new MemoryStream(bytes, (int)trailer.MainBlockPointer, (int)(bytes.Length - trailer.MainBlockPointer)))); NRelSectionsChunkModel sections = serializer .Deserialize <NRelSectionsChunkModel>( new DefaultStreamReaderStrategy(new MemoryStream(bytes, (int)mainBlock.SectionPointer, (int)(bytes.Length - mainBlock.SectionPointer))) .PreprendWithBytes(((int)mainBlock.SectionCount).Reinterpret())); List <string> linesToWrite = new List <string>(sections.Sections.Count()); foreach (var s in sections.Sections) { string log = s.ToString(); Console.WriteLine(log); linesToWrite.Add(log); } File.WriteAllLines($"{Path.GetFileNameWithoutExtension(fileName)}_out.txt", linesToWrite); File.WriteAllBytes($"{Path.GetFileNameWithoutExtension(fileName)}.bytes", serializer.Serialize(sections)); Console.WriteLine("Press any key to close..."); Console.ReadKey(); }
public void RemoveKategori(Kategori Kategori) { var kategori = Kategori; var serializerService = new SerializerService(); var jsonFilename = "kategori.json"; var kategoriLista = serializerService.Deserialize(jsonFilename); kategoriLista.Remove(kategori); serializerService.Serialize(jsonFilename, kategoriLista); }
public static void Test_Cant_Polymorphic_Serialize_Null() { //arrange SerializerService serializer = new SerializerService(); //act serializer.RegisterType <WireDataContractTest>(); serializer.Compile(); Assert.Throws <InvalidOperationException>(() => serializer.Deserialize <WireDataContractTest>(serializer.Serialize(new WireDataContractTest(null, null)))); }
public void Test_No_Stack_Overflow_On_Deserializing_Unknown_Type() { //arrange SerializerService serializer = new SerializerService(); //don't register serializer.Compile(); byte[] bytes = new byte[] { 55, 78 }; //assert Assert.Throws <InvalidOperationException>(() => serializer.Deserialize <PSOBBPacketHeader>(bytes)); }
public static void Test_String_Serializer_Serializes() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize <string>(serializer.Serialize("Hello!")); //assert Assert.AreEqual(value, "Hello!"); }
public static void Add(string searchPath) { string[] paths = Directory.GetFiles(searchPath); foreach (string path in paths) { string culture = Path.GetFileNameWithoutExtension(path); string json = File.ReadAllText(path); Dictionary <string, string?> values = SerializerService.Deserialize <Dictionary <string, string?> >(json); Add(culture, values); } }
public static void Test_Can_Serializer_Then_Deserialize_Basic_Wire_Message() { //arrange SerializerService serializer = new SerializerService(); //act serializer.RegisterType <BasicWireDataContract>(); serializer.Compile(); BasicWireDataContract message = serializer.Deserialize <BasicWireDataContract>(serializer.Serialize(new BasicWireDataContract(5))); //assert Assert.NotNull(message); }
public static void Test_Serializer_Can_Read_Write_Type_With_EnumString_Field() { //arrange SerializerService service = new SerializerService(); service.RegisterType <WireDataContractWithStringEnum>(); service.Compile(); //act WireDataContractWithStringEnum testInstance = service.Deserialize <WireDataContractWithStringEnum>((service.Serialize <WireDataContractWithStringEnum>(new WireDataContractWithStringEnum(TestEnum.Something)))); //assert Assert.AreEqual(testInstance.test, TestEnum.Something); }
public static void Test_NoCsume_Throws_On_Invalid_Key() { //arrange SerializerService service = new SerializerService(); service.RegisterType <TestBaseType>(); service.Compile(); //act Assert.Throws <InvalidOperationException>(() => service.Deserialize <TestBaseType>(service.Serialize((TestBaseType) new ChildType() { i = 2, s = 17 }))); }
public static void Can_Deserialize_With_Flags_Type_Information() { //arrange SerializerService service = new SerializerService(); service.RegisterType <BaseTypeByFlags>(); service.Compile(); //act BaseTypeByFlags flagsInstance = service.Deserialize <BaseTypeByFlags>(new byte[] { 5 | 6, 0, 0, 0, 7 }); //assert Assert.NotNull(flagsInstance); Assert.AreEqual(typeof(ChildTypeByFlags), flagsInstance.GetType()); }
public static void Test_Can_Serialize_Child_Then_Deserialize_To_Base() { //arrange SerializerService serializer = new SerializerService(); //act serializer.RegisterType <WireDataContractTest>(); serializer.Compile(); WireDataContractTest message = serializer.Deserialize <WireDataContractTest>(serializer.Serialize(new WireDataContractTest(new ChildTypeThree(), new ChildTypeThree()))); //assert Assert.NotNull(message); Assert.True(message.test.GetType() == typeof(ChildTypeThree)); }