private static void DrawColor(ICacheEntry obj, object value) { var setting = (Color)value; if (!_colorCache.TryGetValue(obj, out var cacheEntry)) { cacheEntry = new ColorCacheEntry { Tex = new Texture2D(14, 14, TextureFormat.ARGB32, false), Last = setting }; cacheEntry.Tex.FillTexture(setting); _colorCache[obj] = cacheEntry; } GUILayout.Label("R", GUILayout.ExpandWidth(false)); setting.r = GUILayout.HorizontalSlider(setting.r, 0f, 1f, GUILayout.ExpandWidth(true)); GUILayout.Label("G", GUILayout.ExpandWidth(false)); setting.g = GUILayout.HorizontalSlider(setting.g, 0f, 1f, GUILayout.ExpandWidth(true)); GUILayout.Label("B", GUILayout.ExpandWidth(false)); setting.b = GUILayout.HorizontalSlider(setting.b, 0f, 1f, GUILayout.ExpandWidth(true)); GUILayout.Label("A", GUILayout.ExpandWidth(false)); setting.a = GUILayout.HorizontalSlider(setting.a, 0f, 1f, GUILayout.ExpandWidth(true)); GUILayout.Space(4); GUI.changed = false; var isBeingEdited = _currentlyEditingTag == obj; var text = isBeingEdited ? _currentlyEditingText : TomlTypeConverter.ConvertToString(setting, typeof(Color)); text = GUILayout.TextField(text, GUILayout.Width(75)); if (GUI.changed && !text.Equals(TomlTypeConverter.ConvertToString(setting, typeof(Color))) || isBeingEdited) { if (_userHasHitReturn) { _currentlyEditingTag = null; _userHasHitReturn = false; try { obj.SetValue(TomlTypeConverter.ConvertToValue <Color>(text)); } catch { } } else { _currentlyEditingText = text; _currentlyEditingTag = obj; } } if (setting != cacheEntry.Last) { obj.SetValue(setting); cacheEntry.Tex.FillTexture(setting); cacheEntry.Last = setting; } GUILayout.Label(cacheEntry.Tex, GUILayout.ExpandWidth(false)); }
private void DrawEditableValue(ICacheEntry field, object value, params GUILayoutOption[] layoutParams) { var isBeingEdited = _currentlyEditingTag == field; var text = isBeingEdited ? _currentlyEditingText : EditorUtilities.ExtractText(value); var result = GUILayout.TextField(text, layoutParams); if (!Equals(text, result) || isBeingEdited) { if (_userHasHitReturn) { _currentlyEditingTag = null; _userHasHitReturn = false; try { var converted = Convert.ChangeType(result, field.Type()); if (!Equals(converted, value)) { field.SetValue(converted); } } catch (Exception ex) { RuntimeUnityEditorCore.Logger.Log(LogLevel.Error, "[Inspector] Failed to set value - " + ex.Message); } } else { _currentlyEditingText = result; _currentlyEditingTag = field; } } }
async Task WriteToCache <T>(ICacheEntry entry, string key, T obj) { try { if (!UseDistributedCache) { entry.SetOptions(new MemoryCacheEntryOptions() { AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds) }); // Set expiration tokens entry.ExpirationTokens.Add(_cacheDependency.GetToken(key)); entry.SetValue(obj); // need to manually call dispose instead of having a using // statement in case the factory passed in throws, in which case we // do not want to add the entry to the cache entry.Dispose(); //_memoryCache.Set(entry.Key.ToString(), obj, DateTimeOffset.UtcNow.AddSeconds(expirationInSeconds)); return; } var toStore = JsonConvert.SerializeObject(obj); await _distributedCache.SetAsync(key, Encoding.UTF8.GetBytes(toStore), new DistributedCacheEntryOptions { AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds) }); } catch { // DistributedCache storage failed. Fail over to MemoryCache. entry.SetOptions(new MemoryCacheEntryOptions() { AbsoluteExpiration = DateTime.UtcNow.AddSeconds(ExpirationInSeconds) }); // Set expiration tokens entry.ExpirationTokens.Add(_cacheDependency.GetToken(key)); entry.SetValue(obj); // need to manually call dispose instead of having a using // statement in case the factory passed in throws, in which case we // do not want to add the entry to the cache entry.Dispose(); //_memoryCache.Set(key, obj, DateTimeOffset.UtcNow.AddSeconds(expirationInSeconds)); } }
public static void XToCache(XObject xthis, IMemoryCache cache, ISession session, IStringLocalizer xstring) { string key = session.GetString("this"); _XThisCache xthisCache = new _XThisCache(xthis, xstring); using (ICacheEntry entry = cache.CreateEntry(key)) { entry.SetValue(xthisCache); } }
private static void DrawBoolField(ICacheEntry setting, object o) { var boolVal = (bool)setting.GetValue(); var result = GUILayout.Toggle(boolVal, boolVal ? "True" : "False", GUILayout.ExpandWidth(true)); if (result != boolVal) { setting.SetValue(result); } }
public async Task Login(string request_token) { string tokenExchangeEndpoint = $"{this._configuration.GetValue<string>("kiteApiBaseUrl")}{this._configuration.GetValue<string>("kiteAccessTokenUrl")}"; KiteAccessTokenResponseRoot kiteAccessTokenResponseRoot = null; bool cacheFetchResult = this._cache.TryGetValue <KiteAccessTokenResponseRoot>("kite_access_token", out kiteAccessTokenResponseRoot); if (!cacheFetchResult) { try { string accessTokenRequest = $"{this._configuration.GetValue<string>("kiteApiKey")}{request_token}{this._configuration.GetValue<string>("kiteApiSecret")}"; string accessTokenRequestHash = CommonFunctions.ComputeSha256Hash(accessTokenRequest); var param = new Dictionary <string, dynamic> { { "api_key", this._configuration.GetValue <string>("kiteApiKey") }, { "request_token", request_token }, { "checksum", accessTokenRequestHash } }; string paramString = String.Join("&", param.Select(x => CommonFunctions.BuildParam(x.Key, x.Value))); HttpContent accessTokenRequestContent = new StringContent(paramString, Encoding.UTF8, "application/x-www-form-urlencoded"); accessTokenRequestContent.Headers.Add("X-Kite-Version", "3"); HttpResponseMessage access_token_response = await this._httpClient.PostAsync(tokenExchangeEndpoint, accessTokenRequestContent); if (access_token_response.IsSuccessStatusCode) { Stream responseStream = await access_token_response.Content.ReadAsStreamAsync(); var respose = new StreamReader(responseStream).ReadToEnd(); kiteAccessTokenResponseRoot = JsonSerializer.Deserialize <KiteAccessTokenResponseRoot>(respose); MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions(); cacheOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(8)); cacheOptions.Priority = CacheItemPriority.NeverRemove; cacheOptions.RegisterPostEvictionCallback(new PostEvictionDelegate(this.CacheEvictionCallback)); cacheOptions.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot)); using (ICacheEntry cacheEntry = this._cache.CreateEntry((object)"kite_access_token")) { cacheEntry.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot)); cacheEntry.SetOptions(cacheOptions); cacheEntry.SetValue(kiteAccessTokenResponseRoot); } } else { this._logger.LogError(access_token_response.ReasonPhrase); } } catch (Exception ex) { this._logger.LogError(ex.Message); throw new IntelliTradeException("An error occurred while trying to get access token from Kite.", ex); } } }
public static bool Prefix(ICacheEntry field, object value) { if (field.TypeName() == "System.Boolean") { if ((bool)value != GUILayout.Toggle((bool)value, ToStringConverter.GetEditValue(field, value))) { field.SetValue(!(bool)value); } return(false); } return(true); }
private static void DrawVector2(ICacheEntry obj, object value) { var setting = (Vector2)value; var copy = setting; setting.x = DrawSingleVectorSlider(setting.x, "X"); setting.y = DrawSingleVectorSlider(setting.y, "Y"); if (setting != copy) { obj.SetValue(setting); } }
public static TItem GetOrCreate <TItem>(this ICustomCache cache, object key, Func <ICacheEntry, TItem> factory) { if (!cache.TryGetValue(key, out object result)) { ICacheEntry entry = cache.CreateEntry(key); result = factory(entry); entry.SetValue(result); entry.Dispose(); } return((TItem)result); }
private static TItem GetOrCreate <TItem>(this IMemoryCache cache, object key, Func <ICacheEntry, TItem> factory) { object obj; if (!cache.TryGetValue(key, out obj)) { ICacheEntry entry = cache.CreateEntry(key); obj = (object)factory(entry); entry.SetValue(obj); entry.Dispose(); } return((TItem)obj); }
private async Task <IGitHubClient> createNewGitHubClient(ICacheEntry cacheEntry, long installationId) { var gitHubClient = new GitHubClient(new Octokit.ProductHeaderValue("Ahk")) { Credentials = new Credentials(await getInstallationToken(installationId)) }; gitHubClient.SetRequestTimeout(TimeSpan.FromSeconds(15)); cacheEntry.SetValue(gitHubClient); cacheEntry.SetAbsoluteExpiration(TimeSpan.FromMinutes(5)); return(gitHubClient); }
private static void DrawQuaternion(ICacheEntry obj, object value) { var setting = (Quaternion)value; var copy = setting; setting.x = DrawSingleVectorSlider(setting.x, "X"); setting.y = DrawSingleVectorSlider(setting.y, "Y"); setting.z = DrawSingleVectorSlider(setting.z, "Z"); setting.w = DrawSingleVectorSlider(setting.w, "W"); if (setting != copy) { obj.SetValue(setting); } }
protected override bool OnSetValue(object newValue) { if (!FieldInfo.IsInitOnly) { FieldInfo.SetValue(_instance, newValue); // Needed for structs to propagate changes back to the original field/prop if (_parent != null && _parent.CanSetValue()) { _parent.SetValue(_instance); } return(true); } return(false); }
public static TItem GetOrCreate <TItem>(this IMemoryCache cache, object key, Func <ICacheEntry, TItem> factory) { if (!cache.TryGetValue(key, out object result)) { ICacheEntry entry = cache.CreateEntry(key); result = factory(entry); entry.SetValue(result); // need to manually call dispose instead of having a using // in case the factory passed in throws, in which case we // do not want to add the entry to the cache entry.Dispose(); } return((TItem)result); }
public static IStringLocalizer XToCache(XAssembly xassembly, IMemoryCache cache, ISession session, IStringLocalizerFactory factory) { AssemblyName name = new AssemblyName(xassembly.XFullName); string baseName = string.Format("{0}.Properties.Resources", name.Name); IStringLocalizer stringLocalizer = factory.Create(baseName, name.Name); _XStringModel xstring = new _XStringModel(stringLocalizer); string key = typeof(_XStringModel).FullName + "#" + xstring.GetHashCode(); using (ICacheEntry entry = cache.CreateEntry(key)) { entry.SetValue(xstring); } session.SetString("string", key); return(stringLocalizer); }
private static void DrawFlagsField(ICacheEntry setting, IList enumValues, object fieldValue) { var currentValue = Convert.ToInt64(fieldValue); var allValues = enumValues.Cast <Enum>().Select(x => new { name = x.ToString(), val = Convert.ToInt64(x) }).ToArray(); // Vertically stack Horizontal groups of the options to deal with the options taking more width than is available in the window GUILayout.BeginVertical(GUILayout.ExpandWidth(true)); { for (var index = 0; index < allValues.Length;) { GUILayout.BeginHorizontal(); { var currentWidth = 0; for (; index < allValues.Length; index++) { var value = allValues[index]; // Skip the 0 / none enum value, just uncheck everything to get 0 if (value.val != 0) { // Make sure this horizontal group doesn't extend over window width, if it does then start a new horiz group below var textDimension = (int)GUI.skin.toggle.CalcSize(new GUIContent(value.name)).x; currentWidth += textDimension; if (currentWidth > 370) { break; } GUI.changed = false; var newVal = GUILayout.Toggle((currentValue & value.val) == value.val, value.name, GUILayout.ExpandWidth(false)); if (GUI.changed) { var newValue = newVal ? currentValue | value.val : currentValue & ~value.val; setting.SetValue(Enum.ToObject(setting.Type(), newValue)); } } } } GUILayout.EndHorizontal(); } GUI.changed = false; } GUILayout.EndVertical(); // Make sure the reset button is properly spaced GUILayout.FlexibleSpace(); }
public static async Task <TItem> GetOrCreateAsync <TItem>(this IMemoryCache cache, object key, Func <ICacheEntry, Task <TItem> > factory) { object obj; if (!cache.TryGetValue(key, out obj)) { ICacheEntry entry = cache.CreateEntry(key); obj = await factory(entry); entry.SetValue(obj); entry.Dispose(); entry = null; } return((TItem)obj); }
public void NestedLinkContextsCanAggregate() { var clock = new TestClock(); var cache = CreateCache(clock); var obj = new object(); string key1 = "myKey1"; string key2 = "myKey2"; var expirationToken1 = new TestExpirationToken() { ActiveChangeCallbacks = true }; var expirationToken2 = new TestExpirationToken() { ActiveChangeCallbacks = true }; ICacheEntry entry1 = null; ICacheEntry entry2 = null; using (entry1 = cache.CreateEntry(key1)) { entry1.SetValue(obj); entry1 .AddExpirationToken(expirationToken1) .SetAbsoluteExpiration(TimeSpan.FromSeconds(10)); using (entry2 = cache.CreateEntry(key2)) { entry2.SetValue(obj); entry2 .AddExpirationToken(expirationToken2) .SetAbsoluteExpiration(TimeSpan.FromSeconds(15)); } } Assert.Equal(2, ((CacheEntry)entry1)._expirationTokens.Count()); Assert.NotNull(((CacheEntry)entry1)._absoluteExpiration); Assert.Equal(clock.UtcNow + TimeSpan.FromSeconds(10), ((CacheEntry)entry1)._absoluteExpiration); Assert.Single(((CacheEntry)entry2)._expirationTokens); Assert.NotNull(((CacheEntry)entry2)._absoluteExpiration); Assert.Equal(clock.UtcNow + TimeSpan.FromSeconds(15), ((CacheEntry)entry2)._absoluteExpiration); }
private void CacheEvictionCallback(object key, object value, EvictionReason reason, object state) { if (EvictionReason.Expired == reason) { KiteAccessTokenResponseRoot kiteAccessTokenResponseRoot = (KiteAccessTokenResponseRoot)value; MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions(); cacheOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(8)); cacheOptions.Priority = CacheItemPriority.NeverRemove; cacheOptions.RegisterPostEvictionCallback(new PostEvictionDelegate(this.CacheEvictionCallback)); cacheOptions.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot)); using (ICacheEntry cacheEntry = this._cache.CreateEntry((object)"kite_access_token")) { cacheEntry.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot)); cacheEntry.SetOptions(cacheOptions); cacheEntry.SetValue(kiteAccessTokenResponseRoot); } } }
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 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); }
/// <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); } }
private static void DrawComboboxField(ICacheEntry setting, IList list, object value) { var buttonText = new GUIContent(value.ToString()); var dispRect = GUILayoutUtility.GetRect(buttonText, GUI.skin.button, GUILayout.ExpandWidth(true)); if (!_comboBoxCache.TryGetValue(setting, out var box)) { box = new ComboBox(dispRect, buttonText, list.Cast <object>().Select(x => new GUIContent(x.ToString())).ToArray(), GUI.skin.button, Inspector.MaxWindowY); _comboBoxCache[setting] = box; } else { box.Rect = dispRect; box.ButtonContent = buttonText; } box.Show(id => { if (id >= 0 && id < list.Count) { setting.SetValue(list[id]); } }); }