Beispiel #1
0
        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);
            }
        }
Beispiel #2
0
        protected override void Serialize(T file, Stream stream)
        {
            using TextWriter writer = new StreamWriter(stream);
            string json = SerializerService.Serialize(file);

            writer.Write(json);
        }
        private static void TextEncodingRoundrip(Encoding encoding)
        {
            using var stream = new MemoryStream();

            using (var writer = new ObjectWriter(stream, leaveOpen: true))
            {
                SerializerService.WriteTo(encoding, writer, CancellationToken.None);
            }

            stream.Position = 0;

            using var reader = ObjectReader.TryGetReader(stream);
            Assert.NotNull(reader);
            var actualEncoding   = (Encoding)SerializerService.ReadEncodingFrom(reader, CancellationToken.None).Clone();
            var expectedEncoding = (Encoding)encoding.Clone();

            // set the fallbacks to the same instance so that equality comparison does not take them into account:
            actualEncoding.EncoderFallback   = EncoderFallback.ExceptionFallback;
            actualEncoding.DecoderFallback   = DecoderFallback.ExceptionFallback;
            expectedEncoding.EncoderFallback = EncoderFallback.ExceptionFallback;
            expectedEncoding.DecoderFallback = DecoderFallback.ExceptionFallback;

            Assert.Equal(expectedEncoding.GetPreamble(), actualEncoding.GetPreamble());
            Assert.Equal(expectedEncoding.CodePage, actualEncoding.CodePage);
            Assert.Equal(expectedEncoding.WebName, actualEncoding.WebName);
            Assert.Equal(expectedEncoding, actualEncoding);
        }
        private static INetworkSerializationService BuildClientSerializer()
        {
            SerializerService serializer = new SerializerService();

            GamePacketMetadataMarker
            .SerializableTypes
            .Concat(GamePacketMetadataMarker.GamePacketPayloadTypes)
            .Where(t => t != typeof(SMSG_CONTACT_LIST_PAYLOAD) && t != typeof(SMSG_SPELL_GO_Payload))
            .ToList()
            .ForEach(t => serializer.RegisterType(t));

            //Register all unimplemented stubs
            foreach (Type t in GamePacketStubMetadataMarker.GamePacketPayloadStubTypes.Where(t => GamePacketMetadataMarker.UnimplementedOperationCodes.Value.Contains(t.GetCustomAttribute <GamePayloadOperationCodeAttribute>().OperationCode)))
            {
                serializer.RegisterType(t);
            }

            //Also the header types
            serializer.RegisterType <ServerPacketHeader>();
            serializer.RegisterType <OutgoingClientPacketHeader>();
            serializer.RegisterType <SMSG_CONTACT_LIST_DTO_PROXY>();
            serializer.RegisterType <SMSG_SPELL_GO_DTO_PROXY>();

            serializer.Compile();

            return(new FreecraftCoreGladNetSerializerAdapter(serializer));
        }
Beispiel #5
0
        public PropSheet(string fileName)
        {
            try
            {
                this.rows = new Dictionary <uint, Prop>();

                uint index = 0;
                Dictionary <string, string> stringRows = SerializerService.DeserializeFile <Dictionary <string, string> >(fileName);
                foreach ((string key, string value) in stringRows)
                {
                    string[] parts = value.Split(';', StringSplitOptions.RemoveEmptyEntries);

                    (ushort modelSet, ushort modelBase, ushort modelVariant) = IItemConverter.SplitString(key);
                    Prop prop = new Prop();
                    prop.Name = parts[0].Trim();

                    if (parts.Length == 2)
                    {
                        prop.Description = parts[1].Trim();
                    }

                    prop.ModelBase    = modelBase;
                    prop.ModelVariant = modelVariant;
                    prop.ModelSet     = modelSet;

                    this.rows.Add(index, prop);

                    index++;
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Failed to load json data: {fileName}", ex);
            }
        }
Beispiel #6
0
        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]);
            }
        }
        public void Test_Can_Serialize_All_Concrete_Payloads(Type t)
        {
            //arrange
            SerializerService serializer = new SerializerService();

            //Abstracts can't be created
            if (t.IsAbstract)            //if it's unknown then it's probably default and thus unwritable
            {
                return;
            }

            TPayloadBaseType payload = (TPayloadBaseType)Activator.CreateInstance(t, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, new object[0], null);

            //act
            Span <byte> buffer = new Span <byte>(new byte[62000]);
            int         offset = 0;

            //We have to suppress these exceptions because some payloads have complex object graphs and
            //need more than default initialization to be serializable
            try
            {
                serializer.Write(payload, buffer, ref offset);

                //assert
                Assert.True(offset != 0);
            }
            catch (ArgumentNullException e)
            {
            }
            catch (Exception e)
            {
                Assert.Warn($"Type: {t.Name} may not be serializable. It's not determinable. This can happen if it has class/complex fields and should be ignored. \n\nException: {e.Message}");
            }
        }
    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);
    }
Beispiel #9
0
        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}.");
            }
        }
Beispiel #10
0
        private async Task Run()
        {
            if (this.isRunning)
            {
                return;
            }

            this.isRunning = true;
            Random rnd = new Random();

            while (this.IsVisible)
            {
                List <Entry> entries = SerializerService.DeserializeFile <List <Entry> >("Data/Images.json");

                while (this.IsVisible && entries.Count > 0)
                {
                    int index = rnd.Next(entries.Count);
                    await this.Show(entries[index], rnd);

                    entries.RemoveAt(index);
                    await Task.Delay(5000);
                }
            }

            this.isRunning = false;
        }
Beispiel #11
0
        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);
        }
Beispiel #12
0
        public static void Test_Can_Register_SeperatedCollection_Type()
        {
            //arrange
            SerializerService serializer = new SerializerService();

            Assert.DoesNotThrow(() => serializer.RegisterType <TestSeperatedCollection>());
        }
Beispiel #13
0
        public static void Test_Can_Regiser_Multilevel_Polymorphic_Type()
        {
            //arrange
            SerializerService serializer = new SerializerService();

            Assert.DoesNotThrow(() => serializer.RegisterType <TestBaseClass>());
        }
Beispiel #14
0
        protected override T Deserialize(Stream stream)
        {
            using TextReader reader = new StreamReader(stream);
            string json = reader.ReadToEnd();

            return(SerializerService.Deserialize <T>(json));
        }
Beispiel #15
0
 private static void NewMethod(Stopwatch watch, SerializerService serializer)
 {
     watch.Start();
     serializer.RegisterType <PlayerCharacterDataModel>();
     serializer.Compile();
     watch.Stop();
 }
        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);
        }
Beispiel #17
0
        public static void SaveTemplate(SkeletonFile skeleton)
        {
            string name = "Generated_";

            if (skeleton.ModelTypes != null)
            {
                for (int i = 0; i < skeleton.ModelTypes.Count; i++)
                {
                    if (i > 0)
                    {
                        name += "_";
                    }

                    name += skeleton.ModelTypes[i];
                }
            }

            if (skeleton.Race != null)
            {
                name += "_" + skeleton.Race;
            }

            if (skeleton.Age != null)
            {
                name += "_" + skeleton.Age;
            }

            SerializerService.SerializeFile("Data/Skeletons/" + name + ".json", skeleton);
            BoneNameFiles.Add(skeleton);
        }
        public void Test_Patching_Payload_Deserializes_To_Correct_Values()
        {
            //arrange
            SerializerService serializer = new SerializerService();

            serializer.RegisterPolymorphicSerializer <PSOBBPatchPacketPayloadClient, PSOBBPatchPacketPayloadClient_AutoGeneratedTemplateSerializerStrategy>();
            serializer.RegisterPolymorphicSerializer <PSOBBPatchPacketPayloadServer, PSOBBPatchPacketPayloadServer_AutoGeneratedTemplateSerializerStrategy>();
            Span <byte> buffer = new Span <byte>(new byte[500]);

            PatchingWelcomePayload payload = new PatchingWelcomePayload("Patch Server. Copyright SonicTeam, LTD. 2001", 506953426, 214005626);

            //assert
            int offset = 0;

            serializer.Write(payload, buffer, ref offset);
            int size = offset;

            offset = 0;
            PatchingWelcomePayload deserializedPayload = (PatchingWelcomePayload)serializer.Read <PSOBBPatchPacketPayloadServer>(buffer.Slice(0, size), ref offset);

            //assert
            Assert.AreEqual(payload.PatchCopyrightMessage, deserializedPayload.PatchCopyrightMessage);
            Assert.AreEqual(payload.ClientVector, deserializedPayload.ClientVector);
            Assert.AreEqual(payload.ServerVector, deserializedPayload.ServerVector);
            Assert.AreEqual(0x99, deserializedPayload.OperationCode);
        }
Beispiel #19
0
        private SkeletonFile Load(string path)
        {
            SkeletonFile template = SerializerService.DeserializeFile <SkeletonFile>(path);

            BoneNameFiles.Add(template);

            if (template.BasedOn != null)
            {
                SkeletonFile baseTemplate = this.Load("Data/Skeletons/" + template.BasedOn);
                template.CopyBaseValues(baseTemplate);
            }

            // Validate that all bone names are unique
            if (template.BoneNames != null)
            {
                HashSet <string> boneNames = new HashSet <string>();

                foreach ((string orignal, string name) in template.BoneNames)
                {
                    if (boneNames.Contains(name))
                    {
                        throw new Exception($"Duplicate bone name: {name} in skeleton file: {path}");
                    }

                    boneNames.Add(name);
                }
            }

            return(template);
        }
        public static void Test_Can_Register_Child_of_Expected_Runtime_BaseType()
        {
            //arrange
            SerializerService serivce = new SerializerService();

            Assert.DoesNotThrow(() => serivce.RegisterType <ChildType>());
        }
        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]);
            }
        }
        private void Generic_CanDeserialize_CaptureTest <TBasePayloadType>(PacketCaptureTestEntry entry)
            where TBasePayloadType : IPacketPayload, IOperationCodeable
        {
            //arrange
            SerializerService serializer = Serializer;
            TBasePayloadType  payload;

            //act
            try
            {
                payload = serializer.Deserialize <TBasePayloadType>(entry.BinaryData);

                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, payload.OperationCode, $"Mismatched {nameof(payload.OperationCode)} on packet capture File: {entry.FileName}. Expected: {entry.OpCode} Was: {payload.OperationCode}");
        }
Beispiel #23
0
        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);
                    }
                }
            });
        }
Beispiel #24
0
        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));
        }
        public void Test_Can_Register_All_Concrete_Models(Type t)
        {
            //We have to do abit of a hack if it's a generic type
            //We need a closed generic. DBCs usually are generic if they have strings
            if (t.IsGenericTypeDefinition)
            {
                //TODO: Handle contraints better, causes throw and this is a hack to catch
                //TODO: Support closing multiple type arg generics
                //Assuming this can work, assuming all 1 generic param for now.
                try
                {
                    t = t.MakeGenericType(typeof(StringDBCReference));
                }
                catch (Exception e)
                {
                    Assert.Inconclusive($"Cannot test Type: {t.Name} because closed generic could not be made. Maybe caused by constaints. Error: {e.Message}");
                }
            }

            //arrange
            SerializerService serializer = new SerializerService();

            //assert
            Assert.DoesNotThrow(() => serializer.RegisterType(t));
            Assert.DoesNotThrow(() => serializer.Compile());

            Assert.True(serializer.isTypeRegistered(t), $"Failed to register Type: {t.Name}");
        }
Beispiel #26
0
        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.Read <GamePacketPayload>(new Span <byte>(entry.BinaryData), 0);
            }
            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.OperationCode, $"Mismatched {nameof(NetworkOperationCode)} on packet capture File: {entry.FileName}. Expected: {entry.OpCode} Was: {payload.OperationCode}");
        }
Beispiel #27
0
        public void Test_Can_Link_PatchingUpOneDir()
        {
            //arrange
            SerializerService serializer = new SerializerService();

            serializer.Link <PatchingInformationPayload, PSOBBPatchPacketPayloadServer>();
            serializer.Compile();
        }
Beispiel #28
0
        public void Test_Can_Register_PatchingLoginRequestPayload()
        {
            //arrange
            SerializerService serializer = new SerializerService();

            serializer.RegisterType(typeof(PatchingLoginRequestPayload));
            serializer.Compile();
        }
        public static void Test_Can_Register_ReverseFixedByteArray_Type()
        {
            //arrange
            SerializerService serializer = new SerializerService();

            //assert
            Assert.DoesNotThrow(() => serializer.RegisterType <ReverseArrayByteTest>());
        }
Beispiel #30
0
        public static byte[] MemoryCompress(object obj, AcedCompressionLevel level)
        {
            byte[]       objs     = SerializerService.Serialize(obj);
            AcedDeflator instance = new AcedDeflator();

            byte[] bytes = instance.Compress(objs, 0, objs.Length, level, 0, 0);
            return(bytes);
        }
		public void Cleanup()
		{
			_service = null;
		}
		public void Init()
		{
			_service = new SerializerService ();
		}