Exemple #1
0
 internal TypeReference()
 {
     _forTypeMemoizer = new Memoizer<Type, CodeTypeReference>(ComputeForType, null);
     _fromStringMemoizer = new Memoizer<KeyValuePair<string, bool>, CodeTypeReference>(ComputeFromString, null);
     _nullableForTypeMemoizer = new Memoizer<Type, CodeTypeReference>(ComputeNullableForType, null);
     _fromStringGenericMemoizer = new Memoizer<KeyValuePair<string, CodeTypeReference>, CodeTypeReference>(ComputeFromStringGeneric, null);
 }
Exemple #2
0
 private static void Main()
 {
     Console.WriteLine("Executing queries. Please be patient.");
     var memoizer = new Memoizer<int, Dictionary<string, CacheEntry<int>>>();
     var memoizedAsyncFunc = memoizer.Memoize(AsyncQuery);
     ExecuteAsyncQuery(memoizedAsyncFunc.InvokeAsync, () => ExecuteAsyncQuery(memoizedAsyncFunc.InvokeAsync));
     Console.Read();
 }
        internal FunctionImportEntityTypeMappingConditionValue(string columnName, XPathNavigator columnValue, LineInfo lineInfo)
            : base(columnName, lineInfo)
        {
            DebugCheck.NotNull(columnValue);

            _xPathValue = columnValue;
            _convertedValues = new Memoizer<Type, object>(GetConditionValue, null);
        }
Exemple #4
0
        /// <summary>
        /// Initializes a new FunctionImportEntityTypeMappingConditionValue instance.
        /// </summary>
        /// <param name="columnName">The name of the column used to evaluate the condition.</param>
        /// <param name="value">The value to compare with.</param>
        public FunctionImportEntityTypeMappingConditionValue(string columnName, object value)
            : base(Check.NotNull(columnName, "columnName"), LineInfo.Empty)
        {
            Check.NotNull(value, "value");

            _value           = value;
            _convertedValues = new Memoizer <Type, object>(GetConditionValue, null);
        }
    /* After this we can instatntiate abilities.*/
    void InstantiateDatabases()
    {
        if (showDebug) Debug.Log("MyMonoBehaviour: Instantiating databases...");

        memoizer = new Memoizer();

        if (showDebug) Debug.Log("MyMonoBehaviour: Finished instantiating databases!");
    }
Exemple #6
0
        internal FunctionImportEntityTypeMappingConditionValue(string columnName, XPathNavigator columnValue, LineInfo lineInfo)
            : base(columnName, lineInfo)
        {
            DebugCheck.NotNull(columnValue);

            _xPathValue      = columnValue;
            _convertedValues = new Memoizer <Type, object>(GetConditionValue, null);
        }
        /// <summary>
        /// Initializes a new FunctionImportEntityTypeMappingConditionValue instance.
        /// </summary>
        /// <param name="columnName">The name of the column used to evaluate the condition.</param>
        /// <param name="value">The value to compare with.</param>
        public FunctionImportEntityTypeMappingConditionValue(string columnName, object value)
            : base(Check.NotNull(columnName, "columnName"), LineInfo.Empty)
        {
            Check.NotNull(value, "value");

            _value = value;
            _convertedValues = new Memoizer<Type, object>(GetConditionValue, null);
        }
        internal FunctionImportEntityTypeMappingConditionValue(string columnName, XPathNavigator columnValue, LineInfo lineInfo)
            : base(columnName, lineInfo)
        {
            //Contract.Requires(columnValue != null);

            _xPathValue = columnValue;
            _convertedValues = new Memoizer<Type, object>(GetConditionValue, null);
        }
 Expression <Func <TSubscription, DateTime?> > Order <TSubscription>()
 {
     return(Memoizer.Memoize(typeof(TSubscription), _ =>
     {
         var p = Expression.Parameter(typeof(TSubscription));
         return Expression.Lambda <Func <TSubscription, DateTime?> >(Expression.Property(p, _lastRunTimeProperty), p);
     }));
 }
Exemple #10
0
 internal FunctionImportReturnTypeStructuralTypeColumnRenameMapping(string defaultMemberName)
 {
     _defaultMemberName         = defaultMemberName;
     _columnListForType         = new Collection <FunctionImportReturnTypeStructuralTypeColumn>();
     _columnListForIsTypeOfType = new Collection <FunctionImportReturnTypeStructuralTypeColumn>();
     _renameCache = new Memoizer <StructuralType, FunctionImportReturnTypeStructuralTypeColumn>(
         GetRename, EqualityComparer <StructuralType> .Default);
 }
 internal FunctionImportReturnTypeStructuralTypeColumnRenameMapping(string defaultMemberName)
 {
     _defaultMemberName = defaultMemberName;
     _columnListForType = new Collection<FunctionImportReturnTypeStructuralTypeColumn>();
     _columnListForIsTypeOfType = new Collection<FunctionImportReturnTypeStructuralTypeColumn>();
     _renameCache = new Memoizer<StructuralType, FunctionImportReturnTypeStructuralTypeColumn>(
         GetRename, EqualityComparer<StructuralType>.Default);
 }
        public void SimpleMemoizerFunction_ReturnCachedFunction()
        {
            Func <int> simpleValueFunction = null;

            simpleValueFunction = Memoizer.Memoize(() => SimpleValueFunction(simpleValueFunction));
            var result = simpleValueFunction();

            Assert.AreEqual(3, result);
        }
Exemple #13
0
        public void FunctionMemoizationExtensions_MemoizeWeak_TDelegate_HasValueTypeButNoMemoizer()
        {
            var n = 0;

            var mem = Memoizer.CreateWeak(WeakMemoizationCacheFactory.Unbounded);
            var f   = new Func <int, string, bool>((x, s) => { n++; return(s.Length == x); });

            Assert.ThrowsException <ArgumentNullException>(() => mem.MemoizeWeak(f, MemoizationOptions.None, memoizer: null));
        }
        public MemoizingTypeMappingStrategy(IFudgeTypeMappingStrategy inner)
        {
            _inner = inner;
            _getNameCache = new Memoizer<Type, string>(GetNameImpl);
            _getTypeCache = new Memoizer<string, Type>(GetTypeImpl);

            var weakRef = new WeakReference(this);
            HookUpWeakClearingDelegate(weakRef);
        }
 internal FunctionImportEntityTypeMappingConditionValue(
     string columnName,
     XPathNavigator columnValue,
     LineInfo lineInfo)
     : base(columnName, lineInfo)
 {
     this._xPathValue      = columnValue;
     this._convertedValues = new Memoizer <Type, object>(new Func <Type, object>(this.GetConditionValue), (IEqualityComparer <Type>)null);
 }
Exemple #16
0
        public void Memoize(TActor actor)
        {
            var memento = Memoizer.GetMemento(actor);

            if (!(memento is PassthroughMemento <TActor>))
            {
                Cache.Store(memento);
                Store.Store(memento);
            }
        }
 static bool HasBinder(Type t)
 {
     return(Memoizer.Memoize(t, _ => new
     {
         hasBinder =
             t.GetCustomAttributes(typeof(ModelBinderAttribute), true).Any() ||
             System.Web.Mvc.ModelBinders.Binders.ContainsKey(t)
     })
            .hasBinder);
 }
        public MemoizingTypeMappingStrategy(IFudgeTypeMappingStrategy inner)
        {
            _inner        = inner;
            _getNameCache = new Memoizer <Type, string>(GetNameImpl);
            _getTypeCache = new Memoizer <string, Type>(GetTypeImpl);

            var weakRef = new WeakReference(this);

            HookUpWeakClearingDelegate(weakRef);
        }
        public void MemoizerConcurrentFunctionWithValueInput_ReturnCachedFunctions()
        {
            Func <int, int> fibonacci = null;

            fibonacci = Memoizer.ConcurrentMemoize((int n1) => Fibonacci(n1, fibonacci));
            var result = fibonacci(3);

            Assert.AreEqual(2, result);
            _numberOfCallsMemoizer = _numberOfCalls = 0;
        }
Exemple #20
0
        public void Memoizer_Create()
        {
            var res = Memoizer.Create(new MyCacheFactory()).Memoize <string, int>(s => s.Length, MemoizationOptions.None, EqualityComparer <string> .Default);

            Assert.IsNotNull(res);

            Assert.IsNotNull(res.Delegate);
            Assert.IsNotNull(res.Cache);

            Assert.IsTrue(res.Cache is MyCache <string, int>);
        }
Exemple #21
0
        /// <summary>Returns all the items of the specified type from this item collection.</summary>
        /// <returns>
        /// A collection of type <see cref="T:System.Collections.ObjectModel.ReadOnlyCollection`1" /> that contains all the items of the specified type.
        /// </returns>
        /// <typeparam name="T">The type returned by the method.</typeparam>
        public virtual ReadOnlyCollection <T> GetItems <T>() where T : GlobalItem
        {
            Memoizer <Type, ICollection> itemsCache = this._itemsCache;

            if (this._itemsCache == null || this._itemCount != this.Count)
            {
                Interlocked.CompareExchange <Memoizer <Type, ICollection> >(ref this._itemsCache, new Memoizer <Type, ICollection>(new Func <Type, ICollection>(this.InternalGetItems), (IEqualityComparer <Type>)null), itemsCache);
                this._itemCount = this.Count;
            }
            return(this._itemsCache.Evaluate(typeof(T)) as ReadOnlyCollection <T>);
        }
Exemple #22
0
 static IPropDesc pd(Type host, Guid guid, PropertyInfo pi = null)
 {
     return(Memoizer.Memoize(new { host = host, guid }, _ =>
     {
         if (pi == null)
         {
             throw new InvalidOperationException("Property " + pi.DeclaringType.Name + "." + pi.Name + " has not beed declared in advance. Make sure you [Export] at least one AuditEventKind that has this property in it.");
         }
         return Activator.CreateInstance(typeof(PropDesc <,>).MakeGenericType(host, pi.PropertyType), pi) as IPropDesc;
     }));
 }
Exemple #23
0
        public void FunctionMemoizationExtensions_Memoize_NoArgs_ArgumentChecking()
        {
            var m = Memoizer.Create(MemoizationCacheFactory.Unbounded);

#pragma warning disable IDE0034 // Simplify 'default' expression (illustrative of method signature)
            Assert.ThrowsException <ArgumentNullException>(() => FunctionMemoizationExtensions.Memoize(default(Func <int>)));

            Assert.ThrowsException <ArgumentNullException>(() => FunctionMemoizationExtensions.Memoize(default(IMemoizer), () => 42));
            Assert.ThrowsException <ArgumentNullException>(() => FunctionMemoizationExtensions.Memoize(m, default(Func <int>)));
#pragma warning restore IDE0034 // Simplify 'default' expression
        }
        private void Select(string parameters)
        {
            if (parameters.Contains("or", StringComparison.InvariantCultureIgnoreCase) &&
                parameters.Contains("and", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new ArgumentException(
                          "This method supports only AND or only OR condition. Example: select id, firstname, lastname where firstname = 'John' and lastname = 'Doe' and dateofbirth = '02/02/2000'",
                          nameof(parameters));
            }

            SearchCondition condition = parameters.Contains("and", StringComparison.InvariantCultureIgnoreCase)
                ? SearchCondition.And
                : SearchCondition.Or;
            var words = parameters
                        .Split(this.Separator.ToArray())
                        .Where(s => s.Length > 0)
                        .ToList();
            var           keyValuePairs = new List <KeyValuePair <string, string> >();
            int           i             = 0;
            List <string> columns       = new List <string>();

            while (i < words.Count && !words[i].Equals("where", StringComparison.InvariantCultureIgnoreCase))
            {
                columns.Add(words[i++]);
            }

            while (++i < words.Count)
            {
                keyValuePairs.Add(new KeyValuePair <string, string>(words[i].ToUpperInvariant(), words[i + 1]));
                i += 2;
            }

            if (columns.Count == 0)
            {
                columns = this.NamesOfRecordElements;
            }
            else
            {
                this.IsValid(columns);
            }

            IEnumerable <FileCabinetRecord> records = null;

            if (this.Service is FileCabinetMemoryService)
            {
                records = Memoizer.GetMemoizer(this.Service).Select(parameters, keyValuePairs, condition);
            }
            else
            {
                records = this.Service.GetRecords().Where(keyValuePairs, condition);
            }

            this.printer(columns, records);
        }
Exemple #25
0
        public void Memoizer_CreateWeak()
        {
            var res = Memoizer.CreateWeak(new MyWeakCacheFactory()).MemoizeWeak <string, int>(s => s.Length, MemoizationOptions.None);

            Assert.IsNotNull(res);

            Assert.IsNotNull(res.Delegate);
            Assert.IsNotNull(res.Cache);

            Assert.IsTrue(res.Cache is MyCache <string, int>);
        }
        // used by EntityStoreSchemaGenerator to start with an empty (primitive types only) StoreItemCollection and 
        // add types discovered from the database
        internal StoreItemCollection(DbProviderFactory factory, DbProviderManifest manifest, string providerManifestToken)
            : base(DataSpace.SSpace)
        {
            Debug.Assert(factory != null, "factory is null");
            Debug.Assert(manifest != null, "manifest is null");

            _providerFactory = factory;
            _providerManifest = manifest;
            _providerManifestToken = providerManifestToken;
            _cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);
            LoadProviderManifest(_providerManifest, true /*checkForSystemNamespace*/);
        }
        // used by EntityStoreSchemaGenerator to start with an empty (primitive types only) StoreItemCollection and
        // add types discovered from the database
        internal StoreItemCollection(DbProviderFactory factory, DbProviderManifest manifest, string providerManifestToken)
            : base(DataSpace.SSpace)
        {
            DebugCheck.NotNull(factory);
            DebugCheck.NotNull(manifest);

            _providerFactory       = factory;
            _providerManifest      = manifest;
            _providerManifestToken = providerManifestToken;
            _cachedCTypeFunction   = new Memoizer <EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);
            LoadProviderManifest(_providerManifest);
        }
        public void MemoizerFunctionWithValueInput_ReturnCachedFunctions()
        {
            Func <int, int> fibonacci = null;

            fibonacci = Memoizer.Memoize((int n1) => Fibonacci(n1, fibonacci));
            var cachedResult = fibonacci(4);
            var result       = Fibonacci(4);

            Assert.AreEqual(3, cachedResult);
            Assert.AreEqual(3, result);
            Assert.Less(_numberOfCallsMemoizer, _numberOfCalls);
        }
        // used by EntityStoreSchemaGenerator to start with an empty (primitive types only) StoreItemCollection and
        // add types discovered from the database
        internal StoreItemCollection(DbProviderFactory factory, DbProviderManifest manifest, string providerManifestToken)
            : base(DataSpace.SSpace)
        {
            Debug.Assert(factory != null, "factory is null");
            Debug.Assert(manifest != null, "manifest is null");

            _providerFactory       = factory;
            _providerManifest      = manifest;
            _providerManifestToken = providerManifestToken;
            _cachedCTypeFunction   = new Memoizer <EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);
            LoadProviderManifest(_providerManifest, true /*checkForSystemNamespace*/);
        }
        public IContext <TActor> GetContext <TActor>(TActor actor) where TActor : class
        {
            var originalState = Memoizer.GetMemento(actor);

            if (Configuration.Replay)
            {
                return(new ReplayContext <TActor>(actor, originalState));
            }
            var keyAccessor = Assimilate.GetInstanceOf <IKeyAccessor>();

            return(new MikadoContext <TActor>(actor, originalState, keyAccessor, Publisher, _rulesRunner));
        }
        public IContext GetContext <TActor>(TActor actor, IEnumerable <IObserver <IEvent> > listeners)
            where TActor : class
        {
            var originalState = Memoizer.GetMemento(actor);

            if (Configuration.Replay)
            {
                return(new ReplayContext <TActor>(actor, originalState));
            }

            return(new MikadoContext <TActor>(actor, originalState, KeyAccessor, Publisher, _rulesRunner, listeners));
        }
Exemple #32
0
        private static void Main()
        {
            Console.WriteLine("Executing queries. Please be patient.");

            var memoizer = new Memoizer<int, Dictionary<string, CacheEntry<int>>>();
            var memoizedTaskAsyncFunc = memoizer.MemoizeTask<int>(TaskAsyncQuery);

            ExecuteTaskAsyncQuery(memoizedTaskAsyncFunc, QueryArg).Wait();
            ExecuteTaskAsyncQuery(memoizedTaskAsyncFunc, QueryArg).Wait();

            Console.Write("Press any key to exit.");
            Console.Read();
        }
Exemple #33
0
 /// <summary>
 ///     Construct a new EntityContainer mapping object
 ///     passing in the C-space EntityContainer  and
 ///     the s-space Entity container metadata objects.
 /// </summary>
 /// <param name="entityContainer"> Entity Continer type that is being mapped on the C-side </param>
 /// <param name="storageEntityContainer"> Entity Continer type that is being mapped on the S-side </param>
 internal StorageEntityContainerMapping(
     EntityContainer entityContainer, EntityContainer storageEntityContainer,
     StorageMappingItemCollection storageMappingItemCollection, bool validate, bool generateUpdateViews)
 {
     m_entityContainer              = entityContainer;
     m_storageEntityContainer       = storageEntityContainer;
     m_storageMappingItemCollection = storageMappingItemCollection;
     m_memoizedCellGroupEvaluator   = new Memoizer <InputForComputingCellGroups, OutputFromComputeCellGroups>(
         ComputeCellGroups, new InputForComputingCellGroups());
     identity              = entityContainer.Identity;
     m_validate            = validate;
     m_generateUpdateViews = generateUpdateViews;
 }
Exemple #34
0
        public void FunctionMemoizationExtensions_MemoizeWeak_TDelegate_ArgumentChecking()
        {
            var mem = Memoizer.CreateWeak(WeakMemoizationCacheFactory.Unbounded);
            var a   = new A(() => { });

#pragma warning disable IDE0034 // Simplify 'default' expression (illustrative of method signature)
            Assert.ThrowsException <ArgumentNullException>(() => FunctionMemoizationExtensions.MemoizeWeak <A>(default(IWeakMemoizer), a, MemoizationOptions.None));
            Assert.ThrowsException <ArgumentNullException>(() => FunctionMemoizationExtensions.MemoizeWeak <A>(mem, default(A), MemoizationOptions.None));

            Assert.ThrowsException <ArgumentException>(() => FunctionMemoizationExtensions.MemoizeWeak <int>(mem, 42, MemoizationOptions.None));
            Assert.ThrowsException <NotSupportedException>(() => FunctionMemoizationExtensions.MemoizeWeak <Q>(mem, (ref string x) => { }, MemoizationOptions.None));
#pragma warning restore IDE0034 // Simplify 'default' expression
        }
Exemple #35
0
        public void Call_invokes_original_function_the_first_time()
        {
            //Arrange
            var fnSpy = new Mock <Func <int, int, int, int, int> >();

            var memoizedFn = Memoizer.Memoize(fnSpy.Object);

            //Act
            memoizedFn.Call(0, 1, 2, 3);

            //Assert
            fnSpy.Verify(f => f(0, 1, 2, 3), Times.Once());
        }
            internal ViewDictionary(StorageMappingItemCollection storageMappingItemCollection,
                                    out Dictionary <EntitySetBase, GeneratedView> userDefinedQueryViewsDict,
                                    out Dictionary <OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict)
            {
                this.m_storageMappingItemCollection = storageMappingItemCollection;
                this.m_generatedViewsMemoizer       = new Memoizer <EntityContainer, Dictionary <EntitySetBase, GeneratedView> >(SerializedGetGeneratedViews, null);
                this.m_generatedViewOfTypeMemoizer  = new Memoizer <OfTypeQVCacheKey, GeneratedView>(SerializedGeneratedViewOfType, OfTypeQVCacheKey.PairComparer.Instance);

                userDefinedQueryViewsDict       = new Dictionary <EntitySetBase, GeneratedView>(EqualityComparer <EntitySetBase> .Default);
                userDefinedQueryViewsOfTypeDict = new Dictionary <OfTypeQVCacheKey, GeneratedView>(OfTypeQVCacheKey.PairComparer.Instance);

                TryGetUserDefinedQueryView       = userDefinedQueryViewsDict.TryGetValue;
                TryGetUserDefinedQueryViewOfType = userDefinedQueryViewsOfTypeDict.TryGetValue;
            }
Exemple #37
0
 internal StoreItemCollection(
     DbProviderFactory factory,
     DbProviderManifest manifest,
     string providerInvariantName,
     string providerManifestToken)
     : base(DataSpace.SSpace)
 {
     this._providerFactory       = factory;
     this._providerManifest      = manifest;
     this._providerInvariantName = providerInvariantName;
     this._providerManifestToken = providerManifestToken;
     this._cachedCTypeFunction   = new Memoizer <EdmFunction, EdmFunction>(new Func <EdmFunction, EdmFunction>(StoreItemCollection.ConvertFunctionSignatureToCType), (IEqualityComparer <EdmFunction>)null);
     this.LoadProviderManifest(this._providerManifest);
 }
            internal ViewDictionary(StorageMappingItemCollection storageMappingItemCollection, 
                            out Dictionary<EntitySetBase, GeneratedView> userDefinedQueryViewsDict,
                            out Dictionary<OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict)
            {
                this.m_storageMappingItemCollection = storageMappingItemCollection;
                this.m_generatedViewsMemoizer = new Memoizer<EntityContainer, Dictionary<EntitySetBase, GeneratedView>>(SerializedGetGeneratedViews, null);
                this.m_generatedViewOfTypeMemoizer = new Memoizer<OfTypeQVCacheKey, GeneratedView>(SerializedGeneratedViewOfType, OfTypeQVCacheKey.PairComparer.Instance);

                userDefinedQueryViewsDict = new Dictionary<EntitySetBase, GeneratedView>(EqualityComparer<EntitySetBase>.Default);
                userDefinedQueryViewsOfTypeDict = new Dictionary<OfTypeQVCacheKey, GeneratedView>(OfTypeQVCacheKey.PairComparer.Instance);

                TryGetUserDefinedQueryView = userDefinedQueryViewsDict.TryGetValue;
                TryGetUserDefinedQueryViewOfType = userDefinedQueryViewsOfTypeDict.TryGetValue;
            }
        // used by EntityStoreSchemaGenerator to start with an empty (primitive types only) StoreItemCollection and 
        // add types discovered from the database
        internal StoreItemCollection(
            DbProviderFactory factory, DbProviderManifest manifest, string providerInvariantName, string providerManifestToken)
            : base(DataSpace.SSpace)
        {
            DebugCheck.NotNull(factory);
            DebugCheck.NotNull(manifest);

            _providerFactory = factory;
            _providerManifest = manifest;
            _providerInvariantName = providerInvariantName;
            _providerManifestToken = providerManifestToken;
            _cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);
            LoadProviderManifest(_providerManifest);
        }
        private object Invoke(MethodInfo targetMethod, object[] args)
        {
            var  config   = GetConfig(GetMethodNameForCachingPolicy(targetMethod, args));
            bool useCache = config.Enabled == true && IsMethodCached(targetMethod, args);

            if (useCache)
            {
                return(Memoizer.Memoize(DataSource, targetMethod, args, new CacheItemPolicyEx(config)));
            }
            else
            {
                return(targetMethod.Invoke(DataSource, args));
            }
        }
Exemple #41
0
        public void Memoize_correctly_if_the_argument_is_null()
        {
            //Arrange
            var fnSpy = new Mock <Func <object, object, object, object, int> >();

            var memoizedFn = Memoizer.Memoize(fnSpy.Object);

            //Act, call the function a few times
            memoizedFn.Call(null, null, null, null);
            memoizedFn.Call(null, null, null, null);
            memoizedFn.Call(null, null, null, null);

            //Assert
            fnSpy.Verify(f => f(null, null, null, null), Times.Once());
        }
Exemple #42
0
        public void Call_does_not_invoke_original_function_if_the_arguments_are_Equal()
        {
            //Arrange
            var fnSpy = new Mock <Func <int, int, int, int, int> >();

            var memoizedFn = Memoizer.Memoize(fnSpy.Object);

            //Act, call the function a few times
            memoizedFn.Call(0, 1, 2, 3);
            memoizedFn.Call(0, 1, 2, 3);
            memoizedFn.Call(0, 1, 2, 3);

            //Assert
            fnSpy.Verify(f => f(0, 1, 2, 3), Times.Once());
        }
            internal ViewDictionary(
                StorageMappingItemCollection storageMappingItemCollection,
                out Dictionary<EntitySetBase, GeneratedView> userDefinedQueryViewsDict,
                out Dictionary<OfTypeQVCacheKey, GeneratedView> userDefinedQueryViewsOfTypeDict,
                IViewAssemblyCache viewAssemblyCache = null)
            {
                _viewAssemblyCache = viewAssemblyCache ?? DbConfiguration.GetService<IViewAssemblyCache>();
                _storageMappingItemCollection = storageMappingItemCollection;
                _generatedViewsMemoizer =
                    new Memoizer<EntityContainer, Dictionary<EntitySetBase, GeneratedView>>(SerializedGetGeneratedViews, null);
                _generatedViewOfTypeMemoizer = new Memoizer<OfTypeQVCacheKey, GeneratedView>(
                    SerializedGeneratedViewOfType, OfTypeQVCacheKey.PairComparer.Instance);

                userDefinedQueryViewsDict = new Dictionary<EntitySetBase, GeneratedView>(EqualityComparer<EntitySetBase>.Default);
                userDefinedQueryViewsOfTypeDict = new Dictionary<OfTypeQVCacheKey, GeneratedView>(OfTypeQVCacheKey.PairComparer.Instance);

                _tryGetUserDefinedQueryView = userDefinedQueryViewsDict.TryGetValue;
                _tryGetUserDefinedQueryViewOfType = userDefinedQueryViewsOfTypeDict.TryGetValue;
            }
Exemple #44
0
        public void TestSingleCall()
        {
            const int N = 10;

            int numCalls = 0;

            var seq = Enumerable.Range(0, N).Select(n => { numCalls++; return n; });
            var memo = new Memoizer<int>(seq);

            int i = 0;
            foreach (var n in memo)
            {
                Assert.AreEqual(i++, n);
            }
            Assert.AreEqual(N, i);

            for (i = 0; i < N; i++)
            {
                Assert.AreEqual(i, memo[i]);
            }
            Assert.AreEqual(N, numCalls);
        }
        public void ConcurrentAddsReturnSingelton()
        {
            var wait = TimeSpan.FromMinutes(1);

            var b = new Barrier(2);
            long functionCount = 0;
            var m = new Memoizer<int, object>(i =>
                                          {
                                              var count = Interlocked.Increment(ref functionCount);
                                              if (count > 2)
                                              {
                                                  throw new Exception("Too many executions " + count);
                                              }
                                              Assert.True(b.SignalAndWait(wait));
                                              return new object();
                                          });
            const int arg = 1;
            var o1 = Task<object>.Factory.StartNew(() => m.Get(arg));
            var o2 = Task<object>.Factory.StartNew(() => m.Get(arg));
            Assert.True(o1.Wait(wait));
            Assert.True(o2.Wait(wait));
            Assert.Equal(2, functionCount);
            Assert.Equal(o1.Result, o2.Result);
        }
 public override void SetUp()
 {
     base.SetUp();
     memoizer = new Memoizer(localCache);
 }
 public void WhenValueNotPresentPopulatesAndMemoizesIt()
 {
     Memoizer<int> memoizer = new Memoizer<int>();
     Assert.AreEqual(42, memoizer.Memoize(() => 42));
     Assert.AreEqual(42, memoizer.Memoize(() => { throw new InvalidOperationException("Should not be called"); }));
 }
        /// <summary>Initializes a new instances of the <see cref="T:System.Data.Entity.Core.Metadata.Edm.StoreItemCollection" /> class.</summary>
        /// <param name="model">The model of the <see cref="T:System.Data.Entity.Core.Metadata.Edm.StoreItemCollection" />.</param>
        public StoreItemCollection(EdmModel model)
            : base(DataSpace.SSpace)
        {
            Check.NotNull(model, "model");
            DebugCheck.NotNull(model.ProviderInfo);
            DebugCheck.NotNull(model.ProviderManifest);

            _providerManifest = model.ProviderManifest;
            _providerInvariantName = model.ProviderInfo.ProviderInvariantName;
            _providerFactory = DbConfiguration.DependencyResolver.GetService<DbProviderFactory>(_providerInvariantName);
            _providerManifestToken = model.ProviderInfo.ProviderManifestToken;
            _cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);

            LoadProviderManifest(_providerManifest);

            _schemaVersion = model.SchemaVersion;

            model.Validate();

            foreach (var globalItem in model.GlobalItems)
            {
                globalItem.SetReadOnly();

                AddInternal(globalItem);
            }
        }
Exemple #49
0
 protected override Func<int, IEnumerable<int>> GetQuery()
 {
     var memoizer = new Memoizer<int, Dictionary<string, CacheEntry<int>>>();
     var memoizedFunc = memoizer.Memoize<int>(BaseQuery);
     return memoizedFunc.Invoke;
 }
        private IList<EdmSchemaError> Init(IEnumerable<XmlReader> xmlReaders,
                                           IEnumerable<string> filePaths, bool throwOnError,
                                           out DbProviderManifest providerManifest,
                                           out DbProviderFactory providerFactory,
                                           out string providerManifestToken,
                                           out Memoizer<EdmFunction, EdmFunction> cachedCTypeFunction)
        {
            EntityUtil.CheckArgumentNull(xmlReaders, "xmlReaders");
            // 'filePaths' can be null

            cachedCTypeFunction = new Memoizer<EdmFunction, EdmFunction>(ConvertFunctionSignatureToCType, null);

            Loader loader = new Loader(xmlReaders, filePaths, throwOnError);
            providerFactory = loader.ProviderFactory;
            providerManifest = loader.ProviderManifest;
            providerManifestToken = loader.ProviderManifestToken;

            // load the items into the colleciton
            if (!loader.HasNonWarningErrors)
            {
                LoadProviderManifest(loader.ProviderManifest, true /* check for system namespace */);
                List<EdmSchemaError> errorList = EdmItemCollection.LoadItems(_providerManifest, loader.Schemas, this);
                foreach (var error in errorList)
                {
                    loader.Errors.Add(error);
                }
                
                if (throwOnError && errorList.Count != 0)
                    loader.ThrowOnNonWarningErrors();
            }
            
            return loader.Errors;
        }