예제 #1
0
        /// <summary>
        /// Gets the name of the table as it is mapped in the database.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityType">Type of the entity.</param>
        /// <returns>
        /// The table name including the schema.
        /// </returns>
        public static string GetTableName(this DbContext context, Type entityType)
        {
            Argument.IsNotNull("context", context);
            Argument.IsNotNull("entityType", entityType);

            return(_tableNameCache.GetFromCacheOrFetch(entityType, () =>
            {
                var objectContext = context.GetObjectContext();
                return GetTableName(objectContext, entityType);
            }));
        }
        public ImageSource ResolveImageFromUri(Uri uri, string defaultUrl = null)
        {
            if (uri == null)
            {
                return(GetDefaultImage(defaultUrl));
            }

            lock (_lockObject)
            {
                return(_packageDetailsCache.GetFromCacheOrFetch(uri.AbsoluteUri, () => CreateImage(uri, defaultUrl)));
            }
        }
예제 #3
0
        /// <summary>
        /// Gets the string with the specified culture.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="cultureInfo">The culture information.</param>
        /// <returns>The string or <c>null</c> if the resource cannot be found.</returns>
        /// <exception cref="ArgumentException">The <paramref name="resourceName" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="cultureInfo" /> is <c>null</c>.</exception>
        public string GetString(string resourceName, CultureInfo cultureInfo)
        {
            Argument.IsNotNullOrWhitespace("resourceName", resourceName);
            Argument.IsNotNull("cultureInfo", cultureInfo);

            var resourceKey = new LanguageResourceKey(resourceName, cultureInfo);

            return(_stringCache.GetFromCacheOrFetch(resourceKey, () =>
            {
                foreach (var resourceFile in _languageSources)
                {
                    try
                    {
                        var value = GetString(resourceFile, resourceName, cultureInfo);
                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            return value;
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Failed to get string for resource name '{0}' from resource file '{1}'", resourceName, resourceFile);
                    }
                }

                return null;
            }));
        }
예제 #4
0
        /// <summary>
        /// Gets the property info from the cache.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="property">The property.</param>
        /// <param name="ignoreCase">if set to <c>true</c>, ignore case.</param>
        /// <returns>PropertyInfo.</returns>
        public static PropertyInfo GetPropertyInfo(object obj, string property, bool ignoreCase = false)
        {
            string cacheKey = $"{obj.GetType().FullName}_{property}_{ignoreCase}";

            return(_availableProperties.GetFromCacheOrFetch(cacheKey, () =>
            {
                var objectType = obj.GetType();

                if (!ignoreCase)
                {
                    // Use old mechanism to ensure no breaking changes / performance hite
                    return objectType.GetPropertyEx(property);
                }

                var allProperties = objectType.GetPropertiesEx();

                foreach (var propertyInfo in allProperties)
                {
                    if (string.Equals(propertyInfo.Name, property, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
                    {
                        return propertyInfo;
                    }
                }

                return null;
            }));
        }
예제 #5
0
        /// <summary>
        /// Gets the name of the entity set in the <see cref="DbContext" /> for the specified entity type.
        /// </summary>
        /// <param name="dbContext">The db context.</param>
        /// <param name="entityType">Type of the entity.</param>
        /// <returns>The name of the entity set.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="dbContext" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="entityType" /> is <c>null</c>.</exception>
        public static string GetEntitySetName(this DbContext dbContext, Type entityType)
        {
            Argument.IsNotNull("dbContext", dbContext);
            Argument.IsNotNull("entityType", entityType);

            var entitySetName = _entitySetNameCache.GetFromCacheOrFetch(new Tuple <Type, Type>(dbContext.GetType(), entityType), () =>
            {
                var objectContext = dbContext.GetObjectContext();
                var entitySet     = objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace)
                                    .BaseEntitySets.FirstOrDefault(bes => bes.ElementType.Name == entityType.Name);

                if (entitySet == null && entityType.BaseType != null)
                {
                    // recursive method call, should be no problem as the compiler wont allow circular base class dependencies
                    return(dbContext.GetEntitySetName(entityType.BaseType));
                }

                if (entitySet == null)
                {
                    throw new InstanceNotFoundException(String.Format("No EntitySet has been found for the provided Type '{0}'", entityType));
                }

                return(entitySet.Name);
            });

            return(entitySetName);
        }
예제 #6
0
        /// <summary>
        /// Gets the fields
        /// </summary>
        /// <param name="type">Type of the model.</param>
        /// <returns>A hash set containing the fields.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public Dictionary <string, MemberMetadata> GetFields(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_fieldsCache.GetFromCacheOrFetch(type, () =>
            {
                var dictionary = new Dictionary <string, MemberMetadata>();

                var fields = type.GetFieldsEx();
                foreach (var fieldInfo in fields)
                {
                    if (fieldInfo.Name.Contains("__BackingField") ||
                        fieldInfo.DeclaringType == typeof(ModelBase))
                    {
                        continue;
                    }

                    var memberMetadata = new MemberMetadata(type, fieldInfo.FieldType, SerializationMemberGroup.Field, fieldInfo.Name)
                    {
                        Tag = fieldInfo
                    };

                    var nameOverride = GetNameOverrideForSerialization(fieldInfo);
                    if (!string.IsNullOrWhiteSpace(nameOverride))
                    {
                        memberMetadata.MemberNameForSerialization = nameOverride;
                    }

                    dictionary[fieldInfo.Name] = memberMetadata;
                }

                return dictionary;
            }));
        }
예제 #7
0
        /// <summary>
        /// Determines the interesting dependency properties.
        /// </summary>
        /// <returns>A list of names with dependency properties to subscribe to.</returns>
        private List <DependencyPropertyInfo> DetermineInterestingDependencyProperties()
        {
            var targetControlType = TargetControlType;

            return(_dependencyPropertiesToSubscribe.GetFromCacheOrFetch(targetControlType, () =>
            {
                var controlDependencyProperties = TargetControl.GetDependencyProperties();
                var dependencyProperties = new List <DependencyPropertyInfo>();

                if ((_dependencyPropertySelector == null) || (_dependencyPropertySelector.MustSubscribeToAllDependencyProperties(targetControlType)))
                {
                    dependencyProperties.AddRange(controlDependencyProperties);
                }
                else
                {
                    var dependencyPropertiesToSubscribe = _dependencyPropertySelector.GetDependencyPropertiesToSubscribeTo(targetControlType);
                    if (!dependencyPropertiesToSubscribe.Contains("DataContext"))
                    {
                        dependencyPropertiesToSubscribe.Add("DataContext");
                    }

                    foreach (var gatheredDependencyProperty in controlDependencyProperties)
                    {
                        if (dependencyPropertiesToSubscribe.Contains(gatheredDependencyProperty.PropertyName))
                        {
                            dependencyProperties.Add(gatheredDependencyProperty);
                        }
                    }
                }

                return dependencyProperties;
            }));
        }
예제 #8
0
        /// <summary>
        /// Gets the resource manager.
        /// </summary>
        /// <param name="source">The source.</param>
        private ResourceManager GetResourceManager(string source)
        {
            return(_resourceFileCache.GetFromCacheOrFetch(source, () =>
            {
                try
                {
#if NETFX_CORE && !WIN81
                    var resourceLoader = new ResourceManager(source);
#elif WIN81
                    var resourceLoader = ResourceManager.GetForCurrentView(source);
#else
                    var splittedString = source.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    var assemblyName = splittedString[1].Trim();
                    var containingAssemblyName = string.Format("{0},", assemblyName);
                    var assembly = AssemblyHelper.GetLoadedAssemblies().FirstOrDefault(x => x.FullName.Contains(containingAssemblyName));
                    if (assembly == null)
                    {
                        return null;
                    }

                    string resourceFile = splittedString[0];
                    var resourceLoader = new ResourceManager(resourceFile, assembly);
#endif

                    return resourceLoader;
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "Failed to get the resource manager for source '{0}'", source);
                    return null;
                }
            }));
        }
예제 #9
0
        /// <summary>
        /// Gets the entity key of the specified entity type in the <see cref="DbContext" />.
        /// </summary>
        /// <param name="dbContext">The db context.</param>
        /// <param name="dbEntityEntry">Type of the entity.</param>
        /// <returns>The entity key.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="dbContext"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="dbEntityEntry"/> is <c>null</c>.</exception>
        public static EntityKey GetEntityKey(this DbContext dbContext, DbEntityEntry dbEntityEntry)
        {
            Argument.IsNotNull("dbContext", dbContext);
            Argument.IsNotNull("dbEntityEntry", dbEntityEntry);

            var entityType = dbEntityEntry.GetEntityType();

            var keySet = _entityKeyCache.GetFromCacheOrFetch(new Tuple <Type, Type>(dbContext.GetType(), entityType), () =>
            {
                var entitySet = dbContext.GetEntitySet(entityType);

                return((from keyMember in entitySet.ElementType.KeyMembers
                        select keyMember.Name).ToList());
            });

            var entitySetName = dbContext.GetFullEntitySetName(entityType);
            var currentValues = dbEntityEntry.CurrentValues;

            var keys = new List <EntityKeyMember>();

            foreach (var keySetItem in keySet)
            {
                keys.Add(new EntityKeyMember
                {
                    Key   = keySetItem,
                    Value = currentValues[keySetItem]
                });
            }

            var entityKey = new EntityKey(entitySetName, keys.ToArray());

            return(entityKey);
        }
예제 #10
0
        /// <summary>
        /// Gets the dependency property cache key prefix.
        /// </summary>
        /// <param name="frameworkElement">The framework element.</param>
        /// <returns>The dependency property cache key prefix based on the framework element..</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="frameworkElement"/> is <c>null</c>.</exception>
        public static string GetDependencyPropertyCacheKeyPrefix(FrameworkElement frameworkElement)
        {
            Argument.IsNotNull("frameworkElement", frameworkElement);

            var frameworkElementType = frameworkElement.GetType();

            return(_cacheKeyCache.GetFromCacheOrFetch(frameworkElementType, () => frameworkElement.GetType().FullName.Replace(".", "_")));
        }
예제 #11
0
        /// <summary>
        /// Gets the properties to serialize for the specified object.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The list of properties to serialize.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public virtual HashSet <string> GetPropertiesToSerialize(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_propertiesToSerializeCache.GetFromCacheOrFetch(type, () =>
            {
                var properties = new HashSet <string>();

                var propertyDataManager = PropertyDataManager.Default;
                var catelTypeInfo = propertyDataManager.GetCatelTypeInfo(type);
                var catelProperties = catelTypeInfo.GetCatelProperties();
                var catelPropertyNames = new HashSet <string>(catelProperties.Keys);
                foreach (var modelProperty in catelProperties)
                {
                    var propertyData = modelProperty.Value;

                    if (!typeof(ModelBase).IsAssignableFromEx(propertyData.Type) && !propertyData.IsSerializable)
                    {
                        Log.Warning("Property '{0}' is not serializable, so will be excluded from the serialization", propertyData.Name);
                        continue;
                    }

                    if (!propertyData.IncludeInSerialization)
                    {
                        Log.Debug("Property '{0}' is flagged to be excluded from serialization", propertyData.Name);
                        continue;
                    }

                    var propertyInfo = propertyData.GetPropertyInfo(type);
                    if (propertyInfo != null)
                    {
                        if (!AttributeHelper.IsDecoratedWithAttribute <ExcludeFromSerializationAttribute>(propertyInfo.PropertyInfo))
                        {
                            properties.Add(modelProperty.Key);
                        }
                    }
                    else
                    {
                        // Dynamic property, always include
                        properties.Add(modelProperty.Key);
                    }
                }

                var typeProperties = type.GetPropertiesEx();
                foreach (var typeProperty in typeProperties)
                {
                    if (!catelPropertyNames.Contains(typeProperty.Name))
                    {
                        if (AttributeHelper.IsDecoratedWithAttribute <IncludeInSerializationAttribute>(typeProperty))
                        {
                            properties.Add(typeProperty.Name);
                        }
                    }
                }

                return properties;
            }));
        }
예제 #12
0
        /// <summary>
        /// Determines whether the property is decorated with the specified attribute.
        /// </summary>
        /// <param name="attributeType">Type of the attribute.</param>
        /// <returns><c>true</c> if the property is decorated with the specified attribute.; otherwise, <c>false</c>.</returns>
        public bool IsDecoratedWithAttribute(Type attributeType)
        {
            Argument.IsNotNull("attributeType", attributeType);

            return(_decoratedWithAttributeCache.GetFromCacheOrFetch(attributeType, () =>
            {
                return AttributeHelper.IsDecoratedWithAttribute(PropertyInfo, attributeType);
            }));
        }
예제 #13
0
        /// <summary>
        /// Gets the catel properties to serialize.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The list of properties to serialize.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public virtual Dictionary <string, MemberMetadata> GetCatelPropertiesToSerialize(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_catelPropertiesToSerializeCache.GetFromCacheOrFetch(type, () =>
            {
                var serializableMembers = new Dictionary <string, MemberMetadata>();

                var properties = GetCatelProperties(type);
                foreach (var modelProperty in properties)
                {
                    var memberMetadata = modelProperty.Value;
                    var propertyData = (PropertyData)memberMetadata.Tag;

                    bool isSerializable = propertyData.IsSerializable || propertyData.Type.IsModelBase();
                    if (!isSerializable)
                    {
                        // CTL-550
                        var cachedPropertyInfo = propertyData.GetPropertyInfo(type);
                        if (cachedPropertyInfo.IsDecoratedWithAttribute <IncludeInSerializationAttribute>())
                        {
                            isSerializable = true;
                        }
                    }

                    if (!isSerializable)
                    {
                        Log.Warning("Property '{0}' is not serializable, so will be excluded from the serialization. If this property needs to be included, use the 'IncludeInSerializationAttribute'", propertyData.Name);
                        continue;
                    }

                    if (!propertyData.IncludeInSerialization)
                    {
                        Log.Debug("Property '{0}' is flagged to be excluded from serialization", propertyData.Name);
                        continue;
                    }

                    var propertyInfo = propertyData.GetPropertyInfo(type);
                    if (propertyInfo != null)
                    {
                        if (!propertyInfo.IsDecoratedWithAttribute <ExcludeFromSerializationAttribute>())
                        {
                            serializableMembers.Add(modelProperty.Key, memberMetadata);
                        }
                    }
                    else
                    {
                        // Dynamic property, always include
                        serializableMembers.Add(modelProperty.Key, memberMetadata);
                    }
                }

                return serializableMembers;
            }));
        }
예제 #14
0
        /// <summary>
        /// Gets the name of the property based on the expression.
        /// </summary>
        /// <param name="propertyExpression">The property expression.</param>
        /// <param name="allowNested">If set to <c>true</c>, nested properties are allowed.</param>
        /// <param name="nested">If set to <c>true</c>, this is a nested call.</param>
        /// <returns>The string representing the property name or <see cref="string.Empty"/> if no property can be found.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="propertyExpression"/> is <c>null</c>.</exception>
        /// <exception cref="NotSupportedException">The specified expression is not a member access expression.</exception>
        private static string GetPropertyName(Expression propertyExpression, bool allowNested = false, bool nested = false)
        {
            Argument.IsNotNull("propertyExpression", propertyExpression);

            const string NoMemberExpression = "The expression is not a member access expression";

            string cacheKey = string.Format("{0}_{1}_{2}", propertyExpression, allowNested, nested);

            return(_expressionNameCache.GetFromCacheOrFetch(cacheKey, () =>
            {
                MemberExpression memberExpression;

                var unaryExpression = propertyExpression as UnaryExpression;
                if (unaryExpression != null)
                {
                    memberExpression = unaryExpression.Operand as MemberExpression;
                }
                else
                {
                    memberExpression = propertyExpression as MemberExpression;
                }

                if (memberExpression == null)
                {
                    if (nested)
                    {
                        return string.Empty;
                    }

                    Log.Error(NoMemberExpression);
                    throw new NotSupportedException(NoMemberExpression);
                }

                var propertyInfo = memberExpression.Member as PropertyInfo;
                if (propertyInfo == null)
                {
                    if (nested)
                    {
                        return string.Empty;
                    }

                    Log.Error(NoMemberExpression);
                    throw new NotSupportedException(NoMemberExpression);
                }

                if (allowNested && (memberExpression.Expression != null) && (memberExpression.Expression.NodeType == ExpressionType.MemberAccess))
                {
                    var propertyName = GetPropertyName(memberExpression.Expression, true, true);

                    return propertyName + (!string.IsNullOrEmpty(propertyName) ? "." : string.Empty) + propertyInfo.Name;
                }

                return propertyInfo.Name;
            }));
        }
        public IPropertyCollection GetInstanceProperties(Type targetType)
        {
            Argument.IsNotNull(() => targetType);

            return(_cache.GetFromCacheOrFetch(targetType, () =>
            {
                var instanceProperties = new InstanceProperties(targetType);

                _filterCustomizationService.CustomizeInstanceProperties(instanceProperties);

                return instanceProperties;
            }));
        }
예제 #16
0
        /// <summary>
        /// Gets the string with the specified culture.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="cultureInfo">The culture information.</param>
        /// <returns>The string or <c>null</c> if the resource cannot be found.</returns>
        /// <exception cref="ArgumentException">The <paramref name="resourceName" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="cultureInfo" /> is <c>null</c>.</exception>
        public string GetString(string resourceName, CultureInfo cultureInfo)
        {
            Argument.IsNotNullOrWhitespace("resourceName", resourceName);
            Argument.IsNotNull("cultureInfo", cultureInfo);

            if (CacheResults)
            {
                var resourceKey = new LanguageResourceKey(resourceName, cultureInfo);
                return(_stringCache.GetFromCacheOrFetch(resourceKey, () => GetStringInternal(resourceName, cultureInfo)));
            }

            return(GetStringInternal(resourceName, cultureInfo));
        }
예제 #17
0
        /// <summary>
        /// Gets the name of the entity set in the <see cref="DbContext" /> for the specified entity type.
        /// </summary>
        /// <param name="dbContext">The db context.</param>
        /// <param name="entityType">Type of the entity.</param>
        /// <returns>The name of the entity set.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="dbContext" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="entityType" /> is <c>null</c>.</exception>
        public static string GetEntitySetName(this DbContext dbContext, Type entityType)
        {
            Argument.IsNotNull("dbContext", dbContext);
            Argument.IsNotNull("entityType", entityType);

            var entitySetName = _entitySetNameCache.GetFromCacheOrFetch(new Tuple <Type, Type>(dbContext.GetType(), entityType), () =>
            {
                var objectContext = dbContext.GetObjectContext();
                return(objectContext.MetadataWorkspace.GetEntityContainer(objectContext.DefaultContainerName, DataSpace.CSpace).BaseEntitySets.First(bes => bes.ElementType.Name == entityType.Name).Name);
            });

            return(entitySetName);
        }
예제 #18
0
        /// <summary>
        /// Ensures that the specified theme is loaded.
        /// </summary>
        /// <param name="resourceUri">The resource URI.</param>
        public static void EnsureThemeIsLoaded(Uri resourceUri)
        {
            EnsureThemeIsLoaded(resourceUri, () =>
            {
                var application = Application.Current;
                if (application == null)
                {
                    return(false);
                }

                return(ThemeLoadedCache.GetFromCacheOrFetch(resourceUri, () => ContainsDictionary(application.Resources, resourceUri)));
            });
        }
예제 #19
0
            public List <ConstructorInfo> GetConstructors(int parameterCount, bool mustMatchExactCount)
            {
                string key = string.Format("{0}_{1}", parameterCount, mustMatchExactCount);

                return(_callCache.GetFromCacheOrFetch(key, () =>
                {
                    var constructors = new List <ConstructorInfo>();

                    constructors.AddRange(GetConstructors(parameterCount, mustMatchExactCount, true));
                    constructors.AddRange(GetConstructors(parameterCount, mustMatchExactCount, false));

                    return constructors;
                }));
            }
예제 #20
0
        /// <summary>
        /// Provides an access point to allow a custom implementation in order to retrieve the available validator for the specified type.
        /// </summary>
        /// <param name="targetType">The target type.</param>
        /// <returns>The <see cref="IValidator" /> for the specified type or <c>null</c> if no validator is available for the specified type.</returns>
        protected override IValidator GetValidator(Type targetType)
        {
            return(_validatorPerType.GetFromCacheOrFetch(targetType, () =>
            {
                ValidateModelAttribute attribute;
                if (AttributeHelper.TryGetAttribute(targetType, out attribute))
                {
                    var validator = TypeFactory.Default.CreateInstance(attribute.ValidatorType) as IValidator;
                    return validator;
                }

                return null;
            }));
        }
예제 #21
0
        /// <summary>
        /// Gets the catel property names.
        /// </summary>
        /// <param name="type">Type of the model.</param>
        /// <returns>A hash set containing the Catel property names.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public HashSet <string> GetCatelPropertyNames(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_catelPropertyNamesCache.GetFromCacheOrFetch(type, () =>
            {
                var propertyDataManager = PropertyDataManager.Default;
                var catelTypeInfo = propertyDataManager.GetCatelTypeInfo(type);
                var properties = (from property in catelTypeInfo.GetCatelProperties()
                                  where !property.Value.IsModelBaseProperty
                                  select property.Key);

                return new HashSet <string>(properties);
            }));
        }
예제 #22
0
        /// <summary>
        /// Gets the property information.
        /// </summary>
        /// <param name="containingType">Type of the containing.</param>
        /// <returns>CachedPropertyInfo.</returns>
        public CachedPropertyInfo GetPropertyInfo(Type containingType)
        {
            Argument.IsNotNull("containingType", containingType);

            return(_cachedPropertyInfo.GetFromCacheOrFetch(containingType, () =>
            {
                var propertyInfo = containingType.GetPropertyEx(Name, BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                if (propertyInfo == null)
                {
                    return null;
                }

                return new CachedPropertyInfo(propertyInfo);
            }));
        }
예제 #23
0
        /// <summary>
        /// Gets the properties to serialize for the specified object.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>The list of properties to serialize.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public virtual Dictionary <string, MemberMetadata> GetRegularPropertiesToSerialize(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_regularPropertiesToSerializeCache.GetFromCacheOrFetch(type, () =>
            {
                var serializableMembers = new Dictionary <string, MemberMetadata>();

                var catelPropertyNames = new HashSet <string>();

                var isModelBase = type.IsModelBase();
                if (isModelBase)
                {
                    catelPropertyNames = GetCatelPropertyNames(type, true);
                }

                var regularProperties = GetRegularProperties(type);
                foreach (var typeProperty in regularProperties)
                {
                    var memberMetadata = typeProperty.Value;
                    var propertyInfo = (PropertyInfo)memberMetadata.Tag;

                    if (!catelPropertyNames.Contains(memberMetadata.MemberName))
                    {
                        // If not a ModelBase, include by default
                        var include = !isModelBase;

                        if (propertyInfo.IsDecoratedWithAttribute <IncludeInSerializationAttribute>())
                        {
                            include = true;
                        }

                        if (propertyInfo.IsDecoratedWithAttribute <ExcludeFromSerializationAttribute>())
                        {
                            include = false;
                        }

                        if (include)
                        {
                            serializableMembers.Add(typeProperty.Key, memberMetadata);
                        }
                    }
                }

                return serializableMembers;
            }));
        }
예제 #24
0
        /// <summary>
        /// Gets the resource manager.
        /// </summary>
        /// <param name="source">The source.</param>
        private ResourceManager GetResourceManager(string source)
        {
            Func <ResourceManager> retrievalFunc = () =>
            {
                try
                {
#if NETFX_CORE && WIN80
                    var resourceLoader = new ResourceManager(source);
#elif NETFX_CORE
                    var resourceLoader = ResourceManager.GetForCurrentView(source);
#else
                    var splittedString = source.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    var assemblyName           = splittedString[1].Trim();
                    var containingAssemblyName = string.Format("{0},", assemblyName);

                    var loadedAssemblies = AssemblyHelper.GetLoadedAssemblies();

                    // Invert so design-time will always pick the latest version
                    loadedAssemblies.Reverse();

                    var assembly = loadedAssemblies.FirstOrDefault(x => x.FullName.StartsWith(containingAssemblyName));
                    if (assembly == null)
                    {
                        return(null);
                    }

                    string resourceFile   = splittedString[0];
                    var    resourceLoader = new ResourceManager(resourceFile, assembly);
#endif

                    return(resourceLoader);
                }
                catch (Exception ex)
                {
                    Log.Warning(ex, "Failed to get the resource manager for source '{0}'", source);
                    return(null);
                }
            };

            if (CacheResults)
            {
                return(_resourceFileCache.GetFromCacheOrFetch(source, retrievalFunc));
            }

            return(retrievalFunc());
        }
        public virtual string GetMachineId(string separator = "-", bool hashCombination = true)
        {
            Argument.IsNotNull(() => separator);

            var key = string.Format("machineid_{0}_{1}", separator, hashCombination);

            return(_cacheStorage.GetFromCacheOrFetch(key, () =>
            {
                Log.Debug("Retrieving machine id");

                var cpuId = string.Empty;
                var motherboardId = string.Empty;
                var hddId = string.Empty;
                var gpuId = string.Empty;

                TaskHelper.RunAndWait(new Action[]
                {
                    () => cpuId = "CPU >> " + GetCpuId(),
                    () => motherboardId = "BASE >> " + GetMotherboardId(),
                    () => hddId = "HDD >> " + GetHardDriveId(),
                    () => gpuId = "GPU >> " + GetGpuId(),
                    //() => gpuId = "MAC >> " + _systemIdentificationService.GetMacId(),
                });

                var values = new List <string>(new[]
                {
                    cpuId,
                    motherboardId,
                    hddId,
                    gpuId
                });

                var hashedValues = new List <string>();

                foreach (var value in values)
                {
                    var hashedValue = CalculateMd5Hash(value);
                    hashedValues.Add(hashedValue);

                    Log.Debug("* {0} => {1}", value, hashedValue);
                }

                var machineId = string.Join(separator, hashedValues);

                Log.Debug("Hashed machine id '{0}'", machineId);

                if (hashCombination)
                {
                    machineId = CalculateMd5Hash(machineId);
                }

                return machineId;
            }));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModelPropertyDescriptor" /> class.
        /// </summary>
        /// <param name="viewModel">The view model. Can be <c>null</c> for generic property definitions.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="propertyType">Type of the property.</param>
        /// <param name="attributes">The attributes.</param>
        /// <exception cref="ArgumentException">The <paramref name="propertyName" /> is <c>null</c> or whitespace.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="propertyType" /> is <c>null</c>.</exception>
        /// <remarks>Must be kept internal because it contains special generic options such as a null view model.</remarks>
        internal ViewModelPropertyDescriptor(ViewModelBase viewModel, string propertyName, Type propertyType, Attribute[] attributes)
            : base(propertyName, attributes)
        {
            Argument.IsNotNullOrWhitespace("propertyName", propertyName);
            Argument.IsNotNull("propertyType", propertyType);

            _viewModel     = viewModel;
            _viewModelType = (viewModel != null) ? viewModel.GetType() : null;
            _propertyName  = propertyName;
            _propertyType  = propertyType;

            if (_viewModelType != null)
            {
                string cacheKey = string.Format("{0}_{1}", _viewModelType.FullName, propertyName);
                _propertyInfo = _propertyInfoCache.GetFromCacheOrFetch(cacheKey, () => _viewModelType.GetPropertyEx(propertyName));
            }
        }
예제 #27
0
        /// <summary>
        /// Gets the signature of a method.
        /// </summary>
        /// <param name="constructorInfo">The member info.</param>
        /// <returns>The signature of the member info.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="constructorInfo"/> is <c>null</c>.</exception>
        public static string GetSignature(this ConstructorInfo constructorInfo)
        {
            Argument.IsNotNull("constructorInfo", constructorInfo);

            return(_constructorSignatureCache.GetFromCacheOrFetch(constructorInfo, () =>
            {
                var stringBuilder = new StringBuilder();

                stringBuilder.Append(GetMethodBaseSignaturePrefix(constructorInfo));
                stringBuilder.Append("ctor(");
                var param = constructorInfo.GetParameters().Select(p => String.Format("{0} {1}", p.ParameterType.Name, p.Name)).ToArray();
                stringBuilder.Append(String.Join(", ", param));
                stringBuilder.Append(")");

                return stringBuilder.ToString();
            }));
        }
예제 #28
0
        /// <summary>
        /// Gets the field names.
        /// </summary>
        /// <param name="type">Type of the model.</param>
        /// <returns>A hash set containing the field names.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public HashSet <string> GetFieldNames(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_fieldNamesCache.GetFromCacheOrFetch(type, () =>
            {
                var fieldNames = GetFieldsToSerialize(type);

                var finalFields = new HashSet <string>();
                foreach (var fieldName in fieldNames)
                {
                    finalFields.Add(fieldName);
                }

                return finalFields;
            }));
        }
예제 #29
0
        /// <summary>
        /// Gets the regular property names.
        /// </summary>
        /// <param name="type">Type of the model.</param>
        /// <returns>A hash set containing the regular property names.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception>
        public HashSet <string> GetRegularPropertyNames(Type type)
        {
            Argument.IsNotNull("type", type);

            return(_regularPropertyNamesCache.GetFromCacheOrFetch(type, () =>
            {
                var regularPropertyNames = GetRegularProperties(type);

                var finalProperties = new HashSet <string>();
                foreach (var propertyName in regularPropertyNames)
                {
                    finalProperties.Add(propertyName.Key);
                }

                return finalProperties;
            }));
        }
예제 #30
0
        /// <summary>
        /// Gets the entity key of the specified entity type in the <see cref="DbContext" />.
        /// </summary>
        /// <param name="dbContext">The db context.</param>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="keyValue">The key value.</param>
        /// <returns>The entity key.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="dbContext"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="entityType"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="keyValue"/> is <c>null</c>.</exception>
        public static EntityKey GetEntityKey(this DbContext dbContext, Type entityType, object keyValue)
        {
            Argument.IsNotNull("dbContext", dbContext);
            Argument.IsNotNull("entityType", entityType);
            Argument.IsNotNull("keyValue", keyValue);

            var keyPropertyName = _entityKeyPropertyNameCache.GetFromCacheOrFetch(new Tuple <Type, Type>(dbContext.GetType(), entityType), () =>
            {
                var entitySet = GetEntitySet(dbContext, entityType);
                return(entitySet.ElementType.KeyMembers[0].ToString());
            });

            var entitySetName = GetFullEntitySetName(dbContext, entityType);

            var entityKey = new EntityKey(entitySetName, new[] { new EntityKeyMember(keyPropertyName, keyValue) });

            return(entityKey);
        }