public bool TryGetCacheEntry(object key, out ICacheEntry value) { if (this.cache.ContainsKey(key)) { value = this.cache[key]; return true; } else { value = null; return false; } }
public void RemoveByPattern(string pattern) // From Documentation { // Remove the Cache by the passesed pattern at run time, Reflection provides us manipulation on objects at run time var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); // Find Entries Collection type of MemoryCache in Memory - .Net Documentation var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; // Get Values of EntriesCollection dynamically List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { // Search every Cache item in Cache Entries Collection ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } // Regex : Regular Expression var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); // Rule, Matching foreach (var key in keysToRemove) { // In the Cache data search the keys are matched with the value and remove them all _memoryCache.Remove(key); // Remove from memory } }
//çalışma anında bellekten silmeye yarar.(reflection ile yapılır.) public void RemoveByPattern(string pattern) { var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
public void RemoveByPattern(string pattern) //RemoveByPattern çalışma anında bellekten silmeye yarıyor. { var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); //Bir şey cache lendiğinde EntriesCollection diye birşeyin içine atılıyor.//Git bellekteki EntriesCollection ı bul var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; //definitionu memorycacahe olanları bul List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); //herbir cache elemanını gez cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
public void RemoveByPattern(string pattern) //çalışma anında bellekten silmeye yarıyor { var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); //git belleğe bak entrinscollection bul _memory cache olanı bul her birini gez kurala uyanları listele foreach le gez ve kaldır. var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
public static void SetEditValue(ICacheEntry field, object value, string result) { var valueType = field.Type(); object converted; if (valueType == typeof(string)) { converted = result; } else { var typeConverter = TomlTypeConverter.GetConverter(valueType); converted = typeConverter != null?typeConverter.ConvertToObject(result, valueType) : Convert.ChangeType(result, valueType); } if (!Equals(converted, value)) { field.SetValue(converted); } }
public void RemoveByPattern(string pattern) { var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); // BindingFlags=> https://docs.microsoft.com/en-us/dotnet/api/system.reflection.bindingflags?redirectedfrom=MSDN&view=net-5.0 var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; //https://github.com/dotnet/runtime/issues/36026 List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
private async Task <string> GetAccessTokenFromAuthServerAsync(ICacheEntry cacheEntry) { TokenResponse tokenResponse = await _httpClient.RequestClientCredentialsTokenAsync( new ClientCredentialsTokenRequest { Address = _fhirClientSettings.AuthenticationTokenEndpoint, ClientId = _fhirClientSettings.AuthenticationClientId, ClientSecret = _fhirClientSettings.AuthenticationClientSecret, Scope = _fhirClientSettings.AuthenticationScope }); if (tokenResponse.IsError) { throw new Exception($"Failed to retrieve access token: {tokenResponse.Error}"); } cacheEntry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(tokenResponse.ExpiresIn - 30); return(tokenResponse.AccessToken); }
private void DrawSingleContentEntry(ICacheEntry entry) { GUILayout.BeginHorizontal(_inspectorRecordHeight); { try { GUILayout.Label(entry.TypeName(), _inspectorTypeWidth); var value = entry.GetValue(); if (entry.CanEnterValue() || value is Exception) { DrawVariableNameEnterButton(entry); } else { GUILayout.TextArea(entry.Name(), GUI.skin.label, _inspectorNameWidth); } if (entry.CanSetValue() && ToStringConverter.CanEditValue(entry, value)) { DrawEditableValue(entry, value, GUILayout.ExpandWidth(true)); } else { GUILayout.TextArea(ToStringConverter.ObjectToString(value), GUI.skin.label, GUILayout.ExpandWidth(true)); } if (DnSpyHelper.IsAvailable && GUILayout.Button("^", _dnSpyButtonOptions)) { DnSpyHelper.OpenInDnSpy(entry); } } catch (Exception ex) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, $"Failed to draw setting {entry?.Name()} - {ex.Message}"); GUILayout.TextArea(ex.Message, GUI.skin.label, GUILayout.ExpandWidth(true)); } } GUILayout.EndHorizontal(); }
private void DrawVariableNameEnterButton(ICacheEntry field) { if (_alignedButtonStyle == null) { _alignedButtonStyle = new GUIStyle(GUI.skin.button) { alignment = TextAnchor.MiddleLeft, wordWrap = true }; } if (GUILayout.Button(field.Name(), _alignedButtonStyle, _inspectorNameWidth)) { var val = field.EnterValue(); if (val != null) { var entry = val as InspectorStackEntryBase ?? new InstanceStackEntry(val, field.Name(), field); Push(entry, IsContextClick()); } } }
public static bool Prefix(ICacheEntry entry) { switch (entry.TypeName()) { case "UnityEngine.Color": ColorFix(entry); break; case "UnityEngine.Texture2D": Texture2DFix(entry); break; case "UnityEngine.Sprite": SpriteFix(entry); break; default: break; } return(true); }
private async Task <T> GetContentAsync <T>(ICacheEntry entry, string path, Func <IFileInfo, Task <T> > getContent) { var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext); path = urlHelper.Content(path); var fileProvider = _hostingEnvironment.WebRootFileProvider; var changeToken = fileProvider.Watch(path); entry.SetPriority(CacheItemPriority.NeverRemove); entry.AddExpirationToken(changeToken); var file = fileProvider.GetFileInfo(path); if (file == null || !file.Exists) { return(default(T)); } return(await getContent(file)); }
public void RemoveByPattern(string pattern)//çalıştırdığımız metodun namespacei,ismi, method ismi, parametrelerine göre key oluşturuyor. //key daha önceden varsa cacheden al yoksa veritabanından al. { var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
public void RemoveByPattern(string pattern) { //çalışma ananda bellekten silmeye yarıyor >>Reflection //cache dataların bellekte tutulduğu yer >>EntriesCollection var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } //Regex bir string ifadenin (metin) belirli kurallara uyumluluğunu kontrol etmeye ve düzenlemeye yarar. var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
public void RemoveByPattern(string pattern)//! ona verdi. patterna göre silme işlemi yapıcak -- çalışma anında bellekten silmeye yarıyor { //git belleğe bak , bellekte memorycache türünde olan enti.collec. ı bul var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic;//definition ı memory cache olanları bul List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection)//her bir cache elemanını gez { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } //şu kurala uyanlar var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); //pattern oluşturma var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); //benim gönderd. değerlerden uyan varsa keystoRemove a atıcak foreach (var key in keysToRemove) //keylerini buluyorum ve remove ediyorum { _memoryCache.Remove(key); } }
public static async Task <T> GetOrCreateAsync <T>(string cacheKey, Func <string, Task <T> > factory) { // async version of GetOrCreate if (!TryGetValue(cacheKey, out object value)) { value = await factory(cacheKey); // NOT thread locked. but safe-ish. lock (_cacheKeys) { // Debug.Assert(!_cacheKeys.Contains(cacheKey)); ICacheEntry entry = CreateEntry(cacheKey); entry.Value = value; entry.Dispose(); // This is what actually adds it to the cache. Weird. } } else { // Debug.Assert(_cacheKeys.Contains(cacheKey)); } return((T)value); }
public void WithAbsoluteExpirationRelativeToNowOption() { using MockMemoryCache mockMemoryCache = MockMemoryCache.Default; dynamic instance = TestHelpers.CreateInstance <MemoryCacheEntryOptionsTestClass>(MemoryCacheEntryOptionsTests.TestResult.Assembly, mockMemoryCache); dynamic result = instance.WithAbsoluteExpirationRelativeToNowOption(1); ICacheEntry lastCreatedCacheEntry = mockMemoryCache.LastCreatedCacheEntry; Assert.Equal(TimeSpan.FromSeconds(1), lastCreatedCacheEntry.AbsoluteExpirationRelativeToNow); Assert.Null(lastCreatedCacheEntry.SlidingExpiration); Assert.Equal(CacheItemPriority.Normal, lastCreatedCacheEntry.Priority); result = instance.WithAbsoluteExpirationRelativeToNowOption(1); Thread.Sleep(1000); result = instance.WithAbsoluteExpirationRelativeToNowOption(1); Assert.Equal(2, mockMemoryCache.CountSets); Assert.Equal(3, mockMemoryCache.CountGets); }
private static async Task <T> CacheItem <T>(this ICacheEntry cacheEntry, IMemoryCache memoryCache, string key, IObservable <T> factory, int timeout, Func <int, TimeSpan> time = null) { time ??= (i => TimeSpan.FromMinutes(i)); cacheEntry.AbsoluteExpirationRelativeToNow = time(timeout); var result = await factory; var tokenSource = new CancellationTokenSource(time(timeout - 5)); TokenSources.TryAdd(key, tokenSource); var expirationToken = new CancellationChangeToken(tokenSource.Token); cacheEntry.ExpirationTokens.Add(expirationToken); cacheEntry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration() { EvictionCallback = (o, value, reason, state) => { memoryCache.GetOrCreate(key, entry => Observable.Defer(() => factory), timeout, time).ObserveOn(ImmediateScheduler.Instance) .SubscribeOn(ImmediateScheduler.Instance).Subscribe(); } }); return(result); }
public void RemoveByPattern(string pattern) { //Verdiğimiz pattern'e göre silme işlemi yapacak //Reflection - koda çalışma anında müdahale yapmak var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); //Bellekteki EntriesCollection bulur var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; //defination _memoryCache olanları bul List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) //Herbir Cache elemanını gez { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); //Pattern oluşturma var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); //Bu kurala uyanlar foreach (var key in keysToRemove) { _memoryCache.Remove(key); //Sileceğim değerler } }
public void ConverterCacheEntriesTests() { ICache cache = InstantiateCache(); IConverter cDown = new ConvertDown(); IConverter cUp = new ConvertUp(); for (int i = 0; i < 3; i++) { cache.Add(cDown.Convert(i), cDown.Convert(i + 1)); } ICollection convEntries = ConverterCollections.GetCacheEntries(cache.Entries, cUp, cDown, cUp, cDown); Assert.IsNotNull(convEntries); Assert.AreEqual(convEntries.Count, 3); ArrayList list = new ArrayList(convEntries); Assert.AreEqual(list.Count, 3); object o = list[0]; Assert.IsNotNull(o); Assert.IsInstanceOf(typeof(ICacheEntry), o); ICacheEntry entry = o as ICacheEntry; Assert.IsNotNull(entry); Assert.AreEqual(Convert.ToInt32(entry.Key) + 1, Convert.ToInt32(entry.Value)); IEnumerator enumerator = convEntries.GetEnumerator(); Assert.IsNotNull(enumerator); enumerator.Reset(); Assert.IsTrue(enumerator.MoveNext()); o = enumerator.Current; Assert.IsNotNull(o); Assert.IsInstanceOf(typeof(ICacheEntry), o); entry = o as ICacheEntry; Assert.IsNotNull(entry); Assert.AreEqual(Convert.ToInt32(entry.Key) + 1, Convert.ToInt32(entry.Value)); }
private SemaphoreSlim GetSemaphore(string key, string operationId, ILogger?logger) { object _semaphore; if (_lockCache.TryGetValue(key, out _semaphore)) { return((SemaphoreSlim)_semaphore); } lock (_lockPool[GetLockIndex(key)]) { if (_lockCache.TryGetValue(key, out _semaphore)) { return((SemaphoreSlim)_semaphore); } _semaphore = new SemaphoreSlim(1, 1); using ICacheEntry entry = _lockCache.CreateEntry(key); entry.Value = _semaphore; entry.SlidingExpiration = _slidingExpiration; entry.RegisterPostEvictionCallback((key, value, reason, state) => { try { ((SemaphoreSlim)value).Dispose(); } catch (Exception exc) { if (logger?.IsEnabled(LogLevel.Warning) ?? false) { logger.LogWarning(exc, "FUSION (K={CacheKey}): an error occurred while trying to dispose a SemaphoreSlim in the reactor", key); } } }); return((SemaphoreSlim)_semaphore); } }
private static Func <object, string> CreateMap(ICacheEntry cacheEntry) { var sourceType = cacheEntry.Key as Type; var properties = sourceType .GetProperties(BindingFlags.Instance | BindingFlags.Public) .Where(p => p.CanRead) .OrderBy(p => p.Name); // Ensure we get a consistent result for unit tests var formatString = String.Join("&", properties.Select((p, i) => $"{p.Name}={{{i}}}")); var formatMethod = typeof(String).GetMethod(nameof(String.Format), new[] { typeof(string), typeof(object[]) }); var parameter = Expression.Parameter(typeof(object)); var castParameter = sourceType == typeof(object) ? (Expression)parameter : Expression.Convert(parameter, sourceType); var propertyAccessors = properties .Select(p => Expression.Property(castParameter, p)) .Select(p => { if (p.Type == typeof(bool)) { var toString = typeof(Boolean).GetMethod(nameof(Boolean.ToString), Type.EmptyTypes); var toLower = typeof(String).GetMethod(nameof(String.ToLower), Type.EmptyTypes); return((Expression)Expression.Call(Expression.Call(p, toString), toLower)); } if (p.Type != typeof(object)) { return(Expression.Convert(p, typeof(object))); } return(p); }); var arguments = Expression.NewArrayInit(typeof(object), propertyAccessors); var call = Expression.Call(formatMethod, Expression.Constant(formatString), arguments); return(Expression.Lambda <Func <object, string> >(call, parameter).Compile()); }
public void RemoveByPattern(string pattern) { //reflection ile çalışma anında elimizde bulunan nesnelere ve hatta olmayanları da yeniden oluşturmak gibi çalışmalar yapabiliriz //kodu çalışma anında oluşturma ,çalışma anında müdahale etme şeylerini reflection ile yapıyoruz. var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic; List <ICacheEntry> cacheCollectionValues = new List <ICacheEntry>(); foreach (var cacheItem in cacheEntriesCollection) { ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null); cacheCollectionValues.Add(cacheItemValue); } var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase); var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList(); foreach (var key in keysToRemove) { _memoryCache.Remove(key); } }
private static void DrawGenericEditableValue(ICacheEntry field, object value, params GUILayoutOption[] layoutParams) { var isBeingEdited = _currentlyEditingTag == field; var text = isBeingEdited ? _currentlyEditingText : ToStringConverter.GetEditValue(field, value); var result = GUILayout.TextField(text, layoutParams); if (!Equals(text, result) || isBeingEdited) { if (_userHasHitReturn) { _currentlyEditingTag = null; _userHasHitReturn = false; ToStringConverter.SetEditValue(field, value, result); } else { _currentlyEditingText = result; _currentlyEditingTag = field; } } }
/// <summary> /// Applies the values of an existing <see cref="MemoryCacheEntryOptions"/> to the entry. /// </summary> /// <param name="entry">The <see cref="ICacheEntry"/>.</param> /// <param name="options">Set the values of these options on the <paramref name="entry"/>.</param> /// <returns>The <see cref="ICacheEntry"/> for chaining.</returns> public static ICacheEntry SetOptions(this ICacheEntry entry, MemoryCacheEntryOptions options) { ThrowHelper.ThrowIfNull(options); entry.AbsoluteExpiration = options.AbsoluteExpiration; entry.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow; entry.SlidingExpiration = options.SlidingExpiration; entry.Priority = options.Priority; entry.Size = options.Size; foreach (IChangeToken expirationToken in options.ExpirationTokens) { entry.AddExpirationToken(expirationToken); } foreach (PostEvictionCallbackRegistration postEvictionCallback in options.PostEvictionCallbacks) { entry.RegisterPostEvictionCallback(postEvictionCallback.EvictionCallback !, postEvictionCallback.State); } return(entry); }
public async Task <IBitmap> GetImageAsync(Uri uri, CancellationToken cancellationToken = default) { if (this.memoryCache.TryGetValue(uri, out IBitmap image)) { return(image); } HttpResponseMessage response = await this.httpClient.GetAsync(uri, cancellationToken).ConfigureAwait(false); if (response.IsSuccessStatusCode) { var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); image = this.bitmapFactory.Create(responseStream); using ICacheEntry cacheEntry = this.memoryCache.CreateEntry(uri); cacheEntry.SetValue(image); cacheEntry.SetSize(responseStream.Length); } return(image); }
private async Task <string> GetAgsToken(ICacheEntry entry) { AgsTokenResponse tokenData = null; try { tokenData = await AgsServer.GenerateToken(_options.Scheme, _options.Host, _options.Port, _options.Instance, _options.Username, _options.Password); } catch { //failed to get token the usual way. } try { //Try the Network Collector way(copied code from Dinesh) if (tokenData is null) { var baseUrl = $"{_options.Scheme}://{_options.Host}:{_options.Port}/{_options.Instance}"; var op = new Operation(baseUrl); var referer = baseUrl; var token = await op.Authenticate(_options.Username, _options.Password, null, referer); } } catch (Exception e) { Console.WriteLine(e); throw; } // set cache entry expiry var expires = FromUnixTime(tokenData.expires); entry.AbsoluteExpiration = expires.AddMinutes(-1); return(tokenData.token); }
public static bool CanEditValue(ICacheEntry field, object value) { var valueType = field.Type(); if (valueType == null) { return(false); } if (valueType == typeof(string)) { return(true); } if (_canCovertCache.TryGetValue(valueType, out var stored)) { return(stored); } if (TomlTypeConverter.GetConverter(valueType) != null) { _canCovertCache[valueType] = true; return(true); } try { var converted = ToStringConverter.ObjectToString(value); var _ = Convert.ChangeType(converted, valueType); _canCovertCache[valueType] = true; return(true); } catch { _canCovertCache[valueType] = false; return(false); } }
/// <summary> /// Adds an object to distributed cache /// </summary> /// <param name="key">Cache Key</param> /// <param name="value">Cache object</param> /// <param name="options">Distributed cache options. <see cref="ExtendedDistributedCacheEntryOptions"/></param> public void Set(string key, byte[] value, ExtendedDistributedCacheEntryOptions options) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } using (ICacheEntry cacheEntry = CreateEntry(key)) { var memoryCacheEntryOptions = GetMemoryCacheEntryOptions(options, value.LongLength); cacheEntry.SetOptions(memoryCacheEntryOptions); if (memoryCacheEntryOptions.AbsoluteExpiration != null) { cacheEntry.SetAbsoluteExpiration(memoryCacheEntryOptions.AbsoluteExpiration.Value); } if (memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow != null) { cacheEntry.SetAbsoluteExpiration(memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow.Value); } if (memoryCacheEntryOptions.SlidingExpiration != null) { cacheEntry.SetSlidingExpiration(memoryCacheEntryOptions.SlidingExpiration.Value); } cacheEntry.SetPriority(memoryCacheEntryOptions.Priority); cacheEntry.SetSize(value.LongLength); cacheEntry.SetValue(value); } }
public void ConverterCacheEnumeratorTests() { ICache cache = InstantiateCache(); IConverter conv = new ConvertDown(); for (int i = 0; i < 3; i++) { cache.Add(i, i + 1); } ICacheEnumerator cacheEnumerator = cache.GetEnumerator(); ICacheEnumerator convEnum = ConverterCollections.GetCacheEnumerator(cacheEnumerator, conv, conv, conv); Assert.IsNotNull(convEnum); Assert.IsTrue(convEnum.MoveNext()); convEnum.MoveNext(); convEnum.MoveNext(); Assert.IsFalse(convEnum.MoveNext()); convEnum.Reset(); Assert.IsTrue(convEnum.MoveNext()); object o = convEnum.Current; ICacheEntry entry = convEnum.Entry; Assert.AreEqual(o, entry); Assert.AreEqual(entry.Key, convEnum.Key); Assert.AreEqual(entry.Value, convEnum.Value); Assert.AreEqual(entry.Key, conv.Convert(cacheEnumerator.Key)); Assert.AreEqual(entry.Value, conv.Convert(cacheEnumerator.Value)); Assert.IsInstanceOf(typeof(ConverterCollections.ConverterCacheEnumerator), convEnum); ConverterCollections.ConverterCacheEnumerator cce = convEnum as ConverterCollections.ConverterCacheEnumerator; Assert.IsNotNull(cce); Assert.AreEqual(cce.ConverterKeyUp, conv); Assert.AreEqual(cce.ConverterValueUp, conv); }
public override void OnClearCachedValue(ICacheEntry entry) { int rowIndex; int columnIndex; EvaluationCell cell = (EvaluationCell)_formulaCellsByCacheEntry[entry]; if (cell == null) { Loc loc = (Loc)_plainCellLocsByCacheEntry[entry]; if (loc == null) { throw new InvalidOperationException("can't find cell or location"); } rowIndex = loc.RowIndex; columnIndex = loc.ColumnIndex; } else { rowIndex = cell.RowIndex; columnIndex = cell.ColumnIndex; } log("Clear", rowIndex, columnIndex, entry.GetValue()); }
public virtual void OnChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, IEvaluationCell cell, ICacheEntry entry) { // do nothing }
public override void OnStartEvaluate(IEvaluationCell cell, ICacheEntry entry) { _countCacheMisses++; }
public virtual void OnReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry) { // do nothing }
public override void OnStartEvaluate(IEvaluationCell cell, ICacheEntry entry) { _evalCount++; }
public virtual void OnStartEvaluate(IEvaluationCell cell, ICacheEntry entry) { // do nothing }
public virtual void OnClearDependentCachedValue(ICacheEntry entry, int depth) { // do nothing }
public virtual void SortDependentCachedValues(ICacheEntry[] entries) { // do nothing }
public virtual void OnClearCachedValue(ICacheEntry entry) { // do nothing }
public virtual void OnEndEvaluate(ICacheEntry entry, ValueEval result) { // do nothing }