Example #1
0
        public override void SetUp()
        {
            base.SetUp();

            objectRepository = new Dictionary <string, object>();

            codingStyle = BuildRoutine.CodingStyle().FromBasic()
                          .AddTypes(GetType().Assembly, t => t.IsPublic && t.Namespace != null && t.Namespace.StartsWith(RootNamespace))

                          .Initializers.Add(c => c.Constructors().When(t => t.IsValueType && t.Namespace?.StartsWith(RootNamespace) == true))
                          .Datas.Add(c => c.PublicProperties(m => !m.IsInherited()).When(t => t.Namespace?.StartsWith(RootNamespace) == true))
                          .Operations.Add(c => c.PublicMethods(m => !m.IsInherited()).When(t => t.Namespace?.StartsWith(RootNamespace) == true))

                          .IdExtractor.Set(c => c.IdByProperty(p => p.Returns <string>("Id")).When(t => t.Namespace != null && t.Namespace.StartsWith(RootNamespace)))
                          .Locator.Set(c => c.Locator(l => l.SingleBy(id => objectRepository[id])).When(t => t.Namespace != null && t.Namespace.StartsWith(RootNamespace) && t.Properties.Any(m => m.Returns <string>("Id"))))

                          .NextLayer()
            ;

            var cache = new DictionaryCache();

            ctx = new DefaultCoreContext(codingStyle, cache);

            testing = new ObjectService(ctx, cache);
        }
Example #2
0
        public void TestSetNotPresent()
        {
            var cache  = new DictionaryCache();
            var result = cache.Fetch("NotExistingKey");

            result.Should().BeNull();
        }
        public WorkflowParcelService()
        {
            _workflowSetStateParcelCache = new DictionaryCache<Guid, WorkflowSetStateParcel>(new TimeSpan(0, 5, 0),
                                                                                     FillParcelCache);
            _workflowErrorMessageCache = new DictionaryCache<Guid, string>(new TimeSpan(0, 5, 0), FillErrorMessageCache);

        }
Example #4
0
        public static IList <AttachmentData> ToViewList(this IQueryable <Attachment> nodes, CategoryDictionary suffix = CategoryDictionary.None)
        {
            Dictionary <int, MessageData> dicMessages = new Dictionary <int, MessageData>();
            var nodeList = nodes.ToList();
            var results  = nodeList.Select(node => new AttachmentData()
            {
                Id                 = node.Id,
                TargetId           = node.TargetId,
                AttachmentTypeId   = node.AttachmentTypeId,
                AttachmentFormatId = node.AttachmentFormatId,
                Description        = node.Description,
                Size               = node.Size,
                CreateTime         = node.CreateTime,
                Path               = node.Path,
                OriginalName       = node.OriginalName,
                LogicalName        = node.LogicalName,
            }).ToList();

            for (int i = 0; i < nodeList.Count(); i++)
            {
                results[i].AttachmentFormat = DictionaryCache.Get()[results[i].AttachmentFormatId].ToViewData();
                results[i].AttachmentType   = DictionaryCache.Get()[results[i].AttachmentTypeId].ToViewData();
                results[i].Target           = nodeList[i].ToViewData().Target;
            }
            return(results);
        }
        public void Ctor_Connected()
        {
            MockRepository mockRepository;
            const string   name = "Name";
            DictionaryCache <long, string>   dictionaryCache;
            Mock <IDistributedMemoryManager> memoryManagerMock;
            Mock <IChannel <RedisPubSubCacheMessage <long> > > channelMock;

            mockRepository  = new MockRepository(MockBehavior.Strict);
            dictionaryCache = new DictionaryCache <long, string>();
            channelMock     = mockRepository.Create <IChannel <RedisPubSubCacheMessage <long> > >();
            channelMock.Setup(c => c.Subscribe());
            channelMock.Setup(c => c.Dispose());
            memoryManagerMock = mockRepository.Create <IDistributedMemoryManager>();
            memoryManagerMock.Setup(mm => mm.IsConnected).Returns(true);
            memoryManagerMock.Setup(mm => mm.GetChannel <RedisPubSubCacheMessage <long> >(
                                        RedisPubSubCacheHelpers.GetChannelName(name))).Returns(channelMock.Object);

            using (RedisPubSubCache <long, string> redisCache =
                       new RedisPubSubCache <long, string>(dictionaryCache, name, memoryManagerMock.Object))
            {
                Assert.That(redisCache, Has.Property("Name").EqualTo(name));
                Assert.That(redisCache, Has.Property("InnerCache").SameAs(dictionaryCache));
                Assert.That(redisCache.MemoryManager, Is.SameAs(memoryManagerMock.Object));
                Assert.That(redisCache.Channel, Is.SameAs(channelMock.Object));
            }

            mockRepository.VerifyAll();
        }
Example #6
0
        public static void Main(string[] args)
        {
//            cache.Add("key", 1);
//            cache.Add("key", 2);
//            cache["key"] = 3;

//            cache.Set("key", 4, TimeSpan.FromMinutes(1));
//            cache.Set("key", 5, TimeSpan.FromMinutes(1));
//            Console.WriteLine(cache.Get<int>("key"));

//            var sn = "CL201912170001";
//            var server = new ServerModel();
//            server.ip = EndPointUtil.GetLocalIp();
//            server.online = true;
//            server.lastMsgTime = DateTime.Now.Ticks;
//            CacheService.Set("Acceptor:Laser:" + sn, server,-1);

            DictionaryCache <string, int> map = new DictionaryCache <string, int>();

            map.Set("key1", 1);
            map.Set("key2", 2);
            var tasks = map.GetEnumerator();

//            for (var task = tasks.Current;tasks.MoveNext();)
//            {
//                Console.WriteLine(task.Key);
//                Console.WriteLine(task.Value);
//            }
            while (tasks.MoveNext())
            {
                var task = tasks.Current;
                Console.WriteLine(task.Key);
                Console.WriteLine(task.Value);
            }
        }
Example #7
0
        public void Test_ItemsRemoved()
        {
            CacheInvalidator <int, string> cacheInvalidator;
            ICache <int, string>           cache;
            const int    testKey1   = 42;
            const int    testKey2   = 54;
            const string testValue1 = "foo";
            const string testValue2 = "bar";

            cache = new DictionaryCache <int, string>();
            cache.Add(testKey1, testValue1);
            cache.Add(testKey2, testValue2);

            cacheInvalidator = new CacheInvalidator <int, string>(cache, "foo");

            using (CacheContext cacheContext = new CacheContext())
            {
                cacheContext.Entities.Add(testKey1);
                cacheInvalidator.AddInvalidations(cacheContext, testKey1);
            }
            using (CacheContext cacheContext = new CacheContext())
            {
                cacheContext.Entities.Add(testKey2);
                cacheInvalidator.AddInvalidations(cacheContext, testKey2);
            }

            cache.Remove(testKey1);

            Assert.That(cacheInvalidator.EntityToCacheKey.Keys, Has.None.EqualTo(testKey1));
            Assert.That(cacheInvalidator.EntityToCacheKey.Keys, Has.Exactly(1).EqualTo(testKey2));
        }
Example #8
0
        public void ValueAndExpiry_TakeFromRecycleQueueBeforeCreatingNew()
        {
            var cache = new DictionaryCache <int, int>(EqualityComparer <int> .Default, TimeSpan.FromMilliseconds(100));

            for (var i = 0; i < 100; i++)
            {
                cache.Set(i, i, TimeSpan.FromMilliseconds(1));
            }

            Thread.Sleep(TimeSpan.FromSeconds(3));

            var debugInfo = cache.GetDebugInfo();

            debugInfo.Values.Should().BeEmpty();
            debugInfo.ValueAndExpiryPool.PeekAll().Should().HaveCount(100);

            for (var i = 0; i < 100; i++)
            {
                cache.Set(i, i, TimeSpan.FromSeconds(1));
            }

            debugInfo = cache.GetDebugInfo();

            debugInfo.Values.Should().HaveCount(100);
            debugInfo.ValueAndExpiryPool.PeekAll().Should().BeEmpty();
        }
Example #9
0
        /// <summary>
        /// 获得配置相关的设备
        /// </summary>
        /// <param name="configDetail"></param>
        /// <returns></returns>
        public List <int> GetMeterIdsInRoom(ConfigDetail configDetail, bool?isInUsed = null)
        {
            var building = buildingBLL.Find(configDetail.BuildingId);
            var bTreeId  = DictionaryCache.Get()[(int)configDetail.BuildingCategoryId].TreeId;
            var eTreeId  = DictionaryCache.Get()[(int)configDetail.EnergyCategoryId].TreeId;
            var meterIds = meterBLL.Filter(o =>
                                           //是其建筑下设备
                                           (configDetail.BuildingId == o.Building.Id ||
                                            o.Building.TreeId.StartsWith(building.TreeId + "-"))
                                           //分类正确,默认使用顶级分类
                                           && (configDetail.BuildingCategoryId == o.Building.BuildingCategoryId ||
                                               o.Building.BuildingCategoryDict.TreeId.StartsWith(bTreeId + "-"))
                                           //&& (configDetail.EnergyCategoryId == o.EnergyCategoryId ||
                                           //o.EnergyCategoryDict.TreeId.StartsWith(eTreeId + "-"))
                                           && (configDetail.EnergyCategoryId == o.EnergyCategoryId) &&
                                           o.TypeDict.ThirdValue == 1 &&
                                           o.Enable &&
                                           o.Access != null &&
                                           o.GbCode != null &&
                                           o.TypeDict.SecondValue == 1 &&
                                           (isInUsed == null?true:isInUsed == o.Enable)
                                           ).Select(o => o.Id).ToList();

            return(meterIds);
        }
Example #10
0
 public static FeedbackData ToViewData(this Feedback node, CategoryDictionary suffix = CategoryDictionary.None)
 {
     if (node == null)
     {
         return(null);
     }
     return(new FeedbackData()
     {
         Id = node.Id,
         UserId = node.UserId,
         TypeId = node.TypeId,
         Description = node.Description,
         CreateTime = node.CreateTime,
         HandleUserId = node.HandleUserId,
         HandleTime = node.HandleTime,
         HandleReply = node.HandleReply,
         Rating = node.Rating,
         Comment = node.Comment,
         StateId = node.StateId,
         StateName = DictionaryCache.Get()[node.StateId].ChineseName,
         TypeName = DictionaryCache.Get()[node.TypeId].ChineseName,
         IsDeleted = node.IsDeleted,
         User = ((suffix & CategoryDictionary.User) == CategoryDictionary.User) && node.HandleUser != null?node.User.ToViewData() : null,
                    HandleUser = ((suffix & CategoryDictionary.Manager) == CategoryDictionary.Manager) && node.HandleUser != null?node.HandleUser.ToViewData() : null,
                                     State = node.State.ToViewData()
     });
 }
Example #11
0
        public static MessageData ToShortViewData(this Message node, CategoryDictionary suffix = CategoryDictionary.None)
        {
            if (node == null)
            {
                return(null);
            }
            var model = new MessageData()
            {
                Id                    = node.Id,
                MessageTypeId         = node.MessageTypeId,
                CreateDate            = node.CreateDate,
                EndDate               = node.EndDate,
                MessageSourceTypeId   = node.MessageSourceTypeId,
                SrcId                 = node.SrcId,
                Subject               = node.Subject,
                Body                  = node.Body,
                Url                   = node.Url,
                ActiveDate            = node.ActiveDate,
                IsDeleted             = node.IsDeleted,
                NotActiveDate         = node.NotActiveDate,
                AlertLevelId          = node.AlertLevelId, //告警等级
                MessageTypeName       = node.MessageType == null?DictionaryCache.Get()[node.MessageTypeId].ChineseName : node.MessageType.ChineseName,
                MessageSourceTypeName = node.MessageSourceType == null?DictionaryCache.Get()[node.MessageSourceTypeId].ChineseName : node.MessageSourceType.ChineseName,
            };

            return(model);
        }
Example #12
0
        public void WhenKeyUpdated_KeyExpiryTimeStillProcessedAsNormal()
        {
            var cache = new DictionaryCache <int, int>(EqualityComparer <int> .Default, TimeSpan.FromMilliseconds(100));

            for (var i = 0; i < 100; i++)
            {
                cache.Set(i, i, TimeSpan.FromMilliseconds(10));
            }

            for (var i = 0; i < 100; i++)
            {
                cache.Set(i, i, TimeSpan.FromMilliseconds(500));
            }

            Thread.Sleep(TimeSpan.FromMilliseconds(100));

            for (var i = 0; i < 100; i++)
            {
                cache.TryGet(i, out _).Should().BeTrue();
            }

            var debugInfo = cache.GetDebugInfo();

            debugInfo.ValueAndExpiryPool.PeekAll().Should().HaveCount(1);

            Thread.Sleep(TimeSpan.FromSeconds(3));

            debugInfo = cache.GetDebugInfo();
            debugInfo.ValueAndExpiryPool.PeekAll().Should().HaveCount(101);

            for (var i = 0; i < 100; i++)
            {
                cache.TryGet(i, out _).Should().BeFalse();
            }
        }
Example #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PdbModule"/> class.
        /// </summary>
        /// <param name="module">The XML module description.</param>
        /// <param name="pdbFile">Already opened PDB file.</param>
        public PdbModule(XmlModule module, PdbFile pdbFile)
        {
            PdbFile             = pdbFile;
            Name                = !string.IsNullOrEmpty(module.Name) ? module.Name : Path.GetFileNameWithoutExtension(module.SymbolsPath).ToLower();
            Namespace           = module.Namespace;
            globalScopeCache    = SimpleCache.CreateStruct(() => new PdbGlobalScope(this));
            builtinSymbolsCache = new DictionaryCache <TypeIndex, PdbSymbol>(CreateBuiltinSymbol);
            allSymbolsCache     = new ArrayCache <PdbSymbol>(PdbFile.TpiStream.TypeRecordCount, CreateSymbol);
            definedSymbolsCache = new ArrayCache <PdbSymbol>(PdbFile.TpiStream.TypeRecordCount, true, GetDefinedSymbol);
            constantsCache      = SimpleCache.CreateStruct(() =>
            {
                Dictionary <string, ConstantSymbol> constants = new Dictionary <string, ConstantSymbol>();

                foreach (SymbolRecordKind kind in ConstantSymbol.Kinds)
                {
                    foreach (ConstantSymbol c in PdbFile.PdbSymbolStream[kind].OfType <ConstantSymbol>())
                    {
                        if (!constants.ContainsKey(c.Name))
                        {
                            constants.Add(c.Name, c);
                        }
                    }
                }
                return((IReadOnlyDictionary <string, ConstantSymbol>)constants);
            });
        }
        public void Clear()
        {
            int[] values          = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            int   evaluationCount = 0;
            DictionaryCache <int, string> cache = new DictionaryCache <int, string>(key =>
            {
                evaluationCount++;
                return(key.ToString());
            });

            foreach (int value in values)
            {
                Assert.Equal(value.ToString(), cache[value]);
            }
            Assert.Equal(values.Length, cache.Count);
            Assert.Equal(values.Length, evaluationCount);
            cache.Clear();
            Assert.Equal(0, cache.Count);
            foreach (int value in values)
            {
                Assert.Equal(value.ToString(), cache[value]);
            }
            Assert.Equal(values.Length, cache.Count);
            Assert.Equal(2 * values.Length, evaluationCount);
        }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SymbolStream"/> class.
        /// </summary>
        /// <param name="reader">Binary reader.</param>
        /// <param name="end">End of the symbol stream in binary reader. If it is less than 0 or bigger than binary reader length, it will be read fully.</param>
        public DebugSubsectionStream(IBinaryReader reader, long end = -1)
        {
            Reader     = reader;
            references = new List <DebugSubsectionReference>();

            long position = reader.Position;

            if (end < 0 || end > reader.Length)
            {
                end = reader.Length;
            }

            while (position < end)
            {
                DebugSubsectionKind kind = (DebugSubsectionKind)reader.ReadUint();
                uint dataLen             = reader.ReadUint();

                references.Add(new DebugSubsectionReference
                {
                    DataOffset = position + 8,
                    Kind       = kind,
                    DataLen    = dataLen,
                });
                position += dataLen + 8;
                reader.Move(dataLen);
            }

            debugSubsectionsByKind = new DictionaryCache <DebugSubsectionKind, DebugSubsection[]>(GetDebugSubsectionsByKind);
        }
Example #16
0
        /// <summary>
        /// Check if user has permisson for a module
        /// </summary>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public bool HasPermissionForModule(string moduleName)
        {
            // Creating key for action permission
            var key = string.Format(
                "Module[{0}]",
                moduleName);

            return(this.LockedResult(
                       criteria:
                       () => _ModulePermissions == null,
                       locked:
                       () => _ModulePermissions =
                           new DictionaryCache <bool>(
                               keyText =>
            {
                // Searching module by name
                var module =
                    SecuritySystem.Instance
                    .SecuredModules
                    .AsParallel()
                    .FirstOrDefault(m => m.Name == keyText);

                // Checking if module exists and this user has permission
                return module == null ||
                module.CheckUserPermission(this);
            }),
                       unlocked:
                       () => _ModulePermissions)[key]);
        }
Example #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClrMdHeap"/> class.
 /// </summary>
 /// <param name="runtime">The runtime.</param>
 public VSClrHeap(VSClrRuntime runtime)
 {
     VSRuntime           = runtime;
     canWalkHeapCache    = SimpleCache.Create(() => Proxy.GetClrHeapCanWalkHeap(VSRuntime.Process.Id, VSRuntime.Id));
     totalHeapSizeCache  = SimpleCache.Create(() => Proxy.GetClrHeapTotalHeapSize(VSRuntime.Process.Id, VSRuntime.Id));
     typesByAddressCache = new DictionaryCache <ulong, VSClrType>((a) => default(VSClrType));
 }
Example #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PdbStringTable"/> class.
        /// </summary>
        /// <param name="reader">Stream binary reader.</param>
        public PdbStringTable(IBinaryReader reader)
        {
            // Read header
            Signature         = reader.ReadUint();
            HashVersion       = reader.ReadUint();
            StringsStreamSize = reader.ReadUint();

            // Read strings table
            StringsStream = reader.ReadSubstream(StringsStreamSize);
            stringsCache  = new DictionaryCache <uint, string>((uint offset) =>
            {
                StringsStream.Position = offset;
                return(StringsStream.ReadCString().String);
            });

            // Read table of offsets that can be accessed by hash function
            uint offsetsCount = reader.ReadUint();

            Offsets = reader.ReadUintArray((int)offsetsCount);

            // Read epilogue
            StringsCount = reader.ReadInt();

            dictionaryCache = SimpleCache.CreateStruct(() =>
            {
                Dictionary <uint, string> strings = new Dictionary <uint, string>();

                foreach (uint offset in Offsets)
                {
                    strings[offset] = stringsCache[offset];
                }
                return(strings);
            });
        }
Example #19
0
        public void TestComplexParametersMethod()
        {
            var instanceMock  = new Mock <IAwesomeInterface>();
            var cacheProvider = new DictionaryCache <IAwesomeInterface>();

            var proxy = new SleipnerProxy <IAwesomeInterface>(instanceMock.Object, cacheProvider);

            proxy.Config(a =>
            {
                a.DefaultIs().CacheFor(50);
            });

            var methodReturnValue = new[] { "", "" }.ToList();

            instanceMock.Setup(a => a.ParameteredMethod("a", 0, new [] { "a", "b" })).Returns(methodReturnValue);
            instanceMock.Setup(a => a.ParameteredMethod("a", 0, new [] { "a", "c" })).Returns(methodReturnValue);

            for (var i = 0; i <= 10; i++)
            {
                proxy.Object.ParameteredMethod("a", 0, new[] { "a", "b" });
                proxy.Object.ParameteredMethod("a", 0, new[] { "a", "c" });
            }

            instanceMock.Verify(a => a.ParameteredMethod("a", 0, new[] { "a", "b" }), Times.Once());
            instanceMock.Verify(a => a.ParameteredMethod("a", 0, new[] { "a", "c" }), Times.Once());
        }
        public void TestReturnsCachedItemWithinPeriod_ListType()
        {
            var cache = new DictionaryCache <IAwesomeInterface>();

            var configProvider = new BasicConfigurationProvider <IAwesomeInterface>();

            configProvider.For(a => a.ParameteredMethod(Param.IsAny <string>(), Param.IsAny <int>(), Param.IsAny <List <string> >())).CacheFor(10);

            var proxyContext = ProxyRequest <IAwesomeInterface> .FromExpression(a => a.ParameteredMethod("a", 2, new List <string>()
            {
                "a", "b"
            }));

            var val = Enumerable.Empty <string>();

            var cachePolicy = configProvider.GetPolicy(proxyContext.Method, proxyContext.Parameters);

            Assert.IsNotNull(cachePolicy, "Config provider didn't return a cache policy");
            Assert.IsTrue(cachePolicy.CacheDuration == 10, "Cache provider returned an unexpected cache policy");

            cache.StoreItem(proxyContext, cachePolicy, val);
            var returnedValue = cache.GetItem(proxyContext, cachePolicy);

            Assert.AreEqual(val, returnedValue.Object);
        }
Example #21
0
        public void TestNoCache()
        {
            var instanceMock  = new Mock <IAwesomeInterface>();
            var cacheProvider = new DictionaryCache <IAwesomeInterface>();

            var proxy = new SleipnerProxy <IAwesomeInterface>(instanceMock.Object, cacheProvider);

            proxy.Config(a =>
            {
                a.DefaultIs().CacheFor(50);
                a.For(b => b.ParameteredMethod(Param.IsAny <string>(), Param.IsAny <int>())).DisableCache();
            });

            var methodReturnValue = new[] { "", "" };

            instanceMock.Setup(a => a.ParameteredMethod("", 0)).Returns(methodReturnValue);
            instanceMock.Setup(a => a.ParameterlessMethod()).Returns(methodReturnValue);

            proxy.Object.ParameteredMethod("", 0);
            proxy.Object.ParameteredMethod("", 0);
            proxy.Object.ParameteredMethod("", 0);

            proxy.Object.ParameterlessMethod();
            proxy.Object.ParameterlessMethod();
            proxy.Object.ParameterlessMethod();

            instanceMock.Verify(a => a.ParameteredMethod("", 0), Times.Exactly(3));
            instanceMock.Verify(a => a.ParameterlessMethod(), Times.Once());
        }
Example #22
0
        public void TestStrangeGenericMethod()
        {
            var instanceMock  = new Mock <IAwesomeInterface>();
            var cacheProvider = new DictionaryCache <IAwesomeInterface>();

            var proxy = new SleipnerProxy <IAwesomeInterface>(instanceMock.Object, cacheProvider);

            proxy.Config(a =>
            {
                a.DefaultIs().CacheFor(50);
            });

            var dictReturn = new Dictionary <string, int>()
            {
                { "a", 1 },
                { "b", 2 },
                { "c", 3 },
            };

            instanceMock.Setup(a => a.StrangeGenericMethod("a", new[] { 1, 2, 3 })).Returns(dictReturn);

            for (var i = 0; i < 10; i++)
            {
                var result = proxy.Object.StrangeGenericMethod("a", new[] { 1, 2, 3 });
                Assert.AreSame(result, dictReturn);
            }

            instanceMock.Verify(a => a.StrangeGenericMethod("a", new[] { 1, 2, 3 }), Times.Once());
        }
Example #23
0
        public void Test_OnRelationshipChange()
        {
            CacheInvalidator <int, string> cacheInvalidator;
            ICache <int, string>           cache;

            EntityRef[]       testRelationshipTypes;
            const int         numRelationshipTypes = 10;
            Func <long, bool> relationshipTypesToRemove;

            cache = new DictionaryCache <int, string>();
            for (int i = 0; i < numRelationshipTypes; i++)
            {
                cache.Add(i, i.ToString());
            }

            relationshipTypesToRemove = e => e % 2 == 0; // All even numbered relationship types.
            testRelationshipTypes     = Enumerable.Range(0, numRelationshipTypes)
                                        .Where(i => relationshipTypesToRemove(i))
                                        .Select(i => new EntityRef(i)).ToArray();

            cacheInvalidator = new CacheInvalidator <int, string>(cache, "a");

            for (int i = 0; i < numRelationshipTypes; i++)
            {
                using (CacheContext cacheContext = new CacheContext())
                {
                    cacheContext.RelationshipTypes.Add(i);
                    cacheInvalidator.AddInvalidations(cacheContext, i);
                }
            }

            cacheInvalidator.OnRelationshipChange(testRelationshipTypes);

            Assert.That(cache.Where(ce => relationshipTypesToRemove(ce.Key)), Is.Empty);
        }
Example #24
0
        public static IList <GroupData> ToViewList(this IQueryable <Group> nodes, CategoryDictionary suffix = CategoryDictionary.None)
        {
            UserBLL userBLL = new UserBLL();

            if (nodes == null)
            {
                return(null);
            }
            var nodeList = nodes.ToList();
            var results  = nodeList.Select(node => new GroupData()
            {
                Id              = node.Id,
                GroupTypeId     = node.GroupTypeId,
                Name            = node.Name,
                Description     = node.Description,
                Enable          = node.Enable,
                RegeneratorId   = node.RegeneratorId,
                RegeneratorName = node.RegeneratorName,
                UpdatingTime    = node.UpdatingTime,
                GroupTypeName   = node.GroupType == null ? DictionaryCache.Get()[node.GroupTypeId].ChineseName : node.GroupType.ChineseName,
                Regenerator     = (suffix & CategoryDictionary.User) == CategoryDictionary.User ? (node.Regenerator == null ? userBLL.Find(node.RegeneratorId).ToViewData() : node.Regenerator.ToViewData()) : null,
            }).ToList();

            return(results);
        }
        public static IList <ActivityRecordData> ToViewList(this IQueryable <ActivityRecord> nodes, CategoryDictionary suffix = CategoryDictionary.None)
        {
            UserBLL        userBLL        = new UserBLL();
            MaintenanceBLL maintenanceBLL = new MaintenanceBLL();

            if (nodes == null)
            {
                return(null);
            }
            var nodeList = nodes.ToList();
            var results  = nodeList.Select(node => new ActivityRecordData()
            {
                Id          = node.Id,
                TargetId    = node.TargetId,
                PublisherId = node.PublisherId,
                StateId     = node.StateId,
                Description = node.Description,
                CreateDate  = node.CreateDate,
                //Target = node.TargetId != null ? node.MaintenanceTarget == null ? maintenanceBLL.Find(node.TargetId).ToViewData() : node.MaintenanceTarget.ToViewData() : null,
                //Publisher = node.PublisherId != null ? node.Publisher == null ? userBLL.Find(node.PublisherId).ToViewData() : node.Publisher.ToViewData() : null,
                StateName = DictionaryCache.Get()[(int)node.StateId].ChineseName
            }).ToList();

            return(results);
        }
Example #26
0
        public static MeterDiagram ToViewDiagram(this Meter node /*,  int layer = 0 */)
        {
            var model = new MeterDiagram()
            {
                Id               = node.Id,
                ParentId         = node.ParentId,
                TreeId           = node.TreeId,
                Rank             = node.Rank,
                ParentName       = node.Parent == null ? null : node.Parent.Name,
                BrandId          = node.BrandId,
                Type             = node.Type,
                EnergyCategoryId = node.EnergyCategoryId,
                TypeName         = node.TypeDict == null ? null : DictionaryCache.Get()[node.EnergyCategoryId].ChineseName,
                BrandType        = node.Brand == null ? null : node.Brand.Name,
                Name             = node.Name,
                Enable           = node.Enable,
                Access           = node.Access,
                Address          = node.Address,
                RelayElecState   = node.RelayElecState,
                PaulElecState    = node.PaulElecState,
                HasPrivilege     = 0,
                MacAddress       = node.MacAddress,
                HasChildren      = node.Children.Count(),
                IsTurnOn         = node.IsTurnOn
            };

            var ctx = new EmpContext();

            model.ExtensionFields = ctx.ExtensionFields.Where(x => x.Table == "Meter" && x.JoinId == node.Id).ToViewList();

            return(model);
        }
Example #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Module" /> class.
        /// </summary>
        /// <param name="process">The process.</param>
        /// <param name="address">The module address.</param>
        internal Module(Process process, ulong address)
        {
            Address = address;
            Process = process;
            Id      = uint.MaxValue;
            name    = SimpleCache.Create(() =>
            {
                string name = Context.Debugger.GetModuleName(this);

                Process.UpdateModuleByNameCache(this, name);
                return(name);
            });
            imageName       = SimpleCache.Create(() => Context.Debugger.GetModuleImageName(this));
            loadedImageName = SimpleCache.Create(() => Context.Debugger.GetModuleLoadedImage(this));
            symbolFileName  = SimpleCache.Create(() => Context.Debugger.GetModuleSymbolFile(this));
            mappedImageName = SimpleCache.Create(() => Context.Debugger.GetModuleMappedImage(this));
            moduleVersion   = SimpleCache.Create(() =>
            {
                ModuleVersion version = new ModuleVersion();

                Context.Debugger.GetModuleVersion(this, out version.Major, out version.Minor, out version.Revision, out version.Patch);
                return(version);
            });
            timestampAndSize = SimpleCache.Create(() => Context.Debugger.GetModuleTimestampAndSize(this));
            clrModule        = SimpleCache.Create(() => Process.ClrRuntimes.SelectMany(r => r.Modules).Where(m => m.ImageBase == Address).FirstOrDefault());
            pointerSize      = SimpleCache.Create(() => Process.GetPointerSize());
            TypesByName      = new DictionaryCache <string, CodeType>(GetTypeByName);
            TypesById        = new DictionaryCache <uint, CodeType>(GetTypeById);
            ClrTypes         = new DictionaryCache <IClrType, CodeType>(GetClrCodeType);
            GlobalVariables  = new DictionaryCache <string, Variable>(GetGlobalVariable);
            UserTypeCastedGlobalVariables = Context.UserTypeMetadataCaches.CreateDictionaryCache <string, Variable>((name) => Process.CastVariableToUserType(GlobalVariables[name]));
        }
Example #28
0
        //public static MaintenanceData ToViewData(this Maintenance node, CategoryDictionary suffix = CategoryDictionary.None)
        //{
        //    if (node == null)
        //        return null;
        //    return new MaintenanceData()
        //    {
        //        Id = node.Id,
        //        MaintenanceCategoryId = node.MaintenanceCategoryId,
        //        StateId = node.StateId,
        //        UserId = node.UserId,
        //        Title = node.Title,
        //        Content = node.Content,
        //        Picture = node.Picture,
        //        ObjectCategoryId = node.ObjectCategoryId,
        //        OperateObjectId = node.OperateObjectId,
        //        CreateDate = node.CreateDate,
        //        Comment = node.Comment,
        //        Rating = node.Rating,
        //        OperatorDiscription = node.OperatorDiscription
        //        //User = ((suffix & CategoryDictionary.User) == CategoryDictionary.User) && node.User != null ? node.User.ToViewData() : null,
        //        //MaintenanceCategory = node.MaintenanceCategory.ToViewData(),
        //        //State = node.MaintenanceState.ToViewData(),
        //        //ObjectCategory = node.MaintenanceObjectCategory.ToViewData()

        //    };
        //}

        //public static IList<MaintenanceData> ToViewList(this IQueryable<Maintenance> nodes, CategoryDictionary suffix = CategoryDictionary.None)
        //{
        //    if (nodes == null)
        //        return null;
        //    var nodeList = nodes.ToList();
        //    //var results = nodes.ToList().Select(x => x.ToViewData(suffix)).ToList();
        //    var results = nodeList.Select(node => new MaintenanceData()
        //    {
        //        Id = node.Id,
        //        MaintenanceCategoryId = node.MaintenanceCategoryId,
        //        StateId = node.StateId,
        //        UserId = node.UserId,
        //        Title = node.Title,
        //        Content = node.Content,
        //        Picture = node.Picture,
        //        ObjectCategoryId = node.ObjectCategoryId,
        //        OperateObjectId = node.OperateObjectId,
        //        CreateDate = node.CreateDate,
        //        Comment = node.Comment,
        //        Rating = node.Rating,
        //        OperatorDiscription = node.OperatorDiscription,

        //    }).ToList();

        //    return results;
        //}

        //public static Maintenance ToModel(this MaintenanceData node)
        //{
        //    return new Maintenance()
        //    {
        //        Id = node.Id,
        //        MaintenanceCategoryId = node.MaintenanceCategoryId,
        //        StateId = node.StateId,
        //        UserId = node.UserId,
        //        Title = node.Title,
        //        Content = node.Content,
        //        Picture = node.Picture,
        //        ObjectCategoryId = node.ObjectCategoryId,
        //        OperateObjectId = node.OperateObjectId,
        //        CreateDate = node.CreateDate,
        //        Comment = node.Comment,
        //        Rating = node.Rating,
        //        OperatorDiscription = node.OperatorDiscription,

        //    };
        //}
        #endregion

        #region Maintenance
        public static MaintenanceData ToViewData(this Maintenance node, CategoryDictionary suffix = CategoryDictionary.None)
        {
            UserBLL     userBLL     = new UserBLL();
            BuildingBLL buildingBLL = new BuildingBLL();

            if (node == null)
            {
                return(null);
            }
            return(new MaintenanceData()
            {
                Id = node.Id,
                MaintenanceCategoryId = node.MaintenanceCategoryId,
                StateId = node.StateId,
                UserId = node.UserId,
                BuildingId = node.BuildingId,
                ApproverId = node.ApproverId,
                OperatorId = node.OperatorId,
                Title = node.Title,
                Content = node.Content,
                PictureId = node.PictureId,
                CreateDate = node.CreateDate,
                Rating = node.Rating,
                MaintenanceTime = node.MaintenanceTime,
                PurchasingId = node.PurchasingId,
                PictureUrl = node.PictureUrl,
                User = ((suffix & CategoryDictionary.User) == CategoryDictionary.User) ? node.User.ToViewData() : null,         // node.User == null ? userBLL.Find(node.UserId).ToViewData() : node.User.ToViewData(),
                Approver = ((suffix & CategoryDictionary.User) == CategoryDictionary.User) ? node.Approver.ToViewData() : null, //node.ApproverId != null ? node.Approver == null ? userBLL.Find(node.ApproverId).ToViewData() : node.Approver.ToViewData() : null,
                Operator = ((suffix & CategoryDictionary.User) == CategoryDictionary.User) ? node.Operator.ToViewData() : null, //node.OperatorId != null ? node.Operator == null ? userBLL.Find(node.OperatorId).ToViewData() : node.Operator.ToViewData() : null,
                //State = node.State.ToViewData(),
                StateName = DictionaryCache.Get()[(int)node.StateId].ChineseName,
                BuildingName = buildingBLL.Find(node.BuildingId).Name,
            });
        }
Example #29
0
        public void Test_InvalidateEntries_AccessRule()
        {
            AccessRule accessRule;
            Subject    subject;
            ICache <SubjectPermissionTypesTuple, IEnumerable <AccessRuleQuery> > dictionaryCache;
            SecurityQueryCacheInvalidator securityQueryCacheInvalidator;

            subject = new Subject();
            subject.Save();

            accessRule = new AccessRule();
            accessRule.AllowAccessBy = subject;
            accessRule.Save();

            dictionaryCache = new DictionaryCache <SubjectPermissionTypesTuple, IEnumerable <AccessRuleQuery> >
            {
                { new SubjectPermissionTypesTuple(subject.Id, 2, new long[0]), new AccessRuleQuery[0] },
                { new SubjectPermissionTypesTuple(subject.Id, 3, new long[0]), new AccessRuleQuery[0] },
                { new SubjectPermissionTypesTuple(subject.Id + 1, 3, new long[0]), new AccessRuleQuery[0] },
                { new SubjectPermissionTypesTuple(subject.Id + 2, 3, new long[0]), new AccessRuleQuery[0] }
            };

            securityQueryCacheInvalidator = new SecurityQueryCacheInvalidator(dictionaryCache);
            securityQueryCacheInvalidator.InvalidateCacheEntries(new []
            {
                new SubjectPermissionTypesTuple(subject.Id, 2, new long[0]),
                new SubjectPermissionTypesTuple(subject.Id, 3, new long[0]),
            }, () => "test");

            Assert.That(dictionaryCache, Has.None.Property("Key").Property("SubjectId").EqualTo(subject.Id));
        }
Example #30
0
 public WorkflowStateService()
 {
     _billDemandStateCache       = new DictionaryCache <byte, WorkflowDbState>(new TimeSpan(0, 30, 0), FillBillDemandStates);
     _demandStateCache           = new DictionaryCache <byte, WorkflowDbState>(new TimeSpan(0, 30, 0), FillDemandStates);
     _demandAdjustmentStateCache = new DictionaryCache <byte, WorkflowDbState>(new TimeSpan(0, 30, 0), FillDemandAdjustmentStates);
     _workflowStateInfosCache    = new DictionaryCache <WorkflowState, WorkflowStateInfo>(new TimeSpan(0, 30, 0), FillWorkflowStateInfos);
 }
Example #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SymbolStream"/> class.
        /// </summary>
        /// <param name="stream">PDB symbol stream.</param>
        public SymbolStream(PdbStream stream)
        {
            IBinaryReader reader = stream.Reader;

            Reader     = reader;
            references = new List <SymbolReference>();

            long position = reader.Position, end = reader.Length;

            while (position < end)
            {
                RecordPrefix prefix = RecordPrefix.Read(reader);

                if (prefix.RecordLength < 2)
                {
                    throw new Exception("CV corrupt record");
                }

                SymbolRecordKind kind    = (SymbolRecordKind)prefix.RecordKind;
                ushort           dataLen = prefix.DataLen;

                references.Add(new SymbolReference
                {
                    DataOffset = (uint)position + RecordPrefix.Size,
                    Kind       = kind,
                    DataLen    = dataLen,
                });
                position += dataLen + RecordPrefix.Size;
                reader.ReadFake(dataLen);
            }

            symbolsByKind = new DictionaryCache <SymbolRecordKind, SymbolRecord[]>(GetSymbolsByKind);
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DiaModule"/> class.
        /// </summary>
        /// <param name="pdbPath">The PDB path.</param>
        /// <param name="module">The module.</param>
        public DiaModule(string pdbPath, Module module)
        {
            Module = module;
            dia = new DiaSource();
            dia.loadDataFromPdb(pdbPath);
            dia.openSession(out session);
            globalScope = session.globalScope;
            typeAllFields = new DictionaryCache<uint, List<Tuple<string, uint, int>>>(GetTypeAllFields);
            typeFields = new DictionaryCache<uint, List<Tuple<string, uint, int>>>(GetTypeFields);
            basicTypes = SimpleCache.Create(() =>
            {
                var types = new Dictionary<string, IDiaSymbol>();
                var basicTypes = globalScope.GetChildren(SymTagEnum.SymTagBaseType);

                foreach (var type in basicTypes)
                {
                    try
                    {
                        string typeString = TypeToString.GetTypeString(type);

                        if (!types.ContainsKey(typeString))
                        {
                            types.Add(typeString, type);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                return types;
            });
            symbolNamesByAddress = new DictionaryCache<uint, Tuple<string, ulong>>((distance) =>
            {
                IDiaSymbol symbol;
                int displacement;
                string name;

                session.findSymbolByRVAEx(distance, SymTagEnum.SymTagNull, out symbol, out displacement);
                symbol.get_undecoratedNameEx(0 | 0x8000 | 0x1000, out name);
                return Tuple.Create(name, (ulong)displacement);
            });

            session.loadAddress = module.Address;
            enumTypeNames = new DictionaryCache<uint, Dictionary<ulong, string>>(GetEnumName);
        }
        public void Call_The_Function_When_Instructed_To_BypassCache()
        {
            // Arrange
            ICache cache = new DictionaryCache();
            const bool bypassCache = true;
            bool functionCalled = false;

            // Act
            cache.GetOrAdd( bypassCache, "SomeKey", TimeSpan.FromSeconds( 30 ), () =>
            {
                functionCalled = true;

                return GetCustomer( 1 );
            } );

            // Assert
            Assert.True( functionCalled );
        }
Example #34
0
        public void TestReturnsCachedItemWithinPeriod_ListType()
        {
            var cache = new DictionaryCache<IAwesomeInterface>();

            var configProvider = new BasicConfigurationProvider<IAwesomeInterface>();
            configProvider.For(a => a.ParameteredMethod(Param.IsAny<string>(), Param.IsAny<int>(), Param.IsAny<List<string>>())).CacheFor(10);

            var proxyContext = ProxyRequest<IAwesomeInterface>.FromExpression(a => a.ParameteredMethod("a", 2, new List<string>() {"a", "b"}));
            var val = Enumerable.Empty<string>();

            var cachePolicy = configProvider.GetPolicy(proxyContext.Method, proxyContext.Parameters);
            Assert.IsNotNull(cachePolicy, "Config provider didn't return a cache policy");
            Assert.IsTrue(cachePolicy.CacheDuration == 10, "Cache provider returned an unexpected cache policy");

            cache.StoreItem(proxyContext, cachePolicy, val);
            var returnedValue = cache.GetItem(proxyContext, cachePolicy);

            Assert.AreEqual(val, returnedValue.Object);
        }
Example #35
0
        public void TestReturnsCachedItemWithinPeriod()
        {
            ICacheProvider<IDummyInterface> cache = new DictionaryCache<IDummyInterface>();

            var configProvider = new BasicConfigurationProvider<IDummyInterface>();
            configProvider.For(a => a.GetProgramCards(Param.IsAny<string>(), Param.IsAny<DateTime>())).CacheFor(10);

            var proxyContext = ProxyRequest<IDummyInterface>.FromExpression(a => a.GetProgramCards("", DateTime.Now));
            var val = Enumerable.Empty<object>();

            var cachePolicy = configProvider.GetPolicy(proxyContext.Method, proxyContext.Parameters);
            Assert.IsNotNull(cachePolicy, "Config provider didn't return a cache policy");
            Assert.IsTrue(cachePolicy.CacheDuration == 10, "Cache provider returned an unexpected cache policy");

            cache.StoreItem(proxyContext, cachePolicy, val);
            var returnedValue = cache.GetItem(proxyContext, cachePolicy);

            Assert.AreEqual(val, returnedValue.Object);
        }
Example #36
0
        public void TestReturnsStaleOutsidePeriod()
        {
            ICacheProvider<IDummyInterface> cache = new DictionaryCache<IDummyInterface>();

            var configProvider = new BasicConfigurationProvider<IDummyInterface>();
            configProvider.For(a => a.GetProgramCards(Param.IsAny<string>(), Param.IsAny<DateTime>())).CacheFor(2).ExpireAfter(3);

            var proxyContext = ProxyRequest<IDummyInterface>.FromExpression(a => a.GetProgramCards("", DateTime.Now));
            var val = Enumerable.Empty<object>();

            var cachePolicy = configProvider.GetPolicy(proxyContext.Method, proxyContext.Parameters);
            Assert.IsNotNull(cachePolicy, "Config provider didn't return a cache policy");
            Assert.IsTrue(cachePolicy.CacheDuration == 2, "Cache provider returned an unexpected cache policy");

            cache.StoreItem(proxyContext, cachePolicy, val);
            Thread.Sleep(2000 + 100);
            var returnedValue = cache.GetItem(proxyContext, cachePolicy);

            Assert.IsTrue(returnedValue.State == CachedObjectState.Stale);
        }
        public ICache GetCache(string cacheName)
        {
            if (string.IsNullOrEmpty(cacheName))
            {
                throw new CacheException("Cache name cannot be null or empty");
            }

            lock (_caches)
            {
                if (_caches.ContainsKey(cacheName))
                {
                    return _caches[cacheName];
                }

                ICache cache = new DictionaryCache();
                _caches.Add(cacheName, cache);

                return cache;
            }
        }
Example #38
0
        public void TestDurationCache()
        {
            var instanceMock = new Mock<IAwesomeInterface>();
            var cacheProvider = new DictionaryCache<IAwesomeInterface>();

            var proxy = new SleipnerProxy<IAwesomeInterface>(instanceMock.Object, cacheProvider);
            proxy.Config(a =>
                             {
                                 a.DefaultIs().CacheFor(50);
                             });

            var methodReturnValue = new[] {"", ""};
            instanceMock.Setup(a => a.ParameteredMethod("", 0)).Returns(methodReturnValue);

            proxy.Object.ParameteredMethod("", 0);
            proxy.Object.ParameteredMethod("", 0);
            proxy.Object.ParameteredMethod("", 0);

            instanceMock.Verify(a => a.ParameteredMethod("", 0), Times.Once());
        }
        public void Call_The_Function_When_A_Value_Does_Not_Exist_In_Cache()
        {
            // Arrange
            ICache cache = new DictionaryCache();

            const int customerId = 1;

            bool functionCalled = false;

            // Act
            var customer = cache.GetOrAdd( customerId.ToString(), TimeSpan.FromSeconds( 30 ), () =>
                {
                    functionCalled = true;

                    return GetCustomer( customerId );
                } );

            // Assert
            Assert.That( customer.CustomerId == customerId );
            Assert.True( functionCalled  );
        }
        public void Not_Call_The_Function_When_A_Value_Exists_In_Cache()
        {
            // Arrange
            ICache cache = new DictionaryCache();

            const int customerId = 1;

            bool functionCalled = false;

            cache.GetOrAdd( customerId.ToString(), TimeSpan.FromSeconds( 30 ), () => GetCustomer( customerId ) );

            // Act
            cache.GetOrAdd( customerId.ToString(), TimeSpan.FromSeconds( 30 ), () =>
                {
                    functionCalled = true;

                    return GetCustomer( customerId );
                } );

            // Assert
            Assert.False( functionCalled );
        }
        public void Interception_Test()
        {
            var kernel = new StandardKernel(new Module());
            kernel.Components.Add<IPlanningStrategy, ObjectCachePlanningStrategy>();

            var manager = kernel.Get<IObjectCacheManager>();
            var method = typeof(Descriptor).GetMethod("GetMetadata");
            var cache = new DictionaryCache<object>();
            var keyval = new Dictionary<MethodInfo, ICache<object>>();

            keyval.Add(method, cache);
            manager.SetupCache(typeof (Descriptor), keyval);

            var descriptor = kernel.Get<IDescriptor>();

            var data = descriptor.GetMetadata(typeof (int));

            Assert.AreEqual(descriptor.Count, 1);

            var data2 = descriptor.GetMetadata(typeof(int));

            Assert.AreEqual(descriptor.Count, 1);
        }
Example #42
0
        public void TestComplexParametersMethod()
        {
            var instanceMock = new Mock<IAwesomeInterface>();
            var cacheProvider = new DictionaryCache<IAwesomeInterface>();

            var proxy = new SleipnerProxy<IAwesomeInterface>(instanceMock.Object, cacheProvider);
            proxy.Config(a =>
            {
                a.DefaultIs().CacheFor(50);
            });

            var methodReturnValue = new[] { "", "" }.ToList();
            instanceMock.Setup(a => a.ParameteredMethod("a", 0, new [] { "a", "b" })).Returns(methodReturnValue);
            instanceMock.Setup(a => a.ParameteredMethod("a", 0, new [] { "a", "c" })).Returns(methodReturnValue);

            for (var i = 0; i <= 10; i++)
            {
                proxy.Object.ParameteredMethod("a", 0, new[] { "a", "b" });
                proxy.Object.ParameteredMethod("a", 0, new[] { "a", "c" });
            }

            instanceMock.Verify(a => a.ParameteredMethod("a", 0, new[] { "a", "b" }), Times.Once());
            instanceMock.Verify(a => a.ParameteredMethod("a", 0, new[] { "a", "c" }), Times.Once());
        }
Example #43
0
        public void It_should_not_make_duplicate_calls_while_cache_is_in_flight()
        {
            var cacheProvider = new DictionaryCache<IAwesomeInterface>();
            var sleipnerProxy = new SleipnerProxy<IAwesomeInterface>(Mock.Object, cacheProvider);
            sleipnerProxy.Config(a => { a.DefaultIs().CacheFor(10); });

            var target = sleipnerProxy.Object;

            var tasks = new[]
                            {
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameterlessMethod()),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameterlessMethod()),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1)),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 2)),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 2)),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameterlessMethod()),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameterlessMethod()),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1, new[] {"1", "2", "3"})),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1, new[] {"1", "2", "3"})),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1, new[] {"1", "2", "3"})),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1, new[] {"1", "2", "3"})), //4 times
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1, new[] {"d", "2", "3"})),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("", 1, new[] {"d", "2", "3"})), //2 times
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("1", 1, new[] {"1", "2", "3"})),
                                Task<IEnumerable<string>>.Factory.StartNew(() => target.ParameteredMethod("1", 1, new[] {"1", "2", "3"})) //2 times
                            };

            Task.WaitAll(tasks);

            Mock.Verify(a => a.ParameterlessMethod(), Times.Exactly(1));
            Mock.Verify(a => a.ParameteredMethod("", 1), Times.Exactly(1));
            Mock.Verify(a => a.ParameteredMethod("", 2), Times.Exactly(1));
            Mock.Verify(a => a.ParameteredMethod("", 1, new[] {"1", "2", "3"}), Times.Exactly(1));
            Mock.Verify(a => a.ParameteredMethod("", 1, new[] {"d", "2", "3"}), Times.Exactly(1));
            Mock.Verify(a => a.ParameteredMethod("1", 1, new[] {"1", "2", "3"}), Times.Exactly(1));
        }
 public WeaverImports(ModuleWeaver moduleWeaver, WeaverReferences references)
 {
     _moduleWeaver = moduleWeaver;
     _references = references;
     Cache = new DictionaryCache();
 }
Example #45
0
 /// <summary>
 /// Static constructor.
 /// </summary>
 static DbgEngDll()
 {
     // Populate flow controlers lazely.
     //
     // NOTE: Client passed needs to be set to process with selected processId.
     debugeeFlowControlers =
         new DictionaryCache<uint, DebuggeeFlowController>(
             (processId) => new DebuggeeFlowController(ThreadClient));
 }
Example #46
0
 public TestClass3(DictionaryCache cache)
 {
     Cache = cache;
 }
Example #47
0
        public void TestGenericMethod()
        {
            var instanceMock = new Mock<IAwesomeInterface>();
            var cacheProvider = new DictionaryCache<IAwesomeInterface>();

            var proxy = new SleipnerProxy<IAwesomeInterface>(instanceMock.Object, cacheProvider);
            proxy.Config(a =>
            {
                a.DefaultIs().CacheFor(50);
            });

            var methodReturnValue = new[] { "", "" }.ToList();
            instanceMock.Setup(a => a.GenericMethod<string>("", 0)).Returns(methodReturnValue);
            instanceMock.Setup(a => a.GenericMethod<object>("", 0)).Returns(new object[] { 1, 2 });

            proxy.Object.GenericMethod<string>("", 0);
            proxy.Object.GenericMethod<object>("", 0);

            instanceMock.Verify(a => a.GenericMethod<string>("", 0), Times.Once());
        }
Example #48
0
        /// <summary>
        /// Static constructor
        /// </summary>
        static Cache()
        {
            // Declare the list that will hold an instance of each dataCache (This may include DataCacheGroup items)
            dataCaches = new List<ICachedData>();

            // Note: Implement a instance of each implementation of AbstractCache and assign it to an internal property
            // Note: Independent caches can be declared as instances of their dataCache type. For dependant caches add them to a instance of DataCacheGroup first. 
            // Note: Since DatacacheGroup also implements ICachedData it can be added to the dataCaches collection.
            // Note: DO NOT, add a cache as its own instance AND in a DataCacheGroup as it will get invalidated twice when InvalidateAll is called.
            
            BusinessByShortName = new BusinessByShortNameCache();
            dataCaches.Add(BusinessByShortName);

            Business = new BusinessCache();
            dataCaches.Add(Business);
    
            
            // Note: Setup the Cache for the Room Type
            // Note: This runs on a timer and is periodically refreshed
            int? timerInternal = null;
            int? startupDelay = null;
            int? promoTimerInternal = null;
            int? promoStartupDelay = null;
            int? rateCacheCacheInterval = null;
            if (ROOM_TYPE_CACHE_TIMER_STARTUP_DELAY.HasValue)
            {
                startupDelay = (int)ROOM_TYPE_CACHE_TIMER_STARTUP_DELAY.Value.TotalMilliseconds;
            }
            if (ROOM_TYPE_CACHE_TIMER_INTERVAL.HasValue)
            {
                timerInternal = (int)ROOM_TYPE_CACHE_TIMER_INTERVAL.Value.TotalMilliseconds;
            }
            if (PROMO_CACHE_TIMER_INTERVAL.HasValue)
            {
                promoTimerInternal = (int) PROMO_CACHE_TIMER_INTERVAL.Value.TotalMilliseconds;
            }
            if (PROMO_CACHE_TIMER_STARTUP_DELAY.HasValue)
            {
                promoStartupDelay = (int)PROMO_CACHE_TIMER_STARTUP_DELAY.Value.TotalMilliseconds;
            }
            if (RATECACHE_CACHE_TIMER_INTERVAL.HasValue)
            {
                rateCacheCacheInterval = (int) RATECACHE_CACHE_TIMER_INTERVAL.Value.TotalMilliseconds;
            }

            RoomType = new RoomTypeCache(startupDelay, timerInternal, false);
            dataCaches.Add(RoomType);

            PromoCache = new PromotionCache(promoStartupDelay, promoTimerInternal, false);
            dataCaches.Add(PromoCache);

            DictionaryCache = new DictionaryCache(startupDelay, timerInternal, false);
            dataCaches.Add(DictionaryCache);

            RatePlanViewCache = new RatePlanViewCache(startupDelay, timerInternal, false);
            dataCaches.Add(RatePlanViewCache);

            FxRateCache = new FxCacheCache(FXRATE_CACHE_TIMER_INTERVAL);
            dataCaches.Add(FxRateCache);

            CurrencyCache = new CurrencyCacheCache(CURRENCY_CACHE_TIMER_INTERVAL);
            dataCaches.Add(CurrencyCache);

            // if no interval, disable the cache (offline searches)
            RateCacheCache = new RateCacheCache(0, rateCacheCacheInterval, rateCacheCacheInterval.HasValue);
            dataCaches.Add(RateCacheCache);
        }
Example #49
0
        public void TestStrangeGenericMethod_NoCache()
        {
            var instanceMock = new Mock<IAwesomeInterface>();
            var cacheProvider = new DictionaryCache<IAwesomeInterface>();

            var proxy = new SleipnerProxy<IAwesomeInterface>(instanceMock.Object, cacheProvider);
            proxy.Config(a =>
            {
                a.DefaultIs().DisableCache();
            });

            var dictReturn = new Dictionary<string, int>()
                                 {
                                     {"a", 1},
                                     {"b", 2},
                                     {"c", 3},
                                 };
            instanceMock.Setup(a => a.StrangeGenericMethod("a", new[] { 1, 2, 3 })).Returns(dictReturn);

            for (var i = 0; i < 10; i++)
            {
                var result = proxy.Object.StrangeGenericMethod("a", new[] { 1, 2, 3 });
                Assert.AreSame(result, dictReturn);
            }

            instanceMock.Verify(a => a.StrangeGenericMethod("a", new[] { 1, 2, 3 }), Times.Exactly(10));
        }
Example #50
0
        public void TestNoCache()
        {
            var instanceMock = new Mock<IAwesomeInterface>();
            var cacheProvider = new DictionaryCache<IAwesomeInterface>();

            var proxy = new SleipnerProxy<IAwesomeInterface>(instanceMock.Object, cacheProvider);
            proxy.Config(a =>
            {
                a.DefaultIs().CacheFor(50);
                a.For(b => b.ParameteredMethod(Param.IsAny<string>(), Param.IsAny<int>())).DisableCache();
            });

            var methodReturnValue = new[] { "", "" };
            instanceMock.Setup(a => a.ParameteredMethod("", 0)).Returns(methodReturnValue);
            instanceMock.Setup(a => a.ParameterlessMethod()).Returns(methodReturnValue);

            proxy.Object.ParameteredMethod("", 0);
            proxy.Object.ParameteredMethod("", 0);
            proxy.Object.ParameteredMethod("", 0);

            proxy.Object.ParameterlessMethod();
            proxy.Object.ParameterlessMethod();
            proxy.Object.ParameterlessMethod();

            instanceMock.Verify(a => a.ParameteredMethod("", 0), Times.Exactly(3));
            instanceMock.Verify(a => a.ParameterlessMethod(), Times.Once());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DiaSymbolProvider"/> class.
 /// </summary>
 public DiaSymbolProvider()
 {
     runtimeCodeTypeAndOffsetCache = new DictionaryCache<Tuple<Process, ulong>, Tuple<CodeType, int>>(GetRuntimeCodeTypeAndOffset);
 }
Example #52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StateCache"/> class.
 /// </summary>
 public StateCache(DbgEngDll dbgEngDll)
 {
     CurrentThread = new DictionaryCache<Process, Thread>(CacheCurrentThread);
     CurrentStackFrame = new DictionaryCache<Thread, StackFrame>(CacheCurrentStackFrame);
     this.dbgEngDll = dbgEngDll;
 }
Example #53
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Process"/> class.
        /// </summary>
        /// <param name="id">The identifier.</param>
        internal Process(uint id)
        {
            Id = id;
            systemId = SimpleCache.Create(() => Context.Debugger.GetProcessSystemId(this));
            upTime = SimpleCache.Create(() => Context.Debugger.GetProcessUpTime(this));
            pebAddress = SimpleCache.Create(() => Context.Debugger.GetProcessEnvironmentBlockAddress(this));
            executableName = SimpleCache.Create(() => Context.Debugger.GetProcessExecutableName(this));
            dumpFileName = SimpleCache.Create(() => Context.Debugger.GetProcessDumpFileName(this));
            actualProcessorType = SimpleCache.Create(() => Context.Debugger.GetProcessActualProcessorType(this));
            effectiveProcessorType = SimpleCache.Create(() => Context.Debugger.GetProcessEffectiveProcessorType(this));
            threads = SimpleCache.Create(() => Context.Debugger.GetProcessThreads(this));
            modules = SimpleCache.Create(() => Context.Debugger.GetProcessModules(this));
            userTypes = SimpleCache.Create(GetUserTypes);
            clrDataTarget = SimpleCache.Create(() =>
            {
                var dataTarget = Microsoft.Diagnostics.Runtime.DataTarget.CreateFromDataReader(new CsDebugScript.CLR.DataReader(this));

                dataTarget.SymbolLocator.SymbolPath += ";http://symweb";
                return dataTarget;
            });
            clrRuntimes = SimpleCache.Create(() =>
            {
                try
                {
                    return ClrDataTarget.ClrVersions.Select(clrInfo => new Runtime(this, clrInfo.CreateRuntime())).ToArray();
                }
                catch
                {
                    return new Runtime[0];
                }
            });
            currentAppDomain = SimpleCache.Create(() => ClrRuntimes.SelectMany(r => r.AppDomains).FirstOrDefault());
            ModulesByName = new DictionaryCache<string, Module>(GetModuleByName);
            ModulesById = new DictionaryCache<ulong, Module>(GetModuleByAddress);
            Variables = new DictionaryCache<Tuple<CodeType, ulong, string, string>, Variable>((tuple) => new Variable(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4));
            UserTypeCastedVariables = new DictionaryCache<Variable, Variable>((variable) => Variable.CastVariableToUserType(variable));
            GlobalCache.UserTypeCastedVariables.Add(UserTypeCastedVariables);
            ClrModuleCache = new DictionaryCache<Microsoft.Diagnostics.Runtime.ClrModule, Module>((clrModule) =>
            {
                // TODO: This needs to change when ClrModule starts to be child of Module
                Module module = ModulesById[clrModule.ImageBase];

                module.ClrModule = clrModule;
                module.ImageName = clrModule.Name;
                if (clrModule.Pdb != null && !string.IsNullOrEmpty(clrModule.Pdb.FileName))
                {
                    try
                    {
                        if (!module.SymbolFileName.ToLowerInvariant().EndsWith(".pdb"))
                        {
                            module.SymbolFileName = clrModule.Pdb.FileName;
                        }
                    }
                    catch
                    {
                        module.SymbolFileName = clrModule.Pdb.FileName;
                    }
                }
                module.Name = Path.GetFileNameWithoutExtension(clrModule.Name);
                module.LoadedImageName = clrModule.Name;
                module.Size = clrModule.Size;
                return module;
            });
            dumpFileMemoryReader = SimpleCache.Create(() =>
            {
                try
                {
                    return string.IsNullOrEmpty(DumpFileName) ? null : new DumpFileMemoryReader(DumpFileName);
                }
                catch (Exception)
                {
                    return null;
                }
            });
            memoryRegions = SimpleCache.Create(() =>
            {
                if (DumpFileMemoryReader != null)
                    return DumpFileMemoryReader.GetMemoryRanges();
                else
                    return Context.Debugger.GetMemoryRegions(this);
            });
            memoryRegionFinder = SimpleCache.Create(() => new MemoryRegionFinder(MemoryRegions));
            TypeToUserTypeDescription = new DictionaryCache<Type, UserTypeDescription[]>(GetUserTypeDescription);
            ansiStringCache = new DictionaryCache<Tuple<ulong, int>, string>(DoReadAnsiString);
            unicodeStringCache = new DictionaryCache<Tuple<ulong, int>, string>(DoReadUnicodeString);
        }
Example #54
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Module" /> class.
        /// </summary>
        /// <param name="process">The process.</param>
        /// <param name="address">The module address.</param>
        internal Module(Process process, ulong address)
        {
            Address = address;
            Process = process;
            name = SimpleCache.Create(() =>
            {
                string name = Context.Debugger.GetModuleName(this);

                Process.UpdateModuleByNameCache(this, name);
                return name;
            });
            imageName = SimpleCache.Create(() => Context.Debugger.GetModuleImageName(this));
            loadedImageName = SimpleCache.Create(() => Context.Debugger.GetModuleLoadedImage(this));
            symbolFileName = SimpleCache.Create(() => Context.Debugger.GetModuleSymbolFile(this));
            mappedImageName = SimpleCache.Create(() => Context.Debugger.GetModuleMappedImage(this));
            moduleVersion = SimpleCache.Create(() =>
            {
                ModuleVersion version = new ModuleVersion();

                Context.Debugger.GetModuleVersion(this, out version.Major, out version.Minor, out version.Revision, out version.Patch);
                return version;
            });
            timestampAndSize = SimpleCache.Create(() => Context.Debugger.GetModuleTimestampAndSize(this));
            clrModule = SimpleCache.Create(() => Process.ClrRuntimes.SelectMany(r => r.ClrRuntime.Modules).Where(m => m.ImageBase == Address).FirstOrDefault());
            clrPdbReader = SimpleCache.Create(() =>
            {
                try
                {
                    string pdbPath = ClrModule.Runtime.DataTarget.SymbolLocator.FindPdb(ClrModule.Pdb);

                    if (!string.IsNullOrEmpty(pdbPath))
                    {
                        return new Microsoft.Diagnostics.Runtime.Utilities.Pdb.PdbReader(pdbPath);
                    }
                }
                catch (Exception)
                {
                }

                return null;
            });
            TypesByName = new DictionaryCache<string, CodeType>(GetTypeByName);
            TypesById = new DictionaryCache<uint, CodeType>(GetTypeById);
            ClrTypes = new DictionaryCache<Microsoft.Diagnostics.Runtime.ClrType, CodeType>(GetClrCodeType);
            GlobalVariables = new DictionaryCache<string, Variable>(GetGlobalVariable);
            UserTypeCastedGlobalVariables = new DictionaryCache<string, Variable>((name) =>
            {
                Variable variable = Process.CastVariableToUserType(GlobalVariables[name]);

                if (UserTypeCastedGlobalVariables.Count == 0)
                {
                    GlobalCache.VariablesUserTypeCastedFieldsByName.Add(UserTypeCastedGlobalVariables);
                }

                return variable;
            });
        }
 public ContractUploadBuinessService ()
 {
     _defaultFilialCache = new DictionaryCache<Guid, Guid?>(new TimeSpan(1, 0, 0), FillDefaultFilials);
 }