コード例 #1
0
                public static Type[] GetKnownTypes()
                {
                    var assembly = AppDomain.CurrentDomain.GetLoadedAssemblies(false).FirstOrDefault(a => a.FullName.StartsWith("DynamicClasses", StringComparison.Ordinal));
                    var types    = new List <Type>(assembly == null ? ArrayShim.Empty <Type>() : assembly.GetTypes().Where(t => t.Name.StartsWith("DynamicClass", StringComparison.Ordinal)).ToArray());

                    return(types.ToArray());
                }
コード例 #2
0
        /// <summary>
        /// Resolves the specified types with the specified tag.
        /// </summary>
        /// <param name="types">The types.</param>
        /// <param name="tag">The tag.</param>
        /// <returns>A list of resolved types. If one of the types cannot be resolved, that location in the array will be <c>null</c>.</returns>
        public object[] ResolveMultiple(Type[] types, object tag = null)
        {
            Argument.IsNotNull("types", types);

            if (types.Length == 0)
            {
                return(ArrayShim.Empty <object>());
            }

            int typeCount     = types.Length;
            var resolvedTypes = new object[typeCount];

            lock (_serviceLocator)
            {
                for (int i = 0; i < typeCount; i++)
                {
                    try
                    {
                        resolvedTypes[i] = Resolve(types[i], tag);
                    }
                    catch (TypeNotRegisteredException ex)
                    {
                        Log.Debug(ex, "Failed to resolve type '{0}', returning null", ex.RequestedType.GetSafeFullName(false));
                    }
                }
            }

            return(resolvedTypes);
        }
コード例 #3
0
        /// <summary>
        /// Converts an <see cref="Enumerable" /> into a <see cref="IReadOnlyList{T}" /> or <see cref="IReadOnlyCollection{T}" />
        /// </summary>
        /// <param name="instance">The enumerable</param>
        /// <param name="type">The type</param>
        /// <returns>The <see cref="IReadOnlyList{T}" /> or <see cref="IReadOnlyCollection{T}" /> as <see cref="IEnumerable" /></returns>
        public static IEnumerable AsReadOnly(this IEnumerable instance, Type type)
        {
            var list       = instance.ToList(type);
            var methodInfo = AsReadOnlyGenericMethodInfoCache.GetFromCacheOrFetch(type, () => list.GetType().GetMethodEx("AsReadOnly"));

            return((IEnumerable)methodInfo.Invoke(list, ArrayShim.Empty <object>()));
        }
コード例 #4
0
ファイル: CatelTypeInfo.cs プロジェクト: lixingx86/Catel
        /// <summary>
        /// Finds the properties that represent a <see cref="PropertyData"/>.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The list of <see cref="PropertyData"/> elements found as properties.</returns>
        /// <exception cref="InvalidOperationException">One ore more properties are not declared correctly.</exception>
        private IEnumerable <PropertyData> FindCatelProperties(Type type)
        {
            // CTL-212: Generic types are not supported for FieldInfo.GetValue
            if (type.ContainsGenericParametersEx())
            {
                return(ArrayShim.Empty <PropertyData>());
            }

            PreventWrongDeclaredProperties(type);

            // Properties - actual addition
            var foundProperties = new List <PropertyData>();

            var properties = new List <PropertyInfo>();

            properties.AddRange(type.GetPropertiesEx(BindingFlagsHelper.GetFinalBindingFlags(true, true, true), true));
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(PropertyData))
                {
                    var propertyValue = property.GetValue(null, null) as PropertyData;
                    if (propertyValue != null)
                    {
                        foundProperties.Add(propertyValue);
                    }
                }
            }

            return(foundProperties);
        }
コード例 #5
0
            public static object Apply(JintRuntime runtime, object @this, JsObject callee, object[] arguments)
            {
                if (!JsValue.IsFunction(@this))
                    throw new ArgumentException("The target of call() must be a function");

                object target;

                if (arguments.Length >= 1 && !JsValue.IsNullOrUndefined(arguments[0]))
                    target = arguments[0];
                else
                    target = runtime.Global.GlobalScope;

                object[] argumentsCopy;

                if (arguments.Length >= 2)
                {
                    var shim = new ArrayShim(arguments[1]);

                    argumentsCopy = new object[shim.Length];

                    foreach (var item in shim)
                    {
                        argumentsCopy[item.Key] = item.Value;
                    }
                }
                else
                {
                    argumentsCopy = JsValue.EmptyArray;
                }

                // Executes the statements in 'that' and use _this as the target of the call
                return ((JsObject)@this).Execute(runtime, target, argumentsCopy);
            }
コード例 #6
0
ファイル: ExceptionFactory.cs プロジェクト: shekky/Catel
        /// <summary>
        /// Creates the exception with the message and inner exception. If the exception does not support creation with
        /// inner exceptions, it will use the message only.
        /// </summary>
        /// <param name="exceptionType">Type of the exception.</param>
        /// <param name="message">The message.</param>
        /// <param name="innerException">The inner exception.</param>
        /// <returns>The created exception or <c>null</c> if there was no valid constructor available.</returns>
        public static Exception CreateException(Type exceptionType, string message, Exception innerException = null)
        {
            // Try 1: with inner exception
            if (innerException != null)
            {
                var argsWithInnerException      = new object[] { message, innerException };
                var exceptionWithInnerException = CreateException(exceptionType, argsWithInnerException);
                if (exceptionWithInnerException != null)
                {
                    return(exceptionWithInnerException);
                }
            }

            // try 2: without inner exception
            var args      = new object[] { message };
            var exception = CreateException(exceptionType, args);

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

            // try 3: without anything
            exception = CreateException(exceptionType, ArrayShim.Empty <object>());
            if (exception != null)
            {
                return(exception);
            }

            return(null);
        }
コード例 #7
0
        /// <summary>
        /// Finds the fields that represent a <see cref="PropertyData"/>.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The list of <see cref="PropertyData"/> elements found as fields.</returns>
        /// <exception cref="InvalidOperationException">One ore more fields are not declared correctly.</exception>
        private IEnumerable <PropertyData> FindCatelFields(Type type)
        {
            // CTL-212: Generic types are not supported for FieldInfo.GetValue
            if (type.ContainsGenericParametersEx())
            {
                return(ArrayShim.Empty <PropertyData>());
            }

            PreventWrongDeclaredFields(type);

            // Fields - actual addition
            var foundFields = new List <PropertyData>();

            var fields = new List <FieldInfo>();

            fields.AddRange(type.GetFieldsEx(BindingFlagsHelper.GetFinalBindingFlags(true, true, false)));
            foreach (var field in fields)
            {
                if (field.FieldType == typeof(PropertyData))
                {
                    var propertyValue = (field.IsStatic ? field.GetValue(null) : field.GetValue(this)) as PropertyData;
                    if (propertyValue != null)
                    {
                        foundFields.Add(propertyValue);
                    }
                }
            }

            return(foundFields);
        }
コード例 #8
0
        /// <summary>
        /// Gets the types prefiltered by assembly. If types must be retrieved from a single assembly only, this method is very fast.
        /// </summary>
        /// <param name="assembly">Name of the assembly.</param>
        /// <param name="predicate">The predicate.</param>
        /// <param name="allowInitialization">If set to <c>true</c>, allow initialization of the AppDomain if it hasn't happened yet. If <c>false</c>, deal with the types currently in the cache.</param>
        /// <returns>System.Type[].</returns>
        private static Type[] GetTypesPrefilteredByAssembly(Assembly assembly, Func <Type, bool> predicate, bool allowInitialization)
        {
            if (allowInitialization)
            {
                InitializeTypes(assembly);
            }

            var assemblyName = (assembly != null) ? TypeHelper.GetAssemblyNameWithoutOverhead(assembly.FullName) : string.Empty;

            // IMPORTANT NOTE!!!! DON'T USE LOGGING IN THE CODE BELOW BECAUSE IT MIGHT CAUSE DEADLOCK (BatchLogListener will load
            // async stuff which can deadlock). Keep it simple without calls to other code. Do any type initialization *outside*
            // the lock and make sure not to make calls to other methods

            Dictionary <string, Type> typeSource = null;

            lock (_lockObject)
            {
                if (!string.IsNullOrWhiteSpace(assemblyName))
                {
                    _typesByAssembly.TryGetValue(assemblyName, out typeSource);
                }
                else
                {
                    typeSource = _typesWithAssembly;
                }
            }

            if (typeSource == null)
            {
                return(ArrayShim.Empty <Type>());
            }

            var retryCount = 3;

            while (retryCount > 0)
            {
                retryCount--;

                try
                {
                    if (predicate != null)
                    {
                        return(typeSource.Values.Where(predicate).ToArray());
                    }

                    return(typeSource.Values.ToArray());
                }
                catch (Exception)
                {
                    // Ignore
                }
            }

            return(ArrayShim.Empty <Type>());

            // IMPORTANT NOTE: READ NOTE ABOVE BEFORE EDITING THIS METHOD!!!!
        }
コード例 #9
0
        /// <summary>
        /// Converts the list of objects to an array of attributes, very easy to use during GetCustomAttribute reflection.
        /// </summary>
        /// <param name="objects">The object array, can be <c>null</c>.</param>
        /// <returns>Attribute array or empty array if <paramref name="objects"/> is <c>null</c>.</returns>
        public static Attribute[] ToAttributeArray(this object[] objects)
        {
            if (objects == null)
            {
                return(ArrayShim.Empty <Attribute>());
            }

            return(objects.Cast <Attribute>().ToArray());
        }
コード例 #10
0
        /// <summary>
        /// Converts a string to a byte array.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The byte array value of the string.</returns>
        public static byte[] ToByteArray(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(ArrayShim.Empty <byte>());
            }

            var encoding = new UTF8Encoding();

            return(encoding.GetBytes(value));
        }
コード例 #11
0
        /// <summary>
        /// Gets the properties of the view.
        /// </summary>
        /// <param name="view">The view.</param>
        /// <returns>List of properties.</returns>
        public static string[] GetProperties(this IView view)
        {
            Argument.IsNotNull("view", view);

#if !XAMARIN
            var viewProperties = ((FrameworkElement)view).GetDependencyProperties();
            return(viewProperties.Select(x => x.PropertyName).ToArray());
#else
            return(ArrayShim.Empty <string>());
#endif
        }
コード例 #12
0
ファイル: AppDomain.cs プロジェクト: xubinvc/Catel
        public Assembly[] GetAssemblies()
        {
            lock (_lock)
            {
                if (_loadedAssemblies == null)
                {
                    var loadedAssemblies = new List <Assembly>();

#if NETFX_CORE
                    var folder = Package.Current.InstalledLocation;

                    // Note: normally it's bad practice to use task.Wait(), but GetAssemblies must be blocking to cache it all

                    var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, new[] { ".dll", ".exe", ".winmd" });
                    queryOptions.FolderDepth = FolderDepth.Shallow;

                    var queryResult = folder.CreateFileQueryWithOptions(queryOptions);

                    var task = queryResult.GetFilesAsync().AsTask();
                    task.Wait();

                    var files = task.Result.ToList();

                    var arrayToIgnore = KnownPrefixesToIgnore.ToArray();

                    foreach (var file in files)
                    {
                        if (file.Name.StartsWithAnyIgnoreCase(arrayToIgnore))
                        {
                            continue;
                        }

                        var assembly = LoadAssemblyFromFile(file);
                        if (assembly != null)
                        {
                            loadedAssemblies.Add(assembly);
                        }
                    }
#else
                    var currentdomain = typeof(string).GetTypeInfo().Assembly.GetType("System.AppDomain").GetRuntimeProperty("CurrentDomain").GetMethod.Invoke(null, ArrayShim.Empty <object>());
                    var method        = currentdomain.GetType().GetRuntimeMethod("GetAssemblies", ArrayShim.Empty <Type>());
                    var assemblies    = method.Invoke(currentdomain, ArrayShim.Empty <object>()) as Assembly[];
                    loadedAssemblies.AddRange(assemblies);
#endif

                    _loadedAssemblies = loadedAssemblies.ToArray();
                }

                return(_loadedAssemblies);
            }
        }
コード例 #13
0
        /// <summary>
        /// Constructs the view with the view model. First, this method tries to inject the specified DataContext into the
        /// view. If the view does not contain a constructor with this parameter type, it will try to use the default constructor
        /// and set the DataContext manually.
        /// </summary>
        /// <param name="viewType">Type of the view to instantiate.</param>
        /// <param name="dataContext">The data context to inject into the view. In most cases, this will be a view model.</param>
        /// <returns>
        /// The constructed view or <c>null</c> if it was not possible to construct the view.
        /// </returns>
        /// <exception cref="ArgumentNullException">The <paramref name="viewType" /> is <c>null</c>.</exception>
        public static FrameworkElement ConstructViewWithViewModel(Type viewType, object dataContext)
        {
            Argument.IsNotNull("viewType", viewType);

            Log.Debug("Constructing view for view type '{0}'", viewType.Name);

            FrameworkElement view;

            // First, try to constructor directly with the data context
            if (dataContext != null)
            {
                var injectionConstructor = viewType.GetConstructorEx(new[] { dataContext.GetType() });
                if (injectionConstructor != null)
                {
                    view = (FrameworkElement)injectionConstructor.Invoke(new[] { dataContext });

                    Log.Debug("Constructed view using injection constructor");

                    return(view);
                }
            }

            Log.Debug("No constructor with data (of type '{0}') injection found, trying default constructor", ObjectToStringHelper.ToTypeString(dataContext));

            // Try default constructor
            var defaultConstructor = viewType.GetConstructorEx(ArrayShim.Empty <Type>());

            if (defaultConstructor is null)
            {
                Log.Error("View '{0}' does not have an injection or default constructor thus cannot be constructed", viewType.Name);
                return(null);
            }

            try
            {
                view = (FrameworkElement)defaultConstructor.Invoke(null);
            }
            catch (Exception ex)
            {
                throw Log.ErrorAndCreateException <InvalidOperationException>(ex, "Failed to construct view '{0}' with both injection and empty constructor", viewType.Name);
            }

            view.DataContext = dataContext;

            Log.Debug("Constructed view using default constructor and setting DataContext afterwards");

            return(view);
        }
コード例 #14
0
        /// <summary>
        /// Gets the auto complete values.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="filter">The filter.</param>
        /// <param name="source">The source.</param>
        /// <returns>System.String[].</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is <c>null</c>.</exception>
        public virtual string[] GetAutoCompleteValues(string property, string filter, IEnumerable source)
        {
            Argument.IsNotNull("source", source);

            if (source is string)
            {
                return(ArrayShim.Empty <string>());
            }

            var propertyValues = new List <string>();

            if (string.IsNullOrWhiteSpace(property))
            {
                try
                {
                    // Filter items directly
                    propertyValues.AddRange(from x in source.OfType <string>()
                                            select x);
                }
                catch (Exception)
                {
                    // Swallow
                }
            }
            else
            {
                propertyValues.AddRange(from x in source.Cast <object>()
                                        select GetPropertyValue(x, property));
            }

            propertyValues = propertyValues.Where(x => !string.Equals(x, "null")).Distinct().ToList();

            var filteredValues = propertyValues;

            if (!string.IsNullOrEmpty(filter))
            {
                filteredValues = filteredValues.Where(x => x.Contains(filter)).ToList();
            }

            var orderedPropertyValues = filteredValues.GroupBy(x => x).Select(g => new
            {
                Value = g.Key,
                Count = g.Select(x => x).Distinct().Count()
            }).OrderBy(x => x.Count).Select(x => x.Value).Take(10);

            return(orderedPropertyValues.OrderBy(x => x).ToArray());
        }
コード例 #15
0
        /// <summary>
        /// Gets the known types via attributes.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The list of known types via the <see cref="KnownTypeAttribute"/>.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        protected virtual Type[] GetKnownTypesViaAttributes(Type type)
        {
            Argument.IsNotNull("type", type);

            string typeName = type.AssemblyQualifiedName;

            if (string.IsNullOrWhiteSpace(typeName))
            {
                return(ArrayShim.Empty <Type>());
            }

            return(_knownTypesByAttributesCache.GetFromCacheOrFetch(typeName, () =>
            {
                var additionalTypes = new List <Type>();
                var knownTypeAttributes = type.GetCustomAttributesEx(typeof(KnownTypeAttribute), true);
                foreach (var attr in knownTypeAttributes)
                {
                    var ktattr = attr as KnownTypeAttribute;
                    if (ktattr != null)
                    {
                        if (ktattr.MethodName != null)
                        {
                            var mi = type.GetMethodEx(ktattr.MethodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

                            // this can be null because we are also getting here through the recursive behaviour
                            // of GetCustomAttributesEx. We are getting at this point once per class derived from a
                            // base class having a KnownType() with a method. This can be ignored
                            if (mi != null)
                            {
                                var types = mi.Invoke(null, null) as IEnumerable <Type>;
                                if (types != null)
                                {
                                    additionalTypes.AddRange(types);
                                }
                            }
                        }
                        else
                        {
                            additionalTypes.Add(ktattr.Type);
                        }
                    }
                }

                return additionalTypes.ToArray();
            }));
        }
コード例 #16
0
ファイル: PropertyHelper.cs プロジェクト: shekky/Catel
        /// <summary>
        /// Gets hidden property value.
        /// </summary>
        /// <typeparam name="TValue">The type of the T value.</typeparam>
        /// <param name="obj">The obj.</param>
        /// <param name="property">The property.</param>
        /// <param name="baseType">The base Type.</param>
        /// <returns>``0.</returns>
        /// <exception cref="PropertyNotFoundException"></exception>
        /// <exception cref="System.ArgumentNullException">The <paramref name="obj" /> is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentException">The <paramref name="property" /> is <c>null</c> or whitespace.</exception>
        /// <exception cref="System.ArgumentException">The <paramref name="property" /> is <c>null</c> or whitespace.</exception>
        /// <exception cref="System.ArgumentNullException">The <paramref name="obj" /> is <c>null</c>.</exception>
        public static TValue GetHiddenPropertyValue <TValue>(object obj, string property, Type baseType)
        {
            Argument.IsNotNull("obj", obj);
            Argument.IsNotNullOrWhitespace("property", property);
            Argument.IsNotNull("baseType", baseType);
            Argument.IsOfType("obj", obj, baseType);

            var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
            var propertyInfo = baseType.GetPropertyEx(property, bindingFlags);

            if (propertyInfo == null)
            {
                throw Log.ErrorAndCreateException(s => new PropertyNotFoundException(property),
                                                  "Hidden property '{0}' is not found on the base type '{1}'", property, baseType.GetType().Name);
            }

            return((TValue)propertyInfo.GetValue(obj, bindingFlags, null, ArrayShim.Empty <object>(), CultureInfo.InvariantCulture));
        }
コード例 #17
0
        /// <summary>
        /// Modifies the source data before passing it to the target for display in the UI.
        /// </summary>
        /// <param name="value">The source data being passed to the target.</param>
        /// <param name="targetType">The <see cref="T:System.Type" /> of data expected by the target dependency property.</param>
        /// <param name="parameter">An optional parameter to be used in the converter logic.</param>
        /// <returns>The value to be passed to the target dependency property.</returns>
        protected override object Convert(object value, Type targetType, object parameter)
        {
            var methodName = parameter as string;

            if (value is null || methodName is null)
            {
                return(value);
            }

            var bindingFlags = BindingFlagsHelper.GetFinalBindingFlags(true, true);
            var methodInfo   = value.GetType().GetMethodEx(methodName, ArrayShim.Empty <Type>(), bindingFlags);

            if (methodInfo is null)
            {
                return(value);
            }

            return(methodInfo.Invoke(value, ArrayShim.Empty <object>()));
        }
コード例 #18
0
        /// <summary>
        /// Converters the stream to a byte array.
        /// </summary>
        /// <param name="stream">The stream to convert to a byte array.</param>
        /// <returns>The byte array representing the stream.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="stream"/> is <c>null</c>.</exception>
        public static byte[] ToByteArray(this Stream stream)
        {
            Argument.IsNotNull("stream", stream);

            stream.Position = 0L;

            var length = (int)stream.Length;

            if (length == 0)
            {
                return(ArrayShim.Empty <byte>());
            }

            var buffer = new byte[length];

            stream.Read(buffer, 0, length);

            return(buffer);
        }
コード例 #19
0
ファイル: AssemblyHelper.cs プロジェクト: xaecors/Catel
        /// <summary>
        /// Gets all types from the assembly safely. Sometimes, the <see cref="ReflectionTypeLoadException"/> is thrown,
        /// and no types are returned. In that case the user must manually get the successfully loaded types from the
        /// <see cref="ReflectionTypeLoadException.Types"/>.
        /// <para/>
        /// This method automatically loads the types. If the <see cref="ReflectionTypeLoadException"/> occurs, this method
        /// will return the types that were loaded successfully.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <param name="logLoaderExceptions">If set to <c>true</c>, the loader exceptions will be logged.</param>
        /// <returns>The array of successfully loaded types.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="assembly"/> is <c>null</c>.</exception>
        public static Type[] GetAllTypesSafely(this Assembly assembly, bool logLoaderExceptions = true)
        {
            Argument.IsNotNull("assembly", assembly);

            Type[] foundAssemblyTypes;

            RegisterAssemblyWithVersionInfo(assembly);

            try
            {
                foundAssemblyTypes = assembly.GetTypesEx();
            }
            catch (ReflectionTypeLoadException typeLoadException)
            {
                foundAssemblyTypes = (from type in typeLoadException.Types
                                      where type != null
                                      select type).ToArray();

                Log.Warning("A ReflectionTypeLoadException occured, adding all {0} types that were loaded correctly", foundAssemblyTypes.Length);

                if (logLoaderExceptions)
                {
                    Log.Warning("The following loading exceptions occurred:");

                    foreach (var error in typeLoadException.LoaderExceptions)
                    {
                        // Fix mono issue https://github.com/Catel/Catel/issues/1071
                        if (error != null)
                        {
                            Log.Warning("  " + error.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to get types from assembly '{0}'", assembly.FullName);

                foundAssemblyTypes = ArrayShim.Empty <Type>();
            }

            return(foundAssemblyTypes);
        }
コード例 #20
0
            /// <summary>
            /// Determines whether the specified type is serializable.
            /// </summary>
            /// <param name="type">The type.</param>
            /// <returns><c>true</c> if the specified type is serializable; otherwise, <c>false</c>.</returns>
            /// <exception cref="ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
            public bool IsTypeSerializable(Type type)
            {
                return(_isTypeSerializableCache.GetFromCacheOrFetch(type, () =>
                {
                    if (type.IsAbstractEx())
                    {
                        return false;
                    }

                    if (type.IsInterfaceEx())
                    {
                        return false;
                    }

                    if (type.IsEnumEx())
                    {
                        return true;
                    }

                    if (IsSpecialCollectionType(type))
                    {
                        return true;
                    }

                    // Should have an empty constructor
                    if (type.GetConstructorEx(ArrayShim.Empty <Type>()) == null)
                    {
                        return false;
                    }

                    // Type must be public
                    if (!type.IsPublicEx() && !type.IsNestedPublicEx())
                    {
                        return false;
                    }

                    // TODO: Add more checks?

                    return true;
                }));
            }
コード例 #21
0
            private static void AssertSerializationCalls(object obj, string serializationMode, string[] fieldNames)
            {
                foreach (var fieldName in fieldNames)
                {
                    var field      = obj.GetType().GetFieldEx(fieldName);
                    var fieldValue = (int)field.GetValue(obj);

                    Assert.AreEqual(1, fieldValue, $"{obj.GetType().Name}.{fieldName} should have been 1 for serialization mode {serializationMode}");
                }

                var methodInfo = obj.GetType().GetMethodEx("ClearSerializationCounters");

                methodInfo.Invoke(obj, ArrayShim.Empty <object>());

                if (obj is ComputerSettings computerSettings)
                {
                    foreach (var iniFile in computerSettings.IniFileCollection)
                    {
                        AssertSerializationCalls(iniFile, serializationMode, fieldNames);
                    }

                    return;
                }
                else if (obj is IniFile iniFile)
                {
                    foreach (var iniEntry in iniFile.IniEntryCollection)
                    {
                        AssertSerializationCalls(iniEntry, serializationMode, fieldNames);
                    }

                    return;
                }
                else if (obj is IniEntry iniEntry)
                {
                    // No need to check children
                    return;
                }

                Assert.Fail($"Unsupported model '{obj.GetType()}'");
            }
コード例 #22
0
        public async Task <IEnumerable <LogFilterGroup> > LoadAsync()
        {
            var applicationDataDirectory = Catel.IO.Path.GetApplicationDataDirectory();
            var configFile = Path.Combine(applicationDataDirectory, LogFilterGroupsConfigFile);

            if (_fileService.Exists(configFile))
            {
                try
                {
                    using (var stream = _fileService.OpenRead(configFile))
                    {
                        return((LogFilterGroup[])_xmlSerializer.Deserialize(typeof(LogFilterGroup[]), stream));
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }

            return(ArrayShim.Empty <LogFilterGroup>());
        }
コード例 #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NotSupportedInPlatformException"/> class.
 /// </summary>
 /// <param name="message">The message.</param>
 public NotSupportedInPlatformException(string message)
     : this(message, ArrayShim.Empty <object>())
 {
 }
コード例 #24
0
ファイル: TypeFactory.cs プロジェクト: xubinvc/Catel
        /// <summary>
        /// Creates an instance of the specified type using the specified parameters as injection values.
        /// </summary>
        /// <param name="typeToConstruct">The type to construct.</param>
        /// <param name="tag">The preferred tag when resolving dependencies.</param>
        /// <param name="parameters">The parameters to inject.</param>
        /// <param name="autoCompleteDependencies">if set to <c>true</c>, the additional dependencies will be auto completed.</param>
        /// <returns>The instantiated type using dependency injection.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="typeToConstruct" /> is <c>null</c>.</exception>
        private object CreateInstanceWithSpecifiedParameters(Type typeToConstruct, object tag, object[] parameters, bool autoCompleteDependencies)
        {
            Argument.IsNotNull("typeToConstruct", typeToConstruct);

            if (parameters == null)
            {
                parameters = ArrayShim.Empty <object>();
            }

            var previousRequestPath = _currentTypeRequestPath.Value;

            try
            {
                var typeRequestInfo = new TypeRequestInfo(typeToConstruct);
                _currentTypeRequestPath.Value = TypeRequestPath.Branch(previousRequestPath, typeRequestInfo);

                var constructorCacheKey = new ConstructorCacheKey(typeToConstruct, autoCompleteDependencies, parameters);

                var typeConstructorsMetadata = GetTypeMetaData(typeToConstruct);

                var constructorCacheValue = GetConstructor(constructorCacheKey);

                if (constructorCacheValue.ConstructorInfo != null)
                {
                    var cachedConstructor            = constructorCacheValue.ConstructorInfo;
                    var instanceCreatedWithInjection = TryCreateToConstruct(typeToConstruct, cachedConstructor, tag, parameters, false, false, typeConstructorsMetadata);
                    if (instanceCreatedWithInjection != null)
                    {
                        return(instanceCreatedWithInjection);
                    }

                    Log.Warning("Found constructor for type '{0}' in constructor, but it failed to create an instance. Removing the constructor from the cache", typeToConstruct.FullName);

                    SetConstructor(constructorCacheKey, constructorCacheValue, null);
                }

                Log.Debug("Creating instance of type '{0}' using specific parameters. No constructor found in the cache, so searching for the right one", typeToConstruct.FullName);

                var constructors = typeConstructorsMetadata.GetConstructors(parameters.Length, !autoCompleteDependencies).SortByParametersMatchDistance(parameters).ToList();

                for (int i = 0; i < constructors.Count; i++)
                {
                    var constructor = constructors[i];

                    var instanceCreatedWithInjection = TryCreateToConstruct(typeToConstruct, constructor, tag, parameters, true, i < constructors.Count - 1, typeConstructorsMetadata);
                    if (instanceCreatedWithInjection != null)
                    {
                        // We found a constructor that works, cache it
                        SetConstructor(constructorCacheKey, constructorCacheValue, constructor);

                        // Only update the rule when using a constructor for the first time, not when using it from the cache
                        ApiCop.UpdateRule <TooManyDependenciesApiCopRule>("TypeFactory.LimitDependencyInjection", x => x.SetNumberOfDependenciesInjected(typeToConstruct, constructor.GetParameters().Count()));

                        return(instanceCreatedWithInjection);
                    }
                }

                Log.Debug("No constructor could be used, cannot construct type '{0}' with the specified parameters", typeToConstruct.FullName);
            }
            catch (CircularDependencyException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to construct type '{0}'", typeToConstruct.FullName);

                throw;
            }
            finally
            {
                _currentTypeRequestPath.Value = previousRequestPath;
            }

            return(null);
        }
コード例 #25
0
 /// <summary>
 /// Wraps the specified framework element without any buttons.
 /// </summary>
 /// <param name="frameworkElement">The framework element.</param>
 /// <param name="wrapOptions">The wrap options.</param>
 /// <param name="parentContentControl">The parent content control.</param>
 /// <returns>
 ///     <see cref="Grid"/> that contains the wrapped content.
 /// </returns>
 /// <remarks>
 /// The framework element that is passed must be disconnected from the parent first. It is recommended to first check whether a
 /// framework element can be wrapped by using the <see cref="CanBeWrapped"/> method.
 /// <para />
 /// This method will automatically handle the disconnecting of the framework element from the parent is the <paramref name="parentContentControl"/>
 /// is passed.
 /// </remarks>
 public Grid Wrap(FrameworkElement frameworkElement, WrapControlServiceWrapOptions wrapOptions, ContentControl parentContentControl = null)
 {
     return(Wrap(frameworkElement, wrapOptions, ArrayShim.Empty <DataWindowButton>(), parentContentControl));
 }
コード例 #26
0
        private void UpdateShapeColor(Shape shape, bool isSelected)
        {
            var storyboard = new Storyboard();

            if (shape is not null && shape.Fill is null)
            {
#pragma warning disable WPF0041 // Set mutable dependency properties using SetCurrentValue.
                shape.Fill = (SolidColorBrush)TryFindResource(ThemingKeys.AccentColorBrush40);
#pragma warning restore WPF0041 // Set mutable dependency properties using SetCurrentValue.
            }

            var fromColor   = ((SolidColorBrush)shape?.Fill)?.Color ?? Colors.Transparent;
            var targetColor = this.GetAccentColorBrush(isSelected).Color;

            var colorAnimation = new ColorAnimation(fromColor, (Color)targetColor, WizardConfiguration.AnimationDuration);
            Storyboard.SetTargetProperty(colorAnimation, new PropertyPath("Fill.(SolidColorBrush.Color)", ArrayShim.Empty <object>()));

            storyboard.Children.Add(colorAnimation);

            storyboard.Begin(shape);
        }
コード例 #27
0
ファイル: TypeHelperFacts.cs プロジェクト: xaecors/Catel
 public void ReturnsEmptyStringForEmptyArray()
 {
     Assert.AreEqual(string.Empty, TypeHelper.FormatInnerTypes((IEnumerable <string>)ArrayShim.Empty <string>()));
 }
コード例 #28
0
        public Assembly[] GetAssemblies()
        {
            lock (_lock)
            {
                if (_loadedAssemblies == null)
                {
                    var loadedAssemblies = new List <Assembly>();

#if NETFX_CORE
                    var folder = Package.Current.InstalledLocation;

                    // Note: normally it's bad practice to use task.Wait(), but GetAssemblies must be blocking to cache it all

                    // Note: winmd cannot be read, see https://stackoverflow.com/questions/9136683/cannot-get-types-from-winmd-file,
                    // so we create a hashset of all winmd files and ignore them
                    var winmdQueryOptions = new QueryOptions(CommonFileQuery.OrderByName, new[] { ".winmd" });
                    winmdQueryOptions.FolderDepth = FolderDepth.Shallow;

                    var winmdQueryResult = folder.CreateFileQueryWithOptions(winmdQueryOptions);
                    var winmdTask        = winmdQueryResult.GetFilesAsync().AsTask();
                    winmdTask.Wait();
                    var winmdFiles = new HashSet <string>(winmdTask.Result.Select(x => x.Name.Substring(0, x.Name.Length - x.FileType.Length)), StringComparer.OrdinalIgnoreCase);

                    // Get assemblies
                    var assemblyQueryOptions = new QueryOptions(CommonFileQuery.OrderByName, new[] { ".dll", ".exe" /*, ".winmd" */ });
                    assemblyQueryOptions.FolderDepth = FolderDepth.Shallow;

                    var assemblyQueryResult = folder.CreateFileQueryWithOptions(assemblyQueryOptions);
                    var assembliesTask      = assemblyQueryResult.GetFilesAsync().AsTask();
                    assembliesTask.Wait();
                    var assemblyFiles = assembliesTask.Result.ToImmutableHashSet();

                    var arrayToIgnore = KnownPrefixesToIgnore.ToArray();

                    foreach (var file in assemblyFiles)
                    {
                        try
                        {
                            if (file.Name.StartsWithAnyIgnoreCase(arrayToIgnore))
                            {
                                continue;
                            }

                            Log.Debug($"Loading assembly from file '{file.Name}'");

                            var assemblyName = file.Name.Substring(0, file.Name.Length - file.FileType.Length);
                            if (winmdFiles.Contains(assemblyName))
                            {
                                Log.Debug($"Ignoring assembly load of '{file.Name}' because it's (most likely) not a managed assembly (because .winmd exists)");
                                continue;
                            }

                            var assembly = LoadAssemblyFromFile(file);
                            if (assembly != null)
                            {
                                loadedAssemblies.Add(assembly);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Warning(ex, $"Failed to load assembly '{file}'");
                        }
                    }
#else
                    var currentdomain = typeof(string).GetTypeInfo().Assembly.GetType("System.AppDomain").GetRuntimeProperty("CurrentDomain").GetMethod.Invoke(null, ArrayShim.Empty <object>());
                    var method        = currentdomain.GetType().GetRuntimeMethod("GetAssemblies", ArrayShim.Empty <Type>());
                    var assemblies    = method.Invoke(currentdomain, ArrayShim.Empty <object>()) as Assembly[];
                    loadedAssemblies.AddRange(assemblies);
#endif

                    _loadedAssemblies = loadedAssemblies.ToArray();
                }

                return(_loadedAssemblies);
            }
        }
コード例 #29
0
ファイル: TypeRequestPath.cs プロジェクト: xaecors/Catel
 /// <summary>
 /// Creates root of type request path.
 /// </summary>
 /// <param name="name">Path's name</param>
 /// <returns></returns>
 public static TypeRequestPath Root(string name = null)
 {
     return(new TypeRequestPath(ArrayShim.Empty <TypeRequestInfo>(), name));
 }
コード例 #30
0
        /// <summary>
        /// Raises the events for differences.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="oldValidationData">The old validation data.</param>
        /// <param name="newValidationData">The new validation data.</param>
        private void RaiseEventsForDifferences(object value, ValidationData oldValidationData, ValidationData newValidationData)
        {
            // Warnings - fields
            RaiseEventsForDifferencesInFields(value, oldValidationData?.FieldWarnings ?? (IEnumerable <FieldWarningOrErrorInfo>)ArrayShim.Empty <FieldWarningOrErrorInfo>(), newValidationData.FieldWarnings, ValidationType.Warning);

            // Warnings - business
            RaiseEventsForDifferencesInBusiness(value, oldValidationData?.BusinessWarnings ?? (IEnumerable <BusinessWarningOrErrorInfo>)ArrayShim.Empty <BusinessWarningOrErrorInfo>(), newValidationData.BusinessWarnings, ValidationType.Warning);

            // Errors - fields
            RaiseEventsForDifferencesInFields(value, oldValidationData?.FieldErrors ?? (IEnumerable <FieldWarningOrErrorInfo>)ArrayShim.Empty <FieldWarningOrErrorInfo>(), newValidationData.FieldErrors, ValidationType.Error);

            // Errors - business
            RaiseEventsForDifferencesInBusiness(value, oldValidationData?.BusinessErrors ?? (IEnumerable <BusinessWarningOrErrorInfo>)ArrayShim.Empty <BusinessWarningOrErrorInfo>(), newValidationData.BusinessErrors, ValidationType.Error);
        }
コード例 #31
0
 public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
 {
     return(ArrayShim.Empty <object>());
 }