public static void Register(System.Type tp, IService service)
        {
            if (tp == null)
            {
                throw new System.ArgumentNullException("tp");
            }
            if (!tp.IsClass || tp.IsAbstract || !typeof(IService).IsAssignableFrom(tp))
            {
                throw new System.ArgumentException("Type must be a concrete class that implements IService.", "tp");
            }


            System.Reflection.FieldInfo field;
            try
            {
                var klass = typeof(Entry <>);
                klass = klass.MakeGenericType(tp);
                field = klass.GetField("Instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
            }
            catch (System.Exception ex)
            {
                throw new System.InvalidOperationException("Failed to resolve type '" + tp.Name + "'.", ex);
            }

            if (field == null)
            {
                throw new System.InvalidOperationException("Failed to resolve type '" + tp.Name + "'.");
            }

            if (field.GetValue(null) != null)
            {
                throw new System.InvalidOperationException("You must first unregister a service before registering a new one.");
            }
            field.SetValue(null, service);
        }
        public static void Unregister(System.Type tp, bool donotSignalUnregister = false)
        {
            if (tp == null)
            {
                throw new System.ArgumentNullException("tp");
            }
            if (!tp.IsClass || tp.IsAbstract || !typeof(IService).IsAssignableFrom(tp))
            {
                throw new System.ArgumentException("Type must be a concrete class that implements IService.", "tp");
            }

            IService inst;

            try
            {
                var klass = typeof(Entry <>);
                klass = klass.MakeGenericType(tp);
                var field = klass.GetField("Instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                inst = field.GetValue(null) as IService;
                if (inst != null)
                {
                    field.SetValue(null, null);
                }
            }
            catch (System.Exception ex)
            {
                throw new System.InvalidOperationException("Failed to resolve type '" + tp.Name + "'.", ex);
            }

            if (!donotSignalUnregister && inst != null)
            {
                inst.SignalServiceUnregistered();
            }
        }
Ejemplo n.º 3
0
        public static T GetOrCreate(System.Type tp, bool persistent = false, string name = null)
        {
            if (tp == null)
            {
                throw new System.ArgumentNullException("tp");
            }
            if (!typeof(ScriptableObject).IsAssignableFrom(tp) || !typeof(T).IsAssignableFrom(tp))
            {
                throw new System.ArgumentException("Type must be a Component that implements " + typeof(T).Name);
            }

            var inst = Services.Get <T>();

            if (inst != null)
            {
                return(inst);
            }

            if (name == null)
            {
                name = "Service." + typeof(T).Name;
            }
            var obj = ScriptableObject.CreateInstance(tp) as ScriptableObject;

            obj.name = name;
            return(obj as T);
        }
Ejemplo n.º 4
0
        string[] _getTypeNames(System.Type typeBase, string[] assemblyNames)
        {
            List <string> typeNames = new List <string>();

            foreach (string assemblyName in assemblyNames)
            {
                Assembly assembly = null;
                try
                {
                    assembly = Assembly.Load(assemblyName);
                }
                catch
                {
                    continue;
                }

                if (assembly == null)
                {
                    continue;
                }

                System.Type[] types = assembly.GetTypes();
                foreach (System.Type type in types)
                {
                    if (type.IsClass && !type.IsAbstract && typeBase.IsAssignableFrom(type))
                    {
                        typeNames.Add(type.FullName);
                    }
                }
            }

            typeNames.Sort();
            return(typeNames.ToArray());
        }
Ejemplo n.º 5
0
        private static System.Reflection.FieldInfo GetStaticEntryFieldInfo(System.Type tp, bool createIfNotFound)
        {
            System.Reflection.FieldInfo result = null;
            if (_staticFieldTable.TryGetValue(tp, out result))
            {
                return(result);
            }

            if (createIfNotFound)
            {
                try
                {
                    var klass = typeof(Entry <>);
                    klass  = klass.MakeGenericType(tp);
                    result = klass.GetField("Instance", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    _staticFieldTable[tp] = result;
                }
                catch (System.Exception ex)
                {
                    throw new System.InvalidOperationException("Failed to resolve type '" + tp.Name + "'.", ex);
                }
            }

            return(result);
        }
Ejemplo n.º 6
0
        public static T GetOrCreate(System.Type tp, bool persistent = false, string name = null)
        {
            if (tp == null)
            {
                throw new System.ArgumentNullException("tp");
            }
            if (!typeof(Component).IsAssignableFrom(tp) || !typeof(T).IsAssignableFrom(tp))
            {
                throw new System.ArgumentException("Type must be a Component that implements " + typeof(T).Name);
            }

            var inst = Services.Get <T>();

            if (inst != null)
            {
                return(inst);
            }

            if (name == null)
            {
                name = "Service." + typeof(T).Name;
            }
            var go = new GameObject(name);

            if (persistent)
            {
                GameObject.DontDestroyOnLoad(go);
            }
            return(go.AddComponent(tp) as T);
        }
Ejemplo n.º 7
0
        object IConvertible.ToType(System.Type conversionType, IFormatProvider?provider)
        {
            if (Proxies.ContainsKey(conversionType))
            {
                return(Proxies[conversionType]);
            }

            if (ToTypeCore(out var converted))
            {
                return(Proxies[conversionType] = converted !);
            }

            throw new InvalidCastException($"Unable to cast {this.GetType().FullName} into {conversionType.FullName}");

            bool ToTypeCore(out object?result)
            {
                if (!conversionType.IsInstanceOfType(this))
                {
                    return(MakeProxy(conversionType, false, out result));
                }

                result = this;
                return(true);
            }
        }
        /// <summary>
        /// Imports values from external source
        /// </summary>
        /// <param name="importer">User who importing values</param>
        /// <param name="vocabularyType">Type of vocabulary</param>
        /// <param name="source">External source</param>
        public Dictionary <string, string> Import(User importer, System.Type vocabularyType, IExternalVocabularySource source)
        {
            var newValuesArray = source.GetValuesFromFile();

            _extensibleVocabularyService.AddNewExtendedValuesBy(importer.Id, vocabularyType, newValuesArray);

            return(newValuesArray);
        }
Ejemplo n.º 9
0
        private void _instantiationCreateType()
        {
            if (_oldSelectIndex != _createTypeSelectIndex || _localizationCreate == null)
            {
                System.Type createType = _getType(_LocalizationCreateTypes[_createTypeSelectIndex]);

                _localizationCreate = (LocalizationCreateAndParseBase)Activator.CreateInstance(createType);
                _oldSelectIndex     = _createTypeSelectIndex;
            }
        }
Ejemplo n.º 10
0
        public static bool Exists(System.Type tp)
        {
            IService serv;

            if (_serviceTable.TryGetValue(tp, out serv))
            {
                return(!serv.IsNullOrDestroyed());
            }

            return(false);
        }
 //----------------------------------------------------------------------
 static object CreateDefaultObject(System.Type type)
 {
     if (type.IsValueType)
     {
         return(Activator.CreateInstance(type));
     }
     if (CanSerialiseEnumerable(type))
     {
         var elementType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0];
         return(Activator.CreateInstance(typeof(List <>).MakeGenericType(new Type[] { elementType })));
     }
     return(null);
 }
    static System.Type GetType(string name)
    {
        System.Type type       = null;
        var         assemblies = System.AppDomain.CurrentDomain.GetAssemblies();

        for (int i = 0; i < assemblies.Length; i++)
        {
            type = assemblies[i].GetType(name);
            if (type != null)
            {
                break;
            }
        }
        return(type);
    }
Ejemplo n.º 13
0
        protected static void SetStaticProperty <T>(System.Type type, T value, [CallerMemberName] string?propertyName = null)
        {
            type         = type ?? throw new ArgumentNullException(nameof(type));
            propertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName));

            JsiiTypeAttributeBase.Load(type.Assembly);

            var classAttribute    = ReflectionUtils.GetClassAttribute(type) !;
            var propertyAttribute = GetStaticPropertyAttribute(type, propertyName);

            SetPropertyCore(
                value,
                propertyAttribute,
                (client, jsiiValue) => client.StaticSet(classAttribute.FullyQualifiedName, propertyAttribute.Name, jsiiValue)
                );
        }
Ejemplo n.º 14
0
 //----------------------------------------------------------------------
 static object CreateDefaultObject(System.Type type)
 {
     if (type.IsValueType)
     {
         return((object)System.Activator.CreateInstance(type));
     }
     if (CanSerialiseGenericList(type) && SUPPORT_LISTS)
     {
         return((object)System.Activator.CreateInstance(typeof(List <>).MakeGenericType(new Type[] { type })));
     }
     if (CanSerialiseArray(type))
     {
         return((object)System.Array.CreateInstance(type.GetElementType(), 0));
     }
     return(null);
 }
Ejemplo n.º 15
0
        public static TServiceType GetOrCreate <TServiceType>(System.Type concreteType, bool persistent = false, string name = null) where TServiceType : class, IService
        {
            if (concreteType == null)
            {
                throw new System.ArgumentNullException("concreteType");
            }
            if (!typeof(TServiceType).IsAssignableFrom(concreteType))
            {
                throw new System.ArgumentException("Type must implement " + typeof(TServiceType).Name);
            }

            var inst = Services.Get <TServiceType>();

            if (inst != null)
            {
                return(inst);
            }

            if (typeof(Component).IsAssignableFrom(concreteType))
            {
                var obj = ServiceComponent <TServiceType> .Create(concreteType, persistent, name);

                Services.Register <TServiceType>(obj);
                return(obj);
            }
            else if (typeof(ScriptableObject).IsAssignableFrom(concreteType))
            {
                var obj = ServiceScriptableObject <TServiceType> .Create(concreteType, persistent, name);

                Services.Register <TServiceType>(obj);
                return(obj);
            }
            else
            {
                try
                {
                    var obj = System.Activator.CreateInstance(concreteType) as TServiceType;
                    Services.Register <TServiceType>(obj);
                    return(obj);
                }
                catch (System.Exception ex)
                {
                    throw new System.InvalidOperationException("Supplied concrete service type failed to construct.", ex);
                }
            }
        }
Ejemplo n.º 16
0
        private static bool InterfaceIsActionDelegate(System.Type type)
        {
            if (type == typeof(IFsmActionDelegate))
            {
                return(true);
            }

            foreach (var i in type.GetInterfaces())
            {
                if (InterfaceIsActionDelegate(i))
                {
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 17
0
        protected static T InvokeStaticMethod <T>(System.Type type, System.Type[] parameterTypes, object?[] arguments, [CallerMemberName] string methodName = "")
        {
            JsiiTypeAttributeBase.Load(type.Assembly);

            var methodAttribute = GetStaticMethodAttribute(type, methodName, parameterTypes);
            var classAttribute  = ReflectionUtils.GetClassAttribute(type) !;

            return(InvokeMethodCore <T>(
                       methodAttribute,
                       arguments,
                       (client, args) => throw new NotSupportedException("Async static methods are currently not supported"),
                       (client, args) => client.StaticInvoke(
                           classAttribute.FullyQualifiedName,
                           methodAttribute.Name,
                           ConvertArguments(methodAttribute.Parameters, arguments)
                           )
                       ));
        }
        /// <summary>
        /// Returns list of vocabulary values
        /// </summary>
        /// <param name="vocabularyType">Type of vocabulary</param>
        /// <returns>List of vocabulary values</returns>
        public IEnumerable <VocabularyValue> GetVocabularyValuesExtended(System.Type vocabularyType, string itemType, string search, string userId)
        {
            var plugins      = _pluginsProvider.GetPluginsFor(vocabularyType).ToList();
            var stringValues = new List <VocabularyValue>();

            foreach (var plugin in plugins)
            {
                var vocabularyPlugin = plugin as IVocabularyExtenalSourcePlugin;
                if (vocabularyPlugin != null)
                {
                    stringValues.AddRange(vocabularyPlugin.GetValuesExtended(search, itemType));
                }
            }
            var pluginsCollection = stringValues.Distinct().ToList();

            var systemCollection = _extensibleVocabularyService.GetAllExtenededValues(vocabularyType, userId).Where(v => v.Value.StartsWith(search)).ToList();

            if ("Country".ToLower() == itemType.ToLower())
            {
                foreach (var item in pluginsCollection.Select(f => f.Value).Distinct().ToList())
                {
                    if (null == systemCollection.FirstOrDefault(c => c.Value == item))
                    {
                        systemCollection.Add(new VocabularyValue {
                            Value = item.First().ToString().ToUpper() + item.Substring(1)
                        });
                    }
                }
            }

            if (itemType.ToLower() == "class" || itemType.ToLower() == "order" || itemType.ToLower() == "family")
            {
                systemCollection.AddRange(pluginsCollection.Select(f => f.Value).Distinct().Select(p => new VocabularyValue {
                    Value = p
                }));
            }

            if ("LocationName".ToLower() == itemType.ToLower())
            {
                systemCollection.AddRange(pluginsCollection.Distinct());
            }

            return(systemCollection.OrderBy(o => o.Value));
        }
Ejemplo n.º 19
0
        public static TServiceType Create <TServiceType>(System.Type concreteType, bool persistent = false, string name = null) where TServiceType : class, IService
        {
            var inst = Services.Get <TServiceType>();

            if (inst != null)
            {
                throw new System.InvalidOperationException(string.Format("A service of type '{0}' already exists.", typeof(TServiceType).Name));
            }

            var serv = CreateUnregisteredService <TServiceType>(concreteType, persistent, name);

            if (serv == null)
            {
                return(null);
            }

            Register <TServiceType>(serv);
            return(serv);
        }
Ejemplo n.º 20
0
        public static TServiceType GetOrCreate <TServiceType>(System.Type concreteType, bool persistent = false, string name = null) where TServiceType : class, IService
        {
            var inst = Services.Get <TServiceType>();

            if (inst != null)
            {
                return(inst);
            }

            var serv = CreateUnregisteredService <TServiceType>(concreteType, persistent, name);

            if (serv == null)
            {
                return(null);
            }

            Register <TServiceType>(serv);
            return(serv);
        }
    //----------------------------------------------------------------------
    static bool CanSerialiseType(System.Type _type)
    {
        var param = !_type.IsEnum ? _type : typeof(System.Enum);

        if (!UnitySerialiseFieldByType.ContainsKey(_type))
        {
            if (typeof(UnityEngine.Object).IsAssignableFrom(_type))
            {
                var methodTemplate    = typeof(MonoBehaviourEditor).GetMethod("DrawMonobehaviour", BindingFlags.Static | BindingFlags.NonPublic);
                var newMethod         = methodTemplate.MakeGenericMethod(_type);
                var serialiseDelegate = (SerialiseParameter)Delegate.CreateDelegate(typeof(SerialiseParameter), newMethod);
                UnitySerialiseFieldByType.Add(_type, serialiseDelegate);
            }
            if (!UnitySerialiseFieldByType.ContainsKey(_type))
            {
                return(false);
            }
        }
        return(UnitySerialiseFieldByType.ContainsKey(param));
    }
Ejemplo n.º 22
0
    //----------------------------------------------------------------------
    static bool CanSerialiseGenericList(System.Type _type)
    {
        if (!SUPPORT_LISTS)
        {
            return(false);
        }

        if (!_type.IsGenericType || _type.GetGenericTypeDefinition() != typeof(List <>))
        {
            return(false);
        }
        var parameters = _type.GetGenericArguments();

        if (parameters.Length > 1)
        {
            return(false);
        }
        var param = !parameters[0].IsEnum ? parameters[0] : typeof(System.Enum);

        return(UnitySerialiseFieldByType.ContainsKey(param));
    }
    //----------------------------------------------------------------------
    static bool CanSerialiseEnumerable(System.Type _type)
    {
        //array
        if (_type.IsArray)
        {
            return(CanSerialiseType(_type.GetElementType()));
        }

        //list<T>
        if (!_type.IsGenericType || _type.GetGenericTypeDefinition() != typeof(List <>))
        {
            return(false);
        }
        var parameters = _type.GetGenericArguments();

        if (parameters.Length > 1)
        {
            return(false);
        }
        return(CanSerialiseType(parameters[0]));
    }
Ejemplo n.º 24
0
        private static JsiiPropertyAttribute GetPropertyAttributeCore(System.Type type, string propertyName, BindingFlags bindingFlags)
        {
            type         = type ?? throw new ArgumentNullException(nameof(type));
            propertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName));

            var propertyInfo = type.GetProperty(propertyName, bindingFlags);

            if (propertyInfo == null)
            {
                throw new ArgumentException($"Property {propertyName} does not exist", nameof(propertyName));
            }

            var attribute = propertyInfo.GetCustomAttribute <JsiiPropertyAttribute>();

            if (attribute == null)
            {
                throw new ArgumentException($"Property {propertyName} is missing JsiiPropertyAttribute", nameof(propertyName));
            }

            return(attribute);
        }
Ejemplo n.º 25
0
        public static void Register(System.Type tp, IService service)
        {
            if (tp == null)
            {
                throw new System.ArgumentNullException("tp");
            }
            if (service.IsNullOrDestroyed())
            {
                throw new System.ArgumentNullException("service");
            }
            if (!typeof(IService).IsAssignableFrom(tp))
            {
                throw new System.ArgumentException("Type must implement IService.", "tp");
            }
            if (!tp.IsAssignableFrom(service.GetType()))
            {
                throw new System.ArgumentException(string.Format("Service must implement the service type '{0}' it's being registered for.", tp.Name), "tp");
            }

            System.Reflection.FieldInfo field = GetStaticEntryFieldInfo(tp, true);
            if (field == null)
            {
                throw new System.InvalidOperationException("Failed to resolve type '" + tp.Name + "'.");
            }

            var other = field.GetValue(null);

            if (!other.IsNullOrDestroyed() && !object.ReferenceEquals(other, service))
            {
                throw new System.InvalidOperationException("You must first unregister a service before registering a new one.");
            }

            _services.Add(service);
            field.SetValue(null, service);
            _serviceTable[tp] = service;

            //make sure we don't add it multiple times
            service.Disposed -= OnServiceInadvertentlyDisposed;
            service.Disposed += OnServiceInadvertentlyDisposed;
        }
        /// <summary>
        /// Returns list of vocabulary values
        /// </summary>
        /// <param name="vocabularyType">Type of vocabulary</param>
        /// <returns>List of vocabulary values</returns>
        public IEnumerable <VocabularyValue> GetVocabularyValues(System.Type vocabularyType, string userId)
        {
            var resultCollection = new List <VocabularyValue>();

            resultCollection.AddRange(_extensibleVocabularyService.GetAllExtenededValues(vocabularyType, userId).ToList());

            resultCollection.AddRange(_extensibleVocabularyService.GetExtenededValuesBy(userId, vocabularyType));

            var plugins = _pluginsProvider.GetPluginsFor(vocabularyType).ToList();

            foreach (var plugin in plugins)
            {
                var vocabularyPlugin = plugin as IVocabularyExtenalSourcePlugin;
                if (vocabularyPlugin != null)
                {
                    resultCollection.AddRange(vocabularyPlugin.GetValues());
                }
            }

            // GetValuesExtended(string search, string elementName)
            return(resultCollection.OrderBy(o => o.Value));
        }
Ejemplo n.º 27
0
        public DocumentBuilder(System.Type clazz, Analyzer defaultAnalyzer, IDirectoryProvider[] directoryProviders,
            IIndexShardingStrategy shardingStrategy)
        {
            analyzer = new ScopedAnalyzer();
            beanClass = clazz;
            this.directoryProviders = directoryProviders;
            this.shardingStrategy = shardingStrategy;

            if (clazz == null) throw new AssertionFailure("Unable to build a DocumemntBuilder with a null class");

            rootPropertiesMetadata = new PropertiesMetadata();
            rootPropertiesMetadata.boost = GetBoost(clazz);
            rootPropertiesMetadata.analyzer = defaultAnalyzer;

            Set<System.Type> processedClasses = new HashedSet<System.Type>();
            processedClasses.Add(clazz);
            InitializeMembers(clazz, rootPropertiesMetadata, true, string.Empty, processedClasses);
            //processedClasses.remove( clazz ); for the sake of completness
            analyzer.GlobalAnalyzer = rootPropertiesMetadata.analyzer;
            if (idKeywordName == null)
                throw new SearchException("No document id for: " + clazz.Name);
        }
Ejemplo n.º 28
0
        private static JsiiMethodAttribute GetMethodAttributeCore(System.Type type, string methodName, System.Type[] parameterTypes, BindingFlags bindingFlags)
        {
            methodName     = methodName ?? throw new ArgumentNullException(nameof(methodName));
            type           = type ?? throw new ArgumentNullException(nameof(type));
            parameterTypes = parameterTypes ?? throw new ArgumentNullException(nameof(parameterTypes));

            var methodInfo = type.GetMethod(methodName, bindingFlags, null, parameterTypes, Array.Empty <ParameterModifier>());

            if (methodInfo == null)
            {
                throw new ArgumentException($"Method {methodName} does not exist", nameof(methodName));
            }

            var methodAttribute = methodInfo.GetCustomAttribute <JsiiMethodAttribute>();

            if (methodAttribute == null)
            {
                throw new ArgumentException($"Method {methodName} is missing JsiiMethodAttribute", nameof(methodName));
            }

            return(methodAttribute);
        }
Ejemplo n.º 29
0
        public static TServiceType CreateDecorator <TServiceType>(System.Type decoratorType, bool persistent = false, string name = null) where TServiceType : class, IService
        {
            var inst = Services.Get <TServiceType>();

            if (inst == null)
            {
                throw new System.InvalidOperationException(string.Format("Must create a concreate service of type {0} before decorating it.", typeof(TServiceType).Name));
            }

            if (decoratorType == null)
            {
                throw new System.ArgumentNullException("decoratorType");
            }
            if (!typeof(TServiceType).IsAssignableFrom(decoratorType))
            {
                throw new System.ArgumentException("Decorator Type must implement " + typeof(TServiceType).Name);
            }
            if (!typeof(IServiceDecorator <TServiceType>).IsAssignableFrom(decoratorType))
            {
                throw new System.ArgumentException("Decorator Type must implement IServiceDecorator");
            }

            var replacement = CreateUnregisteredService <TServiceType>(decoratorType, persistent, name);
            var decorator   = replacement as IServiceDecorator <TServiceType>;

            if (decorator == null)
            {
                return(null);
            }

            Entry <TServiceType> .Instance = replacement;
            ReplaceReferences(inst, replacement);

            decorator.Consume(inst);
            return(replacement);
        }
Ejemplo n.º 30
0
 private static JsiiPropertyAttribute GetStaticPropertyAttribute(System.Type type, string propertyName)
 {
     return(GetPropertyAttributeCore(type, propertyName, StaticMemberFlags));
 }
Ejemplo n.º 31
0
 private static JsiiMethodAttribute GetStaticMethodAttribute(System.Type type, string methodName, System.Type[] parameterTypes)
 {
     return(GetMethodAttributeCore(type, methodName, parameterTypes, StaticMemberFlags));
 }