Esempio n. 1
0
        public override fsResult TryDeserialize(fsData storage, ref object instance, Type storageType) {
            var result = fsResult.Success;

            if (UseBool(storageType)) {
                if ((result += CheckType(storage, fsDataType.Boolean)).Succeeded) {
                    instance = storage.AsBool;
                }
                return result;
            }

            if (UseDouble(storageType) || UseInt64(storageType)) {
                if (storage.IsDouble) {
                    instance = Convert.ChangeType(storage.AsDouble, storageType);
                }
                else if (storage.IsInt64) {
                    instance = Convert.ChangeType(storage.AsInt64, storageType);
                }
                else {
                    return fsResult.Fail(GetType().Name + " expected number but got " + storage.Type + " in " + storage);
                }
                return fsResult.Success;
            }

            if (UseString(storageType)) {
                if ((result += CheckType(storage, fsDataType.String)).Succeeded) {
                    instance = storage.AsString;
                }
                return result;
            }

            return fsResult.Fail(GetType().Name + ": Bad data; expected bool, number, string, but got " + storage);
        }
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            var result = fsResult.Success;

            // Verify that we actually have an Object
            if ((result += CheckType(data, fsDataType.Object)).Failed) {
                return result;
            }

            fsMetaType metaType = fsMetaType.Get(storageType);

            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.Name, out propertyData)) {
                    object deserializedValue = null;

                    var itemResult = Serializer.TryDeserialize(propertyData, property.StorageType, ref deserializedValue);
                    result.AddMessages(itemResult);
                    if (itemResult.Failed) continue;

                    property.Write(instance, deserializedValue);
                }
            }

            return result;
        }
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            var instanceType = instance.GetType();

            if (fsConfig.Serialize64BitIntegerAsString && (instanceType == typeof(Int64) || instanceType == typeof(UInt64))) {
                serialized = new fsData((string)Convert.ChangeType(instance, typeof(string)));
                return fsResult.Success;
            }

            if (UseBool(instanceType)) {
                serialized = new fsData((bool)instance);
                return fsResult.Success;
            }

            if (UseInt64(instanceType)) {
                serialized = new fsData((Int64)Convert.ChangeType(instance, typeof(Int64)));
                return fsResult.Success;
            }

            if (UseDouble(instanceType)) {
                serialized = new fsData((double)Convert.ChangeType(instance, typeof(double)));
                return fsResult.Success;
            }

            if (UseString(instanceType)) {
                serialized = new fsData((string)Convert.ChangeType(instance, typeof(string)));
                return fsResult.Success;
            }

            serialized = null;
            return fsResult.Fail("Unhandled primitive type " + instance.GetType());
        }
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            var database = Serializer.Context.Get<List<UnityEngine.Object>>();
            var o = instance as UnityEngine.Object;

            var index = -1;
            for (var i = 0; i < database.Count; i++){
                if (ReferenceEquals(database[i], o)){
                    index = i;
                    break;
                }
            }

            //this is done to avoid serializing 0 because it's default value of int and will not be printed,
            //which is done for performance. Thus we always start from index 1.
            if (database.Count == 0){
                database.Add(null);
            }

            if (index <= 0){
                index = database.Count;
                database.Add(o);
            }

            serialized = new fsData(index);
            return fsResult.Success;
        }
        public override fsResult TrySerialize(object instance_, out fsData serialized, Type storageType) {
            var instance = (IEnumerable)instance_;
            var result = fsResult.Success;

            Type elementType = GetElementType(storageType);

            serialized = fsData.CreateList(HintSize(instance));
            var serializedList = serialized.AsList;

            foreach (object item in instance) {
                fsData itemData;

                // note: We don't fail the entire deserialization even if the item failed
                var itemResult = Serializer.TrySerialize(elementType, item, out itemData);
                result.AddMessages(itemResult);
                if (itemResult.Failed) continue;

                serializedList.Add(itemData);
            }

            // Stacks iterate from back to front, which means when we deserialize we will deserialize
            // the items in the wrong order, so the stack will get reversed.
            if (IsStack(instance.GetType())) {
                serializedList.Reverse();
            }

            return result;
        }
        public override void OnBeforeDeserializeAfterInstanceCreation(Type storageType, object instance, ref fsData data) {
            if (instance is fsISerializationCallbacks == false) {
                throw new InvalidCastException("Please ensure the converter for " + storageType + " actually returns an instance of it, not an instance of " + instance.GetType());
            }

            ((fsISerializationCallbacks)instance).OnBeforeDeserialize(storageType, ref data);
        }
Esempio n. 7
0
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            // note: IList[index] is **significantly** faster than Array.Get, so make sure we use
            //       that instead.

            IList arr = (Array)instance;
            Type elementType = storageType.GetElementType();

            var result = fsResult.Success;

            serialized = fsData.CreateList(arr.Count);
            var serializedList = serialized.AsList;

            for (int i = 0; i < arr.Count; ++i) {
                object item = arr[i];

                fsData serializedItem;

                var itemResult = Serializer.TrySerialize(elementType, item, out serializedItem);
                result.AddMessages(itemResult);
                if (itemResult.Failed) continue;

                serializedList.Add(serializedItem);
            }

            return result;
        }
Esempio n. 8
0
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            var result = fsResult.Success;

            // Verify that we actually have an List
            if ((result += CheckType(data, fsDataType.Array)).Failed) {
                return result;
            }

            Type elementType = storageType.GetElementType();

            var serializedList = data.AsList;
            var list = new ArrayList(serializedList.Count);
            int existingCount = list.Count;

            for (int i = 0; i < serializedList.Count; ++i) {
                var serializedItem = serializedList[i];
                object deserialized = null;
                if (i < existingCount) deserialized = list[i];

                var itemResult = Serializer.TryDeserialize(serializedItem, elementType, ref deserialized);
                result.AddMessages(itemResult);
                if (itemResult.Failed) continue;

                if (i < existingCount) list[i] = deserialized;
                else list.Add(deserialized);
            }

            instance = list.ToArray(elementType);
            return result;
        }
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            serialized = fsData.CreateDictionary();
            var result = fsResult.Success;

            fsMetaType metaType = fsMetaType.Get(Serializer.Config, instance.GetType());
            metaType.EmitAotData();

            for (int i = 0; i < metaType.Properties.Length; ++i) {
                fsMetaProperty property = metaType.Properties[i];
                if (property.CanRead == false) continue;

                fsData serializedData;

                var itemResult = Serializer.TrySerialize(property.StorageType, property.OverrideConverterType,
                                                         property.Read(instance), out serializedData);
                result.AddMessages(itemResult);
                if (itemResult.Failed) {
                    continue;
                }

                serialized.AsDictionary[property.JsonName] = serializedData;
            }

            return result;
        }
Esempio n. 10
0
        private static IEnumerable<string> Print(fsData data) {
            if (data.IsBool) {
                yield return "" + data.AsBool.ToString().ToLower() + "";
                yield return "  " + data.AsBool.ToString().ToLower() + "";
                yield return " " + data.AsBool.ToString().ToLower() + "   ";
                yield return " \n" + data.AsBool.ToString().ToLower() + "\n   ";
            }

            else if (data.IsDouble) {
                yield return "" + ConvertDoubleToString(data.AsDouble) + "";
                yield return "  " + ConvertDoubleToString(data.AsDouble) + "";
                yield return " " + ConvertDoubleToString(data.AsDouble) + "   ";
                yield return " \n" + ConvertDoubleToString(data.AsDouble) + "\n   ";
            }

            else if (data.IsInt64) {
                yield return "" + data.AsInt64 + "";
                yield return "  " + data.AsInt64 + "";
                yield return " " + data.AsInt64 + "   ";
                yield return " \n" + data.AsInt64 + "\n   ";
            }

            else if (data.IsNull) {
                yield return "null";
                yield return "  null";
                yield return " null  ";
                yield return " \nnull\n   ";
            }

            else if (data.IsString) {
                yield return "\"" + data.AsString + "\"";
                yield return " \"" + data.AsString + "\"";
                yield return "\"" + data.AsString + "\" ";
                yield return "  \"" + data.AsString + "\"  ";
                yield return "\n\"" + data.AsString + "\" \n ";
            }

            else if (data.IsList) {
                foreach (string permutation in Permutations(data.AsList, 0)) {
                    yield return "[" + permutation + "]";
                    yield return " [" + permutation + "]";
                    yield return "[ " + permutation + "]";
                    yield return "[" + permutation + " ]";
                    yield return "[" + permutation + "] ";
                    yield return " \n[\n" + permutation + "\n] \n";
                }
            }

            else if (data.IsDictionary) {
                foreach (string permutation in Permutations(data.AsDictionary.ToList(), 0)) {
                    yield return "{" + permutation + "}";
                    yield return " {" + permutation + "}";
                    yield return "{ " + permutation + "}";
                    yield return "{" + permutation + " }";
                    yield return "{" + permutation + "} ";
                    yield return " \n{\n" + permutation + "\n} \n";
                }
            }
        }
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            var obj = (UnityObject)instance;
            var serializationOperator = Serializer.Context.Get<ISerializationOperator>();

            int id = serializationOperator.StoreObjectReference(obj);
            return Serializer.TrySerialize<int>(id, out serialized);
        }
        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;
        }
Esempio n. 13
0
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            if (data.IsString) {
                instance = new Guid(data.AsString);
                return fsResult.Success;
            }

            return fsResult.Fail("fsGuidConverter encountered an unknown JSON data type");
        }
Esempio n. 14
0
 /// <summary>
 /// Returns the data in a pretty printed JSON format.
 /// </summary>
 public static string PrettyJson(fsData data)
 {
     var sb = new StringBuilder();
     using (var writer = new StringWriter(sb)) {
         BuildPrettyString(data, writer, 0);
         return sb.ToString();
     }
 }
Esempio n. 15
0
 /// <summary>
 /// Returns the data in a relatively compressed JSON format.
 /// </summary>
 public static string CompressedJson(fsData data)
 {
     var sb = new StringBuilder();
     using (var writer = new StringWriter(sb)) {
         BuildCompressedString(data, writer);
         return sb.ToString();
     }
 }
Esempio n. 16
0
        public override fsResult TryDeserialize(fsData data, ref object instance_, Type storageType)
        {
            var instance = (IEnumerable)instance_;
            var result = fsResult.Success;

            if ((result += CheckType(data, fsDataType.Array)).Failed) return result;

            if (data.AsList.Count == 0){
                return fsResult.Success;
            }

            //Most used thus special care
            if (instance is IList){
                var args = storageType.GetGenericArguments();
                if (args.Length == 1){
                    var targetList = (IList)instance;
                    var elementType = args[0];
                    for (var i = 0; i < data.AsList.Count; i++){
                        object item = null;
                        Serializer.TryDeserialize(data.AsList[i], elementType, ref item);
                        targetList.Add(item);
                    }
                    return fsResult.Success;
                }
            }

            // For general strategy, instance may already have items in it. We will try to deserialize into
            // the existing element.
            var elementStorageType = GetElementType(storageType);
            var addMethod = GetAddMethod(storageType);
            var getMethod = storageType.GetFlattenedMethod("get_Item");
            var setMethod = storageType.GetFlattenedMethod("set_Item");
            if (setMethod == null) TryClear(storageType, instance);
            var existingSize = TryGetExistingSize(storageType, instance);

            var serializedList = data.AsList;
            for (int i = 0; i < serializedList.Count; ++i) {
                var 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
                var itemResult = Serializer.TryDeserialize(itemData, elementStorageType, ref itemInstance);
                result.AddMessages(itemResult);
                if (itemResult.Failed) continue;

                if (setMethod != null && i < existingSize) {
                    setMethod.Invoke(instance, new object[] { i, itemInstance });
                }
                else {
                    addMethod.Invoke(instance, new object[] { itemInstance });
                }
            }

            return result;
        }
Esempio n. 17
0
		public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType)
		{
            int index = -1;
            var result = Serializer.TryDeserialize<int>(data, ref index);
            if (index == -1)
                throw new InvalidOperationException("Error deserializing Unity object of type " + storageType + ". Index shouldn't be -1. Message: " + result.FormattedMessages);
            instance = serializedObjects[index];
			return fsResult.Success;
		}
Esempio n. 18
0
        private static void BuildCompressedString(fsData data, TextWriter stream)
        {
            switch (data.Type) {
                case fsDataType.Null:
                    stream.Write("null");
                    break;

                case fsDataType.Boolean:
                    if (data.AsBool) stream.Write("true");
                    else stream.Write("false");
                    break;

                case fsDataType.Double:
                    // doubles must *always* include a decimal
                    stream.Write(ConvertDoubleToString(data.AsDouble));
                    break;

                case fsDataType.Int64:
                    stream.Write(data.AsInt64);
                    break;

                case fsDataType.String:
                    stream.Write('"');
                    stream.Write(EscapeString(data.AsString));
                    stream.Write('"');
                    break;

                case fsDataType.Object: {
                        stream.Write('{');
                        bool comma = false;
                        foreach (var entry in data.AsDictionary) {
                            if (comma) stream.Write(',');
                            comma = true;
                            stream.Write('"');
                            stream.Write(entry.Key);
                            stream.Write('"');
                            stream.Write(":");
                            BuildCompressedString(entry.Value, stream);
                        }
                        stream.Write('}');
                        break;
                    }

                case fsDataType.Array: {
                        stream.Write('[');
                        bool comma = false;
                        foreach (var entry in data.AsList) {
                            if (comma) stream.Write(',');
                            comma = true;
                            BuildCompressedString(entry, stream);
                        }
                        stream.Write(']');
                        break;
                    }
            }
        }
        public override fsResult TrySerialize(object instance_, out fsData serialized, Type storageType)
        {
            serialized = fsData.Null;

            var result = fsResult.Success;

            var instance = (IDictionary)instance_;

            Type keyStorageType, valueStorageType;
            GetKeyValueTypes(instance.GetType(), out keyStorageType, out valueStorageType);

            // No other way to iterate dictionaries and still have access to the
            // key/value info
            IDictionaryEnumerator enumerator = instance.GetEnumerator();

            bool allStringKeys = true;
            var serializedKeys = new List<fsData>(instance.Count);
            var serializedValues = new List<fsData>(instance.Count);
            while (enumerator.MoveNext()) {
                fsData keyData, valueData;
                if ((result += Serializer.TrySerialize(keyStorageType, enumerator.Key, out keyData)).Failed) return result;
                if ((result += Serializer.TrySerialize(valueStorageType, enumerator.Value, out valueData)).Failed) return result;

                serializedKeys.Add(keyData);
                serializedValues.Add(valueData);

                allStringKeys &= keyData.IsString;
            }

            if (allStringKeys) {
                serialized = fsData.CreateDictionary();
                var serializedDictionary = serialized.AsDictionary;

                for (int i = 0; i < serializedKeys.Count; ++i) {
                    fsData key = serializedKeys[i];
                    fsData value = serializedValues[i];
                    serializedDictionary[key.AsString] = value;
                }
            }
            else {
                serialized = fsData.CreateList(serializedKeys.Count);
                var serializedList = serialized.AsList;

                for (int i = 0; i < serializedKeys.Count; ++i) {
                    fsData key = serializedKeys[i];
                    fsData value = serializedValues[i];

                    var container = new Dictionary<string, fsData>();
                    container["Key"] = key;
                    container["Value"] = value;
                    serializedList.Add(new fsData(container));
                }
            }

            return result;
        }
Esempio n. 20
0
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) {
            serialized = fsData.Null;
            var result = fsResult.Success;

            fsMetaProperty property;
            if ((result += GetProperty(instance, out property)).Failed) return result;

            var actualInstance = property.Read(instance);
            return Serializer.TrySerialize(property.StorageType, actualInstance, out serialized);
        }
Esempio n. 21
0
        /// <summary>
        /// Parses the specified input. Returns a failure state if parsing failed.
        /// </summary>
        /// <param name="input">The input to parse.</param>
        /// <param name="data">The parsed data. This is undefined if parsing fails.</param>
        /// <returns>The parsed input.</returns>
        public static fsResult Parse(string input, out fsData data)
        {
            if (string.IsNullOrEmpty(input)) {
                data = default(fsData);
                return fsResult.Fail("No input");
            }

            var context = new fsJsonParser(input);
            return context.RunParse(out data);
        }
		public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType){
			var database = Serializer.Context.Get<List<UnityEngine.Object>>();
			var index = (int)data.AsInt64;
			
			if (index >= database.Count)
				return fsResult.Warn("A Unity Object reference has not been deserialized");
			
			instance = database[index];
			return fsResult.Success;
		}
        /// <summary>
        /// Construct an object instance that will be passed to TryDeserialize. This should **not**
        /// deserialize the object.
        /// </summary>
        /// <param name="data">The data the object was serialized with.</param>
        /// <param name="storageType">The field/property type that is storing the instance.</param>
        /// <returns>An object instance</returns>
        public virtual object CreateInstance(fsData data, Type storageType) {
            if (RequestCycleSupport(storageType)) {
                throw new InvalidOperationException("Please override CreateInstance for " +
                    GetType().FullName + "; the object graph for " + storageType +
                    " can contain potentially contain cycles, so separated instance creation " +
                    "is needed");
            }

            return storageType;
        }
Esempio n. 24
0
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            if (data.IsString == false) {
                return fsResult.Fail("Type converter requires a string");
            }

            instance = fsTypeLookup.GetType(data.AsString);
            if (instance == null) {
                return fsResult.Fail("Unable to find type " + data.AsString);
            }
            return fsResult.Success;
        }
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType)
        {
            var serializationOperator = Serializer.Context.Get<ISerializationOperator>();

            int id = default(int);
            var fail = Serializer.TryDeserialize(data, ref id);
            if (fail.Failed) return fail;

            instance = serializationOperator.RetrieveObjectReference(id);
            return fsResult.Success;
        }
Esempio n. 26
0
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull){
                return;
            }

            var json = data.AsDictionary;

            fsData typeData;
            if (json.TryGetValue("$type", out typeData)){

                var serializedType = ReflectionTools.GetType( typeData.AsString );

                if (serializedType == null || serializedType == typeof(MissingConnection)){
                    //TargetType is either the one missing or the one previously stored as missing in the MissingConnection.
                    var targetFullTypeName = serializedType == null? typeData.AsString : json["missingType"].AsString;
                    //Try find type with same name in some other namespace that is subclass of Connection
                    var typeNameWithoutNS = targetFullTypeName.Split('.').LastOrDefault();
                    foreach(var type in ReflectionTools.GetAllTypes()){
                        if (type.Name == typeNameWithoutNS && type.IsSubclassOf(typeof(NodeCanvas.Framework.Connection))){
                            json["$type"] = new fsData(type.FullName);
                            return;
                        }
                    }
                }

                //Handle missing serialized Connection type
                if (serializedType == null){
                    //inject the 'MissingConnection' type and store recovery serialization state.
                    //recoveryState and missingType are serializable members of MissingConnection.
                    json["recoveryState"] = new fsData( data.ToString() );
                    json["missingType"] = new fsData( typeData.AsString );
                    json["$type"] = new fsData( typeof(MissingConnection).FullName );
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingConnection)){

                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType( json["missingType"].AsString );
                    if (missingType != null){

                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json = json.Concat( recoverJson.Where( kvp => !json.ContainsKey(kvp.Key) ) ).ToDictionary( c => c.Key, c => c.Value );
                        json["$type"] = new fsData( missingType.FullName );
                        data = new fsData( json );
                    }
                }
            }
        }
Esempio n. 27
0
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) {
            var result = fsResult.Success;

            fsMetaProperty property;
            if ((result += GetProperty(instance, out property)).Failed) return result;

            object actualInstance = null;
            if ((result += Serializer.TryDeserialize(data, property.StorageType, ref actualInstance)).Failed)
                return result;

            property.Write(instance, actualInstance);
            return result;
        }
        public override void OnBeforeDeserialize(Type storageType, ref fsData data)
        {
            if (data.IsNull)
                return;

            var json = data.AsDictionary;

            if (json.ContainsKey("$type")){

                var serializedType = ReflectionTools.GetType( json["$type"].AsString );

                //Handle missing serialized Node type
                if (serializedType == null){

                    //inject the 'MissingTask' type and store recovery serialization state
                    json["recoveryState"] = new fsData( data.ToString() );
                    json["missingType"] = new fsData( json["$type"].AsString );

                    Type missingNodeType = null;
                    if (storageType == typeof(ActionTask))
                        missingNodeType = typeof(MissingAction);
                    if (storageType == typeof(ConditionTask))
                        missingNodeType = typeof(MissingCondition);
                    if (missingNodeType == null){
                        Debug.LogError("Can't resolve missing Task type");
                        return;
                    }

                    json["$type"] = new fsData( missingNodeType.FullName );

                    //There is no way to know DecalredOnly properties to save just them instead of the whole object since we dont have an actual type
                }

                //Recover possible found serialized type
                if (serializedType == typeof(MissingAction) || serializedType == typeof(MissingCondition)){

                    //Does the missing type now exists? If so recover
                    var missingType = ReflectionTools.GetType( json["missingType"].AsString );
                    if (missingType != null){

                        var recoveryState = json["recoveryState"].AsString;
                        var recoverJson = fsJsonParser.Parse(recoveryState).AsDictionary;

                        //merge the recover state *ON TOP* of the current state, thus merging only Declared recovered members
                        json = json.Concat( recoverJson.Where( kvp => !json.ContainsKey(kvp.Key) ) ).ToDictionary( c => c.Key, c => c.Value );
                        json["$type"] = new fsData( missingType.FullName );
                        data = new fsData( json );
                    }
                }
            }
        }
Esempio n. 29
0
        public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType)
        {
            if (data.IsString == false) {
                return fsResult.Fail("Date deserialization requires a string, not " + data.Type);
            }

            if (storageType == typeof(DateTime)) {
                DateTime result;
                if (DateTime.TryParse(data.AsString, null, DateTimeStyles.RoundtripKind, out result)) {
                    instance = result;
                    return fsResult.Success;
                }

                // DateTime.TryParse can fail for some valid DateTime instances.
                // Try to use Convert.ToDateTime.
                if (fsGlobalConfig.AllowInternalExceptions) {
                    try {
                        instance = Convert.ToDateTime(data.AsString);
                        return fsResult.Success;
                    }
                    catch (Exception e) {
                        return fsResult.Fail("Unable to parse " + data.AsString + " into a DateTime; got exception " + e);
                    }
                }

                return fsResult.Fail("Unable to parse " + data.AsString + " into a DateTime");
            }

            if (storageType == typeof(DateTimeOffset)) {
                DateTimeOffset result;
                if (DateTimeOffset.TryParse(data.AsString, null, DateTimeStyles.RoundtripKind, out result)) {
                    instance = result;
                    return fsResult.Success;
                }

                return fsResult.Fail("Unable to parse " + data.AsString + " into a DateTimeOffset");
            }

            if (storageType == typeof(TimeSpan)) {
                TimeSpan result;
                if (TimeSpan.TryParse(data.AsString, out result)) {
                    instance = result;
                    return fsResult.Success;
                }

                return fsResult.Fail("Unable to parse " + data.AsString + " into a TimeSpan");
            }

            throw new InvalidOperationException("FullSerializer Internal Error -- Unexpected deserialization type");
        }
Esempio n. 30
0
		public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
		{
            var obj = instance as UnityObject;
            int idx = serializedObjects.IndexOf(obj);
            if (idx == -1)
            {
                Serializer.TrySerialize<int>(serializedObjects.Count, out serialized);
			    serializedObjects.Add(obj);
            }
            else 
                Serializer.TrySerialize<int>(idx, out serialized);

			return fsResult.Success;
		}
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new LayerMask());
 }
Esempio n. 32
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new SaveFile_HeadData());
 }
Esempio n. 33
0
            private fsResult DeserializeImportedComponents(fsData fsData, GameObject gameObject, Mod mod)
            {
                fsResult fsResult = fsResult.Success;

                if ((fsResult += CheckType(fsData, fsDataType.Object)).Failed)
                {
                    return(fsResult);
                }
                Dictionary <string, fsData> dict = fsData.AsDictionary;

                // Restore components on this gameobject
                fsData components;

                if ((fsResult += CheckKey(dict, "Components", out components)).Failed)
                {
                    return(fsResult);
                }
                if (!components.IsNull)
                {
                    if ((fsResult += CheckType(components, fsDataType.Array)).Failed)
                    {
                        return(fsResult);
                    }
                    foreach (fsData componentData in components.AsList)
                    {
                        // Get type name
                        string typeName;
                        if ((fsResult += DeserializeMember(componentData.AsDictionary, null, "$type", out typeName)).Failed)
                        {
                            return(fsResult);
                        }

                        // Add component and deserialize
                        Type type = FindType(mod, typeName);
                        if (type == null)
                        {
                            return(fsResult += fsResult.Fail(string.Format("Failed to find type {0}.", typeName)));
                        }
                        object instance = gameObject.AddComponent(type);
                        if ((fsResult += fsSerializer.TryDeserialize(componentData, type, ref instance)).Failed)
                        {
                            return(fsResult);
                        }
                    }
                }

                // Restore components on children
                fsData children;

                if ((fsResult += CheckKey(dict, "Children", out children)).Failed)
                {
                    return(fsResult);
                }
                if (!children.IsNull)
                {
                    if ((fsResult += CheckType(children, fsDataType.Object)).Failed)
                    {
                        return(fsResult);
                    }
                    foreach (KeyValuePair <string, fsData> childData in children.AsDictionary)
                    {
                        Transform child = gameObject.transform.Find(childData.Key);
                        if (child == null)
                        {
                            return(fsResult += fsResult.Fail(string.Format("{0} not found on {1}", childData.Key, gameObject.name)));
                        }
                        if ((fsResult += DeserializeImportedComponents(childData.Value, child.gameObject, mod)).Failed)
                        {
                            return(fsResult);
                        }
                    }
                }

                return(fsResult);
            }
Esempio n. 34
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new GUIStyle());
 }
Esempio n. 35
0
        public override fsResult TryDeserialize(fsData data, ref object instance_, Type storageType)
        {
            IDictionary instance = (IDictionary)instance_;
            fsResult    result   = fsResult.Success;

            Type keyStorageType, valueStorageType;

            GetKeyValueTypes(instance.GetType(), out keyStorageType, out valueStorageType);

            if (data.IsList)
            {
                List <fsData> list = data.AsList;
                for (int i = 0; i < list.Count; ++i)
                {
                    fsData item = list[i];

                    fsData keyData, valueData;
                    if ((result += CheckType(item, fsDataType.Object)).Failed)
                    {
                        return(result);
                    }

                    if ((result += CheckKey(item, "Key", out keyData)).Failed)
                    {
                        return(result);
                    }

                    if ((result += CheckKey(item, "Value", out valueData)).Failed)
                    {
                        return(result);
                    }

                    object keyInstance = null, valueInstance = null;
                    if ((result += Serializer.TryDeserialize(keyData, keyStorageType, ref keyInstance)).Failed)
                    {
                        return(result);
                    }

                    if ((result += Serializer.TryDeserialize(valueData, valueStorageType, ref valueInstance)).Failed)
                    {
                        return(result);
                    }

                    AddItemToDictionary(instance, keyInstance, valueInstance);
                }
            }
            else if (data.IsDictionary)
            {
                foreach (KeyValuePair <string, fsData> entry in data.AsDictionary)
                {
                    if (fsSerializer.IsReservedKeyword(entry.Key))
                    {
                        continue;
                    }

                    fsData keyData = new fsData(entry.Key), valueData = entry.Value;
                    object keyInstance = null, valueInstance = null;

                    if ((result += Serializer.TryDeserialize(keyData, keyStorageType, ref keyInstance)).Failed)
                    {
                        return(result);
                    }

                    if ((result += Serializer.TryDeserialize(valueData, valueStorageType, ref valueInstance)).Failed)
                    {
                        return(result);
                    }

                    AddItemToDictionary(instance, keyInstance, valueInstance);
                }
            }
            else
            {
                return(FailExpectedType(data, fsDataType.Array, fsDataType.Object));
            }

            return(result);
        }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  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.GetCredentialByname("text-to-speech-sdk")[0].Credentials;

            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
            };

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _textToSpeech = new TextToSpeech(credentials);

            ////  Synthesize
            //Log.Debug("TestTextToSpeech.RunTest()", "Attempting synthesize.");
            //_textToSpeech.Voice = VoiceType.en_US_Allison;
            //_textToSpeech.ToSpeech(HandleToSpeechCallback, OnFail, _testString, true);
            //while (!_synthesizeTested)
            //    yield return null;

            ////  Synthesize Conversation string
            //Log.Debug("TestTextToSpeech.RunTest()", "Attempting synthesize a string as returned by Watson Conversation.");
            //_textToSpeech.Voice = VoiceType.en_US_Allison;
            //_textToSpeech.ToSpeech(HandleConversationToSpeechCallback, OnFail, _testConversationString, true);
            //while (!_synthesizeConversationTested)
            //    yield return null;

            //	Get Voices
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get voices.");
            _textToSpeech.GetVoices(OnGetVoices, OnFail);
            while (!_getVoicesTested)
            {
                yield return(null);
            }

            //	Get Voice
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get voice {0}.", VoiceType.en_US_Allison);
            _textToSpeech.GetVoice(OnGetVoice, OnFail, VoiceType.en_US_Allison);
            while (!_getVoiceTested)
            {
                yield return(null);
            }

            //	Get Pronunciation
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get pronunciation of {0}", _testWord);
            _textToSpeech.GetPronunciation(OnGetPronunciation, OnFail, _testWord, VoiceType.en_US_Allison);
            while (!_getPronuciationTested)
            {
                yield return(null);
            }

            //  Get Customizations
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a list of customizations");
            _textToSpeech.GetCustomizations(OnGetCustomizations, OnFail);
            while (!_getCustomizationsTested)
            {
                yield return(null);
            }

            //  Create Customization
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to create a customization");
            _textToSpeech.CreateCustomization(OnCreateCustomization, OnFail, _customizationName, _customizationLanguage, _customizationDescription);
            while (!_createCustomizationTested)
            {
                yield return(null);
            }

            //  Get Customization
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a customization");
            if (!_textToSpeech.GetCustomization(OnGetCustomization, OnFail, _createdCustomizationId))
            {
                Log.Debug("TestTextToSpeech.RunTest()", "Failed to get custom voice model!");
            }
            while (!_getCustomizationTested)
            {
                yield return(null);
            }

            //  Update Customization
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to update a customization");
            Word[] wordsToUpdateCustomization =
            {
                new Word()
                {
                    word        = "hello",
                    translation = "hullo"
                },
                new Word()
                {
                    word        = "goodbye",
                    translation = "gbye"
                },
                new Word()
                {
                    word        = "hi",
                    translation = "ohioooo"
                }
            };

            _customVoiceUpdate = new CustomVoiceUpdate()
            {
                words       = wordsToUpdateCustomization,
                description = "My updated description",
                name        = "My updated name"
            };

            if (!_textToSpeech.UpdateCustomization(OnUpdateCustomization, OnFail, _createdCustomizationId, _customVoiceUpdate))
            {
                Log.Debug("TestTextToSpeech.UpdateCustomization()", "Failed to update customization!");
            }
            while (!_updateCustomizationTested)
            {
                yield return(null);
            }

            //  Get Customization Words
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get a customization's words");
            if (!_textToSpeech.GetCustomizationWords(OnGetCustomizationWords, OnFail, _createdCustomizationId))
            {
                Log.Debug("TestTextToSpeech.GetCustomizationWords()", "Failed to get {0} words!", _createdCustomizationId);
            }
            while (!_getCustomizationWordsTested)
            {
                yield return(null);
            }

            //  Add Customization Words
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to add words to a customization");
            Word[] wordArrayToAddToCustomization =
            {
                new Word()
                {
                    word        = "bananna",
                    translation = "arange"
                },
                new Word()
                {
                    word        = "orange",
                    translation = "gbye"
                },
                new Word()
                {
                    word        = "tomato",
                    translation = "tomahto"
                }
            };

            Words wordsToAddToCustomization = new Words()
            {
                words = wordArrayToAddToCustomization
            };

            if (!_textToSpeech.AddCustomizationWords(OnAddCustomizationWords, OnFail, _createdCustomizationId, wordsToAddToCustomization))
            {
                Log.Debug("TestTextToSpeech.AddCustomizationWords()", "Failed to add words to {0}!", _createdCustomizationId);
            }
            while (!_addCustomizationWordsTested)
            {
                yield return(null);
            }

            //  Get Customization Word
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to get the translation of a custom voice model's word.");
            string customIdentifierWord = wordsToUpdateCustomization[0].word;

            if (!_textToSpeech.GetCustomizationWord(OnGetCustomizationWord, OnFail, _createdCustomizationId, customIdentifierWord))
            {
                Log.Debug("TestTextToSpeech.GetCustomizationWord()", "Failed to get the translation of {0} from {1}!", customIdentifierWord, _createdCustomizationId);
            }
            while (!_getCustomizationWordTested)
            {
                yield return(null);
            }

            //  Delete Customization Word
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to delete customization word from custom voice model.");
            string wordToDelete = "goodbye";

            if (!_textToSpeech.DeleteCustomizationWord(OnDeleteCustomizationWord, OnFail, _createdCustomizationId, wordToDelete))
            {
                Log.Debug("TestTextToSpeech.DeleteCustomizationWord()", "Failed to delete {0} from {1}!", wordToDelete, _createdCustomizationId);
            }
            while (!_deleteCustomizationWordTested)
            {
                yield return(null);
            }

            //  Delete Customization
            Log.Debug("TestTextToSpeech.RunTest()", "Attempting to delete a customization");
            if (!_textToSpeech.DeleteCustomization(OnDeleteCustomization, OnFail, _createdCustomizationId))
            {
                Log.Debug("TestTextToSpeech.DeleteCustomization()", "Failed to delete custom voice model!");
            }
            while (!_deleteCustomizationTested)
            {
                yield return(null);
            }

            Log.Debug("TestTextToSpeech.RunTest()", "Text to Speech examples complete.");

            yield break;
        }
Esempio n. 37
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new DynamicFloat());
 }
Esempio n. 38
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(fsMetaType.Get(storageType).CreateInstance());
 }
Esempio n. 39
0
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            Parameters parameters = (Parameters)instance;

            serialized = null;

            Dictionary <string, fsData> serialization = new Dictionary <string, fsData>();

            if (parameters.text != null)
            {
                serialization.Add("text", new fsData(parameters.text));
            }

            if (parameters.url != null)
            {
                serialization.Add("url", new fsData(parameters.url));
            }

            if (parameters.html != null)
            {
                serialization.Add("html", new fsData(parameters.html));
            }

            if (parameters.clean != null)
            {
                serialization.Add("clean", new fsData((bool)parameters.clean));
            }

            if (parameters.xpath != null)
            {
                serialization.Add("xpath", new fsData(parameters.xpath));
            }

            if (parameters.fallback_to_raw != null)
            {
                serialization.Add("fallback_to_raw", new fsData((bool)parameters.fallback_to_raw));
            }

            if (parameters.return_analyzed_text != null)
            {
                serialization.Add("return_analyzed_text", new fsData((bool)parameters.return_analyzed_text));
            }

            if (parameters.xpath != null)
            {
                serialization.Add("xpath", new fsData(parameters.xpath));
            }

            if (parameters.limit_text_characters != null)
            {
                serialization.Add("limit_text_characters", new fsData((int)parameters.limit_text_characters));
            }

            fsData tempData = null;

            _serializer.TrySerialize(parameters.features, out tempData);
            serialization.Add("features", tempData);

            serialized = new fsData(serialization);

            return(fsResult.Success);
        }
Esempio n. 40
0
        public override fsResult TrySerialize(object instance_, out fsData serialized, Type storageType)
        {
            serialized = fsData.Null;

            fsResult result = fsResult.Success;

            IDictionary instance = (IDictionary)instance_;

            Type keyStorageType, valueStorageType;

            GetKeyValueTypes(instance.GetType(), out keyStorageType, out valueStorageType);

            // No other way to iterate dictionaries and still have access to the
            // key/value info
            IDictionaryEnumerator enumerator = instance.GetEnumerator();

            bool          allStringKeys    = true;
            List <fsData> serializedKeys   = new List <fsData>(instance.Count);
            List <fsData> serializedValues = new List <fsData>(instance.Count);

            while (enumerator.MoveNext())
            {
                fsData keyData, valueData;
                if ((result += Serializer.TrySerialize(keyStorageType, enumerator.Key, out keyData)).Failed)
                {
                    return(result);
                }

                if ((result += Serializer.TrySerialize(valueStorageType, enumerator.Value, out valueData)).Failed)
                {
                    return(result);
                }

                serializedKeys.Add(keyData);
                serializedValues.Add(valueData);

                allStringKeys &= keyData.IsString;
            }

            if (allStringKeys)
            {
                serialized = fsData.CreateDictionary();
                Dictionary <string, fsData> serializedDictionary = serialized.AsDictionary;

                for (int i = 0; i < serializedKeys.Count; ++i)
                {
                    fsData key   = serializedKeys[i];
                    fsData value = serializedValues[i];
                    serializedDictionary[key.AsString] = value;
                }
            }
            else
            {
                serialized = fsData.CreateList(serializedKeys.Count);
                List <fsData> serializedList = serialized.AsList;

                for (int i = 0; i < serializedKeys.Count; ++i)
                {
                    fsData key   = serializedKeys[i];
                    fsData value = serializedValues[i];

                    Dictionary <string, fsData> container = new Dictionary <string, fsData>();
                    container["Key"]   = key;
                    container["Value"] = value;
                    serializedList.Add(new fsData(container));
                }
            }

            return(result);
        }
Esempio n. 41
0
 public override object CreateInstance(fsData data, System.Type storageType)
 {
     return(new DynamicString());
 }
Esempio n. 42
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  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.GetCredentialByname("visual-recognition-sdk-cf")[0].Credentials;

            _apikey = credential.ApiKey.ToString();
            _url    = credential.Url.ToString();

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(_apikey, _url);

            _visualRecognition             = new VisualRecognition(credentials);
            _visualRecognition.VersionDate = _visualRecognitionVersionDate;

            //          Get all classifiers
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get all classifiers");
            if (!_visualRecognition.GetClassifiersBrief(OnGetClassifiers, OnFail))
            {
                Log.Debug("TestVisualRecognition.GetClassifiers()", "Failed to get all classifiers!");
            }

            while (!_getClassifiersTested)
            {
                yield return(null);
            }

#if TRAIN_CLASSIFIER
            _isClassifierReady = false;
            //          Train classifier
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to train classifier");
            string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip";
            string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip";
            Dictionary <string, string> positiveExamples = new Dictionary <string, string>();
            positiveExamples.Add("giraffe", positiveExamplesPath);
            if (!_visualRecognition.TrainClassifier(OnTrainClassifier, OnFail, "unity-test-classifier-ok-to-delete", positiveExamples, negativeExamplesPath))
            {
                Log.Debug("TestVisualRecognition.TrainClassifier()", "Failed to train classifier!");
            }

            while (!_trainClassifierTested)
            {
                yield return(null);
            }

            //          Find classifier by ID
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to find classifier by ID");
            if (!_visualRecognition.GetClassifier(OnGetClassifier, OnFail, _classifierID))
            {
                Log.Debug("TestVisualRecognition.GetClassifier()", "Failed to get classifier!");
            }

            while (!_getClassifierTested)
            {
                yield return(null);
            }
#endif

            //  Classify get
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get classify via URL");
            if (!_visualRecognition.Classify(_imageURL, OnClassifyGet, OnFail))
            {
                Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!");
            }

            while (!_classifyGetTested)
            {
                yield return(null);
            }

            //  Classify post image
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to classify via image on file system");
            string   imagesPath    = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg";
            string[] owners        = { "IBM", "me" };
            string[] classifierIDs = { "default", _classifierID };
            if (!_visualRecognition.Classify(OnClassifyPost, OnFail, imagesPath, owners, classifierIDs, 0.5f))
            {
                Log.Debug("TestVisualRecognition.Classify()", "Classify image failed!");
            }

            while (!_classifyPostTested)
            {
                yield return(null);
            }

            //  Detect faces get
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via URL");
            if (!_visualRecognition.DetectFaces(_imageURL, OnDetectFacesGet, OnFail))
            {
                Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!");
            }

            while (!_detectFacesGetTested)
            {
                yield return(null);
            }

            //  Detect faces post image
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to detect faces via image");
            string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg";
            if (!_visualRecognition.DetectFaces(OnDetectFacesPost, OnFail, faceExamplePath))
            {
                Log.Debug("TestVisualRecognition.DetectFaces()", "Detect faces failed!");
            }

            while (!_detectFacesPostTested)
            {
                yield return(null);
            }

#if DELETE_TRAINED_CLASSIFIER
            Runnable.Run(IsClassifierReady(_classifierToDelete));
            while (!_isClassifierReady)
            {
                yield return(null);
            }

            //  Download Core ML Model
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to get Core ML Model");
            if (!_visualRecognition.GetCoreMLModel(OnGetCoreMLModel, OnFail, _classifierID))
            {
                Log.Debug("TestVisualRecognition.GetCoreMLModel()", "Failed to get core ml model!");
            }
            while (!_getCoreMLModelTested)
            {
                yield return(null);
            }

            //  Delete classifier by ID
            Log.Debug("TestVisualRecognition.RunTest()", "Attempting to delete classifier");
            if (!_visualRecognition.DeleteClassifier(OnDeleteClassifier, OnFail, _classifierToDelete))
            {
                Log.Debug("TestVisualRecognition.DeleteClassifier()", "Failed to delete classifier!");
            }

            while (!_deleteClassifierTested)
            {
                yield return(null);
            }
#endif

            Log.Debug("TestVisualRecognition.RunTest()", "Visual Recogition tests complete");
            yield break;
        }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  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.GetCredentialByname("assistant-sdk")[0].Credentials;
            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
            };

            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            _workspaceId = credential.WorkspaceId.ToString();

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _service             = new Assistant(credentials);
            _service.VersionDate = _assistantVersionDate;

            //  List Workspaces
            _service.ListWorkspaces(OnListWorkspaces, OnFail);
            while (!_listWorkspacesTested)
            {
                yield return(null);
            }
            //  Create Workspace
            CreateWorkspace workspace = new CreateWorkspace()
            {
                Name           = _createdWorkspaceName,
                Description    = _createdWorkspaceDescription,
                Language       = _createdWorkspaceLanguage,
                LearningOptOut = true
            };

            _service.CreateWorkspace(OnCreateWorkspace, OnFail, workspace);
            while (!_createWorkspaceTested)
            {
                yield return(null);
            }
            //  Get Workspace
            _service.GetWorkspace(OnGetWorkspace, OnFail, _createdWorkspaceId);
            while (!_getWorkspaceTested)
            {
                yield return(null);
            }
            //  Update Workspace
            UpdateWorkspace updateWorkspace = new UpdateWorkspace()
            {
                Name        = _createdWorkspaceName + "-updated",
                Description = _createdWorkspaceDescription + "-updated",
                Language    = _createdWorkspaceLanguage
            };

            _service.UpdateWorkspace(OnUpdateWorkspace, OnFail, _createdWorkspaceId, updateWorkspace);
            while (!_updateWorkspaceTested)
            {
                yield return(null);
            }

            //  Message with customerID
            //  Create customData object
            Dictionary <string, object> customData = new Dictionary <string, object>();
            //  Create a dictionary of custom headers
            Dictionary <string, string> customHeaders = new Dictionary <string, string>();

            //  Add to the header dictionary
            customHeaders.Add("X-Watson-Metadata", "customer_id=" + _unitySdkTestCustomerID);
            //  Add the header dictionary to the custom data object
            customData.Add(Constants.String.CUSTOM_REQUEST_HEADERS, customHeaders);
            Dictionary <string, object> input = new Dictionary <string, object>();

            input.Add("text", _inputString);
            MessageRequest messageRequest = new MessageRequest()
            {
                Input = input
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest, null, customData);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString0;
            MessageRequest messageRequest0 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest0);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString1;
            MessageRequest messageRequest1 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest1);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString2;
            MessageRequest messageRequest2 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest2);
            while (!_messageTested)
            {
                yield return(null);
            }

            //  List Intents
            _service.ListIntents(OnListIntents, OnFail, _createdWorkspaceId);
            while (!_listIntentsTested)
            {
                yield return(null);
            }
            //  Create Intent
            CreateIntent createIntent = new CreateIntent()
            {
                Intent      = _createdIntent,
                Description = _createdIntentDescription
            };

            _service.CreateIntent(OnCreateIntent, OnFail, _createdWorkspaceId, createIntent);
            while (!_createIntentTested)
            {
                yield return(null);
            }
            //  Get Intent
            _service.GetIntent(OnGetIntent, OnFail, _createdWorkspaceId, _createdIntent);
            while (!_getIntentTested)
            {
                yield return(null);
            }
            //  Update Intents
            string       updatedIntent            = _createdIntent + "-updated";
            string       updatedIntentDescription = _createdIntentDescription + "-updated";
            UpdateIntent updateIntent             = new UpdateIntent()
            {
                Intent      = updatedIntent,
                Description = updatedIntentDescription
            };

            _service.UpdateIntent(OnUpdateIntent, OnFail, _createdWorkspaceId, _createdIntent, updateIntent);
            while (!_updateIntentTested)
            {
                yield return(null);
            }

            //  List Examples
            _service.ListExamples(OnListExamples, OnFail, _createdWorkspaceId, updatedIntent);
            while (!_listExamplesTested)
            {
                yield return(null);
            }
            //  Create Examples
            CreateExample createExample = new CreateExample()
            {
                Text = _createdExample
            };

            _service.CreateExample(OnCreateExample, OnFail, _createdWorkspaceId, updatedIntent, createExample);
            while (!_createExampleTested)
            {
                yield return(null);
            }
            //  Get Example
            _service.GetExample(OnGetExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample);
            while (!_getExampleTested)
            {
                yield return(null);
            }
            //  Update Examples
            string        updatedExample = _createdExample + "-updated";
            UpdateExample updateExample  = new UpdateExample()
            {
                Text = updatedExample
            };

            _service.UpdateExample(OnUpdateExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample, updateExample);
            while (!_updateExampleTested)
            {
                yield return(null);
            }

            //  List Entities
            _service.ListEntities(OnListEntities, OnFail, _createdWorkspaceId);
            while (!_listEntitiesTested)
            {
                yield return(null);
            }
            //  Create Entities
            CreateEntity entity = new CreateEntity()
            {
                Entity      = _createdEntity,
                Description = _createdEntityDescription
            };

            _service.CreateEntity(OnCreateEntity, OnFail, _createdWorkspaceId, entity);
            while (!_createEntityTested)
            {
                yield return(null);
            }
            //  Get Entity
            _service.GetEntity(OnGetEntity, OnFail, _createdWorkspaceId, _createdEntity);
            while (!_getEntityTested)
            {
                yield return(null);
            }
            //  Update Entities
            string       updatedEntity            = _createdEntity + "-updated";
            string       updatedEntityDescription = _createdEntityDescription + "-updated";
            UpdateEntity updateEntity             = new UpdateEntity()
            {
                Entity      = updatedEntity,
                Description = updatedEntityDescription
            };

            _service.UpdateEntity(OnUpdateEntity, OnFail, _createdWorkspaceId, _createdEntity, updateEntity);
            while (!_updateEntityTested)
            {
                yield return(null);
            }

            //  List Values
            _service.ListValues(OnListValues, OnFail, _createdWorkspaceId, updatedEntity);
            while (!_listValuesTested)
            {
                yield return(null);
            }
            //  Create Values
            CreateValue value = new CreateValue()
            {
                Value = _createdValue
            };

            _service.CreateValue(OnCreateValue, OnFail, _createdWorkspaceId, updatedEntity, value);
            while (!_createValueTested)
            {
                yield return(null);
            }
            //  Get Value
            _service.GetValue(OnGetValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue);
            while (!_getValueTested)
            {
                yield return(null);
            }
            //  Update Values
            string      updatedValue = _createdValue + "-updated";
            UpdateValue updateValue  = new UpdateValue()
            {
                Value = updatedValue
            };

            _service.UpdateValue(OnUpdateValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue, updateValue);
            while (!_updateValueTested)
            {
                yield return(null);
            }

            //  List Synonyms
            _service.ListSynonyms(OnListSynonyms, OnFail, _createdWorkspaceId, updatedEntity, updatedValue);
            while (!_listSynonymsTested)
            {
                yield return(null);
            }
            //  Create Synonyms
            CreateSynonym synonym = new CreateSynonym()
            {
                Synonym = _createdSynonym
            };

            _service.CreateSynonym(OnCreateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, synonym);
            while (!_createSynonymTested)
            {
                yield return(null);
            }
            //  Get Synonym
            _service.GetSynonym(OnGetSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym);
            while (!_getSynonymTested)
            {
                yield return(null);
            }
            //  Update Synonyms
            string        updatedSynonym = _createdSynonym + "-updated";
            UpdateSynonym updateSynonym  = new UpdateSynonym()
            {
                Synonym = updatedSynonym
            };

            _service.UpdateSynonym(OnUpdateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym, updateSynonym);
            while (!_updateSynonymTested)
            {
                yield return(null);
            }

            //  List Dialog Nodes
            _service.ListDialogNodes(OnListDialogNodes, OnFail, _createdWorkspaceId);
            while (!_listDialogNodesTested)
            {
                yield return(null);
            }
            //  Create Dialog Nodes
            CreateDialogNode createDialogNode = new CreateDialogNode()
            {
                DialogNode  = _dialogNodeName,
                Description = _dialogNodeDesc
            };

            _service.CreateDialogNode(OnCreateDialogNode, OnFail, _createdWorkspaceId, createDialogNode);
            while (!_createDialogNodeTested)
            {
                yield return(null);
            }
            //  Get Dialog Node
            _service.GetDialogNode(OnGetDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName);
            while (!_getDialogNodeTested)
            {
                yield return(null);
            }
            //  Update Dialog Nodes
            string           updatedDialogNodeName        = _dialogNodeName + "_updated";
            string           updatedDialogNodeDescription = _dialogNodeDesc + "_updated";
            UpdateDialogNode updateDialogNode             = new UpdateDialogNode()
            {
                DialogNode  = updatedDialogNodeName,
                Description = updatedDialogNodeDescription
            };

            _service.UpdateDialogNode(OnUpdateDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName, updateDialogNode);
            while (!_updateDialogNodeTested)
            {
                yield return(null);
            }

            //  List Logs In Workspace
            _service.ListLogs(OnListLogs, OnFail, _createdWorkspaceId);
            while (!_listLogsInWorkspaceTested)
            {
                yield return(null);
            }
            //  List All Logs
            var filter = "(language::en,request.context.metadata.deployment::deployment_1)";

            _service.ListAllLogs(OnListAllLogs, OnFail, filter);
            while (!_listAllLogsTested)
            {
                yield return(null);
            }

            //  List Counterexamples
            _service.ListCounterexamples(OnListCounterexamples, OnFail, _createdWorkspaceId);
            while (!_listCounterexamplesTested)
            {
                yield return(null);
            }
            //  Create Counterexamples
            CreateCounterexample example = new CreateCounterexample()
            {
                Text = _createdCounterExampleText
            };

            _service.CreateCounterexample(OnCreateCounterexample, OnFail, _createdWorkspaceId, example);
            while (!_createCounterexampleTested)
            {
                yield return(null);
            }
            //  Get Counterexample
            _service.GetCounterexample(OnGetCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText);
            while (!_getCounterexampleTested)
            {
                yield return(null);
            }
            //  Update Counterexamples
            string updatedCounterExampleText          = _createdCounterExampleText + "-updated";
            UpdateCounterexample updateCounterExample = new UpdateCounterexample()
            {
                Text = updatedCounterExampleText
            };

            _service.UpdateCounterexample(OnUpdateCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText, updateCounterExample);
            while (!_updateCounterexampleTested)
            {
                yield return(null);
            }

            //  Delete Counterexample
            _service.DeleteCounterexample(OnDeleteCounterexample, OnFail, _createdWorkspaceId, updatedCounterExampleText);
            while (!_deleteCounterexampleTested)
            {
                yield return(null);
            }
            //  Delete Dialog Node
            _service.DeleteDialogNode(OnDeleteDialogNode, OnFail, _createdWorkspaceId, updatedDialogNodeName);
            while (!_deleteDialogNodeTested)
            {
                yield return(null);
            }
            //  Delete Synonym
            _service.DeleteSynonym(OnDeleteSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, updatedSynonym);
            while (!_deleteSynonymTested)
            {
                yield return(null);
            }
            //  Delete Value
            _service.DeleteValue(OnDeleteValue, OnFail, _createdWorkspaceId, updatedEntity, updatedValue);
            while (!_deleteValueTested)
            {
                yield return(null);
            }
            //  Delete Entity
            _service.DeleteEntity(OnDeleteEntity, OnFail, _createdWorkspaceId, updatedEntity);
            while (!_deleteEntityTested)
            {
                yield return(null);
            }
            //  Delete Example
            _service.DeleteExample(OnDeleteExample, OnFail, _createdWorkspaceId, updatedIntent, updatedExample);
            while (!_deleteExampleTested)
            {
                yield return(null);
            }
            //  Delete Intent
            _service.DeleteIntent(OnDeleteIntent, OnFail, _createdWorkspaceId, updatedIntent);
            while (!_deleteIntentTested)
            {
                yield return(null);
            }
            //  Delete Workspace
            _service.DeleteWorkspace(OnDeleteWorkspace, OnFail, _createdWorkspaceId);
            while (!_deleteWorkspaceTested)
            {
                yield return(null);
            }
            //  Delete User Data
            _service.DeleteUserData(OnDeleteUserData, OnFail, _unitySdkTestCustomerID);
            while (!_deleteUserDataTested)
            {
                yield return(null);
            }

            Log.Debug("TestAssistant.RunTest()", "Assistant examples complete.");

            yield break;
        }
Esempio n. 44
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     // In .NET compact, Enum.ToObject(Type, Object) is defined but the overloads like
     // Enum.ToObject(Type, int) are not -- so we get around this by boxing the value.
     return(Enum.ToObject(storageType, (object)0));
 }
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new AnimationCurve());
 }
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            serialized = new fsData(((LooseAssemblyName)instance).name);

            return(fsResult.Success);
        }
Esempio n. 47
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(fsMetaType.Get(Serializer.Config, storageType).CreateInstance());
 }
Esempio n. 48
0
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            serialized = new fsData(((Namespace)instance).FullName);

            return(fsResult.Success);
        }
Esempio n. 49
0
    /// <summary>
    /// Determines whether the specified object is equal to the current object.
    /// </summary>
    public bool Equals(fsData other)
    {
        if (other == null || Type != other.Type)
        {
            return(false);
        }

        switch (Type)
        {
        case fsDataType.Null:
            return(true);

        case fsDataType.Double:
            return(AsDouble == other.AsDouble || Math.Abs(AsDouble - other.AsDouble) < double.Epsilon);

        case fsDataType.Int64:
            return(AsInt64 == other.AsInt64);

        case fsDataType.Boolean:
            return(AsBool == other.AsBool);

        case fsDataType.String:
            return(AsString == other.AsString);

        case fsDataType.Array:
            var thisList  = AsList;
            var otherList = other.AsList;

            if (thisList.Count != otherList.Count)
            {
                return(false);
            }

            for (int i = 0; i < thisList.Count; ++i)
            {
                if (thisList[i].Equals(otherList[i]) == false)
                {
                    return(false);
                }
            }

            return(true);

        case fsDataType.Object:
            var thisDict  = AsDictionary;
            var otherDict = other.AsDictionary;

            if (thisDict.Count != otherDict.Count)
            {
                return(false);
            }

            foreach (string key in thisDict.Keys)
            {
                if (otherDict.ContainsKey(key) == false)
                {
                    return(false);
                }

                if (thisDict[key].Equals(otherDict[key]) == false)
                {
                    return(false);
                }
            }

            return(true);
        }

        throw new Exception("Unknown data type");
    }
 public override void OnAfterSerialize(Type storageType, object instance, ref fsData data)
 {
     ((fsISerializationCallbacks)instance).OnAfterSerialize(storageType, ref data);
 }
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new WeakReference(null));
 }
Esempio n. 52
0
 public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType)
 {
     throw new NotImplementedException();
 }
        public override void OnBeforeDeserializeAfterInstanceCreation(Type storageType, object instance, ref fsData data)
        {
            if (instance is fsISerializationCallbacks == false)
            {
                throw new InvalidCastException("Please ensure the converter for " + storageType + " actually returns an instance of it, not an instance of " + instance.GetType());
            }

            ((fsISerializationCallbacks)instance).OnBeforeDeserialize(storageType, ref data);
        }
Esempio n. 54
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(null);
 }
    void OnMessage(object resp, Dictionary <string, object> customData)
    {
        //  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);
        }

        if (resp != null && (messageResponse.intents.Length > 0 || messageResponse.entities.Length > 0))
        {
            string intent = messageResponse.intents[0].intent;
            Debug.Log("Intent: " + intent);
            string currentMat   = null;
            string currentScale = null;
            string direction    = null;
            if (intent == "move")
            {
                foreach (RuntimeEntity entity in messageResponse.entities)
                {
                    Debug.Log("entityType: " + entity.entity + " , value: " + entity.value);
                    direction = entity.value;
                    gameManager.MoveObject(direction);
                }
            }

            if (intent == "create")
            {
                bool createdObject = false;
                foreach (RuntimeEntity entity in messageResponse.entities)
                {
                    Debug.Log("entityType: " + entity.entity + " , value: " + entity.value);
                    if (entity.entity == "material")
                    {
                        currentMat = entity.value;
                    }
                    if (entity.entity == "scale")
                    {
                        currentScale = entity.value;
                    }
                    else if (entity.entity == "object")
                    {
                        gameManager.CreateObject(entity.value, currentMat, currentScale);
                        createdObject = true;
                        currentMat    = null;
                        currentScale  = null;
                    }
                }

                if (!createdObject)
                {
                    gameManager.PlayError(sorryClip);
                }
            }
            else if (intent == "destroy")
            {
                gameManager.DestroyAtPointer();
            }
            else if (intent == "help")
            {
                if (helpClips.Count > 0)
                {
                    gameManager.PlayClip(helpClips[Random.Range(0, helpClips.Count)]);
                }
            }
        }
        else
        {
            Debug.Log("Failed to invoke OnMessage();");
        }
    }
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new UnityEngine.Vector2());
 }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            try
            {
                VcapCredentials vcapCredentials = new VcapCredentials();
                fsData          data            = null;

                //  Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format.
                //  See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html.
                var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES");
                var fileContent           = File.ReadAllText(environmentalVariable);

                //  Add in a parent object because Unity does not like to deserialize root level collection types.
                fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES");

                //  Convert json to fsResult
                fsResult r = fsJsonParser.Parse(fileContent, 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["speech_to_text"][TestCredentialIndex].Credentials;
                _username = credential.Username.ToString();
                _password = credential.Password.ToString();
                _url      = credential.Url.ToString();
            }
            catch
            {
                Log.Debug("TestSpeechToText.RunTest()", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication");
            }

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(_username, _password, _url);

            //  Or authenticate using token
            //Credentials credentials = new Credentials(_url)
            //{
            //    AuthenticationToken = _token
            //};

            _speechToText             = new SpeechToText(credentials);
            _customCorpusFilePath     = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/theJabberwocky-utf8.txt";
            _customWordsFilePath      = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-words.json";
            _acousticResourceMimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl));

            Runnable.Run(DownloadAcousticResource());
            while (!_isAudioLoaded)
            {
                yield return(null);
            }

            //  Recognize
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to recognize");
            List <string> keywords = new List <string>();

            keywords.Add("speech");
            _speechToText.KeywordsThreshold = 0.5f;
            _speechToText.InactivityTimeout = 120;
            _speechToText.StreamMultipart   = false;
            _speechToText.Keywords          = keywords.ToArray();
            _speechToText.Recognize(HandleOnRecognize, OnFail, _acousticResourceData, _acousticResourceMimeType);
            while (!_recognizeTested)
            {
                yield return(null);
            }

            //  Get models
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get models");
            _speechToText.GetModels(HandleGetModels, OnFail);
            while (!_getModelsTested)
            {
                yield return(null);
            }

            //  Get model
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get model {0}", _modelNameToGet);
            _speechToText.GetModel(HandleGetModel, OnFail, _modelNameToGet);
            while (!_getModelTested)
            {
                yield return(null);
            }

            //  Get customizations
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customizations");
            _speechToText.GetCustomizations(HandleGetCustomizations, OnFail);
            while (!_getCustomizationsTested)
            {
                yield return(null);
            }

            //  Create customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting create customization");
            _speechToText.CreateCustomization(HandleCreateCustomization, OnFail, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity");
            while (!_createCustomizationsTested)
            {
                yield return(null);
            }

            //  Get customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get customization {0}", _createdCustomizationID);
            _speechToText.GetCustomization(HandleGetCustomization, OnFail, _createdCustomizationID);
            while (!_getCustomizationTested)
            {
                yield return(null);
            }

            //  Get custom corpora
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpora for {0}", _createdCustomizationID);
            _speechToText.GetCustomCorpora(HandleGetCustomCorpora, OnFail, _createdCustomizationID);
            while (!_getCustomCorporaTested)
            {
                yield return(null);
            }

            //  Add custom corpus
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName);
            string corpusData = File.ReadAllText(_customCorpusFilePath);

            _speechToText.AddCustomCorpus(HandleAddCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName, true, corpusData);
            while (!_addCustomCorpusTested)
            {
                yield return(null);
            }

            //  Get custom corpus
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName);
            _speechToText.GetCustomCorpus(HandleGetCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName);
            while (!_getCustomCorpusTested)
            {
                yield return(null);
            }

            //  Wait for customization
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Get custom words
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom words.");
            _speechToText.GetCustomWords(HandleGetCustomWords, OnFail, _createdCustomizationID);
            while (!_getCustomWordsTested)
            {
                yield return(null);
            }

            //  Add custom words from path
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath);
            string customWords = File.ReadAllText(_customWordsFilePath);

            _speechToText.AddCustomWords(HandleAddCustomWordsFromPath, OnFail, _createdCustomizationID, customWords);
            while (!_addCustomWordsFromPathTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isCustomizationReady = false;
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Add custom words from object
            Words       words    = new Words();
            Word        w0       = new Word();
            List <Word> wordList = new List <Word>();

            w0.word           = "mikey";
            w0.sounds_like    = new string[1];
            w0.sounds_like[0] = "my key";
            w0.display_as     = "Mikey";
            wordList.Add(w0);
            Word w1 = new Word();

            w1.word           = "charlie";
            w1.sounds_like    = new string[1];
            w1.sounds_like[0] = "char lee";
            w1.display_as     = "Charlie";
            wordList.Add(w1);
            Word w2 = new Word();

            w2.word           = "bijou";
            w2.sounds_like    = new string[1];
            w2.sounds_like[0] = "be joo";
            w2.display_as     = "Bijou";
            wordList.Add(w2);
            words.words = wordList.ToArray();

            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID);
            _speechToText.AddCustomWords(HandleAddCustomWordsFromObject, OnFail, _createdCustomizationID, words);
            while (!_addCustomWordsFromObjectTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isCustomizationReady = false;
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Get custom word
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word);
            _speechToText.GetCustomWord(HandleGetCustomWord, OnFail, _createdCustomizationID, words.words[0].word);
            while (!_getCustomWordTested)
            {
                yield return(null);
            }

            //  Train customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train customization {0}", _createdCustomizationID);
            _speechToText.TrainCustomization(HandleTrainCustomization, OnFail, _createdCustomizationID);
            while (!_trainCustomizationTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isCustomizationReady = false;
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Upgrade customization - not currently implemented in service
            //Log.Debug("ExampleSpeechToText.Examples()", "Attempting to upgrade customization {0}", _createdCustomizationID);
            //_speechToText.UpgradeCustomization(HandleUpgradeCustomization, _createdCustomizationID);
            //while (!_upgradeCustomizationTested)
            //    yield return null;

            //  Delete custom word
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word);
            _speechToText.DeleteCustomWord(HandleDeleteCustomWord, OnFail, _createdCustomizationID, words.words[2].word);
            while (!_deleteCustomWordTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            _readyToContinue = false;
            //  Delete custom corpus
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName);
            _speechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName);
            while (!_deleteCustomCorpusTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            _readyToContinue = false;
            //  Reset customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset customization {0}", _createdCustomizationID);
            _speechToText.ResetCustomization(HandleResetCustomization, OnFail, _createdCustomizationID);
            while (!_resetCustomizationTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            _readyToContinue = false;
            //  Delete customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to delete customization {0}", _createdCustomizationID);
            _speechToText.DeleteCustomization(HandleDeleteCustomization, OnFail, _createdCustomizationID);
            while (!_deleteCustomizationsTested)
            {
                yield return(null);
            }

            //  List acoustic customizations
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customizations");
            _speechToText.GetCustomAcousticModels(HandleGetCustomAcousticModels, OnFail);
            while (!_getAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Create acoustic customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create acoustic customization");
            _speechToText.CreateAcousticCustomization(HandleCreateAcousticCustomization, OnFail, _createdAcousticModelName);
            while (!_createAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Get acoustic customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get acoustic customization {0}", _createdAcousticModelId);
            _speechToText.GetCustomAcousticModel(HandleGetCustomAcousticModel, OnFail, _createdAcousticModelId);
            while (!_getAcousticCustomizationTested)
            {
                yield return(null);
            }

            while (!_isAudioLoaded)
            {
                yield return(null);
            }

            //  Create acoustic resource
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to create audio resource {1} on {0}", _createdAcousticModelId, _acousticResourceName);
            string mimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl));

            _speechToText.AddAcousticResource(HandleAddAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName, mimeType, mimeType, true, _acousticResourceData);
            while (!_addAcousticResourcesTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isAcousticCustomizationReady = false;
            Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId));
            while (!_isAcousticCustomizationReady)
            {
                yield return(null);
            }

            //  List acoustic resources
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resources {0}", _createdAcousticModelId);
            _speechToText.GetCustomAcousticResources(HandleGetCustomAcousticResources, OnFail, _createdAcousticModelId);
            while (!_getAcousticResourcesTested)
            {
                yield return(null);
            }

            //  Train acoustic customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to train acoustic customization {0}", _createdAcousticModelId);
            _speechToText.TrainAcousticCustomization(HandleTrainAcousticCustomization, OnFail, _createdAcousticModelId, null, true);
            while (!_trainAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Get acoustic resource
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to get audio resource {1} from {0}", _createdAcousticModelId, _acousticResourceName);
            _speechToText.GetCustomAcousticResource(HandleGetCustomAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName);
            while (!_getAcousticResourceTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isAcousticCustomizationReady = false;
            Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId));
            while (!_isAcousticCustomizationReady)
            {
                yield return(null);
            }

            //  Delete acoustic resource
            DeleteAcousticResource();
            while (!_deleteAcousticResource)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic resource for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            //  Reset acoustic customization
            Log.Debug("ExampleSpeechToText.Examples()", "Attempting to reset acoustic customization {0}", _createdAcousticModelId);
            _speechToText.ResetAcousticCustomization(HandleResetAcousticCustomization, OnFail, _createdAcousticModelId);
            while (!_resetAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying delete acoustic customization for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            //  Delete acoustic customization
            DeleteAcousticCustomization();
            while (!_deleteAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("ExampleSpeechToText.Examples()", string.Format("Delaying complete for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            Log.Debug("TestSpeechToText.RunTest()", "Speech to Text examples complete.");

            yield break;
        }
Esempio n. 58
0
 public override object CreateInstance(fsData data, Type storageType)
 {
     return(new EventData());
 }
Esempio n. 59
0
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            Features features = (Features)instance;

            serialized = null;

            Dictionary <string, fsData> serialization = new Dictionary <string, fsData>();

            fsData tempData = null;

            if (features.concepts != null)
            {
                _serializer.TrySerialize(features.concepts, out tempData);
                serialization.Add("concepts", tempData);
            }

            if (features.emotion != null)
            {
                _serializer.TrySerialize(features.emotion, out tempData);
                serialization.Add("emotion", tempData);
            }

            if (features.entities != null)
            {
                _serializer.TrySerialize(features.entities, out tempData);
                serialization.Add("entities", tempData);
            }

            if (features.keywords != null)
            {
                _serializer.TrySerialize(features.keywords, out tempData);
                serialization.Add("keywords", tempData);
            }

            if (features.metadata != null)
            {
                _serializer.TrySerialize(features.metadata, out tempData);
                serialization.Add("metadata", tempData);
            }

            if (features.relations != null)
            {
                _serializer.TrySerialize(features.relations, out tempData);
                serialization.Add("relations", tempData);
            }

            if (features.semantic_roles != null)
            {
                _serializer.TrySerialize(features.semantic_roles, out tempData);
                serialization.Add("semantic_roles", tempData);
            }

            if (features.sentiment != null)
            {
                _serializer.TrySerialize(features.sentiment, out tempData);
                serialization.Add("sentiment", tempData);
            }

            if (features.categories != null)
            {
                _serializer.TrySerialize(features.categories, out tempData);
                serialization.Add("categories", tempData);
            }

            serialized = new fsData(serialization);

            return(fsResult.Success);
        }
Esempio n. 60
0
        public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType)
        {
            QueryLarge queryLarge = (QueryLarge)instance;

            serialized = null;

            Dictionary <string, fsData> serialization = new Dictionary <string, fsData>();

            fsData tempData = null;

            if (queryLarge.Filter != null)
            {
                _serializer.TrySerialize(queryLarge.Filter, out tempData);
                serialization.Add("filter", tempData);
            }

            if (queryLarge.Query != null)
            {
                _serializer.TrySerialize(queryLarge.Query, out tempData);
                serialization.Add("query", tempData);
            }

            if (queryLarge.NaturalLanguageQuery != null)
            {
                _serializer.TrySerialize(queryLarge.NaturalLanguageQuery, out tempData);
                serialization.Add("natural_language_query", tempData);
            }

            if (queryLarge.Passages != null)
            {
                _serializer.TrySerialize(queryLarge.Passages, out tempData);
                serialization.Add("passages", tempData);
            }

            if (queryLarge.Aggregation != null)
            {
                _serializer.TrySerialize(queryLarge.Aggregation, out tempData);
                serialization.Add("aggregation", tempData);
            }

            if (queryLarge.Count != null)
            {
                _serializer.TrySerialize(queryLarge.Count, out tempData);
                serialization.Add("count", tempData);
            }

            if (queryLarge.ReturnFields != null)
            {
                _serializer.TrySerialize(queryLarge.ReturnFields, out tempData);
                serialization.Add("return", tempData);
            }

            if (queryLarge.Offset != null)
            {
                _serializer.TrySerialize(queryLarge.Offset, out tempData);
                serialization.Add("offset", tempData);
            }

            if (queryLarge.Sort != null)
            {
                _serializer.TrySerialize(queryLarge.Sort, out tempData);
                serialization.Add("sort", tempData);
            }

            if (queryLarge.Highlight != null)
            {
                _serializer.TrySerialize(queryLarge.Highlight, out tempData);
                serialization.Add("highlight", tempData);
            }

            if (queryLarge.PassagesFields != null)
            {
                _serializer.TrySerialize(queryLarge.PassagesFields, out tempData);
                serialization.Add("passages.fields", tempData);
            }

            if (queryLarge.PassagesCount != null)
            {
                _serializer.TrySerialize(queryLarge.PassagesCount, out tempData);
                serialization.Add("passages.count", tempData);
            }

            if (queryLarge.PassagesCharacters != null)
            {
                _serializer.TrySerialize(queryLarge.PassagesCharacters, out tempData);
                serialization.Add("passages.characters", tempData);
            }

            if (queryLarge.Deduplicate != null)
            {
                _serializer.TrySerialize(queryLarge.Deduplicate, out tempData);
                serialization.Add("deduplicate", tempData);
            }

            if (queryLarge.DeduplicateField != null)
            {
                _serializer.TrySerialize(queryLarge.DeduplicateField, out tempData);
                serialization.Add("deduplicate.field", tempData);
            }

            if (queryLarge.CollectionIds != null)
            {
                _serializer.TrySerialize(queryLarge.CollectionIds, out tempData);
                serialization.Add("collection_ids", tempData);
            }

            if (queryLarge.Similar != null)
            {
                _serializer.TrySerialize(queryLarge.Similar, out tempData);
                serialization.Add("similar", tempData);
            }

            if (queryLarge.SimilarDocumentIds != null)
            {
                _serializer.TrySerialize(queryLarge.SimilarDocumentIds, out tempData);
                serialization.Add("similar.document_ids", tempData);
            }

            if (queryLarge.SimilarFields != null)
            {
                _serializer.TrySerialize(queryLarge.SimilarFields, out tempData);
                serialization.Add("similar.fields", tempData);
            }

            if (queryLarge.Bias != null)
            {
                _serializer.TrySerialize(queryLarge.Bias, out tempData);
                serialization.Add("bias", tempData);
            }

            serialized = new fsData(serialization);

            return(fsResult.Success);
        }