Exemplo n.º 1
0
        public void SetProperty(string propertyName, string propertyValueStr)
        {
            var type       = GetType();
            var properties = PropertiesCache.GetFromCacheOrFetch(type, () => type.GetPropertiesEx());
            var property   = properties.FirstOrDefault(x => x.Name == propertyName);

            SetPropertyValue(property, propertyValueStr);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the member on the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="name">The name.</param>
        /// <param name="bindingFlags">The binding Flags.</param>
        /// <returns>MemberInfo[][].</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        public static MemberInfo[] GetMemberEx(this Type type, string name, BindingFlags bindingFlags)
        {
            Argument.IsNotNull("type", type);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Member, bindingFlags, name);
            return(_fieldCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetMember(name, bindingFlags)));
#else
            return(type.GetTypeInfo().GetMember(name, bindingFlags));
#endif
        }
Exemplo n.º 3
0
        /// <summary>
        /// The get method ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="name">The name.</param>
        /// <param name="bindingFlags">The binding Flags.</param>
        /// <returns>MethodInfo.</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentException">The <paramref name="name" /> is <c>null</c> or whitespace.</exception>
        public static MethodInfo GetMethodEx(this Type type, string name, BindingFlags bindingFlags)
        {
            Argument.IsNotNull("type", type);
            Argument.IsNotNullOrWhitespace("name", name);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Method, bindingFlags, name);
            return(_methodCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetMethod(name, bindingFlags)));
#else
            return(type.GetTypeInfo().GetMethod(name, bindingFlags));
#endif
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets the module assembly ref overriden the version number.
        /// </summary>
        /// <param name="moduleInfo">The module info</param>
        /// <param name="version">The version</param>
        /// <returns>The module assembly ref</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="moduleInfo" /> is <c>null</c>.</exception>
        private ModuleAssemblyRef GetModuleAssemblyRef(ModuleInfo moduleInfo, SemanticVersion version)
        {
            Argument.IsNotNull(() => moduleInfo);

            var        moduleInfoKey       = string.Format(CultureInfo.InvariantCulture, "ModuleName:{0}; ModuleType:{1}; Ref:{2}; Version:{3}", moduleInfo.ModuleName, moduleInfo.ModuleType, moduleInfo.Ref, version);
            ModuleInfo moduleInfoFromCache = _moduleInfoCacheStoreCacheStorage.GetFromCacheOrFetch(moduleInfoKey, () => new ModuleInfo(moduleInfo.ModuleName, moduleInfo.ModuleType)
            {
                Ref = string.Format("{0}, {1}", moduleInfo.GetPackageName().Id, version), DependsOn = moduleInfo.DependsOn
            });

            return(moduleInfoFromCache.GetModuleAssemblyRef(OutputDirectoryAbsoluteUri));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Gets the module assembly ref overriden the version number.
        /// </summary>
        /// <param name="moduleInfo">The module info</param>
        /// <param name="version">The version</param>
        /// <returns>The module assembly ref</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="moduleInfo" /> is <c>null</c>.</exception>
        private string GetModuleAssemblyRef(ModuleInfo moduleInfo, SemanticVersion version)
        {
            // ReSharper disable once ImplicitlyCapturedClosure
            Argument.IsNotNull(() => moduleInfo);

            var key = string.Format(CultureInfo.InvariantCulture, "ModuleName:{0}; ModuleType:{1}; Ref:{2}; Version:{3}", moduleInfo.ModuleName, moduleInfo.ModuleType, moduleInfo.Ref, version);

            return(GetModuleAssemblyRef(_moduleInfoCacheStoreCacheStorage.GetFromCacheOrFetch(key, () => new ModuleInfo(moduleInfo.ModuleName, moduleInfo.ModuleType)
            {
                Ref = string.Format("{0}, {1}", moduleInfo.GetPackageName().Id, version), DependsOn = moduleInfo.DependsOn
            })));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Returns whether the member value should be serialized as dictionary.
        /// </summary>
        /// <param name="memberType">Type of the member.</param>
        /// <returns><c>true</c> if the member value should be serialized as dictionary, <c>false</c> otherwise.</returns>
        protected virtual bool ShouldSerializeAsDictionary(Type memberType)
        {
            return(_shouldSerializeAsDictionaryCache.GetFromCacheOrFetch(memberType, () =>
            {
                var serializerModifiers = SerializationManager.GetSerializerModifiers(memberType);
                if (serializerModifiers != null)
                {
                    foreach (var serializerModifier in serializerModifiers)
                    {
                        var shouldSerializeAsDictionary = serializerModifier.ShouldSerializeAsDictionary();
                        if (shouldSerializeAsDictionary.HasValue)
                        {
                            return shouldSerializeAsDictionary.Value;
                        }
                    }
                }

                if (memberType.IsDictionary())
                {
                    return true;
                }

                return false;
            }));
        }
Exemplo n.º 7
0
        private static Tuple <XmlDocument, XmlNamespaceManager> GetResourceXmlDocument(Uri resourceDictionaryUri)
        {
            return(_resourceDictionaryCache.GetFromCacheOrFetch(resourceDictionaryUri, () =>
            {
                var streamResourceInfo = Application.GetResourceStream(resourceDictionaryUri);
                var reader = new XmlBamlReader(streamResourceInfo.Stream);

                var doc = new XmlDocument();
                doc.Load(reader);

                // Create namespace manager (all namespaces are required)
                var xmlNamespaceManager = new XmlNamespaceManager(doc.NameTable);
                foreach (XmlAttribute namespaceAttribute in doc.DocumentElement.Attributes)
                {
                    // Clean up namespace (remove xmlns prefix)
                    var xmlNamespace = namespaceAttribute.Name.Replace("xmlns", string.Empty).TrimStart(':');
                    xmlNamespaceManager.AddNamespace(xmlNamespace, namespaceAttribute.Value);
                }

                // Add a dummy node
                xmlNamespaceManager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
                xmlNamespaceManager.AddNamespace("ctl", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");

                return new Tuple <XmlDocument, XmlNamespaceManager>(doc, xmlNamespaceManager);
            }));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Determines whether the specified member on the specified model should be ignored by the serialization engine.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="propertyName">Name of the member.</param>
        /// <returns><c>true</c> if the member should be ignored, <c>false</c> otherwise.</returns>
        protected override bool ShouldIgnoreMember(ModelBase model, string propertyName)
        {
            var ignoredMembers = _ignoredMembersCache.GetFromCacheOrFetch(model.GetType(), () =>
            {
                var modelType         = model.GetType();
                var ignoredProperties = new HashSet <string>();

                var properties = modelType.GetPropertiesEx();
                foreach (var property in properties)
                {
                    if (AttributeHelper.IsDecoratedWithAttribute <XmlIgnoreAttribute>(property))
                    {
                        ignoredProperties.Add(property.Name);
                    }
                }

                return(ignoredProperties);
            });

            if (ignoredMembers.Contains(propertyName))
            {
                return(true);
            }

            return(base.ShouldIgnoreMember(model, propertyName));
        }
Exemplo n.º 9
0
        public static Color GetAccentColor(AccentColorStyle colorStyle = AccentColorStyle.AccentColor)
        {
            return(_accentColorsCache.GetFromCacheOrFetch(colorStyle, () =>
            {
                var color = GetAccentColorBrush().Color;

                switch (colorStyle)
                {
                case AccentColorStyle.AccentColor:
                    return Color.FromArgb(255, color.R, color.G, color.B);

                case AccentColorStyle.AccentColor1:
                    return Color.FromArgb(204, color.R, color.G, color.B);

                case AccentColorStyle.AccentColor2:
                    return Color.FromArgb(153, color.R, color.G, color.B);

                case AccentColorStyle.AccentColor3:
                    return Color.FromArgb(102, color.R, color.G, color.B);

                case AccentColorStyle.AccentColor4:
                    return Color.FromArgb(51, color.R, color.G, color.B);

                default:
                    throw new ArgumentOutOfRangeException("colorStyle");
                }
            }));
        }
Exemplo n.º 10
0
        /// <summary>
        /// The get property ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="name">The name.</param>
        /// <param name="bindingFlags">The binding Flags.</param>
        /// <param name="allowExplicitInterfaceProperties">if set to <c>true</c>, this method will check for explicit interface implementations when the property is not found.</param>
        /// <returns>PropertyInfo.</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentException">The <paramref name="name" /> is <c>null</c> or whitespace.</exception>
        public static PropertyInfo GetPropertyEx(this Type type, string name, BindingFlags bindingFlags, bool allowExplicitInterfaceProperties = true)
        {
            Argument.IsNotNull("type", type);
            Argument.IsNotNullOrWhitespace("name", name);

            PropertyInfo propertyInfo = null;

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Property, bindingFlags, name);
            propertyInfo = _propertyCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetProperty(name, bindingFlags));
#else
            propertyInfo = type.GetTypeInfo().GetProperty(name, bindingFlags);
#endif

            if (propertyInfo == null)
            {
                if (allowExplicitInterfaceProperties)
                {
                    foreach (var iface in type.GetInterfacesEx())
                    {
                        propertyInfo = iface.GetPropertyEx(name, bindingFlags, false);
                        if (propertyInfo != null)
                        {
                            break;
                        }
                    }
                }
            }

            return(propertyInfo);
        }
Exemplo n.º 11
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>()));
        }
Exemplo n.º 12
0
 public static SolidColorBrush GetAccentColorBrush(AccentColorStyle colorStyle)
 {
     return(_accentColorBrushesCache.GetFromCacheOrFetch(colorStyle, () =>
     {
         var color = GetAccentColor(colorStyle);
         return new SolidColorBrush(color);
     }));
 }
Exemplo n.º 13
0
 public static SolidColorBrush GetThemeColorBrush(ThemeColorStyle colorStyle = ThemeColorStyle.AccentColor)
 {
     return(_themeColorBrushesCache.GetFromCacheOrFetch(colorStyle, () =>
     {
         var color = GetThemeColor(colorStyle);
         return GetSolidColorBrush(color);
     }));
 }
 private static MethodInfo GetRegisterSimplePropertyMethodInfo(Type modelBaseType)
 {
     return(_registerSimplePropertyCache.GetFromCacheOrFetch(modelBaseType, () =>
     {
         var methodInfo = modelBaseType.GetMethodEx("RegisterDynamicProperty", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.NonPublic);
         return methodInfo;
     }));
 }
Exemplo n.º 15
0
 public SolidColorBrush GetThemeColorBrush(string resourceName)
 {
     return(_resourceBrushesCache.GetFromCacheOrFetch(resourceName, () =>
     {
         var color = GetThemeColor(resourceName);
         return color.ToSolidColorBrush();
     }));
 }
Exemplo n.º 16
0
        public static T GetOrCreateConnectedInstance <T>(this DbProvider dbProvider)
        {
            Argument.IsNotNull(() => dbProvider);

            var instanceCache = ConnectedInstances.GetFromCacheOrFetch(dbProvider.ProviderInvariantName, () => new CacheStorage <Type, object>());

            return((T)instanceCache.GetFromCacheOrFetch(typeof(T), () => CreateConnectedInstance <T>(dbProvider)));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Converts an <see cref="Enumerable" /> into a <see cref="IList{T}" />
        /// </summary>
        /// <param name="instance">The enumerable</param>
        /// <param name="type">The type</param>
        /// <returns>The <see cref="IList{T}" /> as <see cref="IEnumerable" /></returns>
        public static IEnumerable ToList(this IEnumerable instance, Type type)
        {
            Argument.IsNotNull("instance", instance);
            Argument.IsNotNull("type", type);

            var methodInfo = ToListGenericMethodInfoCache.GetFromCacheOrFetch(type, () => ToListMethodInfo.MakeGenericMethod(type));

            return((IEnumerable)methodInfo.Invoke(null, new object[] { instance }));
        }
Exemplo n.º 18
0
        private bool IsTypeBinarySerializable(Type type)
        {
            if (type == null)
            {
                return(false);
            }

            return(TypeBinarySerializableCache.GetFromCacheOrFetch(type, () => type.GetConstructor(TypeArray.From <SerializationInfo, StreamingContext>()) != null));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the <c>ToString(IFormatProvider)</c> method.
        /// </summary>
        /// <param name="memberType">Type of the member.</param>
        /// <returns></returns>
        protected virtual MethodInfo GetObjectToStringMethod(Type memberType)
        {
            var toStringMethod = _toStringMethodCache.GetFromCacheOrFetch(memberType, () =>
            {
                var method = memberType.GetMethodEx("ToString", new[] { typeof(IFormatProvider) }, BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                return(method);
            });

            return(toStringMethod);
        }
Exemplo n.º 20
0
        /// <summary>
        /// The get constructors ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>ConstructorInfo[][].</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        public static ConstructorInfo[] GetConstructorsEx(this Type type)
        {
            Argument.IsNotNull("type", type);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Constructor, BindingFlags.Default, "allctors");
#if NETFX_CORE || PCL
            return(_constructorsCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().DeclaredConstructors.ToArray()));
#else
            return(_constructorsCache.GetFromCacheOrFetch(cacheKey, type.GetConstructors));
#endif
#else
#if NETFX_CORE || PCL
            return(type.GetTypeInfo().DeclaredConstructors.ToArray());
#else
            return(type.GetConstructors());
#endif
#endif
        }
Exemplo n.º 21
0
        /// <summary>
        /// The get fields ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="bindingFlags">The binding Flags.</param>
        /// <returns>FieldInfo[][].</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        public static FieldInfo[] GetFieldsEx(this Type type, BindingFlags bindingFlags)
        {
            Argument.IsNotNull("type", type);
#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Field, bindingFlags);
            return(_fieldsCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetFields(bindingFlags)));
#else
            return(type.GetTypeInfo().GetFields(bindingFlags));
#endif
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the <c>Parse(string, IFormatProvider)</c> method.
        /// </summary>
        /// <param name="memberType">Type of the member.</param>
        /// <returns></returns>
        protected virtual MethodInfo GetObjectParseMethod(Type memberType)
        {
            var parseMethod = _parseMethodCache.GetFromCacheOrFetch(memberType, () =>
            {
                var method = memberType.GetMethodEx("Parse", new[] { typeof(string), typeof(IFormatProvider) }, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
                return(method);
            });

            return(parseMethod);
        }
Exemplo n.º 23
0
            public void AddsItemToCacheAndReturnsIt()
            {
                var cache = new CacheStorage <string, int>();

                var value = cache.GetFromCacheOrFetch("1", () => 1);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(1, cache["1"]);
                Assert.AreEqual(1, value);
            }
Exemplo n.º 24
0
            public void ReturnsCachedItem()
            {
                var cache = new CacheStorage <string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(1, cache["1"]);
                Assert.AreEqual(1, value);
            }
Exemplo n.º 25
0
        /// <summary>
        ///     The get properties ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="bindingFlags">The binding Flags.</param>
        /// <returns>PropertyInfo[][].</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        public static PropertyInfo[] GetPropertiesEx(this Type type, BindingFlags bindingFlags)
        {
            Argument.IsNotNull(nameof(type), type);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Property, bindingFlags);
            return(_propertiesCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetProperties(bindingFlags)));
#else
            return(type.GetTypeInfo().GetProperties(bindingFlags));
#endif
        }
Exemplo n.º 26
0
        /// <summary>
        /// The get constructor ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="types">The types.</param>
        /// <returns>ConstructorInfo.</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentNullException">The <paramref name="types" /> is <c>null</c>.</exception>
        public static ConstructorInfo GetConstructorEx(this Type type, Type[] types)
        {
            Argument.IsNotNull("type", type);
            Argument.IsNotNull("types", types);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Constructor, BindingFlags.Default, types);
#if NETFX_CORE || PCL
            return(_constructorCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetConstructor(types, BindingFlagsHelper.GetFinalBindingFlags(false, false))));
#else
            return(_constructorCache.GetFromCacheOrFetch(cacheKey, () => type.GetConstructor(types)));
#endif
#else
#if NETFX_CORE || PCL
            return(type.GetTypeInfo().GetConstructor(types, BindingFlagsHelper.GetFinalBindingFlags(false, false)));
#else
            return(type.GetConstructor(types));
#endif
#endif
        }
Exemplo n.º 27
0
        /// <summary>
        /// Gets the module assembly ref.
        /// </summary>
        /// <param name="moduleInfo">The module info</param>
        /// <returns>The module assembly ref</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="moduleInfo" /> is <c>null</c>.</exception>
        private string GetModuleAssemblyRef(ModuleInfo moduleInfo)
        {
            // ReSharper disable once ImplicitlyCapturedClosure
            Argument.IsNotNull(() => moduleInfo);

            return(_assemblyRefCacheStorage.GetFromCacheOrFetch(moduleInfo, () =>
            {
                PackageName packageName = moduleInfo.GetPackageName();
                string directoryName = packageName.ToString().Replace(' ', '.');
                return string.Format(CultureInfo.InvariantCulture, RelativeUrlPattern, BaseUrl, directoryName, _frameworkNameIdentifier, moduleInfo.GetAssemblyName());
            }));
        }
Exemplo n.º 28
0
        /// <summary>
        /// The get events ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="flattenHierarchy">The flatten Hierarchy.</param>
        /// <param name="allowStaticMembers">The allow Static Members.</param>
        /// <returns>EventInfo[][].</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        public static EventInfo[] GetEventsEx(this Type type, bool flattenHierarchy = true, bool allowStaticMembers = false)
        {
            Argument.IsNotNull("type", type);
            BindingFlags bindingFlags = BindingFlagsHelper.GetFinalBindingFlags(flattenHierarchy, allowStaticMembers);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Event, bindingFlags);
            return(_eventsCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetEvents(bindingFlags)));
#else
            return(type.GetTypeInfo().GetEvents(bindingFlags));
#endif
        }
Exemplo n.º 29
0
        /// <summary>
        /// Returns whether the member value should be serialized as dictionary.
        /// </summary>
        /// <param name="memberType">Type of the member.</param>
        /// <returns><c>true</c> if the member value should be serialized as dictionary, <c>false</c> otherwise.</returns>
        protected virtual bool ShouldSerializeAsDictionary(Type memberType)
        {
            return(_shouldSerializeAsDictionaryCache.GetFromCacheOrFetch(memberType, () =>
            {
                if (memberType.IsDictionary())
                {
                    return true;
                }

                return false;
            }));
        }
Exemplo n.º 30
0
        /// <summary>
        ///     The get event ex.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="name">The name.</param>
        /// <param name="bindingFlags">The binding Flags.</param>
        /// <returns>EventInfo.</returns>
        /// <exception cref="System.ArgumentNullException">The <paramref name="type" /> is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentException">The <paramref name="name" /> is <c>null</c> or whitespace.</exception>
        public static EventInfo GetEventEx(this Type type, string name, BindingFlags bindingFlags)
        {
            Argument.IsNotNullOrWhitespace(nameof(name), name);
            Argument.IsNotNull(nameof(type), type);

#if ENABLE_CACHE
            var cacheKey = new ReflectionCacheKey(type, ReflectionTypes.Event, bindingFlags, name);
            return(_eventCache.GetFromCacheOrFetch(cacheKey, () => type.GetTypeInfo().GetEvent(name, bindingFlags)));
#else
            return(type.GetTypeInfo().GetEvent(name, bindingFlags));
#endif
        }
Exemplo n.º 31
0
            public void RunMultipleThreadsWithRandomAccessCalls()
            {
                var cacheStorage = new CacheStorage<Guid, int>(() => ExpirationPolicy.Duration(TimeSpan.FromMilliseconds(1)));

                var threads = new List<Thread>();
                for (int i = 0; i < 25; i++)
                {
                    var thread = new Thread(() =>
                    {
                        var random = new Random();

                        for (int j = 0; j < 10000; j++)
                        {
                            var randomGuid = _randomGuids[random.Next(0, 9)];
                            cacheStorage.GetFromCacheOrFetch(randomGuid, () =>
                            {
                                var threadId = Thread.CurrentThread.ManagedThreadId;
                                Log.Info("Key '{0}' is now controlled by thread '{1}'", randomGuid, threadId);
                                return threadId;
                            });

                            ThreadHelper.Sleep(1);
                        }
                    });

                    threads.Add(thread);
                    thread.Start();
                }

                while (true)
                {
                    bool anyThreadAlive = false;

                    foreach (var thread in threads)
                    {
                        if (thread.IsAlive)
                        {
                            anyThreadAlive = true;
                            break;
                        }
                    }

                    if (!anyThreadAlive)
                    {
                        break;
                    }

                    ThreadHelper.Sleep(500);
                }
            }
Exemplo n.º 32
0
            public void ReturnsCachedItem()
            {
                var cache = new CacheStorage<string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(1, cache["1"]);
                Assert.AreEqual(1, value);
            }
Exemplo n.º 33
0
            public void AddsAndExpiresSeveralItems()
            {
                var cache = new CacheStorage<string, int>();
                cache.ExpirationTimerInterval = TimeSpan.FromMilliseconds(250);

                for (int i = 0; i < 5; i++)
                {
                    ThreadHelper.Sleep(1000);

                    int innerI = i;
                    var value = cache.GetFromCacheOrFetch("key", () => innerI, expiration: TimeSpan.FromMilliseconds(250));

                    Assert.AreEqual(i, value);
                }
            }
Exemplo n.º 34
0
            public void AddsAndExpiresSeveralItems()
            {
                var cache = new CacheStorage<string, int>();

                for (int i = 0; i < 5; i++)
                {
                    var value = cache.GetFromCacheOrFetch("key", () => i, expiration: new TimeSpan(0, 0, 1));

                    Assert.AreEqual(i, value);

                    ThreadHelper.Sleep(2000);
                }
            }
Exemplo n.º 35
0
            public void ThrowsArgumentNullExceptionForNullFunction()
            {
                var cache = new CacheStorage<string, int>();

                ExceptionTester.CallMethodAndExpectException<ArgumentNullException>(() => cache.GetFromCacheOrFetch("1", null));
            }
Exemplo n.º 36
0
            public void AddsItemToCacheWithOverrideAndReturnsIt()
            {
                var cache = new CacheStorage<string, int>();

                cache.Add("1", 1);
                var value = cache.GetFromCacheOrFetch("1", () => 2, true);

                Assert.IsTrue(cache.Contains("1"));
                Assert.AreEqual(2, cache["1"]);
                Assert.AreEqual(2, value);
            }