/// <summary> /// Return a dictionary with RedisResult key-value /// </summary> /// <param name="redisResult"></param> /// <returns></returns> private static Dictionary <string, string> ToCustomDictionary(this RedisResult redisResult) { var info = redisResult.ToString(); var dictionary = info?.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries) .Where(part => part.Contains(':')) .Select(part => part.Split(':')) .ToDictionary(split => split[0], split => split[1]); return(dictionary); }
public IEnumerable <MiddlewareParameter> Execute(IEnumerable <MiddlewareParameter> parameters, Session session, ParameterTypeEnum returnTypeWanted) { IDatabase db = REDISConnector.REDISConnector.GetRedis().GetDatabase(datastore); // loaded.Evaluate(db, convertParamNames(parameters),convertParamValues(parameters)); RedisResult res = db.ScriptEvaluate(loaded.Hash, convertParamNames(parameters), convertParameterValues(parameters)); return(new List <MiddlewareParameter> { new MiddlewareParameter <string>("RedisResult", res.ToString(), MiddlewareParameterDirection.Out) }); }
/// <summary> /// Marshall's a JSON result from Redis into a POCO /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="serializedValue"></param> /// <returns></returns> public TResult Deserialize <TResult>(RedisResult serializedValue) { try { return(JsonConvert.DeserializeObject <TResult>(serializedValue.ToString())); } catch (ArgumentNullException) { throw new RedisKeyNotFoundException("Key not present in database"); } }
private RedResult ParseResult(RedisResult nativeRedisResult) { switch (nativeRedisResult.Type) { case ResultType.Error: return(new RedStatusResult(true, nativeRedisResult.ToString())); case ResultType.SimpleString: return(new RedStatusResult(false, nativeRedisResult.ToString())); case ResultType.Integer: case ResultType.BulkString: return(new RedSingleResult((RedisValue)nativeRedisResult, ParseResultType(nativeRedisResult.Type))); case ResultType.MultiBulk: var nativeArray = (RedisResult[])nativeRedisResult; return(new RedArrayResult(nativeArray.Select(nativeResult => ParseResult(nativeResult)).ToArray())); default: return(null); } }
private void button2_Click(object sender, EventArgs e) { string[] strings = textBox1.Text.ToString().Split(' '); object[] ps = new object[strings.Length - 1]; for (int i = 1; i < strings.Length; i++) { ps[i - 1] = strings[i]; } RedisResult redisResult = redis.GetDatabase().Execute(strings[0], ps); textBox2.Clear(); textBox2.AppendText(redisResult.IsNull ? "nil" : redisResult.ToString()); }
public static int AsInt(this RedisResult val) { if (val == null) { return(0); } if (val.HasValue() && !val.IsNull && !val.IsEmpty()) { return(Convert.ToInt32(val.ToString())); } return(0); }
// not too slow, but could be problematic public override Dictionary <RedisId, TimeSpan?> GetTimeToLive <T>(IEnumerable <RedisId> allKeys) { IEnumerable <RedisId> keys = allKeys.Where(x => !string.IsNullOrWhiteSpace(x?.FullKey)); // Lua uses 1-based arrays // Redis has the global "Table" (basically an array with generic indexing) KEYS for key arguments // https://www.lua.org/pil/2.5.html string luaScript = @" local keys = KEYS local retVal = '' local splitString = '|||||' local splitKvp = '^^^^^' local result = {} for i=1,#keys,1 do local ttlthing = redis.call('ttl', keys[i]) retVal = (retVal) .. (keys[i]) .. (splitKvp) .. ttlthing .. (splitString) end return retVal" ; // retVal = (retVal) .. (splitString) // .. (keys[i]) RedisKey[] redisValues = keys.Select(x => (RedisKey)x.FullKey).ToArray(); RedisResult result = RedisService.Database.ScriptEvaluate(luaScript, redisValues); string[] splitResult = result.ToString() .Split(new[] { "|||||" }, StringSplitOptions.RemoveEmptyEntries); Dictionary <RedisId, TimeSpan?> ttls = new Dictionary <RedisId, TimeSpan?>(); foreach (string s in splitResult) { if (string.IsNullOrWhiteSpace(s)) { continue; } string[] splitResult2 = s .Split(new[] { "^^^^^" }, StringSplitOptions.RemoveEmptyEntries); if (splitResult2.Length != 2) { continue; } RedisId key = keys.FirstOrDefault(k => k.FullKey.Contains(s)); int ttlSeconds; bool gotTtlSeconds = int.TryParse(splitResult2[1], out ttlSeconds); if (!gotTtlSeconds) { ttls.Add(key, null); } ttls.Add(key, TimeSpan.FromSeconds(ttlSeconds)); } return(ttls); }
public bool ExecuteScript(string commandJson, out string message) { message = ""; try { var db = Client.GetDatabase(0); RedisResult returnValue = db.Execute("EVALSHA", new object[] { "2a3b179577623abfbcc09958f5e8c99382983a1f", "2", "placeICO", commandJson }); if (returnValue.IsNull) { message = "Return Empty"; return(false); } int result = Int32.Parse(returnValue.ToString().Replace("{", "").Replace("}", "")); if (result == 2) { message = "Success"; return(true); } else if (result == 1) { message = "Insufficient balance"; return(false); } else { message = "Other error"; return(false); } } catch (Exception ex) { message = ex.Message; return(false); } }
internal ResultSet(RedisResult result, GraphCache graphCache) { if (result.Type == ResultType.MultiBulk) { var resultArray = (RedisResult[])result; ScanForErrors(resultArray); _graphCache = graphCache; if (resultArray.Length == 3) { Header = new Header(resultArray[0]); Statistics = new Statistics(resultArray[2]); _rawResults = (RedisResult[])resultArray[1]; Count = _rawResults.Length; } else { Statistics = new Statistics(resultArray[resultArray.Length - 1]); Count = 0; } } else { if (result.Type == ResultType.Error) { throw new NRedisGraphRunTimeException(result.ToString()); } Statistics = new Statistics(result); Count = 0; } }
public TResult Deserialize <TResult>(RedisResult serializedValue) => JsonSerializer.Deserialize <TResult>(serializedValue.ToString());
public JsonResult GeoFences() { try{ if (redis == null) { string tile38Connection = _configuration.GetConnectionString("Tile38Connection"); redis = ConnectionMultiplexer.Connect(tile38Connection); _logger.LogInformation($"Connected to Tile38 {tile38Connection}"); } db = redis.GetDatabase(); var result = db.Execute("CHANS", "*"); _logger.LogInformation(result.ToString()); GeoJSON.Net.Feature.FeatureCollection geofences = new GeoJSON.Net.Feature.FeatureCollection(); // Top level - collection of features System.Diagnostics.Debug.Assert(result.Type == ResultType.MultiBulk); RedisResult[] topLevelRedisArrayResult = ((RedisResult[])result); foreach (RedisResult redisResult in topLevelRedisArrayResult) { // Child level - the geofence System.Diagnostics.Debug.Assert(redisResult.Type == ResultType.MultiBulk); RedisResult[] childRedisArrayResult = ((RedisResult[])redisResult); // First property should be geofence name System.Diagnostics.Debug.Assert(childRedisArrayResult[0].Type == ResultType.BulkString); // Last property should be contain 'WITHIN', 'enter,exit', etc, and geofence GeoJSON RedisResult lastChildResult = childRedisArrayResult[childRedisArrayResult.Count() - 2]; System.Diagnostics.Debug.Assert(lastChildResult.Type == ResultType.MultiBulk); RedisResult[] lastChildResultArray = (RedisResult[])lastChildResult; RedisResult finalChildResult = lastChildResultArray[lastChildResultArray.Count() - 1]; System.Diagnostics.Debug.Assert(finalChildResult.Type == ResultType.BulkString); if (finalChildResult.ToString().StartsWith("{\"type\":\"Polygon\"")) { // _logger.LogInformation("Found GeoJSON!"); GeoJSON.Net.Feature.Feature feature = new GeoJSON.Net.Feature.Feature(Newtonsoft.Json.JsonConvert.DeserializeObject <GeoJSON.Net.Geometry.Polygon>(finalChildResult.ToString())); feature.Properties["Name"] = childRedisArrayResult[0].ToString(); geofences.Features.Add(feature); } } return(new JsonResult(geofences)); } catch (StackExchange.Redis.RedisConnectionException ex) { string message = "Unable to connect to Tile38"; _logger.LogError(0, ex, message); HttpContext.Response.StatusCode = 500; return(new JsonResult(new { message = message, exception = ex })); } catch (Exception ex) { string message = "Unable to retrieve GeoFences from Tile38"; _logger.LogError(0, ex, message); HttpContext.Response.StatusCode = 500; return(new JsonResult(new { message = message, exception = ex })); } }
async Task <bool> Probe() { ConfigurationOptions configDB0 = _configurationOptions.Clone(); configDB0.DefaultDatabase = 0; RedisConnector connectorDB0 = null; try { connectorDB0 = new RedisConnector(configDB0, true); } catch (Exception ex) { throw new RedisHelperException( "Cannot create DbConnection.", ex); } IDatabase db0 = null; try { db0 = connectorDB0.Connection.GetDatabase(0); } catch (Exception ex) { throw new RedisHelperException("Cannot GetDatabase(0).", ex); } TimeSpan pingDuration = default(TimeSpan); try { pingDuration = await db0.PingAsync(); } catch (Exception ex) { throw new RedisHelperException("Cannot ping db0.", ex); } try { _server = connectorDB0.Connection.GetServer( configDB0.EndPoints[0]); _features = _server.Features; } catch (Exception ex) { throw new RedisHelperException( "Cannot get server features.", ex); } try { IGrouping <string, KeyValuePair <string, string> >[] info = await _server.InfoAsync("Server"); if (info[0].Key.Equals("Server", StringComparison.CurrentCultureIgnoreCase)) { foreach (KeyValuePair <string, string> kvp in info[0]) { if (kvp.Key.Equals("redis_version", StringComparison.CurrentCultureIgnoreCase)) { _version = kvp.Value; break; } } } } catch (Exception ex) { throw new RedisHelperException( "Cannot get redis_version.", ex); } sbyte maxDb = 0; do { try { IDatabase nxtDb = connectorDB0 .Connection.GetDatabase(maxDb); RedisResult rr = await nxtDb.ExecuteAsync("PING"); if (rr == null || rr.IsNull || !rr.ToString().Equals( "PONG", StringComparison.CurrentCultureIgnoreCase)) { break; } ++maxDb; } catch { // expected... swallow break; } } while (maxDb < sbyte.MaxValue); _maxDb = maxDb; return(true); }