public void TestPopulateObject() {
            // This test verifies that when we pass in an existing object
            // instance that same instance is used to deserialize into, ie,
            // we can do the equivalent of Json.NET's PopulateObject

            SimpleModel model1 = new SimpleModel { A = 3, B = new List<int> { 1, 2, 3 } };

            fsData data;

            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded);

            model1.A = 1;
            model1.B = new List<int> { 1 };
            SimpleModel model2 = model1;
            Assert.AreEqual(1, model1.A);
            Assert.AreEqual(1, model2.A);
            CollectionAssert.AreEqual(new List<int> { 1 }, model1.B);
            CollectionAssert.AreEqual(new List<int> { 1 }, model2.B);

            Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded);

            // If the same instance was not used, then model2.A will equal 1
            Assert.AreEqual(3, model1.A);
            Assert.AreEqual(3, model2.A);
            CollectionAssert.AreEqual(new List<int> { 1, 2, 3 }, model1.B);
            CollectionAssert.AreEqual(new List<int> { 1, 2, 3 }, model2.B);
            Assert.IsTrue(ReferenceEquals(model1, model2));
        }
Exemplo n.º 2
0
    public void StrangeFormatTests() {
        var serializer = new fsSerializer();
        DateTime time = DateTime.Now;
        serializer.TryDeserialize(new fsData("2016-01-22T12:06:57.503005Z"), ref time).AssertSuccessWithoutWarnings();

        Assert.AreEqual(Convert.ToDateTime("2016-01-22T12:06:57.503005Z"), time);
    }
Exemplo n.º 3
0
        public void VerifyNegativeInfinityRoundTrips() {
            var serializer = new fsSerializer();

            fsData data;
            serializer.TrySerialize(float.NegativeInfinity, out data).AssertSuccessWithoutWarnings();
            Assert.AreEqual("-Infinity", fsJsonPrinter.PrettyJson(data));

            float deserialized = 0f;
            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(float.NegativeInfinity, deserialized);
        }
Exemplo n.º 4
0
        public void VerifyMinValueRoundTrips() {
            var serializer = new fsSerializer();

            fsData data;
            serializer.TrySerialize(float.MinValue, out data).AssertSuccessWithoutWarnings();
            Assert.AreEqual(((double)float.MinValue).ToString(System.Globalization.CultureInfo.InvariantCulture), fsJsonPrinter.PrettyJson(data));

            float deserialized = 0f;
            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(float.MinValue, deserialized);
        }
	// Use this for initialization
	void Start () {



		fsSerializer serializer = new fsSerializer();

		List<PairData> memoryCapacity =  new List<PairData> () {
			new PairData(6, 16), 
			new PairData(4, 8)};
		List<PairData> hdd =  new List<PairData> () {
			new PairData(4, 4), 
			new PairData(4, 8)};
		List<PairData> network =  new List<PairData> () {
			new PairData(2, 10), 
			new PairData(2, 1)};
		List<string> gpu =  new List<string> () {
			"GPU A",
			"GPU B",
			"GPU C"};

		ModelData modelData = new ModelData("Test Model",
		                                    true,
		                                    2,
		                                    4,
		                                    1000,
		                                    8,
		                                    1333,
		                                    memoryCapacity,
		                                    "RAID 0",
		                                    hdd,
		                                    network,
		                                    gpu,
		                                    3,
		                                    "Just a test",
		                                    System.DateTime.Now);

		fsData data;
		serializer.TrySerialize(modelData.GetType(), modelData, out data);

		string dataString = fsJsonPrinter.PrettyJson(data);
		data = fsJsonParser.Parse(dataString);

		Debug.Log(dataString);
		Debug.Log(modelData.ToString());

		object deserialized = null;
		serializer.TryDeserialize(data, typeof(ModelData), ref deserialized);

		ModelData newModelData = (ModelData) deserialized;
		Debug.Log(newModelData.ToString());

		PersistanceManager.StoreLocalModelData("Test Model", dataString, null);

	}
Exemplo n.º 6
0
        public void TestDeserializeWriteOnlyProperty() {
            var data = fsData.CreateDictionary();
            data.AsDictionary["Getter"] = new fsData(111); // not used, but somewhat verifies that we do not try to deserialize into a R/O property
            data.AsDictionary["Setter"] = new fsData(222);

            var model = default(Model);
            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TryDeserialize(data, ref model).Succeeded);

            Assert.AreEqual(222, model._setValue);
        }
Exemplo n.º 7
0
        public void ImportLegacyInheritance() {
            fsData data = fsData.CreateDictionary();
            data.AsDictionary["Type"] = new fsData("System.Int32");
            data.AsDictionary["Data"] = new fsData(32);

            object o = null;
            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TryDeserialize(data, ref o).Succeeded);

            Assert.IsTrue(o.GetType() == typeof(int));
            Assert.IsTrue((int)o == 32);
        }
Exemplo n.º 8
0
        public void VerifyNaNRoundTrips() {
            var serializer = new fsSerializer();

            // todo: could definitely reduce duplication of tests in this file!
            fsData data;
            serializer.TrySerialize(float.NaN, out data).AssertSuccessWithoutWarnings();
            Assert.AreEqual("NaN", fsJsonPrinter.PrettyJson(data));

            float deserialized = 0f;
            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(float.NaN, deserialized);
        }
Exemplo n.º 9
0
        public void VerifyFloatSerializationDoesNotHaveJitter() {
            var serializer = new fsSerializer();

            // We serialize w/o jitter
            fsData data;
            serializer.TrySerialize(0.1f, out data).AssertSuccessWithoutWarnings();
            Assert.AreEqual("0.1", fsJsonPrinter.PrettyJson(data));

            // We deserialize w/o jitter.
            float deserialized = 0f;
            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(0.1f, deserialized);
        }
        private void GetProfileResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            Profile result = new Profile();
            fsData  data   = null;
            Dictionary <string, object> customData = ((GetProfileRequest)req).CustomData;

            customData.Add(Constants.String.RESPONSE_HEADERS, resp.Headers);

            if (resp.Success)
            {
                try
                {
                    fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }

                    object obj = result;
                    r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }

                    customData.Add("json", data);
                }
                catch (Exception e)
                {
                    Log.Error("PersonalityInsights.GetProfileResponse()", "GetProfileResponse Exception: {0}", e.ToString());
                    resp.Success = false;
                }
            }

            if (resp.Success)
            {
                if (((GetProfileRequest)req).SuccessCallback != null)
                {
                    ((GetProfileRequest)req).SuccessCallback(result, customData);
                }
            }
            else
            {
                if (((GetProfileRequest)req).FailCallback != null)
                {
                    ((GetProfileRequest)req).FailCallback(resp.Error, customData);
                }
            }
        }
Exemplo n.º 11
0
    private void OnMessage(object response, Dictionary <string, object> customData)
    {
        Log.Debug("ExampleAssistant.OnMessage()", "Response: {0}", customData["json"].ToString());

        //  Convert resp to fsdata
        fsData   fsdata = null;
        fsResult r      = _serializer.TrySerialize(response.GetType(), response, out fsdata);

        if (!r.Succeeded)
        {
            throw new WatsonException(r.FormattedMessages);
        }

        //  Convert fsdata to MessageResponse
        MessageResponse messageResponse = new MessageResponse();
        object          obj             = messageResponse;

        r = _serializer.TryDeserialize(fsdata, obj.GetType(), ref obj);
        if (!r.Succeeded)
        {
            throw new WatsonException(r.FormattedMessages);
        }

        //  Set context for next round of messaging
        object _tempContext = null;

        (response as Dictionary <string, object>).TryGetValue("context", out _tempContext);

        if (_tempContext != null)
        {
            _context = _tempContext as Dictionary <string, object>;
        }
        else
        {
            Log.Debug("ExampleConversation.OnMessage()", "Failed to get context");
        }

        //  Get intent
        object tempIntentsObj = null;

        (response as Dictionary <string, object>).TryGetValue("intents", out tempIntentsObj);
        object tempIntentObj = (tempIntentsObj as List <object>)[0];
        object tempIntent    = null;

        (tempIntentObj as Dictionary <string, object>).TryGetValue("intent", out tempIntent);
        string intent = tempIntent.ToString();

        _messageTested = true;
    }
    /// <summary>
    /// Get all results from SpecialScore
    /// </summary>
    /// <param name="callback">Callback function to retrieve SpecialScore results from database</param>
    public static void GetResults(Action <Dictionary <string, Dictionary <string, int> > > callback)
    {
        RestClient.Get($"{databaseURL}specialScore.json").Then(resCourse => {
            var jsonRes = resCourse.Text;

            var data            = fsJsonParser.Parse(jsonRes);
            object deserialized = null;
            // Deserialize to Value: object as I only require Key: course
            serializer.TryDeserialize(data, typeof(Dictionary <string, object>), ref deserialized);

            Dictionary <string, object> courseNameDict = deserialized as Dictionary <string, object>;

            Dictionary <string, Dictionary <string, int> > allResults = new Dictionary <string, Dictionary <string, int> >();

            int count = 0;
            foreach (var course in courseNameDict.Keys)
            {
                RestClient.Get($"{databaseURL}specialScore/{course}.json").Then(resScore => {
                    jsonRes = resScore.Text;

                    data         = fsJsonParser.Parse(jsonRes);
                    deserialized = null;
                    serializer.TryDeserialize(data, typeof(Dictionary <string, int>), ref deserialized);

                    Dictionary <string, int> scoreDict = deserialized as Dictionary <string, int>;

                    allResults.Add(course, scoreDict);

                    if (++count == courseNameDict.Keys.Count)
                    {
                        callback(allResults);
                    }
                });
            }
        });
    }
Exemplo n.º 13
0
    public static List <User> AllUsers(string responseJson)
    {
        var    data         = fsJsonParser.Parse(responseJson);
        object deserialized = null;

        serializer.TryDeserialize(data, typeof(AllUserRootObject), ref deserialized);
        var authResponse = deserialized as AllUserRootObject;

        List <User> all_users = new List <User>();

        foreach (var user in authResponse.documents)
        {
            all_users.Add(user.returnUser());
            //Debug.Log(user.returnUser().username);
        }
        return(all_users);
    }
Exemplo n.º 14
0
    // Start is called before the first frame update
    void Awake()
    {
        fsSerializer fsSerializer = new fsSerializer();
        var          result       = fsJsonParser.Parse(collidersFile.text, out fsData fsData);

        if (result.Failed)
        {
            Debug.LogError($"Unable to parse colliders info {result.FormattedMessages}");
        }
        else
        {
            _colliders = new List <ColliderData>();
            fsSerializer.TryDeserialize(fsData, ref _colliders);
        }
    }
Exemplo n.º 15
0
        public void VerifyLargeDoubleRoundTrips()
        {
            double valueToTest = 500000000000000000.0;

            var serializer = new fsSerializer();

            fsData data;
            serializer.TrySerialize(valueToTest, out data).AssertSuccessWithoutWarnings();

            Assert.AreEqual(valueToTest.ToString(System.Globalization.CultureInfo.InvariantCulture), fsJsonPrinter.PrettyJson(data));

            double deserialized = 0f;
            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(valueToTest, deserialized);
        }
Exemplo n.º 16
0
        public static object ToObject(this string json, Type type)
        {
            object result = null;

            try
            {
                if (!string.IsNullOrEmpty(json) && type != null)
                {
                    var data = fsJsonParser.Parse(json);
                    serializer.TryDeserialize(data, type, ref result);
                }

                return(result);
            }
            catch
            {
                if (!string.IsNullOrEmpty(json) && type != null)
                {
                    return(JsonUtility.FromJson(json, type));
                }

                return(result);
            }
        }
Exemplo n.º 17
0
        public static MusicInfo ParseMusicInfo(OpenMpt.ModuleExt moduleExt)
        {
            string message = OpenMptUtility.GetModuleExtMessage(moduleExt);
            string author  = OpenMptUtility.GetModuleExtAuthor(moduleExt);
            string title   = OpenMptUtility.GetModuleExtTitle(moduleExt);

            fsData data = fsJsonParser.Parse(message);

            object   deserialised = null;
            fsResult result       = s_serialiser.TryDeserialize(data, typeof(SerialisedMusicInfo), ref deserialised);

            if (!result.Failed)
            {
                var serialisedMusicInfo = (SerialisedMusicInfo)deserialised;

                return(new MusicInfo(
                           ParseAllMusicSections(serialisedMusicInfo),
                           title,
                           author,
                           serialisedMusicInfo.Comment
                           ));
            }
            return(null);
        }
    // -------------------------------------------------------------------------------

    public void Load()
    {
        // Load our custom CustomClass from its serialised string form, or create a new instance
        if (SerialisedCustomClass != "")
        {
            fsData parsedData       = fsJsonParser.Parse(SerialisedCustomClass);
            object deserializedData = null;
            mSerialiser.TryDeserialize(parsedData, typeof(CustomClass), ref deserializedData).AssertSuccessWithoutWarnings();
            CustomClassInstance = (CustomClass)deserializedData;
        }
        else
        {
            CustomClassInstance = new CustomClass();
        }
    }
Exemplo n.º 19
0
    public static void DeserializeJson()
    {
        var asset = Resources.Load(Path.Combine("metadata", "dm")) as TextAsset;

        if (asset != null)
        {
            var data       = fsJsonParser.Parse(asset.text);
            var serializer = new fsSerializer();
            serializer.TryDeserialize(data, ref objectList).AssertSuccessWithoutWarnings();
        }
        else
        {
            throw new FileNotFoundException();
        }
    }
Exemplo n.º 20
0
        public void VerifyNaNRoundTrips()
        {
            var serializer = new fsSerializer();

            // todo: could definitely reduce duplication of tests in this file!
            fsData data;

            serializer.TrySerialize(float.NaN, out data).AssertSuccessWithoutWarnings();
            Assert.AreEqual("NaN", fsJsonPrinter.PrettyJson(data));

            float deserialized = 0f;

            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(float.NaN, deserialized);
        }
Exemplo n.º 21
0
        public void ImportLegacyInheritance()
        {
            fsData data = fsData.CreateDictionary();

            data.AsDictionary["Type"] = new fsData("System.Int32");
            data.AsDictionary["Data"] = new fsData(32);

            object o          = null;
            var    serializer = new fsSerializer();

            Assert.IsTrue(serializer.TryDeserialize(data, ref o).Succeeded);

            Assert.IsTrue(o.GetType() == typeof(int));
            Assert.IsTrue((int)o == 32);
        }
Exemplo n.º 22
0
        private void TranslateResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            Translations translations = new Translations();
            fsData       data         = null;

            if (resp.Success)
            {
                try
                {
                    fsResult r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }

                    object obj = translations;
                    r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                    if (!r.Succeeded)
                    {
                        throw new WatsonException(r.FormattedMessages);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("Natural Language Classifier", "GetTranslation Exception: {0}", e.ToString());
                    resp.Success = false;
                }
            }

            string customData = ((TranslateReq)req).Data;

            if (((TranslateReq)req).Callback != null)
            {
                ((TranslateReq)req).Callback(resp.Success ? translations : null, !string.IsNullOrEmpty(customData) ? customData : data.ToString());
            }
        }
Exemplo n.º 23
0
    public static void ReadConfigAsJson(Type type, string folder)
    {
        if (readTypes.Contains(type))
        {
            return;
        }
        else
        {
            readTypes.Add(type);
        }
        var exportFields = ClassFieldFilter.GetConfigFieldInfo(type);

        if (exportFields.Count == 0)
        {
            return;
        }
        foreach (var field in exportFields)
        {
            var file = Path.Combine(folder, field.Name + ".json");
            if (!File.Exists(file))
            {
                Debug.LogWarningFormat("Json file {0} not found", field.Name);
                continue;
            }
            FileStream    fs   = File.Open(file, FileMode.Open);
            StringBuilder sb   = new StringBuilder();
            byte[]        b    = new byte[1024];
            UTF8Encoding  temp = new UTF8Encoding(true);

            while (fs.Read(b, 0, b.Length) > 0)
            {
                sb.Append(temp.GetString(b));
            }
            fs.Close();

            fsData   data;
            fsResult res = fsJsonParser.Parse(sb.ToString(), out data);
            if (res.Failed)
            {
                Debug.LogWarningFormat("Json file {0} parsed error {1}", field.Name, res.FormattedMessages);
                continue;
            }

            var value = field.GetValue(null);
            _serializer.TryDeserialize(data, field.FieldType, ref value).AssertSuccess();
            field.SetValue(null, value);
        }
    }
Exemplo n.º 24
0
        public void ImportLegacyCycle() {
            fsData data = fsData.CreateDictionary();
            data.AsDictionary["SourceId"] = new fsData("0");
            data.AsDictionary["Data"] = fsData.CreateDictionary();
            data.AsDictionary["Data"].AsDictionary["Value"] = new fsData(3);
            data.AsDictionary["Data"].AsDictionary["Ref"] = fsData.CreateDictionary();
            data.AsDictionary["Data"].AsDictionary["Ref"].AsDictionary["ReferenceId"] = new fsData("0");

            UnityEngine.Debug.Log(fsJsonPrinter.PrettyJson(data));

            Cycle c = null;
            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TryDeserialize(data, ref c).Succeeded);
            Assert.AreEqual(3, c.Value);
            Assert.AreEqual(c, c.Ref);
        }
Exemplo n.º 25
0
    /// <summary>
    /// Gets all users from the Firebase Database
    /// </summary>
    /// <param name="callback"> What to do after all users are downloaded successfully </param>
    public static void GetUsers(GetUsersCallback callback)
    {
        RestClient.Get($"{databaseURL}users.json").Then(response =>
        {
            var responseJson = response.Text;

            // Using the FullSerializer library: https://github.com/jacobdufault/fullserializer
            // to serialize more complex types (a Dictionary, in this case)
            var data            = fsJsonParser.Parse(responseJson);
            object deserialized = null;
            serializer.TryDeserialize(data, typeof(Dictionary <string, User>), ref deserialized);

            var users = deserialized as Dictionary <string, User>;
            callback(users);
        });
    }
Exemplo n.º 26
0
    protected fsResult DeserializeMember <T>(Dictionary <string, fsData> data, Type overrideConverterType, string name, out T value)
    {
        fsData memberData;

        if (data.TryGetValue(name, out memberData) == false)
        {
            value = default(T);
            return(fsResult.Fail("Unable to find member \"" + name + "\""));
        }

        object storage = null;
        var    result  = Serializer.TryDeserialize(memberData, typeof(T), overrideConverterType, ref storage);

        value = (T)storage;
        return(result);
    }
Exemplo n.º 27
0
 /// <returns>The runtime value of the argument</returns>
 public object UnpackParameter()
 {
     if (argumentValue == null)
     {
         if (isUnityObject)
         {
             argumentValue = objectArgument;
         }
         else
         {
             var parsed = fsJsonParser.Parse(paramAsJson);
             _serializer.TryDeserialize(parsed, argumentType.SystemType, ref argumentValue).AssertSuccess();
         }
     }
     return(argumentValue);
 }
Exemplo n.º 28
0
        public void TestClassWithNoPublicDefaultConstructor()
        {
            var serialized = fsData.CreateDictionary();

            serialized.AsDictionary["a"] = new fsData(3);

            var serializer = new fsSerializer();

            ClassWithNoPublicDefaultConstructor result = null;

            Assert.IsTrue(serializer.TryDeserialize(serialized, ref result).Succeeded);

            // We expect the original value, but not for the constructor to have been called.
            Assert.AreEqual(3, result.a);
            Assert.IsFalse(result.constructorCalled);
        }
Exemplo n.º 29
0
    public static T Deserialize <T>(string serializedState)
    {
        // step 1: parse the JSON data
        fsData data = fsJsonParser.Parse(serializedState);

        // step 2: deserialize the data
        object deserialized = null;

        _serializer.TryDeserialize(data, typeof(T), ref deserialized).AssertSuccessWithoutWarnings();

        if (deserialized != null && deserialized is T)
        {
            return((T)deserialized);
        }
        return(default(T));
    }
Exemplo n.º 30
0
    private GeoJsonRoot ParseData(string geoJsonData)
    {
        fsSerializer serializer = new fsSerializer();

        serializer.Config.GetJsonNameFromMemberName = GetJsonNameFromMemberName;
        serializer.AddConverter(new Converter());
        fsData data = null;

        data = fsJsonParser.Parse(geoJsonData);

        // step 2: deserialize the data
        GeoJsonRoot deserialized = null;

        serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
        return(deserialized);
    }
Exemplo n.º 31
0
        public void MultistageMigration()
        {
            var serializer = new fsSerializer();

            var modelV1 = new VersionedModelV1 {
                a = 3
            };
            fsData serialized;

            serializer.TrySerialize(modelV1, out serialized).AssertSuccessWithoutWarnings();

            var modelV2 = new VersionedModelV2();

            serializer.TryDeserialize(serialized, ref modelV2).AssertSuccessWithoutWarnings();
            Assert.AreEqual(modelV1.a, modelV2.b);
        }
Exemplo n.º 32
0
        public void MultistageMigration()
        {
            var serializer = new fsSerializer();

            var model_v1 = new VersionedModel_v1 {
                A = 3
            };
            fsData serialized;

            serializer.TrySerialize(model_v1, out serialized).AssertSuccessWithoutWarnings();

            var model_v2 = new VersionedModel_v2();

            serializer.TryDeserialize(serialized, ref model_v2).AssertSuccessWithoutWarnings();
            Assert.AreEqual(model_v1.A, model_v2.B);
        }
Exemplo n.º 33
0
        public void MultistageMigration()
        {
            var serializer = new fsSerializer();

            var model_v1 = new VersionedModel_v1 {
                A = 3
            };
            fsData serialized;

            Assert.IsTrue(serializer.TrySerialize(model_v1, out serialized).Succeeded);

            var model_v2 = new VersionedModel_v2();

            Assert.IsTrue(serializer.TryDeserialize(serialized, ref model_v2).Succeeded);
            Assert.AreEqual(model_v1.A, model_v2.B);
        }
        public void TestWarningsFromDirectConverters()
        {
            fsData data;
            var    serializer = new fsSerializer();

            fsResult result = serializer.TrySerialize(new WarningModel(), out data);

            Assert.AreEqual(1, result.RawMessages.Count());
            Assert.AreEqual("Warning", result.RawMessages.First());

            WarningModel model = null;

            result = serializer.TryDeserialize(data, ref model);
            Assert.AreEqual(1, result.RawMessages.Count());
            Assert.AreEqual("Warning", result.RawMessages.First());
        }
Exemplo n.º 35
0
        public void VerifyFloatSerializationDoesNotHaveJitter()
        {
            var serializer = new fsSerializer();

            // We serialize w/o jitter
            fsData data;

            serializer.TrySerialize(0.1f, out data).AssertSuccessWithoutWarnings();
            Assert.AreEqual("0.1", fsJsonPrinter.PrettyJson(data));

            // We deserialize w/o jitter.
            float deserialized = 0f;

            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(0.1f, deserialized);
        }
Exemplo n.º 36
0
    public void LoadResultsData(string uid)
    {
        participantes.Clear();
        //string url = "capitulos_participantes/" + uid + "/participantes";
        //Events.OnGetServerData(url, OnReady, "score", 100);
        //print("LoadData url: " + url);

        string url = Data.Instance.firebaseAuthManager.databaseURL + "/capitulos_participantes/" + uid + "/participantes.json?orderBy=\"score\"&limitToLast=100&auth=" + Data.Instance.userData.token;

        print("LoadResultsData _____" + url);

        RestClient.Get(url).Then(response =>
        {
            //   string username = user.username;
            fsSerializer serializer = new fsSerializer();
            fsData data             = fsJsonParser.Parse(response.Text);
            Dictionary <string, Participante> results = null;
            serializer.TryDeserialize(data, ref results);

            foreach (Participante d in results.Values)
            {
                // print("score: " + d.score);
                int totalCorrect       = 0;
                float totalTimeCorrect = 0;
                foreach (Results r in d.respuestas)
                {
                    if (r.respuesta == 0)
                    {
                        totalTimeCorrect += r.timer;
                        totalCorrect++;
                    }
                }
                d.totalCorrect     = totalCorrect;
                d.totalTimeCorrect = totalTimeCorrect;
                participantes.Add(d);
            }
            participantes = GetOrderByScoreGeneral();

            //foreach (Participante d in participantes)
            //{
            //    print("_________score2: " + d.score);
            //}
        }).Catch(error =>
        {
            Debug.Log(error);
        });
    }
Exemplo n.º 37
0
    private void OnMessage(object resp, Dictionary <string, object> customData)
    {
        fsData   fsdata = null;
        fsResult r      = _serializer.TrySerialize(resp.GetType(), resp, out fsdata);

        if (!r.Succeeded)
        {
            throw new WatsonException(r.FormattedMessages);
        }

        //  Convert fsdata to MessageResponse
        MessageResponse messageResponse = new MessageResponse();
        object          obj             = messageResponse;

        r = _serializer.TryDeserialize(fsdata, obj.GetType(), ref obj);
        if (!r.Succeeded)
        {
            throw new WatsonException(r.FormattedMessages);
        }

        //  Set context for next round of messaging
        object _tempContext = null;

        (resp as Dictionary <string, object>).TryGetValue("context", out _tempContext);

        if (_tempContext != null)
        {
            _context = _tempContext as Dictionary <string, object>;
        }
        else
        {
            Log.Debug("ExampleConversation.OnMessage()", "Failed to get context");
        }

        //if we get a response, do something with it (find the intents, output text, etc.)
        if (resp != null && (messageResponse.intents.Length > 0 || messageResponse.entities.Length > 0))
        {
            string intent = messageResponse.intents[0].intent;
            foreach (string WatsonResponse in messageResponse.output.text)
            {
                outputText += WatsonResponse + " ";
            }
            Debug.Log("Intent/Output Text: " + intent + "/" + outputText);
            CallTTS(outputText);
            outputText = "";
        }
    }
Exemplo n.º 38
0
        private void ConvertDocumentResponse(RESTConnector.Request req, RESTConnector.Response resp)
        {
            ConvertedDocument response = new ConvertedDocument();
            fsData            data     = null;
            fsResult          r;

            if (resp.Success)
            {
                if ((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.Answerunits)
                {
                    try
                    {
                        r = fsJsonParser.Parse(Encoding.UTF8.GetString(resp.Data), out data);
                        if (!r.Succeeded)
                        {
                            throw new WatsonException(r.FormattedMessages);
                        }

                        object obj = response;
                        r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
                        if (!r.Succeeded)
                        {
                            throw new WatsonException(r.FormattedMessages);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Error("DocumentConversion", "ConvertDocumentResponse Exception: {0}", e.ToString());
                        resp.Success = false;
                    }
                }
                else if ((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.NormalizedHtml)
                {
                    response.htmlContent = System.Text.Encoding.Default.GetString(resp.Data);
                }
                else if ((req as ConvertDocumentRequest).ConversionTarget == ConversionTarget.NormalizedText)
                {
                    response.textContent = System.Text.Encoding.Default.GetString(resp.Data);
                }
            }

            if (((ConvertDocumentRequest)req).Callback != null)
            {
                ((ConvertDocumentRequest)req).Callback(resp.Success ? response : null, ((ConvertDocumentRequest)req).Data);
            }
        }
Exemplo n.º 39
0
        public void VerifyLargeDoubleRoundTrips()
        {
            double valueToTest = 500000000000000000.0;

            var serializer = new fsSerializer();

            fsData data;

            serializer.TrySerialize(valueToTest, out data).AssertSuccessWithoutWarnings();

            Assert.AreEqual(valueToTest.ToString(System.Globalization.CultureInfo.InvariantCulture), fsJsonPrinter.PrettyJson(data));

            double deserialized = 0f;

            serializer.TryDeserialize(data, ref deserialized).AssertSuccessWithoutWarnings();
            Assert.AreEqual(valueToTest, deserialized);
        }
Exemplo n.º 40
0
    private static Dictionary <string, TilemapLayer> DeserializeJson()
    {
        Dictionary <string, TilemapLayer> deserializedLayers = new Dictionary <string, TilemapLayer>();
        TextAsset asset = Resources.Load(Path.Combine("metadata", SceneManager.GetActiveScene().name)) as TextAsset;

        if (asset != null)
        {
            fsData       data       = fsJsonParser.Parse(asset.text);
            fsSerializer serializer = new fsSerializer();
            serializer.TryDeserialize(data, ref deserializedLayers).AssertSuccessWithoutWarnings();
        }
        else
        {
            throw new FileNotFoundException("Put your map json to /Assets/Resources/metadata/%mapname%.json!");
        }
        return(deserializedLayers);
    }
Exemplo n.º 41
0
        // -------------------------------------------------------------------------------

        public void Load()
        {
            if (GraphData == null)
            {
                if (SerialisedGraph != "")
                {
                    fsData parsedData        = fsJsonParser.Parse(SerialisedGraph);
                    object deserializedGraph = null;
                    mSerialiser.TryDeserialize(parsedData, typeof(GraphData), ref deserializedGraph).AssertSuccessWithoutWarnings();
                    GraphData = (GraphData)deserializedGraph;
                }
                else
                {
                    GraphData = new GraphData();
                }
            }
        }
        public void VerifyConversion() {
            MyConverter.DidDeserialize = false;
            MyConverter.DidSerialize = false;

            var serializer = new fsSerializer();

            fsData result;
            serializer.TrySerialize(new MyModel(), out result);
            Assert.IsTrue(MyConverter.DidSerialize);
            Assert.IsFalse(MyConverter.DidDeserialize);

            MyConverter.DidSerialize = false;
            object resultObj = null;
            serializer.TryDeserialize(result, typeof (MyModel), ref resultObj);
            Assert.IsFalse(MyConverter.DidSerialize);
            Assert.IsTrue(MyConverter.DidDeserialize);
        }
        public void VerifyPropertyConverter() {
            MyConverter.DidDeserialize = false;
            MyConverter.DidSerialize = false;

            var serializer = new fsSerializer();

            // Make sure to set |a| to some value, otherwise we will short-circuit serialize it to null.
            fsData result;
            serializer.TrySerialize(new ModelWithPropertyConverter { a = 3 }, out result);
            Assert.IsTrue(MyConverter.DidSerialize);
            Assert.IsFalse(MyConverter.DidDeserialize);

            MyConverter.DidSerialize = false;
            object resultObj = null;
            serializer.TryDeserialize(result, typeof(ModelWithPropertyConverter), ref resultObj);
            Assert.IsFalse(MyConverter.DidSerialize);
            Assert.IsTrue(MyConverter.DidDeserialize);
        }
        public void TestOptIn() {
            var model1 = new SimpleModel {
                Serialized0 = 1,
                Serialized1 = 1,
                Serialized2 = 1,
                NotSerialized0 = 1
            };

            fsData data;

            var serializer = new fsSerializer();
            Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded);

            SimpleModel model2 = null;
            Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded);

            Debug.Log(fsJsonPrinter.PrettyJson(data));

            Assert.AreEqual(model1.Serialized0, model2.Serialized0);
            Assert.AreEqual(model1.Serialized1, model2.Serialized1);
            Assert.AreEqual(model1.Serialized2, model2.Serialized2);
            Assert.AreEqual(0, model2.NotSerialized0);
        }
Exemplo n.º 45
0
    public object Deserialize(Stream fileStream, Type type)
    {
        var bytes = new byte[fileStream.Length];
        var count = fileStream.Read(bytes, 0, bytes.Length);

        var jsonString = System.Text.Encoding.UTF8.GetString(bytes, 0, count);
        var data = fsJsonParser.Parse(jsonString);

        var serializer = new fsSerializer();
        object refObject = null;

        serializer.TryDeserialize(data, type, ref refObject);
        return refObject;
    }
Exemplo n.º 46
0
        public void MultistageMigration() {
            var serializer = new fsSerializer();

            var model_v1 = new VersionedModel_v1 {
                A = 3
            };
            fsData serialized;
            Assert.IsTrue(serializer.TrySerialize(model_v1, out serialized).Succeeded);

            var model_v2 = new VersionedModel_v2();
            Assert.IsTrue(serializer.TryDeserialize(serialized, ref model_v2).Succeeded);
            Assert.AreEqual(model_v1.A, model_v2.B);
        }
Exemplo n.º 47
0
        public void MultistageMigration() {
            var serializer = new fsSerializer();

            var model_v1 = new VersionedModel_v1 {
                A = 3
            };
            fsData serialized;
            serializer.TrySerialize(model_v1, out serialized).AssertSuccessWithoutWarnings();

            var model_v2 = new VersionedModel_v2();
            serializer.TryDeserialize(serialized, ref model_v2).AssertSuccessWithoutWarnings();
            Assert.AreEqual(model_v1.A, model_v2.B);
        }