/// <summary> /// Attempts to load saved mod settings from file and updates loaded mods. /// </summary> /// <returns>True if settings loaded successfully.</returns> public static bool LoadModSettings() { fsResult result = new fsResult(); try { string oldFilepath = Path.Combine(ModManager.Instance.ModDirectory, MODCONFIGFILENAME); string filePath = Path.Combine(ModManager.Instance.ModDataDirectory, "Mods.json"); Directory.CreateDirectory(ModManager.Instance.ModDataDirectory); if (File.Exists(oldFilepath)) { MoveOldConfigFile(oldFilepath, filePath); } if (!File.Exists(filePath)) { return(false); } var serializedData = File.ReadAllText(filePath); if (string.IsNullOrEmpty(serializedData)) { return(false); } List <Mod> temp = new List <Mod>(); fsData data = fsJsonParser.Parse(serializedData); result = _serializer.TryDeserialize <List <Mod> >(data, ref temp); if (result.Failed || temp.Count <= 0) { return(false); } foreach (Mod _mod in temp) { if (ModManager.Instance.GetModIndex(_mod.Title) >= 0) { Mod mod = ModManager.Instance.GetMod(_mod.Title); if (mod == null) { continue; } mod.Enabled = _mod.Enabled; mod.LoadPriority = _mod.LoadPriority; ModManager.Instance.mods[ModManager.Instance.GetModIndex(_mod.Title)] = mod; } } return(true); } catch (Exception ex) { Debug.LogError(string.Format("Error trying to load mod settings: {0}", ex.Message)); return(false); } }
private fsResult SerializeImportedComponents(GameObject gameObject, out fsData fsData) { fsData = fsData.Null; fsResult fsResult = fsResult.Success; // Get and destroy only imported components List <fsData> components = null; foreach (var component in gameObject.GetComponents <Component>().Where(x => x)) { if (GetCustomAttribute(component.GetType(), typeof(ImportedComponentAttribute)) != null) { fsData componentData; if ((fsResult += Serializer.TrySerialize(component, out componentData)).Failed) { return(fsResult); } if ((fsResult += ValidateComponentData(componentData)).Failed) { return(fsResult); } (components ?? (components = new List <fsData>())).Add(componentData); UnityEngine.Object.DestroyImmediate(component, true); } } // Iterate children Dictionary <string, fsData> children = null; if (gameObject.transform.childCount > 0) { children = new Dictionary <string, fsData>(); for (int i = 0; i < gameObject.transform.childCount; i++) { Transform transform = gameObject.transform.GetChild(i); fsData childData; if ((fsResult += SerializeImportedComponents(transform.gameObject, out childData)).Failed) { return(fsResult); } if (!childData.IsNull) { children.Add(transform.gameObject.name, childData); } } } // Make fsData only if there are imported components if (components != null || children != null) { fsData = new fsData(new Dictionary <string, fsData> { { "Components", new fsData(components) }, { "Children", new fsData(children) } }); } return(fsResult); }
protected override fsResult DoSerialize(LayerMask model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "value", model.value); return(result); }
private IEnumerator GetCredentials() { //Credentials credentials = new Credentials(_username, _password, _url); #region Get Credentials via internal service VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["conversation"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); //_workspaceId = credential.WorkspaceId.ToString(); #endregion // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); _service = new Assistant(credentials); _service.VersionDate = _versionDate; Runnable.Run(Examples()); }
protected override fsResult DoSerialize(GUIStyleState model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "background", model.background); result += SerializeMember(serialized, null, "textColor", model.textColor); return(result); }
protected override fsResult DoSerialize(Gradient model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "alphaKeys", model.alphaKeys); result += SerializeMember(serialized, null, "colorKeys", model.colorKeys); return(result); }
private static bool EmitFailWarning(fsResult result) { if (fiSettings.EmitWarnings && result.RawMessages.Any()) { Debug.LogWarning(result.FormattedMessages); } return(result.Failed); }
protected override fsResult DoSerialize(Bounds model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "center", model.center); result += SerializeMember(serialized, null, "size", model.size); return(result); }
private static void DeserializeJson(fsSerializer serializer, string json, ref object instance, bool forceReflected) { using (ProfilingUtility.SampleBlock("DeserializeJson")) { fsResult result = DeserializeJsonUtil(serializer, json, ref instance, forceReflected); HandleResult("Deserialization", result, instance as UnityObject); } }
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { Type objectType = (Type)instance; fsResult result = fsResult.Success; instance = JsonUtility.FromJson(fsJsonPrinter.CompressedJson(data), objectType); return(result); }
// Token: 0x06000448 RID: 1096 RVA: 0x0001BAEC File Offset: 0x00019CEC public override fsResult TryDeserialize(fsData data, ref object instance_, Type storageType) { IEnumerable enumerable = (IEnumerable)instance_; fsResult fsResult = fsResult.Success; fsResult fsResult2; fsResult = (fsResult2 = fsResult + base.CheckType(data, fsDataType.Array)); if (fsResult2.Failed) { return(fsResult); } Type elementType = fsIEnumerableConverter.GetElementType(storageType); MethodInfo addMethod = fsIEnumerableConverter.GetAddMethod(storageType); MethodInfo flattenedMethod = storageType.GetFlattenedMethod("get_Item"); MethodInfo flattenedMethod2 = storageType.GetFlattenedMethod("set_Item"); if (flattenedMethod2 == null) { fsIEnumerableConverter.TryClear(storageType, enumerable); } int num = fsIEnumerableConverter.TryGetExistingSize(storageType, enumerable); List <fsData> asList = data.AsList; for (int i = 0; i < asList.Count; i++) { fsData data2 = asList[i]; object obj = null; if (flattenedMethod != null && i < num) { obj = flattenedMethod.Invoke(enumerable, new object[] { i }); } fsResult result = this.Serializer.TryDeserialize(data2, elementType, ref obj); fsResult.AddMessages(result); if (!result.Failed) { if (flattenedMethod2 != null && i < num) { flattenedMethod2.Invoke(enumerable, new object[] { i, obj }); } else { addMethod.Invoke(enumerable, new object[] { obj }); } } } return(fsResult); }
/* * Handler for a successful response from Watson Assistant */ 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); } // Convert response to Dictionart Dictionary <string, object> resp = (response as Dictionary <string, object>); // Set context for next round of messaging object _tempContext = null; resp.TryGetValue("context", out _tempContext); if (_tempContext != null) { _context = _tempContext as Dictionary <string, object>; } else { Log.Debug("ExampleAssistant.OnMessage()", "Failed to get context"); } string intent = GetIntentFromResponse(response); List <object> entities = GetEntitiesFromResponse(response); string dialog = ""; // not all interactions require text answer from Watson dialog = GetDialogFromResponse(response); OnAssistantResponseEventArgs args = new OnAssistantResponseEventArgs(); args.Input = lastInput; args.Intent = intent; args.Entities = entities; args.Dialog = dialog; AssistantResponded(this, args); }
public override fsResult TryDeserialize(fsData data, ref object instance_, Type storageType) { IEnumerable instance = (IEnumerable)instance_; fsResult result = fsResult.Success; if ((result += CheckType(data, fsDataType.Array)).Failed) { return(result); } // For general strategy, instance may already have items in it. We // will try to deserialize into the existing element. Type elementStorageType = GetElementType(storageType); MethodInfo addMethod = GetAddMethod(storageType); MethodInfo getMethod = storageType.GetFlattenedMethod("get_Item"); MethodInfo setMethod = storageType.GetFlattenedMethod("set_Item"); if (setMethod == null) { TryClear(storageType, instance); } int existingSize = TryGetExistingSize(storageType, instance); List <fsData> serializedList = data.AsList; for (int i = 0; i < serializedList.Count; ++i) { fsData itemData = serializedList[i]; object itemInstance = null; if (getMethod != null && i < existingSize) { itemInstance = getMethod.Invoke(instance, new object[] { i }); } // note: We don't fail the entire deserialization even if the // item failed fsResult itemResult = Serializer.TryDeserialize(itemData, elementStorageType, ref itemInstance); result.AddMessages(itemResult); if (itemResult.Failed) { continue; } if (setMethod != null && i < existingSize) { setMethod.Invoke(instance, new[] { i, itemInstance }); } else { addMethod.Invoke(instance, new[] { itemInstance }); } } return(result); }
protected fsResult Override(fsData defaultData, fsData targetData, out fsData outData) { fsResult success = fsResult.Success; outData = fsData.CreateDictionary(); fsResult result2 = success += base.CheckType(defaultData, fsDataType.Object); if (!result2.Failed) { fsResult result3 = success += base.CheckType(targetData, fsDataType.Object); if (result3.Failed) { return(success); } Dictionary <string, fsData> asDictionary = defaultData.AsDictionary; Dictionary <string, fsData> dictionary2 = targetData.AsDictionary; Dictionary <string, fsData> dictionary3 = outData.AsDictionary; foreach (string str in asDictionary.Keys) { fsData data = asDictionary[str]; fsData data2 = null; dictionary2.TryGetValue(str, out data2); if (data.IsDictionary && (data2 != null)) { fsData data3; fsResult result4 = success += base.CheckType(data2, fsDataType.Object); if (result4.Failed) { return(success); } success += this.Override(data, data2, out data3); dictionary3.Add(str, data3); } else if ((data2 == null) || (data.Type == data2.Type)) { dictionary3.Add(str, (data2 == null) ? data : data2); } else if (((data.Type == fsDataType.Double) && (data2.Type == fsDataType.Int64)) || ((data.Type == fsDataType.Int64) && (data2.Type == fsDataType.Double))) { dictionary3.Add(str, data2); } else { success += fsResult.Fail("override value type doesn't match: " + str); } } foreach (string str2 in dictionary2.Keys) { if (!dictionary3.ContainsKey(str2)) { dictionary3.Add(str2, dictionary2[str2]); } } } return(success); }
private fsResult RunParse(out fsData data) { SkipSpace(); if (HasValue() == false) { data = default(fsData); return(MakeFailure("Unexpected end of input")); } switch (Character()) { case 'I': // Infinity case 'N': // NaN case '.': case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return(TryParseNumber(out data)); case '"': { string str; fsResult fail = TryParseString(out str); if (fail.Failed) { data = null; return(fail); } data = new fsData(str); return(fsResult.Success); } case '[': return(TryParseArray(out data)); case '{': return(TryParseObject(out data)); case 't': return(TryParseTrue(out data)); case 'f': return(TryParseFalse(out data)); case 'n': return(TryParseNull(out data)); default: data = null; return(MakeFailure("unable to parse; invalid token \"" + Character() + "\"")); } }
protected override fsResult DoSerialize(AnimationCurve model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "keys", model.keys); result += SerializeMember(serialized, null, "preWrapMode", model.preWrapMode); result += SerializeMember(serialized, null, "postWrapMode", model.postWrapMode); return(result); }
public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) { fsResult result = fsResult.Success; // Verify that we actually have an Object if ((result += CheckType(data, fsDataType.Object)).Failed) { return(result); } fsMetaType metaType = fsMetaType.Get(Serializer.Config, storageType); metaType.EmitAotData(/*throwException:*/ false); for (int i = 0; i < metaType.Properties.Length; ++i) { fsMetaProperty property = metaType.Properties[i]; if (property.CanWrite == false) { continue; } fsData propertyData; if (data.AsDictionary.TryGetValue(property.JsonName, out propertyData)) { object deserializedValue = null; // We have to read in the existing value, since we need to // support partial deserialization. However, this is bad for // perf. // TODO: Find a way to avoid this call when we are not doing // a partial deserialization Maybe through a new // property, ie, Serializer.IsPartialSerialization, // which just gets set when starting a new // serialization? We cannot pipe the information // through CreateInstance unfortunately. if (property.CanRead) { deserializedValue = property.Read(instance); } fsResult itemResult = Serializer.TryDeserialize(propertyData, property.StorageType, property.OverrideConverterType, ref deserializedValue); result.AddMessages(itemResult); if (itemResult.Failed) { continue; } property.Write(instance, deserializedValue); } } return(result); }
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(); Test(_lastIntent != intent); _lastIntent = intent; //messageResponse.Intents != _lastIntent; //_lastIntent = messageResponse.Intents; _messageTested = true; }
protected override fsResult DoDeserialize(Dictionary <string, fsData> data, ref LayerMask model) { fsResult result = fsResult.Success; int t0 = model.value; result += DeserializeMember(data, null, "value", out t0); model.value = t0; return(result); }
protected override fsResult DoSerialize(RectOffset model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "bottom", model.bottom); result += SerializeMember(serialized, null, "left", model.left); result += SerializeMember(serialized, null, "right", model.right); result += SerializeMember(serialized, null, "top", model.top); return(result); }
private void OnConversationResponse(object resp, Dictionary<string, object> customData) { if (resp != null) { // Convert resp to fsdata 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); // remember the context for the next message object tempContext = null; Dictionary<string, object> respAsDict = resp as Dictionary<string, object>; if (respAsDict != null) { respAsDict.TryGetValue("context", out tempContext); } if (tempContext != null) _context = tempContext as Dictionary<string, object>; else Debug.LogError("Failed to get context"); if (ConversationResponse != null) { string respText = ""; string intent = ""; float confidence = 0f; if (messageResponse.output.text.Length > 0) { respText = messageResponse.output.text[0]; } if (messageResponse.intents.Length > 0) { intent = messageResponse.intents[0].intent; confidence = messageResponse.intents[0].confidence; } ConversationResponse(respText, intent, confidence); } } }
/// <summary> /// Deserialize a TextAsset from a mod. /// </summary> private static bool TryDeserialize <T>(Mod mod, string assetName, ref T instance) { var textAsset = mod.GetAsset <TextAsset>(assetName); fsResult fsResult = ModManager._serializer.TryDeserialize(fsJsonParser.Parse(textAsset.text), ref instance); if (fsResult.Failed) { Debug.LogErrorFormat("{0}: Failed to import {1}:\n{2}", mod.Title, assetName, fsResult.FormattedMessages); } return(fsResult.Succeeded); }
protected override fsResult DoSerialize(Rect model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "xMin", model.xMin); result += SerializeMember(serialized, null, "yMin", model.yMin); result += SerializeMember(serialized, null, "xMax", model.xMax); result += SerializeMember(serialized, null, "yMax", model.yMax); return(result); }
private static fsData Parse(string json) { fsData data; fsResult fail = fsJsonParser.Parse(json, out data); if (fail.Failed) { Assert.Fail(fail.FormattedMessages); } return(data); }
// Token: 0x06000462 RID: 1122 RVA: 0x0001C2A0 File Offset: 0x0001A4A0 public override fsResult TryDeserialize(fsData storage, ref object instance, Type storageType) { fsResult fsResult = fsResult.Success; if (fsPrimitiveConverter.UseBool(storageType)) { fsResult fsResult2; fsResult = (fsResult2 = fsResult + base.CheckType(storage, fsDataType.Boolean)); if (fsResult2.Succeeded) { instance = storage.AsBool; } return(fsResult); } if (fsPrimitiveConverter.UseDouble(storageType) || fsPrimitiveConverter.UseInt64(storageType)) { if (storage.IsDouble) { instance = Convert.ChangeType(storage.AsDouble, storageType); } else if (storage.IsInt64) { instance = Convert.ChangeType(storage.AsInt64, storageType); } else { if (!this.Serializer.Config.Serialize64BitIntegerAsString || !storage.IsString || (storageType != typeof(long) && storageType != typeof(ulong))) { return(fsResult.Fail(string.Concat(new object[] { base.GetType().Name, " expected number but got ", storage.Type, " in ", storage }))); } instance = Convert.ChangeType(storage.AsString, storageType); } return(fsResult.Success); } if (fsPrimitiveConverter.UseString(storageType)) { fsResult fsResult3; fsResult = (fsResult3 = fsResult + base.CheckType(storage, fsDataType.String)); if (fsResult3.Succeeded) { instance = storage.AsString; } return(fsResult); } return(fsResult.Fail(base.GetType().Name + ": Bad data; expected bool, number, string, but got " + storage)); }
protected override fsResult DoSerialize(Keyframe model, Dictionary <string, fsData> serialized) { fsResult result = fsResult.Success; result += SerializeMember(serialized, null, "time", model.time); result += SerializeMember(serialized, null, "value", model.value); result += SerializeMember(serialized, null, "tangentMode", model.tangentMode); result += SerializeMember(serialized, null, "inTangent", model.inTangent); result += SerializeMember(serialized, null, "outTangent", model.outTangent); return(result); }
private static byte[] FullSerialise(object obj) { fsData data; fsResult result = fullSerialiser.TrySerialize(obj, out data); if (result.Failed) { throw new Exception("Serialisation failed on " + obj.GetType() + "\n\n" + result.FormattedMessages); } return(Encoding.ASCII.GetBytes(fsJsonPrinter.CompressedJson(data))); }
public static void GetObjectFromJsonFile <T>(string filename, ref T obj) { fsData json_data; fsResult res = fsJsonParser.Parse(GetStringFromFile(filename), out json_data); if (res.Failed) { Log.Error("Error parse json from file: {0}", filename); return; } _serializer.TryDeserialize <T>(json_data, ref obj).AssertSuccess(); }
private static void HandleResult(string label, fsResult result, UnityObject context = null) { result.AssertSuccess(); if (result.HasWarnings) { foreach (var warning in result.RawMessages) { Debug.LogWarning($"[{label}] {warning}\n", context); } } }
private fsData ParseTextData(string textData) { fsData data = null; fsResult parseResult = fsJsonParser.Parse(textData, out data); if (parseResult.Succeeded) { return(data); } Debug.LogError(parseResult.FormattedMessages); return(null); }