Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClrThread"/> class.
        /// </summary>
        /// <param name="thread">The thread.</param>
        /// <param name="clrThread">The CLR thread.</param>
        /// <param name="process">The process.</param>
        internal ClrThread(Thread thread, Microsoft.Diagnostics.Runtime.ClrThread clrThread, Process process)
            : base(thread != null ? thread.Id : uint.MaxValue, clrThread.OSThreadId, process)
        {
            ClrThread = clrThread;
            runtime = SimpleCache.Create(() => Process.ClrRuntimes.Single(r => r.ClrRuntime == clrThread.Runtime));
            appDomain = SimpleCache.Create(() => Runtime.AppDomains.Single(a => a.ClrAppDomain.Address == clrThread.AppDomain));
            clrStackTrace = SimpleCache.Create(() =>
            {
                StackTrace stackTrace = new StackTrace(this);
                uint frameNumber = 0;

                stackTrace.Frames = ClrThread.StackTrace.Where(f => f.Method != null).Select(f =>
                {
                    return new StackFrame(stackTrace, new ThreadContext(f.InstructionPointer, f.StackPointer, ulong.MaxValue))
                    {
                        FrameNumber = frameNumber++,
                        InstructionOffset = f.InstructionPointer,
                        StackOffset = f.StackPointer,
                        FrameOffset = ulong.MaxValue,
                        ReturnOffset = ulong.MaxValue,
                        ClrStackFrame = f,
                    };
                }).ToArray();
                return stackTrace;
            });
            lastThrownException = SimpleCache.Create(() => ClrThread.CurrentException != null ? new ClrException(this, ClrThread.CurrentException) : null);
        }
Ejemplo n.º 2
0
        public void Assignment()
        {
            Context context = new Context();
            SimpleCacheWithContext <int, Context> cache = SimpleCache.CreateWithContext(context, (c) =>
            {
                c.Count++;
                return(42);
            });
            var cache2 = cache;

            Assert.Equal(0, context.Count);
            Assert.False(cache.Cached);
            Assert.Equal(42, cache.Value);
            Assert.Equal(1, context.Count);
            Assert.True(cache.Cached);
            Assert.False(cache2.Cached);
            Assert.Equal(42, cache2.Value);
            Assert.Equal(2, context.Count);
            Assert.True(cache2.Cached);
            var cache3 = cache;

            Assert.True(cache3.Cached);
            Assert.Equal(42, cache3.Value);
            Assert.Equal(2, context.Count);
        }
    public Spawner(GamePrefabs prefabs)
    {
        _cache = new SimpleCache<RelativeSpaceObject>[System.Enum.GetNames(typeof(ESpaceObjects)).Length];

        _cache[(int)ESpaceObjects.Wreck] = new SimpleCache<RelativeSpaceObject>(prefabs.Wreck, 15);
        _cache[(int)ESpaceObjects.WreckLoco] = new SimpleCache<RelativeSpaceObject>(prefabs.WreckLoco, 4);
        _cache[(int)ESpaceObjects.WreckStatic] = new SimpleCache<RelativeSpaceObject>(prefabs.WreckStatic, 7);
        _cache[(int)ESpaceObjects.Jammer] = new SimpleCache<RelativeSpaceObject>(prefabs.Jammer, 3);
        _cache[(int)ESpaceObjects.AlienSmall] = new SimpleCache<RelativeSpaceObject>(prefabs.AlienSmall, 7);
        _cache[(int)ESpaceObjects.AlienBig] = new SimpleCache<RelativeSpaceObject>(prefabs.AlienBig, 6);
        _cache[(int)ESpaceObjects.AlienShield] = new SimpleCache<RelativeSpaceObject>(prefabs.AlienShield, 5);
        _cache[(int)ESpaceObjects.Rocket] = new SimpleCache<RelativeSpaceObject>(prefabs.Rocket, 8);
        _cache[(int)ESpaceObjects.Bullet] = new SimpleCache<RelativeSpaceObject>(prefabs.Bullet, 10);

        _destroyDelegates = new System.Action<RelativeSpaceObject>[_cache.Length];

        for (int i = 0; i < _cache.Length; i++)
        {
            var cache = _cache[i];
            var index = i;

            _destroyDelegates[i] = (x) =>
            {
                cache.Push(x);
                x.OnDestroy -= _destroyDelegates[index];
                x.OnReward -= OnReward;
                LiveObjects.Remove(x);
            };
        }
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StackFrame" /> class.
        /// </summary>
        /// <param name="stackTrace">The stack trace.</param>
        /// <param name="frameContext">The frame context.</param>
        internal StackFrame(StackTrace stackTrace, ThreadContext frameContext)
        {
            StackTrace = stackTrace;
            FrameContext = frameContext;
            sourceFileNameAndLine = SimpleCache.Create(ReadSourceFileNameAndLine);
            functionNameAndDisplacement = SimpleCache.Create(ReadFunctionNameAndDisplacement);
            locals = SimpleCache.Create(GetLocals);
            arguments = SimpleCache.Create(GetArguments);
            clrStackFrame = SimpleCache.Create(() => Thread.ClrThread?.StackTrace.Where(f => f.InstructionPointer == InstructionOffset).FirstOrDefault());
            userTypeConvertedLocals = SimpleCache.Create(() =>
            {
                VariableCollection collection = Variable.CastVariableCollectionToUserType(locals.Value);

                GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedLocals);
                return collection;
            });
            userTypeConvertedArguments = SimpleCache.Create(() =>
            {
                VariableCollection collection = Variable.CastVariableCollectionToUserType(arguments.Value);

                GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedArguments);
                return collection;
            });
            module = SimpleCache.Create(() =>
            {
                var m = Process.GetModuleByInnerAddress(InstructionOffset);

                if (m == null && ClrStackFrame != null)
                    m = Process.ClrModuleCache[ClrStackFrame.Module];
                return m;
            });
        }
        public void StatsGetReset()
        {
            var val1 = "value1";
            var val2 = "value2";

            int capacity = 5;
            var cache    = new SimpleCache <string, string>(capacity);

            cache.GetOrAdd("key1", () => val1);
            cache.GetOrAdd("key2", () => val2);
            cache.GetOrAdd("key1", () => val1);
            cache.GetOrAdd("key2", () => val2);

            var expectedHits      = 2;
            var expectedMisses    = 2;
            var expectedEjections = 0;
            var expectedSize      = 2;

            EvaluateCacheMetrics(cache, expectedHits, expectedMisses, expectedEjections, expectedSize);

            cache.ResetStats();

            expectedHits      = 0;
            expectedMisses    = 0;
            expectedEjections = 0;
            expectedSize      = 2;

            EvaluateCacheMetrics(cache, expectedHits, expectedMisses, expectedEjections, expectedSize);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NamedStreamMap"/> class.
        /// </summary>
        /// <param name="reader">Stream binary reader.</param>
        public NamedStreamMap(IBinaryReader reader)
        {
            uint stringsSizeInBytes = reader.ReadUint();

            StringsStream = reader.ReadSubstream(stringsSizeInBytes);
            HashTable     = new HashTable(reader);
            streamsCache  = SimpleCache.CreateStruct(() =>
            {
                Dictionary <string, int> streams = new Dictionary <string, int>();
                IBinaryReader stringsReader      = StringsStream.Duplicate();

                foreach (var kvp in HashTable.Dictionary)
                {
                    stringsReader.Position = kvp.Key;
                    streams.Add(stringsReader.ReadCString().String, (int)kvp.Value);
                }
                return(streams);
            });
            streamsUppercaseCache = SimpleCache.CreateStruct(() =>
            {
                Dictionary <string, int> streams = new Dictionary <string, int>();

                foreach (var kvp in Streams)
                {
                    streams.Add(kvp.Key.ToUpperInvariant(), kvp.Value);
                }
                return(streams);
            });
        }
        public void ItemsAreBeingCached()
        {
            var val1 = "value1";
            var val2 = "value2";
            var val3 = "value3";

            int capacity = 5;
            var cache    = new SimpleCache <string, string>(capacity);

            cache.GetOrAdd("key1", () => val1);
            cache.GetOrAdd("key2", () => val2);
            cache.GetOrAdd("key3", () => val3);

            //This should not modify the value of key2
            var shouldbeVal2 = cache.GetOrAdd("key2", () => "xyz");

            //Use AreSame to ensure that we are getting a reference match.
            Assert.AreSame(val1, cache.Peek("key1"));
            Assert.AreSame(val2, cache.Peek("key2"));
            Assert.AreSame(val3, cache.Peek("key3"));

            Assert.AreSame(shouldbeVal2, val2);

            var expectedHits      = 1;
            var expectedMisses    = 3;
            var expectedEjections = 0;
            var expectedSize      = 3;

            EvaluateCacheMetrics(cache, expectedHits, expectedMisses, expectedEjections, expectedSize);
        }
Ejemplo n.º 8
0
 private static void AddToCache(SimpleCache cache, string key, BaseDef def)
 {
     AddToTypeCache(def);
     if (key == null)
     {
         key = "";
     }
     if (!cache.TryGetValue(key, out object data))
     {
         cache.Add(key, def);
         return;
     }
     if (data is BaseDef[] list)
     {
         var len     = list.Length;
         var newList = new BaseDef[len + 1];
         Array.Copy(list, newList, len);
         newList[len] = def;
         cache[key]   = newList;
     }
     else
     {
         cache[key] = new BaseDef[] { data as BaseDef, def }
     };
 }
Ejemplo n.º 9
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);
            });
        }
Ejemplo n.º 10
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]));
        }
Ejemplo n.º 11
0
        public ActionResult Friends(string q)
        {
            var token = repository.GetOAuthToken(subdomainid.Value, sessionid.Value.ToString(), OAuthTokenType.FACEBOOK);

            if (token == null)
            {
                return(Json(JavascriptReturnCodes.NOTOKEN.ToJsonOKData(), JsonRequestBehavior.AllowGet));
            }
            var facebook = new FacebookService(token.token_key);

            // see if this is cached
            var cachekey = "friends" + token.token_key;
            var cached   = SimpleCache.Get(cachekey, SimpleCacheType.FACEBOOK) as ResponseCollection <IdName>;

            if (cached == null)
            {
                var response = facebook.People.GetFriends("me");
                SimpleCache.Add(cachekey, response, SimpleCacheType.FACEBOOK);
                cached = response;
            }

            var friends = cached.data.Where(x => x.name.StartsWith(q, true, CultureInfo.InvariantCulture)).Select(x => new { x.id, x.name });

            return(Json(friends.ToList(), JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 12
0
 public void Configuration(IAppBuilder app)
 {
     app.Use(typeof(AuthMiddleware));
     UserContext.Initialize();
     SimpleCache.Initialize();
     RoleBuilder.Init();
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StackFrame" /> class.
        /// </summary>
        /// <param name="stackTrace">The stack trace.</param>
        /// <param name="frameContext">The frame context.</param>
        internal StackFrame(StackTrace stackTrace, ThreadContext frameContext)
        {
            StackTrace                  = stackTrace;
            FrameContext                = frameContext;
            sourceFileNameAndLine       = SimpleCache.Create(ReadSourceFileNameAndLine);
            functionNameAndDisplacement = SimpleCache.Create(ReadFunctionNameAndDisplacement);
            locals                  = SimpleCache.Create(GetLocals);
            arguments               = SimpleCache.Create(GetArguments);
            clrStackFrame           = SimpleCache.Create(() => Thread.ClrThread?.GetClrStackFrame(InstructionOffset));
            userTypeConvertedLocals = SimpleCache.Create(() =>
            {
                VariableCollection collection = Variable.CastVariableCollectionToUserType(locals.Value);

                GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedLocals);
                return(collection);
            });
            userTypeConvertedArguments = SimpleCache.Create(() =>
            {
                VariableCollection collection = Variable.CastVariableCollectionToUserType(arguments.Value);

                GlobalCache.UserTypeCastedVariableCollections.Add(userTypeConvertedArguments);
                return(collection);
            });
            module = SimpleCache.Create(() =>
            {
                var m = Process.GetModuleByInnerAddress(InstructionOffset);

                if (m == null && ClrStackFrame != null)
                {
                    m = Process.ClrModuleCache[ClrStackFrame.Module];
                }
                return(m);
            });
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClrThread"/> class.
        /// </summary>
        /// <param name="thread">The thread.</param>
        /// <param name="clrThread">The CLR thread.</param>
        /// <param name="process">The process.</param>
        internal ClrThread(Thread thread, Microsoft.Diagnostics.Runtime.ClrThread clrThread, Process process)
            : base(thread != null ? thread.Id : uint.MaxValue, clrThread.OSThreadId, process)
        {
            ClrThread     = clrThread;
            runtime       = SimpleCache.Create(() => Process.ClrRuntimes.Single(r => r.ClrRuntime == clrThread.Runtime));
            appDomain     = SimpleCache.Create(() => Runtime.AppDomains.Single(a => a.ClrAppDomain.Address == clrThread.AppDomain));
            clrStackTrace = SimpleCache.Create(() =>
            {
                StackTrace stackTrace = new StackTrace(this);
                uint frameNumber      = 0;

                stackTrace.Frames = ClrThread.StackTrace.Where(f => f.Method != null).Select(f =>
                {
                    return(new StackFrame(stackTrace, new ThreadContext(f.InstructionPointer, f.StackPointer, ulong.MaxValue))
                    {
                        FrameNumber = frameNumber++,
                        InstructionOffset = f.InstructionPointer,
                        StackOffset = f.StackPointer,
                        FrameOffset = ulong.MaxValue,
                        ReturnOffset = ulong.MaxValue,
                        ClrStackFrame = f,
                    });
                }).ToArray();
                return(stackTrace);
            });
            lastThrownException = SimpleCache.Create(() => ClrThread.CurrentException != null ? new ClrException(this, ClrThread.CurrentException) : null);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClrMdModule"/> class.
        /// </summary>
        /// <param name="provider">The CLR provider.</param>
        /// <param name="clrModule">The CLR module.</param>
        public ClrMdModule(CLR.ClrMdProvider provider, Microsoft.Diagnostics.Runtime.ClrModule clrModule)
        {
            Provider     = provider;
            ClrModule    = clrModule;
            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);
            });
            module = SimpleCache.Create(() =>
            {
                return(Provider.GetProcess(ClrModule.Runtime)?.ClrModuleCache[this]);
            });
        }
Ejemplo n.º 16
0
        public void IncompleteResetOnMasterWithException_ReceivedExceptionWithNoData()
        {
            var cache          = new SimpleCache <int, TestResource>();
            var masterInformer = Substitute.For <IInformer <TestResource> >();

            masterInformer.GetResource(ResourceStreamType.ListWatch).Returns(
                Observable.Create <ResourceEvent <TestResource> >(obs =>
            {
                obs.OnNext(new TestResource(1).ToResourceEvent(EventTypeFlags.ResetStart));
                obs.OnError(new TestCompleteException());
                return(Disposable.Empty);
            }));
            var sharedInformer = new SharedInformer <int, TestResource>(masterInformer, _log, x => x.Key, cache);

            var observable = sharedInformer
                             .GetResource(ResourceStreamType.ListWatch)
                             .TimeoutIfNotDebugging()
                             .ToList();

            var dataReceived = false;
            var testComplete = new TaskCompletionSource <bool>();

            observable.Subscribe(
                x => dataReceived = true,
                e => testComplete.TrySetException(e),
                () => testComplete.SetResult(true));

            Func <Task <bool> > act = async() => await testComplete.Task.TimeoutIfNotDebugging();

            act.Should().Throw <TestCompleteException>();
            dataReceived.Should().BeFalse();
        }
        public void CacheReturnsCorrectValuesForKeys()
        {
            int capacity = 5;
            var cache    = new SimpleCache <string, object>(capacity);

            var val1 = "value1";
            var val2 = "value2";
            var val3 = "value3";

            cache.GetOrAdd("key1", () => val1);
            cache.GetOrAdd("key2", () => val2);
            cache.GetOrAdd("key3", () => val3);

            //Use AreSame to ensure that we are getting a reference match.
            Assert.AreSame(val1, cache.Peek("key1"));
            Assert.AreSame(val2, cache.Peek("key2"));
            Assert.AreSame(val3, cache.Peek("key3"));

            var expectedHits      = 0;
            var expectedMisses    = 3;
            var expectedEjections = 0;
            var expectedSize      = 3;

            EvaluateCacheMetrics(cache, expectedHits, expectedMisses, expectedEjections, expectedSize);
        }
Ejemplo n.º 18
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);
            });
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CodeFunction" /> class.
 /// </summary>
 /// <param name="address">The function address.</param>
 /// <param name="process">The process.</param>
 public CodeFunction(ulong address, Process process = null)
 {
     Address = address;
     Process = process ?? Process.Current;
     sourceFileNameAndLine = SimpleCache.Create(ReadSourceFileNameAndLine);
     functionNameAndDisplacement = SimpleCache.Create(ReadFunctionNameAndDisplacement);
 }
Ejemplo n.º 20
0
        public void CircularDependency1()
        {
            var cache = new SimpleCache();

            Func<object> circular = () => cache.Resolve("urn:a", (a) => cache.Resolve("urn:b", (b) => cache.Resolve("urn:c", (c) => cache.Resolve("urn:a", (again) => new object()))));
            ExceptionAssert.Throws<CircularDependencyException>(() => circular());
        }
Ejemplo n.º 21
0
        public long UpdateRouting(TramoDto dto)
        {
            long result = _service.UpdateRouting(dto);

            SimpleCache.CleanCache();
            return(result);
        }
Ejemplo n.º 22
0
        public async Task WhenSecondSubscriber_ReuseMasterConnection()
        {
            var cache          = new SimpleCache <int, TestResource>();
            var masterInformer = Substitute.For <IInformer <TestResource> >();
            var scheduler      = new TestScheduler();

            masterInformer.GetResource(ResourceStreamType.ListWatch)
            .Returns(TestData.Events.ResetWith2_Delay_UpdateToEach.ToTestObservable(scheduler));

            var sharedInformer = new SharedInformer <int, TestResource>(masterInformer, _log, x => x.Key, cache);

            var tcs = new TaskCompletionSource <IList <ResourceEvent <TestResource> > >();

            // we attach after first subscription messages are established, but before any "watch" updates come in
            scheduler.ScheduleAbsolute(50, async() =>
            {
                scheduler.Stop();
                // need to pause virtual time brifly since child subscribers runs on separate thread and needs to be in position before we resume sending messages to master
                var _      = Task.Delay(10).ContinueWith(x => scheduler.Start());
                var second = await sharedInformer
                             .GetResource(ResourceStreamType.ListWatch)
                             .TimeoutIfNotDebugging()
                             .ToList();
                tcs.SetResult(second);
            });

            await sharedInformer
            .GetResource(ResourceStreamType.ListWatch)
            .TimeoutIfNotDebugging()
            .ToList();

            await masterInformer.Received(1).GetResource(ResourceStreamType.ListWatch);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Gets the local variables.
        /// </summary>
        private VariableCollection GetLocals()
        {
            if (clrStackFrame.Cached && ClrStackFrame != null)
            {
                if (ClrStackFrame.Locals.Count > 0)
                {
                    return(ConvertClrToVariableCollection(ClrStackFrame.Locals, GetClrLocalsNames()));
                }
                else
                {
                    return(new VariableCollection(new Variable[0]));
                }
            }

            VariableCollection locals = null;

            try
            {
                locals = Context.SymbolProvider.GetFrameLocals(this, false);
            }
            catch (Exception)
            {
            }

            if ((locals == null || locals.Count == 0) && ClrStackFrame != null && ClrStackFrame.Locals.Count > 0)
            {
                locals = ConvertClrToVariableCollection(ClrStackFrame.Locals, GetClrLocalsNames());
            }

            return(locals);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CodeFunction" /> class.
 /// </summary>
 /// <param name="address">The function address.</param>
 /// <param name="process">The process.</param>
 public CodeFunction(ulong address, Process process = null)
 {
     Address = address;
     Process = process ?? Process.Current;
     sourceFileNameAndLine       = SimpleCache.Create(ReadSourceFileNameAndLine);
     functionNameAndDisplacement = SimpleCache.Create(ReadFunctionNameAndDisplacement);
 }
Ejemplo n.º 25
0
        public int Create(CalzadaDto dto)
        {
            int result = _service.Create(dto);

            SimpleCache.CleanCache();
            return(result);
        }
Ejemplo n.º 26
0
 public void CacheAuthTokens(SimpleCache <AuthTokenDto> localData)
 {
     if (localData != null)
     {
         _localData = localData;
     }
 }
Ejemplo n.º 27
0
    public LiveEffect ParentEffectIf(string alias, Transform parent, Vector2 position, float rotation, EffectConditionDelegate condition)
    {
        SimpleCache <ParticleSystem> cache;

        if (EffectsCached.ContainsKey(alias))
        {
            cache = EffectsCached[alias];
        }
        else
        {
            cache = new SimpleCache <ParticleSystem>(GetEffect(alias).System, 3);
            EffectsCached.Add(alias, cache);
        }

        LiveEffect parentedEffect = new LiveEffect
        {
            Cache     = cache,
            Condition = condition,
            Parent    = parent,
            Position  = position,
            Rotation  = rotation
        };

        _liveEffects.Add(parentedEffect);

        return(parentedEffect);
    }
Ejemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ElfImage"/> class.
        /// </summary>
        /// <param name="path">The image path.</param>
        /// <param name="loadOffset">Offset from where image was loaded.</param>
        public ElfImage(string path, ulong loadOffset = 0)
        {
            elf        = ELFReader.Load <ulong>(path);
            LoadOffset = loadOffset;
            foreach (var segment in elf.Segments)
            {
                if (segment.Type == ELFSharp.ELF.Segments.SegmentType.ProgramHeader)
                {
                    CodeSegmentOffset = segment.Address - (ulong)segment.Offset;
                    break;
                }
            }

            List <PublicSymbol> publicSymbols = new List <PublicSymbol>();
            SymbolTable <ulong> symbols       = elf.Sections.FirstOrDefault(s => s.Type == SectionType.SymbolTable) as SymbolTable <ulong>;

            if (symbols == null || !symbols.Entries.Any())
            {
                symbols = elf.Sections.FirstOrDefault(s => s.Type == SectionType.DynamicSymbolTable) as SymbolTable <ulong>;
            }

            if (symbols != null)
            {
                foreach (SymbolEntry <ulong> symbol in symbols.Entries)
                {
                    publicSymbols.Add(new PublicSymbol(symbol.Name, symbol.Value - CodeSegmentOffset));
                }
            }
            PublicSymbols       = publicSymbols;
            sectionRegions      = SimpleCache.Create(() => elf.Sections.Where(s => s.LoadAddress > 0).OrderBy(s => s.LoadAddress).ToArray());
            sectionRegionFinder = SimpleCache.Create(() => new MemoryRegionFinder(sectionRegions.Value.Select(s => new MemoryRegion {
                BaseAddress = s.LoadAddress, RegionSize = s.Size
            }).ToArray()));
        }
Ejemplo n.º 29
0
        public async Task GetCacheThenSourceAsync_Object_FromCache()
        {
            var sut  = new SimpleCache();
            var key  = "key";
            var name = "name";
            var num  = 2;
            var obj  = new SampleCacheObject {
                Name = name, Number = num
            };

            sut.Set(key, obj);
            var didSourceRun = false;
            var source       = new Func <Task <SampleCacheObject> >(() =>
            {
                didSourceRun = true;
                return(Task.FromResult(obj));
            });
            var result = await sut.GetCacheThenSourceAsync <SampleCacheObject>(
                key : key,
                sourceDelegate : source);

            result.IsCacheNull.Should().Be(false);
            result.ValueOrDefault.Should().NotBeNull();
            result.ValueOrDefault.Number.Should().Be(num);
            result.ValueOrDefault.Name.Should().Be(name);
            didSourceRun.Should().BeFalse();
        }
Ejemplo n.º 30
0
        public long CreateOrUpdate(TramoDto dto)
        {
            long result = _service.CreateOrUpdate(dto);

            SimpleCache.CleanCache();
            return(result);
        }
Ejemplo n.º 31
0
        public void Assignment()
        {
            int count = 0;
            SimpleCacheStruct <int> cache = SimpleCache.CreateStruct(() =>
            {
                count++;
                return(42);
            });
            var cache2 = cache;

            Assert.Equal(0, count);
            Assert.False(cache.Cached);
            Assert.Equal(42, cache.Value);
            Assert.Equal(1, count);
            Assert.True(cache.Cached);
            Assert.False(cache2.Cached);
            Assert.Equal(42, cache2.Value);
            Assert.Equal(2, count);
            Assert.True(cache2.Cached);
            var cache3 = cache;

            Assert.True(cache3.Cached);
            Assert.Equal(42, cache3.Value);
            Assert.Equal(2, count);
        }
Ejemplo n.º 32
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));
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Gets the function arguments.
        /// </summary>
        private VariableCollection GetArguments()
        {
            if (clrStackFrame.Cached && ClrStackFrame != null)
            {
                if (ClrStackFrame.Arguments.Count > 0)
                {
                    return(ConvertClrToVariableCollection(ClrStackFrame.Arguments, GetClrArgumentsNames()));
                }
                else
                {
                    return(new VariableCollection(new Variable[0]));
                }
            }

            VariableCollection arguments = null;

            try
            {
                arguments = Context.SymbolProvider.GetFrameLocals(this, true);
            }
            catch (Exception)
            {
            }

            if ((arguments == null || arguments.Count == 0) && ClrStackFrame != null && ClrStackFrame.Arguments.Count > 0)
            {
                arguments = ConvertClrToVariableCollection(ClrStackFrame.Arguments, GetClrArgumentsNames());
            }

            return(arguments);
        }
Ejemplo n.º 34
0
 public static bool RescheduleMailing(string distributorID, int mailingID, DateTime?newSendDateUTC)
 {
     try
     {
         using (var proxy = ServiceProvider.ServiceClientProvider.GetDistributorCRMServiceProxy())
         {
             var response =
                 proxy.SaveMailing(new SaveMailingRequest1(new SaveMailingScheduleRequest
             {
                 DistributorID = distributorID,
                 MailingID     = mailingID,
                 NewSendDate   = newSendDateUTC
             })).SaveMailingResult;
             if (response.Status == ServiceResponseStatusType.Success)
             {
                 // expire cache
                 SimpleCache.Expire(typeof(DataTable), mailingHistoryCacheKey(distributorID));
                 SimpleCache.Expire(typeof(DataTable), mailingHistoryDetailCacheKey(distributorID, mailingID));
                 return(true);
             }
             return(false);
         }
     }
     catch (Exception ex)
     {
         LoggerHelper.Exception("System.Exception", new Exception(String.Format("RescheduleMailing distributorID:{0} mailingid:{1} newDate:{2} failed",
                                                                                distributorID,
                                                                                mailingID,
                                                                                newSendDateUTC.HasValue ? newSendDateUTC.Value : DateTime.MaxValue), ex));
         return(false);
     }
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Gets the type with the specified name.
        /// </summary>
        /// <param name="name">The type name.</param>
        private CodeType GetTypeByName(string name)
        {
            int moduleIndex = name.IndexOf('!');

            if (moduleIndex > 0)
            {
                if (string.Compare(name.Substring(0, moduleIndex), Name, true) != 0)
                {
                    throw new ArgumentException("Type name contains wrong module name. Don't add it manually, it will be added automatically.");
                }

                name = name.Substring(moduleIndex + 1);
            }

            if (name == CodeType.NakedPointerCodeTypeName)
            {
                return(new NakedPointerCodeType(this));
            }
            else if (name.StartsWith(BuiltinCodeTypes.FakeNameStart))
            {
                return(BuiltinCodeTypes.CreateCodeType(this, name.Substring(BuiltinCodeTypes.FakeNameStart.Length)));
            }

            CodeType codeType    = null;
            bool     clrSearched = false;

            if (clrModule.Cached && ClrModule != null)
            {
                codeType    = GetClrTypeByName(name);
                clrSearched = true;
            }

            try
            {
                if (codeType == null)
                {
                    uint typeId = Context.SymbolProvider.GetTypeId(this, name);

                    if (Context.SymbolProvider.GetTypeTag(this, typeId) != CodeTypeTag.Unsupported)
                    {
                        codeType = TypesById[typeId];
                    }
                }
            }
            catch
            {
            }

            if (!clrSearched && ClrModule != null)
            {
                codeType = GetClrTypeByName(name);
            }

            if (codeType == null)
            {
                throw new Exception(string.Format("Type '{0}' wasn't found", name));
            }

            return(codeType);
        }
Ejemplo n.º 36
0
 public void CaseInsenstive()
 {
     var cache = new SimpleCache();
     var a = cache.Resolve("urn:x-test:foo2", (uri) => new object());
     var b = cache.Resolve("urn:x-test:FOO2", (uri) => new object());
     var c = cache.Resolve("urn:x-test:Foo2", (uri) => new object());
     Assert.AreSame(a, b);
     Assert.AreSame(a, c);
 }
Ejemplo n.º 37
0
        public void Invalidating()
        {
            const string id = "urn:x-test:invalidating";

            var cache = new SimpleCache();
            var a = cache.Resolve(id, (uri) => new object());
            cache.Invalidate(id);
            var b = cache.Resolve(id, (uri) => new object());
            var c = cache.Resolve(id, (uri) => new object());
            Assert.AreNotSame(a, b);
            Assert.AreSame(b, c);
        }
Ejemplo n.º 38
0
        public void Adding_and_retrieving_an_item_should_work_as_expected()
        {
            /* Arrange */
            var c = new SimpleCache<string, string>();
            string key = "Val1";

            /* Act */
            c.Add(key, "TheValue", 10000, false);

            bool exists = c.Contains(key);
            string val = c[key];

            /* Assert */
            exists.Should().BeTrue();
            val.Should().Be("TheValue");
        }
Ejemplo n.º 39
0
        public void Clearing_cache_should_work_as_expected()
        {
            /* Arrange */
            var c = new SimpleCache<string, string>();

            /* Act */
            c.Add("Val1", "TheValue", 10000, false);
            c.Add("Val2", "TheValue2", 10000, false);

            int countPre = c.Count;
            c.Clear();
            int countPost = c.Count;

            /* Assert */
            countPre.Should().Be(2);
            countPost.Should().Be(0);
        }
Ejemplo n.º 40
0
        public void Basic_expiration_should_work_as_expected()
        {
            /* Arrange */
            var c = new SimpleCache<string, string>();
            string key = "Val1";

            /* Act */
            c.Add(key, "TheValue", 10, false);

            Thread.Sleep(11);

            bool exists = c.Contains(key);
            string val = c[key];

            /* Assert */
            exists.Should().BeFalse();
            val.Should().BeNull();
        }
Ejemplo n.º 41
0
        public void Auto_cleanup_should_work_as_expected()
        {
            /* Arrange */
            var c = new SimpleCache<string, string>(15);
            string key = "Val1";

            /* Act */
            c.Add(key, "TheValue", 10, true);
            int countPre = c.Count;

            Thread.Sleep(20);
            string val = c[key];
            int countPost = c.Count;

            /* Assert */
            countPre.Should().Be(1);
            countPost.Should().Be(0);
            val.Should().BeNull();
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Symbol"/> class.
        /// </summary>
        /// <param name="module">The module.</param>
        /// <param name="symbol">The DIA symbol.</param>
        public Symbol(Module module, IDiaSymbol symbol)
        {
            this.symbol = symbol;
            Module = module;
            Tag = (SymTagEnum)symbol.symTag;
            BasicType = (BasicType)symbol.baseType;
            Id = symbol.symIndexId;
            if (Tag != SymTagEnum.SymTagExe)
                Name = TypeToString.GetTypeString(symbol);
            else
                Name = "";

            Name = Name.Replace("<enum ", "<").Replace(",enum ", ",");
            Offset = symbol.offset;

            var size = symbol.length;
            if (size > int.MaxValue)
                throw new ArgumentException("Symbol size is unexpected");
            Size = (int)size;

            // Initialize caches
            fields = SimpleCache.Create(() => symbol.GetChildren(SymTagEnum.SymTagData).Select(s => new SymbolField(this, s)).Where(f => f.Type != null).ToArray());
            baseClasses = SimpleCache.Create(() => symbol.GetChildren(SymTagEnum.SymTagBaseClass).Select(s => Module.GetSymbol(s)).ToArray());
            elementType = SimpleCache.Create(() =>
            {
                if (Tag == SymTagEnum.SymTagPointerType || Tag == SymTagEnum.SymTagArrayType)
                {
                    IDiaSymbol type = symbol.type;

                    if (type != null)
                    {
                        var result = Module.GetSymbol(type);
                        if (Tag == SymTagEnum.SymTagPointerType)
                            result.pointerType.Value = this;
                        return result;
                    }
                }

                return null;
            });
            pointerType = SimpleCache.Create(() =>
            {
                var result = Module.GetSymbol(symbol.objectPointerType);
                result.elementType.Value = this;
                return result;
            });
            userType = SimpleCache.Create(() => (UserType)null);
            enumValues = SimpleCache.Create(() =>
            {
                List<Tuple<string, string>> result = new List<Tuple<string, string>>();

                if (Tag == SymTagEnum.SymTagEnum)
                {
                    foreach (var enumValue in symbol.GetChildren())
                    {
                        result.Add(Tuple.Create(enumValue.name, enumValue.value.ToString()));
                    }
                }

                return result.ToArray();
            });
            namespaces = SimpleCache.Create(() => SymbolNameHelper.GetSymbolNamespaces(Name));
        }
Ejemplo n.º 43
0
 static Weights()
 {
     ItemCache = new SimpleCache<float> { MaxAge = MinCaching };
     LongCache = new SimpleCache<float> { MaxAge = 3000 };
     InvertedPrefix = "[i]";
     CustomPrefix = "[c]";
     PItems = new List<Item>();
     PItems.AddRange(
         new List<Item>
         {
             new Item(
                 "killable", "AA Killable", 20, false,
                 t => t.Health < ObjectManager.Player.GetAutoAttackDamage(t, true) ? 1 : 0,
                 "Checks if target is killable with one auto attack."),
             new Item(
                 "attack-damage", "Attack Damage", 15, false, delegate(Obj_AI_Hero t)
                 {
                     var ad = t.FlatPhysicalDamageMod;
                     var infinity = LongCache.GetOrAdd(
                         "infinity-edge-" + t.ChampionName,
                         () => ItemData.Infinity_Edge.GetItem().IsOwned(t) ? 2.5f : 2);
                     ad += ad / 100 * (t.Crit * 100) * (infinity ?? 1f);
                     var averageArmor = LongCache.GetOrAdd(
                         "average-armor",
                         delegate
                         {
                             return HeroManager.Allies.Select(a => a.Armor).DefaultIfEmpty(0).Average() *
                                    t.PercentArmorPenetrationMod - t.FlatArmorPenetrationMod;
                         });
                     return ad * (100 / (100 + (averageArmor ?? 0))) *
                            (1f / ObjectManager.Player.AttackDelay);
                 }, "AD + Pen + Crit + Speed = Higher Weight"),
             new Item(
                 "ability-power", "Ability Power", 15, false, delegate(Obj_AI_Hero t)
                 {
                     var averageMr = LongCache.GetOrAdd(
                         "average-magic-resist",
                         delegate
                         {
                             return
                                 HeroManager.Allies.Select(a => a.SpellBlock).DefaultIfEmpty(0).Average() *
                                 t.PercentMagicPenetrationMod - t.FlatMagicPenetrationMod;
                         });
                     return t.FlatMagicDamageMod * (100 / (100 + (averageMr ?? 0)));
                 }, "AP + Pen = Higher Weight"),
             new Item(
                 "low-resists", "Resists", 0, true,
                 t =>
                     ObjectManager.Player.FlatPhysicalDamageMod >= ObjectManager.Player.FlatMagicDamageMod
                         ? t.Armor
                         : t.SpellBlock, "Low Armor / Magic-Resist = Higher Weight"),
             new Item("low-health", "Health", 20, true, t => t.Health, "Low Health = Higher Weight"),
             new Item(
                 "short-distance-player", "Distance to Player", 5, true,
                 t => t.Distance(ObjectManager.Player), "Close to Player = Higher Weight"),
             new Item(
                 "short-distance-cursor", "Distance to Cursor", 0, true, t => t.Distance(Game.CursorPos),
                 "Close to Cursor = Higher Weight"),
             new Item(
                 "crowd-control", "Crowd Control", 0, false, delegate(Obj_AI_Hero t)
                 {
                     var buffs =
                         t.Buffs.Where(
                             x =>
                                 x.Type == BuffType.Charm || x.Type == BuffType.Knockback ||
                                 x.Type == BuffType.Suppression || x.Type == BuffType.Fear ||
                                 x.Type == BuffType.Taunt || x.Type == BuffType.Stun ||
                                 x.Type == BuffType.Slow || x.Type == BuffType.Silence ||
                                 x.Type == BuffType.Snare || x.Type == BuffType.Polymorph).ToList();
                     return buffs.Any() ? buffs.Select(x => x.EndTime).DefaultIfEmpty(0).Max() : 0;
                 }, "Checks if the target suffers from any form of crowd control."),
             new Item(
                 "gold", "Acquired Gold", 0, false,
                 t =>
                     (t.MinionsKilled + t.NeutralMinionsKilled) * 27.35f + t.ChampionsKilled * 300f +
                     t.Assists * 85f, "Calculates the approx. amount of Gold."),
             new Item(
                 "team-focus", "Team Focus", 0, false,
                 t =>
                     Aggro.Items.Where(a => a.Value.Target.Hero.NetworkId == t.NetworkId)
                         .Select(a => a.Value.Value)
                         .DefaultIfEmpty(0)
                         .Sum(), "Checks who your allies are targeting."),
             new Item(
                 "focus-me", "Focus Me", 0, false, delegate(Obj_AI_Hero t)
                 {
                     var entry = Aggro.GetSenderTargetItem(t, ObjectManager.Player);
                     return entry != null ? entry.Value : 0;
                 }, "Checks who is targeting you.")
         });
 }
Ejemplo n.º 44
0
 public void Resolving()
 {
     var cache = new SimpleCache();
     Assert.AreEqual("foo", cache.Resolve("urn:x-test:foo", (uri) => "foo"));
 }
Ejemplo n.º 45
0
        static void CacheTest()
        {
            var cache = new NGinnBPM.MessageBus.Impl.SimpleCache<string, string>() {  };
            cache.MaxCapacity = 100;
            for (int i = 0; i < 150; i++)
            {
                var g = cache.Get(i.ToString(), x => "abc_" + i);
            }
            for (int i = 150; i > 0; i--)
            {
                var g = cache.Get(i.ToString(), x => "def_" + i);
            }

            Console.WriteLine("Hits: {0}", cache.HitRatio);

            for (int i = 150; i > 0; i--)
            {
                var g = cache.Get((i % 10).ToString(), x => "def_" + i % 10);
            }

            Console.WriteLine("Hits: {0}", cache.HitRatio);

            cache = new SimpleCache<string, string> { MaxCapacity = 10 };
            for (int i = 0; i < 100; i++)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object v)
                {
                    var r = cache.Get(v.ToString(), delegate(string t)
                    {
                        log.Info("Getting v for {0}", t);
                        Thread.Sleep(1000);
                        log.Info("Got v for {0}", t);
                        return "abc_" + t;
                    });
                }), i % 10);

            }
            Console.ReadLine();
            Console.WriteLine("Hits: {0}", cache.HitRatio);
        }
Ejemplo n.º 46
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;
            });
        }
Ejemplo n.º 47
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);
        }
Ejemplo n.º 48
0
 public void SameObject()
 {
     var cache = new SimpleCache();
     var a = cache.Resolve("urn:x-test:foo1", (uri) => new object());
     var b = cache.Resolve("urn:x-test:foo1", (uri) => new object());
     var c = cache.Resolve("urn:x-test:foo1", (uri) => new object());
     Assert.AreSame(a, b);
     Assert.AreSame(a, c);
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Gets the global or static variable.
        /// </summary>
        /// <param name="name">The variable name.</param>
        /// <returns>Variable if found</returns>
        /// <exception cref="System.ArgumentException">Variable name contains wrong module name. Don't add it manually, it will be added automatically.</exception>
        public Variable GetVariable(string name)
        {
            int moduleIndex = name.IndexOf('!');

            if (moduleIndex > 0)
            {
                if (string.Compare(name, 0, Name, 0, Math.Max(Name.Length, moduleIndex), true) != 0)
                {
                    throw new ArgumentException("Variable name contains wrong module name. Don't add it manually, it will be added automatically.");
                }

                name = name.Substring(moduleIndex + 1);
            }

            return UserTypeCastedGlobalVariables[name];
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Gets the type with the specified name.
        /// </summary>
        /// <param name="name">The type name.</param>
        private CodeType GetTypeByName(string name)
        {
            int moduleIndex = name.IndexOf('!');

            if (moduleIndex > 0)
            {
                if (string.Compare(name.Substring(0, moduleIndex), Name, true) != 0)
                {
                    throw new ArgumentException("Type name contains wrong module name. Don't add it manually, it will be added automatically.");
                }

                name = name.Substring(moduleIndex + 1);
            }

            if (name == CodeType.NakedPointerCodeTypeName)
            {
                return new NakedPointerCodeType(this);
            }

            CodeType codeType = null;

            if (clrModule.Cached && ClrModule != null)
            {
                codeType = GetClrTypeByName(name);
            }

            try
            {
                if (codeType == null)
                {
                    uint typeId = Context.SymbolProvider.GetTypeId(this, name);

                    if (Context.SymbolProvider.GetTypeTag(this, typeId) != Engine.Native.SymTag.Compiland)
                    {
                        codeType = TypesById[typeId];
                    }
                }
            }
            catch
            {
            }

            if (ClrModule != null)
            {
                codeType = GetClrTypeByName(name);
            }

            if (codeType == null)
            {
                throw new Exception(string.Format("Type '{0}' wasn't found", name));
            }

            return codeType;
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AppDomain" /> class.
 /// </summary>
 /// <param name="runtime">The runtime.</param>
 /// <param name="clrAppDomain">The CLR application domain.</param>
 internal AppDomain(Runtime runtime, Microsoft.Diagnostics.Runtime.ClrAppDomain clrAppDomain)
 {
     Runtime = runtime;
     ClrAppDomain = clrAppDomain;
     modules = SimpleCache.Create(() => Runtime.ClrRuntime.Modules.Where(m => m.AppDomains.Contains(ClrAppDomain)).Select(mm => Runtime.Process.ClrModuleCache[mm]).ToArray());
 }
Ejemplo n.º 52
0
 public AuthTokenManager()
 {
     _localData = new SimpleCache<AuthTokenDto>();
 }
Ejemplo n.º 53
0
 public void CacheAuthTokens(SimpleCache<AuthTokenDto> localData)
 {
     if (localData != null)
         _localData = localData;
 }
    public LiveEffect ParentEffectIf(string alias, Transform parent, Vector2 position, float rotation, EffectConditionDelegate condition)
    {
        SimpleCache<ParticleSystem> cache;

        if (EffectsCached.ContainsKey(alias))
            cache = EffectsCached[alias];
        else
        {
            cache = new SimpleCache<ParticleSystem>(GetEffect(alias).System, 3);
            EffectsCached.Add(alias, cache);
        }

        LiveEffect parentedEffect = new LiveEffect
        {
            Cache = cache,
            Condition = condition,
            Parent = parent,
            Position = position,
            Rotation = rotation
        };

        _liveEffects.Add(parentedEffect);

        return parentedEffect;
    }
Ejemplo n.º 55
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);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Gets the local variables.
        /// </summary>
        private VariableCollection GetLocals()
        {
            if (clrStackFrame.Cached && ClrStackFrame != null)
            {
                if (ClrStackFrame.Locals.Count > 0)
                {
                    return ConvertClrToVariableCollection(ClrStackFrame.Locals, GetClrLocalsNames());
                }
                else
                {
                    return new VariableCollection(new Variable[0]);
                }
            }

            VariableCollection locals = null;

            try
            {
                locals = Context.SymbolProvider.GetFrameLocals(this, false);
            }
            catch (Exception)
            {
            }

            if ((locals == null || locals.Count == 0) && ClrStackFrame != null && ClrStackFrame.Locals.Count > 0)
            {
                locals = ConvertClrToVariableCollection(ClrStackFrame.Locals, GetClrLocalsNames());
            }

            return locals;
        }
 public ObjectResultTreeItem(object obj, Type objType, string name, ImageSource image, InteractiveResultVisualizer interactiveResultVisualizer)
 {
     this.obj = obj;
     this.objType = objType;
     this.interactiveResultVisualizer = interactiveResultVisualizer;
     Name = name;
     Image = image;
     valueString = SimpleCache.Create(() => Value.ToString());
 }
Ejemplo n.º 58
0
        public void Sliding_expiration_should_work_as_expected()
        {
            /* Arrange */
            var c = new SimpleCache<string, string>();
            string key = "Val1";

            /* Act */
            c.Add(key, "TheValue", 10, true);

            Thread.Sleep(5);
            string val1 = c[key];

            Thread.Sleep(5);
            string val2 = c[key];

            Thread.Sleep(11);
            string val3 = c[key];

            /* Assert */
            val1.Should().Be("TheValue");
            val2.Should().Be("TheValue");
            val3.Should().BeNull();
        }
Ejemplo n.º 59
0
        public object Convert( object value, Type targetType, object parameter, CultureInfo culture )
        {
            if ( value is int == false )
                return null;

            if ( _DefaultBitmap == null )
            {
                _DefaultBitmap = new BitmapImage();
                _DefaultBitmap.BeginInit();
                _DefaultBitmap.UriSource = new Uri("pack://application:,,,/SpyUO;component/Images/Missing.png");
                _DefaultBitmap.EndInit();
            }

            if ( _EnhancedTexture != null )
            {
                if ( Globals.Instance.EnhancedAssets == null )
                    _EnhancedTexture.Clear();
                else
                    return _EnhancedTexture.Get( (int) value );
            }
            else
            {
                if ( Globals.Instance.EnhancedAssets != null )
                {
                    _EnhancedTexture = new SimpleCache<int, TextureFile>( 100 );
                    _EnhancedTexture.Getter += new SimpleCacheGetter<int, TextureFile>( EnhancedTexture_Getter );
                    return _EnhancedTexture.Get( (int) value );
                }
            }

            if ( _LegacyTexture != null )
            {
                if ( Globals.Instance.LegacyAssets == null )
                    _LegacyTexture.Clear();
                else
                    return _LegacyTexture.Get( (int) value );
            }
            else
            {
                if ( Globals.Instance.LegacyAssets != null )
                {
                    _LegacyTexture = new SimpleCache<int, TextureFile>( 100 );
                    _LegacyTexture.Getter += new SimpleCacheGetter<int, TextureFile>( LegacyTexture_Getter );
                    return _LegacyTexture.Get( (int) value );
                }
            }

            return GetDefaultTexture( (int) value );
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Gets the function arguments.
        /// </summary>
        private VariableCollection GetArguments()
        {
            if (clrStackFrame.Cached && ClrStackFrame != null)
            {
                if (ClrStackFrame.Arguments.Count > 0)
                {
                    return ConvertClrToVariableCollection(ClrStackFrame.Arguments, GetClrArgumentsNames());
                }
                else
                {
                    return new VariableCollection(new Variable[0]);
                }
            }

            VariableCollection arguments = null;

            try
            {
                arguments = Context.SymbolProvider.GetFrameLocals(this, true);
            }
            catch (Exception)
            {
            }

            if ((arguments == null || arguments.Count == 0) && ClrStackFrame != null && ClrStackFrame.Arguments.Count > 0)
            {
                arguments = ConvertClrToVariableCollection(ClrStackFrame.Arguments, GetClrArgumentsNames());
            }

            return arguments;
        }