System.Collections.Generic.IEnumerable.Any()

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Any() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

13798 Examples 7

19 View Source File : ClientSideCaching.cs
License : MIT License
Project Creator : 2881099

void RemoveCache(params string[] keys)
            {
                if (keys?.Any() != true) return;
                foreach (var key in keys)
                {
                    if (_dict.TryRemove(key, out var old))
                    {
                        if (_options.Capacity > 0)
                        {
                            lock (_dictLock)
                            {
                                _dictSort.Remove($"{old.GetTime.ToString("X").PadLeft(16, '0')}{key}");
                            }
                        }
                    }
                }
            }

19 View Source File : SortedSets.cs
License : MIT License
Project Creator : 2881099

long ZStore(bool inter, string destination, string[] keys, int[] weights, ZAggregate? aggregate) => Call((inter ? "ZINTERSTORE" : "ZUNIONSTORE")
            .InputKey(destination, keys?.Length ?? 0)
            .InputKey(keys)
            .InputIf(weights?.Any() == true, weights)
            .InputIf(aggregate != null, "AGGREGATE", aggregate ?? ZAggregate.max), rt => rt
            .ThrowOrValue<long>());

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
    {
        return source == null || !source.Any();
    }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

public IDisposable Subscribe(string[] channels, Action<string, object> handler)
        {
            if (channels?.Any() != true) throw new ArgumentNullException(nameof(channels));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            return _pubsub.Subscribe(false, channels, (p, k, d) => handler(k, d));
        }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

public Resp3Helper.ReadResult<string> AclSetUser(params string[] rule) => rule?.Any() == true ? ExecCmd<string>("ACL", "SETUSER", rule) : throw new ArgumentException(nameof(rule));

19 View Source File : RedisDatabase.cs
License : MIT License
Project Creator : 17MKH

public async Task DeleteByPrefix(string prefix)
    {
        var pageSize = 1000;
        var pageOffset = 0;
        var hasEnd = false;
        while (!hasEnd)
        {
            var keys = GetKeysByPrefix(prefix, pageSize, pageOffset);
            if (keys == null || !keys.Any())
            {
                hasEnd = true;
            }
            else
            {
                try
                {
                    await _db.KeyDeleteAsync(keys.ToArray());
                }
                catch (RedisCommandException ex)
                {
                    if (ex.Message.StartsWith("Multi-key operations must involve a single slot;"))
                    {
                        await Task.WhenAll(keys.Select(m => _db.KeyDeleteAsync(m)));
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
    }

19 View Source File : PipelineAdapter.cs
License : MIT License
Project Creator : 2881099

public object[] EndPipe()
            {
                if (_commands.Any() == false) return new object[0];

                try
                {
                    switch (UseType)
                    {
                        case UseType.Pooling: break;
                        case UseType.Cluster: return ClusterEndPipe();
                        case UseType.Sentinel:
                        case UseType.SingleInside: break;
                        case UseType.SingleTemp: break;
                    }

                    CommandPacket epcmd = "EndPipe";
                    return TopOwner.LogCall(epcmd, () =>
                    {
                        using (var rds = _baseAdapter.GetRedisSocket(null))
                        {
                            EndPipe(rds, _commands);
                        }
                        return _commands.Select(a => a.Result).ToArray();
                    });
                }
                finally
                {
                    Dispose();
                }

                object[] ClusterEndPipe()
                {
                    throw new NotSupportedException();
                }
            }

19 View Source File : LoadBalancing.ConsistentHash.cs
License : MIT License
Project Creator : 1100100

private void OnNodeLeave(string serviceName, IReadOnlyList<string> servicesId)
        {
            if (!servicesId.Any()) return;
            if (!ServicesInfo.TryGetValue(serviceName, out var service)) return;
            foreach (var node in servicesId)
            {
                service.RemoveNode(node);
                Logger.LogTrace($"Removed node {node}");
            }
        }

19 View Source File : DbSet.cs
License : MIT License
Project Creator : 2881099

public void AttachRange(IEnumerable<TEnreplacedy> data) {
			if (data == null || data.Any() == false) return;
			if (_table.Primarys.Any() == false) throw new Exception($"不可附加,实体没有主键:{_fsql.GetEnreplacedyString(_enreplacedyType, data.First())}");
			foreach (var item in data) {
				var key = _fsql.GetEnreplacedyKeyString(_enreplacedyType, item, false);
				if (string.IsNullOrEmpty(key)) throw new Exception($"不可附加,未设置主键的值:{_fsql.GetEnreplacedyString(_enreplacedyType, item)}");

				_states.AddOrUpdate(key, k => CreateEnreplacedyState(item), (k, ov) => {
					_fsql.MapEnreplacedyValue(_enreplacedyType, item, ov.Value);
					ov.Time = DateTime.Now;
					return ov;
				});
			}
		}

19 View Source File : ServiceCollectionExtensions.cs
License : MIT License
Project Creator : 17MKH

public static IServiceCollection AddServicesFromreplacedembly(this IServiceCollection services, replacedembly replacedembly)
    {
        foreach (var type in replacedembly.GetTypes())
        {
            #region ==单例注入==

            var singletonAttr = (SingletonAttribute)Attribute.GetCustomAttribute(type, typeof(SingletonAttribute));
            if (singletonAttr != null)
            {
                //注入自身类型
                if (singletonAttr.Itself)
                {
                    services.AddSingleton(type);
                    continue;
                }

                var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
                if (interfaces.Any())
                {
                    foreach (var i in interfaces)
                    {
                        services.AddSingleton(i, type);
                    }
                }
                else
                {
                    services.AddSingleton(type);
                }

                continue;
            }

            #endregion

            #region ==瞬时注入==

            var transientAttr = (TransientAttribute)Attribute.GetCustomAttribute(type, typeof(TransientAttribute));
            if (transientAttr != null)
            {
                //注入自身类型
                if (transientAttr.Itself)
                {
                    services.AddSingleton(type);
                    continue;
                }

                var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
                if (interfaces.Any())
                {
                    foreach (var i in interfaces)
                    {
                        services.AddTransient(i, type);
                    }
                }
                else
                {
                    services.AddTransient(type);
                }
                continue;
            }

            #endregion

            #region ==Scoped注入==
            var scopedAttr = (ScopedAttribute)Attribute.GetCustomAttribute(type, typeof(ScopedAttribute));
            if (scopedAttr != null)
            {
                //注入自身类型
                if (scopedAttr.Itself)
                {
                    services.AddSingleton(type);
                    continue;
                }

                var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
                if (interfaces.Any())
                {
                    foreach (var i in interfaces)
                    {
                        services.AddScoped(i, type);
                    }
                }
                else
                {
                    services.AddScoped(type);
                }
            }

            #endregion
        }

        return services;
    }

19 View Source File : Hashes.cs
License : MIT License
Project Creator : 2881099

long HSet<T>(bool hmset, string key, string field, T value, params object[] fieldValues)
        {
            if (fieldValues?.Any() == true)
                return Call((hmset ? "HMSET" : "HSET").InputKey(key, field).InputRaw(SerializeRedisValue(value))
                    .InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<long>());
            return Call((hmset ? "HMSET" : "HSET").InputKey(key, field).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
        }

19 View Source File : Robot.cs
License : Apache License 2.0
Project Creator : 2881099

public List<HandPokerComplieResult> replacedysisPlan1() {
			//组合牌型,当机器人是地主,主动出牌时,怎么出牌能收回,或者怎么扔小牌最小合理
			//组合牌型,当机器人是地主,被动出牌时,怎么压死牌最合理

			//组合牌型,当机器人上家是地主,主动出牌时,下家能顶什么牌,地主不要什么牌
			//组合牌型,当机器人上家是地主,被动出牌时

			//组合牌型,当机器人下家是地主,主动出牌时,如果牌不好,则防止出牌让地主拖牌,否则自己逃走
			//组合牌型,当机器人下家是地主,被动出牌时,怎么出牌不让地主拖牌

			var gb = Utils.GroupByPoker(this.pokers.ToArray()).OrderBy(a => a.key).ToList();

			var pks = new List<int>(this.pokers);
			var hands = new List<HandPokerComplieResult>();
			HandPokerComplieResult hand = null;
			var cards = this.GetOutsideCard(); //外面所有的牌
			var gbOutsize = Utils.GroupByPoker(cards.ToArray()).OrderBy(a => a.key).ToList();

			var gbjks = gb.Where(a => a.count == 1 && a.key == 16 || a.key == 17).ToArray(); //王炸作为一手牌
			if (gbjks.Length == 2) {
				hand = Utils.ComplierHandPoker(gbjks);
				hands.Add(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}

			//var gb1 = gb.Where(a => a.count == 1 && a.key < 15).ToList(); //所有单张
			//var gb2 = gb.Where(a => a.count == 2 && a.key < 15).ToList(); //所有两张
			//var gb3 = gb.Where(a => a.count == 3 && a.key < 15).ToList(); //所有三张

			//var gbLow2 = new List<Utils.GroupByPokerResult>();
			//var gbTop2 = new List<Utils.GroupByPokerResult>();
			//var gbLow2Index = gb2.Count - 1;
			//for (var a = gb2.Count - 1; a >= 0; a--) {
			//	if (gbOutsize.Where(z => z.count >= 2).Any()) {
			//		gbLow2Index = a;
			//		break;
			//	}
			//	gbTop2.Add(gb2[a]);
			//}
			//gbTop2.Sort((x, y) => y.key.CompareTo(x.key));
			//for (var a = 0; a < gbLow2Index; a++) {
			//	gbLow2.Add(gb2[a]);
			//}


			//var gbLow1 = gb.Where(a => a.count == 1 && a.key < 10).ToArray(); //单张小牌,10以下
			//var gbLow2 = gb.Where(a => a.count == 2 && a.key < 8).ToArray(); //对子小牌,8以下
			//var gbMid1 = gb.Where(a => a.count == 1 && a.key >= 10 && a.key < 15).ToArray(); //单张中牌,10-A,可以穿牌
			//var gbMid2 = gb.Where(a => a.count == 2 && a.key >= 8 && a.key < 14).ToArray(); //对子小牌,8-K,可以穿牌

			//var gbHard1 = gb.Where(a => (a.count == 1 && a.key >= 10 && a.key < 15) || a.count < 4 && a.key >= 15).OrderBy(a => a.key).ToArray(); //单张硬牌,10以上
			//var gbHard2 = gb.Where(a => a.count == 2 && a.key >= 10).OrderBy(a => a.key).ToArray();
			//var gb1 = gb.Where(a => a.count == 1 && a.key < 15).OrderBy(a => a.key).ToArray(); //所有单张
			//var gb2 = gb.Where(a => a.count == 2 && a.key < 15).OrderBy(a => a.key).ToArray(); //所有两张
			//var gb3 = gb.Where(a => a.count == 3 && a.key < 15).OrderBy(a => a.key).ToArray(); //所有三张
			//var gb4 = gb.Where(a => a.count == 4).OrderBy(a => a.key).ToArray();
			//if (gb1.Length > 0) { //尝试组合三带一个
				
			//}

			//var gbseries = gb.Where(a => a.key < 15).OrderBy(a => a.key).ToArray();
			//var gbseriesStartIndex = 0;
			//for (var a = 0; a < gbseries.Length; a++) {
			//	var pkseries = new List<int>();
			//	pkseries.AddRange(gbseries[a].poker);
			//	for (var b = a + 1; b < gbseries.Length; b++) {
			//		//if (gbseries[b].count < gbseries[a].count)
			//		if (gbseries[b].key - a - 1 == gbseries[a].key) {

			//		}
			//	}
			//}
			//while (true) {
			//	bool isbreak = false;
			//	for (var a = gbseriesStartIndex + 1; a < gbseries.Length; a++) {
			//		if (gbseries[a].key - 1 == gbseries[a - 1].key && gbseries[a].count == gbseries[a - 1].count) {
			//			if (a == gbseries.Length - 1) {
			//				isbreak = true;
			//				break;
			//			}
			//			continue;
			//		}
			//		if (gbseries[a].count == 2 && a - gbseriesStartIndex >= 2) { //连对

			//		}
			//		if (gbseries[a].count == 1 && a - gbseriesStartIndex >= 4) { //顺子

			//		}
			//		gbseriesStartIndex = a;
			//	}
			//	if (isbreak) {

			//	}
			//}
			//for (var a = 1; a < gbseries.Length; a++) {
			//	if (gbseries[a].key - 1 == gbseries[a - 1].key) {

			//	}
			//}

			var gbseries = gb.Where(a => a.key < 15).OrderBy(a => a.key).ToArray();
			var gbseriesStartIndex = 0;
			for (var a = 1; a < gbseries.Length; a++) {
				if (gbseries[a].key - 1 == gbseries[a - 1].key) continue;
				if (a - gbseriesStartIndex >= 4) {
					var gbs = gb.Where((x, y) => y >= gbseriesStartIndex && y < a).ToArray();
					if (gbs.Where(x => x.count == 1).Count() > gbs.Length / 2) { //顺子

					}
				}
				gbseriesStartIndex = a;
			}
			
			var gb4 = gb.Where(a => a.count == 4).ToArray();
			foreach(var g4 in gb4) {
				hand = Utils.ComplierHandPoker(new[] { g4 }); //炸弹作为一手牌
				hands.Add(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			var hand33 = new Stack<HandPokerComplieResult>(); //飞机
			var hand3 = new Stack<HandPokerComplieResult>(); //三条
			var gb3 = gb.Where(a => a.count == 3 && a.key < 15).OrderBy(a => a.key).ToList();
			var gb3seriesStartIndex = 0;
			for (var a = 1; a < gb3.Count; a++) {
				if (Utils.IsSeries(gb3.Where((x, y) => y <= a).Select(x => x.key)) == false || a == gb3.Count - 1) {
					hand = Utils.ComplierHandPoker(gb3.Where((x, y) => y >= gb3seriesStartIndex && y < a));
					if (hand.type == HandPokerType.飞机) hand33.Push(hand);
					if (hand.type == HandPokerType.三条) hand3.Push(hand);
					foreach (var v in hand.value) pks.Remove(v);
					gb3seriesStartIndex = a;
				}
			}
			hand = Utils.ComplierHandPoker(gb.Where(a => a.count == 3 && a.key == 15)); //三条2
			if (hand != null) {
				hand3.Push(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			if (hand33.Any()) hands.AddRange(hand33.ToArray());
			if (hand3.Any()) hands.AddRange(hand3.ToArray());

			var hand22 = new Stack<HandPokerComplieResult>(); //连对
			var hand2 = new Stack<HandPokerComplieResult>(); //对
			var gb2 = gb.Where(a => a.count == 2 && a.key < 15).OrderBy(a => a.key).ToList();
			var gb2seriesStartIndex = 0;
			for (var a = 2; a < gb2.Count; a++) {
				if (Utils.IsSeries(gb2.Where((x, y) => y <= a).Select(x => x.key)) == false || a == gb2.Count - 1) {
					if (a - gb2seriesStartIndex >= 3) {
						hand = Utils.ComplierHandPoker(gb2.Where((x, y) => y >= gb2seriesStartIndex && y < a));
						hand22.Push(hand);
						foreach (var v in hand.value) pks.Remove(v);
					} else {
						for (var b = gb2seriesStartIndex; b < a; b++) {
							hand = Utils.ComplierHandPoker(new[] { gb2[b] });
							hand2.Push(hand);
							foreach (var v in hand.value) pks.Remove(v);
						}
					}
					gb2seriesStartIndex = a;
				}
			}
			hand = Utils.ComplierHandPoker(gb.Where(a => a.count == 2 && a.key == 15)); //对2
			if (hand != null) {
				hand2.Push(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			if (hand22.Any()) hands.AddRange(hand22.ToArray());
			if (hand2.Any()) hands.AddRange(hand2.ToArray());

			var hand11 = new Stack<HandPokerComplieResult>(); //顺子
			var hand1 = new Stack<HandPokerComplieResult>(); //个
			var gb1 = gb.Where(a => a.count == 1 && a.key < 15).OrderBy(a => a.key).ToList();
			var gb1seriesStartIndex = 0;
			for (var a = 4; a < gb1.Count; a++) {
				if (Utils.IsSeries(gb1.Where((x, y) => y <= a).Select(x => x.key)) == false || a == gb1.Count - 1) {
					if (a - gb1seriesStartIndex >= 3) {
						hand = Utils.ComplierHandPoker(gb1.Where((x, y) => y >= gb1seriesStartIndex && y < a));
						hand11.Push(hand);
						foreach (var v in hand.value) pks.Remove(v);
					} else {
						for (var b = gb1seriesStartIndex; b < a; b++) {
							hand = Utils.ComplierHandPoker(new[] { gb1[b] });
							hand1.Push(hand);
							foreach (var v in hand.value) pks.Remove(v);
						}
					}
					gb1seriesStartIndex = a;
				}
			}
			hand = Utils.ComplierHandPoker(gb.Where(a => a.count == 1 && a.key == 15)); //个2
			if (hand != null) {
				hand1.Push(hand);
				foreach (var v in hand.value) pks.Remove(v);
			}
			if (hand11.Any()) hands.AddRange(hand11.ToArray());
			if (hand1.Any()) hands.AddRange(hand1.ToArray());

			return hands;
		}

19 View Source File : QueryableSqlBuilder.cs
License : MIT License
Project Creator : 17MKH

private void ResolveSort(StringBuilder sqlBuilder, Expression exp, LambdaExpression fullExp, SortType sortType)
    {
        switch (exp.NodeType)
        {
            case ExpressionType.MemberAccess:
                //m => m.replacedle
                //m => m.replacedle.Length
                //m => m.T1.replacedle
                //m => m.T1.Length
                //m => m.T1.replacedle.Length
                ResolveSort(sqlBuilder, exp as MemberExpression, sortType);
                break;
            case ExpressionType.Convert:
                //m => m.replacedle.Length
                if (exp is UnaryExpression unaryExpression)
                {
                    ResolveSort(sqlBuilder, unaryExpression.Operand as MemberExpression, sortType);
                }
                break;
            case ExpressionType.Call:
                var callExp = exp as MethodCallExpression;
                var memberExp = callExp!.Object as MemberExpression;
                var columnName = _queryBody.GetColumnName(memberExp);
                object[] args = null;
                if (callExp.Arguments.Any())
                {
                    args = new object[callExp.Arguments.Count];
                    for (int i = 0; i < callExp.Arguments.Count; i++)
                    {
                        args[i] = ((ConstantExpression)callExp.Arguments[i]).Value;
                    }
                }
                sqlBuilder.AppendFormat(" {0} {1},", _dbAdapter.FunctionMapper(callExp.Method.Name, columnName, callExp.Object!.Type, args), sortType == SortType.Asc ? "ASC" : "DESC");
                break;
            case ExpressionType.New:
                //m=>new { m.replacedle.Substring(2) }
                if (exp is NewExpression newExp)
                {
                    foreach (var arg in newExp.Arguments)
                    {
                        ResolveSort(sqlBuilder, arg, fullExp, sortType);
                    }
                }
                break;
        }
    }

19 View Source File : Scripting.cs
License : MIT License
Project Creator : 2881099

public object Eval(string script, string[] keys = null, params object[] arguments) => Call("EVAL"
            .Input(script, keys?.Length ?? 0)
            .InputKeyIf(keys?.Any() == true, keys)
            .Input(arguments), rt => rt.ThrowOrValue());

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public async Task DumpAsync(string output)
        {
            // check and create output folder
            var dumpPath = output;
            while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
            {
                var parent = Path.GetDirectoryName(dumpPath);
                if (parent == null || parent == dumpPath)
                    dumpPath = null;
                else
                    dumpPath = parent;
            }
            if (filesystemStructure is null)
                (filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
            var validators = GetValidationInfo();
            if (!string.IsNullOrEmpty(dumpPath))
            {
                var root = Path.GetPathRoot(Path.GetFullPath(output));
                var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
                if (drive != null)
                {
                    var spaceAvailable = drive.AvailableFreeSpace;
                    TotalFileSize = filesystemStructure.Sum(f => f.Length);
                    var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
                    if (diff > 0)
                        Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
                }
            }

            foreach (var dir in emptyDirStructure)
                Log.Trace($"Empty dir: {dir}");
            foreach (var file in filesystemStructure)
                Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
            var outputPathBase = Path.Combine(output, OutputDir);
            if (!Directory.Exists(outputPathBase))
                Directory.CreateDirectory(outputPathBase);

            TotalFileCount = filesystemStructure.Count;
            TotalSectors = discReader.TotalClusters;
            Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
            var decryptionKey = allMatchingKeys.First().DecryptedKey;
            var sectorSize = (int)discReader.ClusterSize;
            var unprotectedRegions = driveStream.GetUnprotectedRegions();
            ValidationStatus = true;

            foreach (var dir in emptyDirStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
                    var outputName = Path.Combine(outputPathBase, convertedName);
                    if (!Directory.Exists(outputName))
                    {
                        Log.Debug("Creating empty directory " + outputName);
                        Directory.CreateDirectory(outputName);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
                }
            }
            
            foreach (var file in filesystemStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
                    CurrentFileNumber++;
                    var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
                    var inputFilename = Path.Combine(input, convertedFilename);

                    if (!File.Exists(inputFilename))
                    {
                        Log.Error($"Missing {file.Filename}");
                        BrokenFiles.Add((file.Filename, "missing"));
                        continue;
                    }

                    var outputFilename = Path.Combine(outputPathBase, convertedFilename);
                    var fileDir = Path.GetDirectoryName(outputFilename);
                    if (!Directory.Exists(fileDir))
                    {
                        Log.Debug("Creating directory " + fileDir);
                        Directory.CreateDirectory(fileDir);
                    }

                    var error = false;
                    var expectedHashes = (
                        from v in validators
                        where v.Files.ContainsKey(file.Filename)
                        select v.Files[file.Filename].Hashes
                    ).ToList();
                    var lastHash = "";
                    var tries = 2;
                    do
                    {
                        try
                        {
                            tries--;
                            using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
                            using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                            using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
                            Decrypter = decrypter;
                            await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
                            outputStream.Flush();
                            var resultHashes = decrypter.GetHashes();
                            var resultMd5 = resultHashes["MD5"];
                            if (decrypter.WasEncrypted && decrypter.WasUnprotected)
                                Log.Debug("Partially decrypted " + file.Filename);
                            else if (decrypter.WasEncrypted)
                                Log.Debug("Decrypted " + file.Filename);

                            if (!expectedHashes.Any())
                            {
                                if (ValidationStatus == true)
                                    ValidationStatus = null;
                            }
                            else if (!IsMatch(resultHashes, expectedHashes))
                            {
                                error = true;
                                var msg = "Unexpected hash: " + resultMd5;
                                if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
                                {
                                    Log.Error(msg);
                                    BrokenFiles.Add((file.Filename, "corrupted"));
                                    break;
                                }
                                Log.Warn(msg + ", retrying");
                            }

                            lastHash = resultMd5;
                        }
                        catch (Exception e)
                        {
                            Log.Error(e, e.Message);
                            error = true;
                        }
                    } while (error && tries > 0 && !Cts.IsCancellationRequested);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
                }
            }
            Log.Info("Completed");
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

internal void OnDataTrigger(RedisResult rt)
        {
            if (_ondata == null) return;
            while (_ondata.Any())
                _ondata.Dequeue()(rt);
        }

19 View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH

public static object[] Arguments2Object(ReadOnlyCollection<Expression> arguments)
    {
        object[] args = null;
        if (arguments.Any())
        {
            args = new object[arguments.Count];

            for (int i = 0; i < arguments.Count; i++)
            {
                args[i] = ((ConstantExpression)arguments[i]).Value;
            }
        }

        return args;
    }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

internal void Cancel(params Guid[] ids)
            {
                if (ids == null) return;
                var readyUnsubInterKeys = new List<string>();
                foreach (var id in ids)
                {
                    if (_cancels.TryRemove(id, out var oldkeys))
                        foreach (var oldkey in oldkeys)
                        {
                            if (_registers.TryGetValue(oldkey, out var oldrecvs) &&
                                oldrecvs.TryRemove(id, out var oldrecv) &&
                                oldrecvs.Any() == false)
                                readyUnsubInterKeys.Add(oldkey);
                        }
                }
                var unsub = readyUnsubInterKeys.Where(a => !a.StartsWith(_psub_regkey_prefix)).ToArray();
                var punsub = readyUnsubInterKeys.Where(a => a.StartsWith(_psub_regkey_prefix)).Select(a => a.Replace(_psub_regkey_prefix, "")).ToArray();
                if (unsub.Any()) Call("UNSUBSCRIBE".Input(unsub));
                if (punsub.Any()) Call("PUNSUBSCRIBE".Input(punsub));

                if (!_cancels.Any())
                    lock (_lock)
                        if (!_cancels.Any())
                            _redisSocket?.ReleaseSocket();
            }

19 View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

public async Task<IReadOnlyList<ServiceNodeInfo>> GetServiceNodes(string serviceName)
        {
            if (ServiceNodes.TryGetValue(serviceName, out var result))
                return result;
            var serviceNodes = await QueryServiceAsync(serviceName);
            if (!serviceNodes.Any())
            {
                return new List<ServiceNodeInfo>();
            }
            var nodes = serviceNodes.Select(p => new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta)).ToList();
            if (ServiceNodes.TryAdd(serviceName, nodes))
                return nodes;

            throw new InvalidOperationException($"Service {serviceName} not found.");
        }

19 View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : HttpStreamParser.cs
License : MIT License
Project Creator : 1iveowl

private byte[] ResilientHeader(byte[] b)
        {
            if (!IsDone)
            {
                _last4BytesCircularBuffer.Enqueue(b[0]);
            }
            else
            {
                if (!_parserDelegate.IsHeaderDone)
                {
                    var last4Byte = _last4BytesCircularBuffer.ToArray();

                    if (last4Byte != _correctLast4BytesReversed)
                    {
                        byte[] returnNewLine = { 0x0d, 0x0a };

                        var correctionList = new List<byte>();

                        if (last4Byte[0] != _correctLast4BytesReversed[0] || last4Byte[1] != _correctLast4BytesReversed[1])
                        {
                            correctionList.Add(returnNewLine[0]);
                            correctionList.Add(returnNewLine[1]);
                        }

                        if (last4Byte[2] != _correctLast4BytesReversed[2] || last4Byte[3] != _correctLast4BytesReversed[3])
                        {
                            correctionList.Add(returnNewLine[0]);
                            correctionList.Add(returnNewLine[1]);
                        }

                        if (correctionList.Any())
                        {
                            return correctionList.Concat(correctionList.Select(x => x)).ToArray();
                        }
                    }
                }
            }

            return b;
        }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

static object[] PrepareCmd(string cmd, string subcmd = null, params object[] parms)
		{
			if (string.IsNullOrWhiteSpace(cmd)) throw new ArgumentNullException("Redis command not is null or empty.");
			object[] args = null;
			if (parms?.Any() != true)
			{
				if (string.IsNullOrWhiteSpace(subcmd) == false) args = new object[] { cmd, subcmd };
				else args = cmd.Split(' ').Where(a => string.IsNullOrWhiteSpace(a) == false).ToArray();
			}
			else
			{
				var issubcmd = string.IsNullOrWhiteSpace(subcmd) == false;
				args = new object[parms.Length + 1 + (issubcmd ? 1 : 0)];
				var argsIdx = 0;
				args[argsIdx++] = cmd;
				if (issubcmd) args[argsIdx++] = subcmd;
				foreach (var prm in parms) args[argsIdx++] = prm;
			}
			return args;
		}

19 View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

private void RefreshNodes(string serviceName, List<ServiceNodeInfo> currentNodes)
        {
            if (ServiceNodes.TryGetValue(serviceName, out var nodes))
            {
                if (!currentNodes.Any())
                    nodes.Clear();

                var leavedNodes = nodes.Where(p => currentNodes.All(c => c.ServiceId != p.ServiceId)).Select(p => p.ServiceId).ToList();
                if (leavedNodes.Any())
                {
                    Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                    OnNodeLeave?.Invoke(serviceName, leavedNodes);
                    nodes.RemoveAll(p => currentNodes.All(c => c.ServiceId != p.ServiceId));
                }

                var addedNodes = currentNodes.FindAll(p => nodes.All(c => c.ServiceId != p.ServiceId));
                if (addedNodes.Any())
                {
                    nodes.AddRange(addedNodes);
                    Logger.LogTrace(
                        $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                    OnNodeJoin?.Invoke(serviceName, addedNodes);
                }
            }
            else
            {
                if (!currentNodes.Any())
                    ServiceNodes.TryAdd(serviceName, currentNodes);
            }
        }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

public Resp3Helper.ReadResult<string[]> CommandInfo(params string[] command) => command?.Any() == true ? ExecCmd<string[]>("COMMAND", "INFO", command) : throw new ArgumentException(nameof(command));

19 View Source File : MenuService.cs
License : MIT License
Project Creator : 17MKH

[Transaction]
    public async Task<IResultModel> UpdateSort(IList<MenuEnreplacedy> menus)
    {
        if (!menus.Any())
            return ResultModel.Success();

        var tasks = new List<Task>();
        foreach (var menu in menus)
        {
            var task = _repository.Find(m => m.Id == menu.Id).ToUpdate(m => new MenuEnreplacedy
            {
                ParentId = menu.ParentId,
                Sort = menu.Sort
            });
            tasks.Add(task);
        }

        await Task.WhenAll(tasks);

        return ResultModel.Success();
    }

19 View Source File : Connection.cs
License : MIT License
Project Creator : 2881099

public void ClientTracking(bool on_off, long? redirect, string[] prefix, bool bcast, bool optin, bool optout, bool noloop) => Call("CLIENT"
            .SubCommand("TRACKING")
            .InputIf(on_off, "ON")
            .InputIf(!on_off, "OFF")
            .InputIf(redirect != null, "REDIRECT", redirect)
            .InputIf(prefix?.Any() == true, prefix?.Select(a => new[] { "PREFIX", a }).SelectMany(a => a).ToArray())
            .InputIf(bcast, "BCAST")
            .InputIf(optin, "OPTIN")
            .InputIf(optout, "OPTOUT")
            .InputIf(noloop, "NOLOOP"), rt => rt.ThrowOrNothing());

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

public Resp3Helper.ReadResult<int> AclDelUser(params string[] username) => username?.Any() == true ? ExecCmd<int>("ACL", "DELUSER", username) : throw new ArgumentException(nameof(username));

19 View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH

private static void ResolveMemberInit(QueryBody queryBody, Expression exp, LambdaExpression fullLambda, StringBuilder sqlBuilder, IQueryParameters parameters)
    {
        if (exp == null || !(exp is MemberInitExpression initExp) || !initExp.Bindings.Any())
            return;

        for (var i = 0; i < initExp.Bindings.Count; i++)
        {
            if (initExp.Bindings[i] is Memberreplacedignment replacedignment)
            {
                var descriptor = queryBody.Joins.First(m => m.EnreplacedyDescriptor.EnreplacedyType == initExp.Type);
                var col = descriptor.EnreplacedyDescriptor.Columns.FirstOrDefault(m => m.PropertyInfo.Name.Equals(replacedignment.Member.Name));
                if (col != null)
                {
                    if (queryBody.Joins.Count < 2)
                        sqlBuilder.Append(queryBody.DbAdapter.AppendQuote(col.Name));
                    else
                        sqlBuilder.Append($"{queryBody.DbAdapter.AppendQuote(descriptor.Alias)}.{queryBody.DbAdapter.AppendQuote(col.Name)}");

                    sqlBuilder.Append(" = ");

                    Resolve(queryBody, replacedignment.Expression, fullLambda, sqlBuilder, parameters);

                    if (i < initExp.Bindings.Count - 1)
                        sqlBuilder.Append(",");
                }
            }
        }
    }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

public IDisposable PSubscribe(string[] pattern, Action<string, object> handler)
        {
            if (pattern?.Any() != true) throw new ArgumentNullException(nameof(pattern));
            if (handler == null) throw new ArgumentNullException(nameof(handler));
            return _pubsub.Subscribe(true, pattern, (p, k, d) => handler(k, d));
        }

19 View Source File : ConsulServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

public async Task NodeMonitor(CancellationToken cancellationToken)
        {
            Logger.LogTrace("Start refresh service status,waiting for locking...");
            using (await AsyncLock.LockAsync(cancellationToken))
            {
                if (cancellationToken.IsCancellationRequested)
                    return;

                foreach (var service in ServiceNodes)
                {
                    Logger.LogTrace($"Service {service.Key} refreshing...");
                    try
                    {
                        var healthNodes = await QueryServiceAsync(service.Key, cancellationToken);
                        if (cancellationToken.IsCancellationRequested)
                            break;

                        var leavedNodes = service.Value.Where(p => healthNodes.All(a => a.ServiceId != p.ServiceId))
                            .Select(p => p.ServiceId).ToArray();
                        if (leavedNodes.Any())
                        {
                            //RemoveNode(service.Key, leavedNodes);
                            if (!ServiceNodes.TryGetValue(service.Key, out var services)) return;
                            services.RemoveAll(p => leavedNodes.Any(n => n == p.ServiceId));
                            OnNodeLeave?.Invoke(service.Key, leavedNodes);
                            Logger.LogTrace($"These nodes are gone:{string.Join(",", leavedNodes)}");
                        }

                        var addedNodes = healthNodes.Where(p =>
                                service.Value.All(e => e.ServiceId != p.ServiceId)).Select(p =>
                                new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta))
                            .ToList();

                        if (addedNodes.Any())
                        {
                            //AddNode(service.Key, addedNodes);
                            if (ServiceNodes.TryGetValue(service.Key, out var services))
                                services.AddRange(addedNodes);
                            else
                                ServiceNodes.TryAdd(service.Key, addedNodes);

                            OnNodeJoin?.Invoke(service.Key, addedNodes);

                            Logger.LogTrace(
                                $"New nodes added:{string.Join(",", addedNodes.Select(p => p.ServiceId))}");
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }
                Logger.LogTrace("Complete refresh.");
            }
        }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

internal IDisposable Subscribe(bool psub, string[] channels, Action<string, string, object> handler)
            {
                if (_stoped) return new PubSubSubscribeDisposable(this, null);
                channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
                if (channels?.Any() != true) return new PubSubSubscribeDisposable(this, null);

                var id = Guid.NewGuid();
                var time = DateTime.Now;
                var regkeys = channels.Select(a => psub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                for (var a = 0; a < regkeys.Length; a++)
                {
                    ConcurrentDictionary<Guid, RegisterInfo> dict = null;
                    lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary<Guid, RegisterInfo>());
                    dict.TryAdd(id, new RegisterInfo(id, handler, time));
                }
                lock (_lock)
                    _cancels.TryAdd(id, regkeys);
                var isnew = false;
                if (IsSubscribed == false)
                {
                    lock (_lock)
                    {
                        if (IsSubscribed == false)
                        {
                            _redisSocket = _topOwner.Adapter.GetRedisSocket(null);
                            IsSubscribed = isnew = true;
                        }
                    }
                }
                if (isnew)
                {
                    new Thread(() =>
                    {
                        _redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
                        _redisSocket.ReceiveTimeout = TimeSpan.Zero;
                        var timer = new Timer(state =>
                        {
                            _topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
                            try { _redisSocket.Write("PING"); } catch { }
                        }, null, 10000, 10000);
                        var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(false);
                        while (_stoped == false)
                        {
                            RedisResult rt = null;
                            try
                            {
                                rt = _redisSocket.Read(readCmd);
                            }
                            catch
                            {
                                Thread.CurrentThread.Join(100);
                                if (_cancels.Any()) continue;
                                break;
                            }
                            var val = rt.Value as object[];
                            if (val == null) continue; //special case

                            var val1 = val[0].ConvertTo<string>();
                            switch (val1)
                            {
                                case "pong":
                                case "punsubscribe":
                                case "unsubscribe":
                                    continue;
                                case "pmessage":
                                    OnData(val[1].ConvertTo<string>(), val[2].ConvertTo<string>(), val[3]);
                                    continue;
                                case "message":
                                    OnData(null, val[1].ConvertTo<string>(), val[2]);
                                    continue;
                            }
                        }
                        timer.Dispose();
                        lock (_lock)
                        {
                            IsSubscribed = false;
                            _redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
                            _redisSocket.ReleaseSocket();
                            _redisSocket.Dispose();
                            _redisSocket = null;
                        }
                    }).Start();
                }
                Call((psub ? "PSUBSCRIBE" : "SUBSCRIBE").Input(channels));
                return new PubSubSubscribeDisposable(this, () => Cancel(id));
            }

19 View Source File : ModuleCollection.cs
License : MIT License
Project Creator : 17MKH

public void Load()
    {
        var modulesRootPath = Path.Combine(AppContext.BaseDirectory, Constants.ROOT_DIR);
        if (!Directory.Exists(modulesRootPath))
            return;

        var moduleDirs = Directory.GetDirectories(modulesRootPath);
        if (!moduleDirs.Any())
            return;

        _replacedemblyHelper = new replacedemblyHelper();
        var optionsList = new List<ModuleOptions>();
        foreach (var dir in moduleDirs)
        {
            var code = Path.GetFileName(dir)!.Split("_")[1];
            var options = _configuration.Get<ModuleOptions>($"Mkh:Modules:{code}");
            if (options.Db != null)
            {
                options.Code = code;
                options.Dir = dir;
                optionsList.Add(options);
            }
        }

        foreach (var options in optionsList.OrderBy(m => m.Sort))
        {
            LoadModule(options);
        }

        //释放资源
        _replacedemblyHelper = null;
    }

19 View Source File : Scripting.cs
License : MIT License
Project Creator : 2881099

public object EvalSha(string sha1, string[] keys = null, params object[] arguments) => Call("EVALSHA"
            .Input(sha1, keys?.Length ?? 0)
            .InputKeyIf(keys?.Any() == true, keys)
            .Input(arguments), rt => rt.ThrowOrValue());

19 View Source File : RedumpProvider.cs
License : MIT License
Project Creator : 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            var result = new HashSet<DiscKeyInfo>();
            try
            {
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                var embeddedResources = replacedembly.GetManifestResourceNames().Where(n => n.Contains("Disc_Keys") || n.Contains("Disc Keys")).ToList();
                if (embeddedResources.Any())
                    Log.Trace("Loading embedded redump keys");
                else
                    Log.Warn("No embedded redump keys found");
                foreach (var res in embeddedResources)
                {
                    using var resStream = replacedembly.GetManifestResourceStream(res);
                    using var zip = new ZipArchive(resStream, ZipArchiveMode.Read);
                    foreach (var zipEntry in zip.Entries.Where(e => e.Name.EndsWith(".dkey", StringComparison.InvariantCultureIgnoreCase)
                                                                    || e.Name.EndsWith(".key", StringComparison.InvariantCultureIgnoreCase)))
                    {
                        using var keyStream = zipEntry.Open();
                        using var memStream = new MemoryStream();
                        await keyStream.CopyToAsync(memStream, cancellationToken).ConfigureAwait(false);
                        var discKey = memStream.ToArray();
                        if (zipEntry.Length > 256/8*2)
                        {
                            Log.Warn($"Disc key size is too big: {discKey} ({res}/{zipEntry.FullName})");
                            continue;
                        }
                        if (discKey.Length > 16)
                        {
                            discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                        }

                        try
                        {
                            result.Add(new DiscKeyInfo(null, discKey, zipEntry.FullName, KeyType.Redump, discKey.ToHexString()));
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, $"Invalid disc key format: {discKey}");
                        }
                    }
                }
                if (result.Any())
                    Log.Info($"Found {result.Count} embedded redump keys");
                else
                    Log.Warn($"Failed to load any embedded redump keys");
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed to load embedded redump keys");
            }

            Log.Trace("Loading cached redump keys");
            var diff = result.Count;
            try
            {
                if (Directory.Exists(discKeyCachePath))
                {
                    var matchingDiskKeys = Directory.GetFiles(discKeyCachePath, "*.dkey", SearchOption.TopDirectoryOnly)
                        .Concat(Directory.GetFiles(discKeyCachePath, "*.key", SearchOption.TopDirectoryOnly));
                    foreach (var dkeyFile in matchingDiskKeys)
                    {
                        try
                        {
                            try
                            {
                                var discKey = File.ReadAllBytes(dkeyFile);
                                if (discKey.Length > 16)
                                {
                                    try
                                    {
                                        discKey = Encoding.UTF8.GetString(discKey).TrimEnd().ToByteArray();
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Warn(e, $"Failed to convert {discKey.ToHexString()} from hex to binary");
                                    }
                                }
                                result.Add(new DiscKeyInfo(null, discKey, dkeyFile, KeyType.Redump, discKey.ToString()));
                            }
                            catch (InvalidDataException)
                            {
                                File.Delete(dkeyFile);
                                continue;
                            }
                            catch (Exception e)
                            {
                                Log.Warn(e);
                                continue;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e, e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Warn(ex, "Failed to load redump keys from local cache");
            }
            diff = result.Count - diff;
            Log.Info($"Found {diff} cached disc keys");
            return result;
        }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

public Resp3Helper.ReadResult<string> ModuleLoad(string path, params string[] args) => args?.Any() == true ? ExecCmd<string>("MODULE", "LOAD", new[] { path }.Concat(args)) : ExecCmd<string>("MODULE", "LOAD", path);

19 View Source File : EnumerableExtensions.cs
License : MIT License
Project Creator : 17MKH

public static bool NotNullAndEmpty<T>(this IEnumerable<T> source)
    {
        return source != null && source.Any();
    }

19 View Source File : Resp3HelperTests.cs
License : MIT License
Project Creator : 2881099

public Resp3Helper.ReadResult<string[]> CommandGetKeys(params string[] command) => command?.Any() == true ? ExecCmd<string[]>("COMMAND", "GETKEYS", command) : throw new ArgumentException(nameof(command));

19 View Source File : ServiceBuilder.cs
License : MIT License
Project Creator : 1100100

private static bool SameParameters(IReadOnlyCollection<ParameterInfo> parameters1, IReadOnlyList<ParameterInfo> parameters2)
        {
            if (parameters1.Count == parameters2.Count)
            {
                return !parameters1.Where((t, i) => t.ParameterType != parameters2[i].ParameterType || t.IsOptional != parameters2[i].IsOptional || t.Position != parameters2[i].Position || t.HasDefaultValue != parameters2[i].HasDefaultValue).Any();
            }
            return false;
        }

19 View Source File : PipelineAdapter.cs
License : MIT License
Project Creator : 2881099

static void EndPipe(IRedisSocket rds, IEnumerable<PipelineCommand> cmds)
            {
                var err = new List<PipelineCommand>();
                var ms = new MemoryStream();

                try
                {
                    var respWriter = new RespHelper.Resp3Writer(ms, rds.Encoding, rds.Protocol);
                    foreach (var cmd in cmds)
                        respWriter.WriteCommand(cmd.Command);

                    if (rds.IsConnected == false) rds.Connect();
                    ms.Position = 0;
                    ms.CopyTo(rds.Stream);

                    foreach (var pc in cmds)
                    {
                        pc.RedisResult = rds.Read(pc.Command);
                        pc.Result = pc.Parse(pc.RedisResult);
                        if (pc.RedisResult.IsError) err.Add(pc);
#if isasync
                        pc.TrySetResult(pc.Result, pc.RedisResult.IsError ? new RedisServerException(pc.RedisResult.SimpleError) : null);
#endif
                    }
                }
                finally
                {
                    ms.Close();
                    ms.Dispose();
                }

                if (err.Any())
                {
                    var sb = new StringBuilder();
                    for (var a = 0; a < err.Count; a++)
                    {
                        var cmd = err[a].Command;
                        if (a > 0) sb.Append("\r\n");
                        sb.Append(err[a].RedisResult.SimpleError).Append(" {").Append(cmd.ToString()).Append("}");
                    }
                    throw new RedisServerException(sb.ToString());
                }
            }

19 View Source File : ArrayExtensions.cs
License : MIT License
Project Creator : 17MKH

public static T RandomGet<T>(this T[] arr)
    {
        if (arr == null || !arr.Any())
            return default(T);

        var r = new Random();

        return arr[r.Next(arr.Length)];
    }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

internal void UnSubscribe(bool punsub, string[] channels)
            {
                channels = channels?.Distinct().Select(a => punsub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                if (channels.Any() != true) return;
                var ids = channels.Select(a => _registers.TryGetValue(a, out var tryval) ? tryval : null).Where(a => a != null).SelectMany(a => a.Keys).Distinct().ToArray();
                Cancel(ids);
            }

19 View Source File : ConsistentHash.cs
License : MIT License
Project Creator : 1100100

public T GetNodeForKey(string key)
        {
            if (!Ring.Any())
                throw new InvalidOperationException("Can not find the available nodes, please call the AddNode method to add nodes.");

            var hash = HashAlgorithm.Hash(key);
            if (Ring.ContainsKey(hash))
                return Ring[hash];
            var node = Ring.Where(p => p.Key > hash).OrderBy(i => i.Key).Select(p => p.Value).FirstOrDefault();
            if (node != null)
                return node;
            return Ring.FirstOrDefault().Value;
        }

19 View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099

internal protected virtual T LogCall<T>(CommandPacket cmd, Func<T> func)
        {
            cmd.Prefix(Prefix);
            var isnotice = this.Notice != null;
            if (isnotice == false && this.Interceptors.Any() == false) return func();
            Exception exception = null;

            T ret = default(T);
            var isaopval = false;
            IInterceptor[] aops = new IInterceptor[this.Interceptors.Count + (isnotice ? 1 : 0)];
            Stopwatch[] aopsws = new Stopwatch[aops.Length];
            for (var idx = 0; idx < aops.Length; idx++)
            {
                aopsws[idx] = new Stopwatch();
                aopsws[idx].Start();
                aops[idx] = isnotice && idx == aops.Length - 1 ? new NoticeCallInterceptor(this) : this.Interceptors[idx]?.Invoke();
                var args = new InterceptorBeforeEventArgs(this, cmd, typeof(T));
                aops[idx].Before(args);
                if (args.ValueIsChanged && args.Value is T argsValue)
                {
                    isaopval = true;
                    ret = argsValue;
                }
            }
            try
            {
                if (isaopval == false) ret = func();
                return ret;
            }
            catch (Exception ex)
            {
                exception = ex;
                throw;
            }
            finally
            {
                for (var idx = 0; idx < aops.Length; idx++)
                {
                    aopsws[idx].Stop();
                    var args = new InterceptorAfterEventArgs(this, cmd, typeof(T), ret, exception, aopsws[idx].ElapsedMilliseconds);
                    aops[idx].After(args);
                }
            }
        }

19 View Source File : Globals.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static IPAddress GetLocalIPAddress()
    {
        var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();

        foreach (var card in cards)
        {
            if (card.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
                continue;

            var props = card.GetIPProperties();
            if (props == null)
                continue;

            var gateways = props.GatewayAddresses;
            if (!gateways.Any())
                continue;

            var gateway = gateways.FirstOrDefault(g => g.Address.AddressFamily == AddressFamily.InterNetwork);
            if (gateway == null)
                continue;

            foreach (IPAddress ip in props.UnicastAddresses.Select(x => x.Address))
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip;
                }
            }
        }

        throw new Exception("No network adapters with an IPv4 address in the system!");
    }

19 View Source File : LoadBalancing.ConsistentHash.cs
License : MIT License
Project Creator : 1100100

private void OnNodeJoin(string serviceName, IReadOnlyList<ServiceNodeInfo> nodes)
        {
            if (!nodes.Any())
                return;
            if (!ServicesInfo.TryGetValue(serviceName, out var service)) return;
            foreach (var node in nodes)
            {
                service.AddNode(node, node.ServiceId);
                Logger.LogTrace($"Added node {node.ServiceId}");
            }
        }

19 View Source File : LoadBalancing.WeightedPolling.cs
License : MIT License
Project Creator : 1100100

public string NextConnectionString(IReadOnlyList<SlaveConfiguration> slaves)
        {
            if (slaves == null || !slaves.Any())
                throw new ArgumentNullException(nameof(slaves));
            if (slaves.Count == 1)
                return slaves.First().ConnectionString;
            lock (LockObject)
            {
                var index = -1;
                var total = 0;
                for (var i = 0; i < slaves.Count; i++)
                {
                    slaves[i].Attach += slaves[i].Weight;
                    total += slaves[i].Weight;
                    if (index == -1 || slaves[index].Attach < slaves[i].Attach)
                    {
                        index = i;
                    }
                }
                slaves[index].Attach -= total;
                return slaves[index].ConnectionString;
            }
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static MemberDeclarationSyntax GenerateMethod(string routePrefix, MethodInfo methodInfo, string serviceName)
        {
            if (methodInfo.ReturnType.Namespace != typeof(Task).Namespace)
                throw new NotSupportedException($"Only support proxy asynchronous methods.[{methodInfo.DeclaringType?.Namespace}.{methodInfo.DeclaringType?.Name}.{methodInfo.Name}]");

            var methodAttr = methodInfo.GetCustomAttribute<ServiceRouteAttribute>();
            var serviceRoute = $"{routePrefix}/{(methodAttr == null ? methodInfo.Name : methodAttr.Route)}";
            var returnDeclaration = GenerateType(methodInfo.ReturnType);

            var argDeclarations = new List<SyntaxNodeOrToken>();
            foreach (var arg in methodInfo.GetParameters())
            {
                argDeclarations.Add(arg.ParameterType.IsGenericType
                    ? SyntaxFactory.Parameter(SyntaxFactory.Identifier(arg.Name))
                        .WithType(GenerateType(arg.ParameterType))
                    : SyntaxFactory.Parameter(SyntaxFactory.Identifier(arg.Name))
                        .WithType(GenerateQualifiedNameSyntax(arg.ParameterType)));

                argDeclarations.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
            }

            if (argDeclarations.Any())
            {
                argDeclarations.RemoveAt(argDeclarations.Count - 1);
            }

            //Generate return type.
            var methodDeclaration = SyntaxFactory.MethodDeclaration(methodInfo.ReturnType == typeof(void) ? SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)) : returnDeclaration, SyntaxFactory.Identifier(methodInfo.Name));

            if (methodInfo.ReturnType.Namespace == typeof(Task).Namespace)
            {
                methodDeclaration = methodDeclaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                    SyntaxFactory.Token(SyntaxKind.AsyncKeyword)));
            }
            else
            {
                methodDeclaration = methodDeclaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
            }

            methodDeclaration = methodDeclaration.WithParameterList(
                SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList<ParameterSyntax>(argDeclarations)));


            ExpressionSyntax expressionSyntax;

            if (methodInfo.ReturnType == typeof(Task))
            {
                expressionSyntax = SyntaxFactory.IdentifierName("InvokeAsync");
            }
            else
            {
                expressionSyntax = SyntaxFactory.GenericName(SyntaxFactory.Identifier("InvokeAsync"))
                    .WithTypeArgumentList(((GenericNameSyntax)returnDeclaration).TypeArgumentList);
            }

            var argNames = methodInfo.GetParameters().Select(p => SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(p.Name))).ToList();
            var token = new SyntaxNodeOrToken[]
            {
                SyntaxFactory.Argument(SyntaxFactory
                    .ArrayCreationExpression(SyntaxFactory
                        .ArrayType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)))
                        .WithRankSpecifiers(SyntaxFactory.SingletonList(
                            SyntaxFactory.ArrayRankSpecifier(
                                SyntaxFactory.SingletonSeparatedList<ExpressionSyntax>(
                                    SyntaxFactory.OmittedArraySizeExpression())))))
                    .WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression,
                        SyntaxFactory.SeparatedList<ExpressionSyntax>(argNames)))),

                SyntaxFactory.Token(SyntaxKind.CommaToken),
                SyntaxFactory.Argument(
                    SyntaxFactory.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        SyntaxFactory.Literal(serviceRoute))),
                SyntaxFactory.Token(SyntaxKind.CommaToken),
                SyntaxFactory.Argument(
                    SyntaxFactory.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        SyntaxFactory.Literal(serviceName)))
            };

            expressionSyntax = SyntaxFactory.AwaitExpression(SyntaxFactory.InvocationExpression(expressionSyntax)
                .WithArgumentList(
                    SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(token))
                ));

            StatementSyntax statementSyntax;
            if (methodInfo.ReturnType != typeof(Task) && methodInfo.ReturnType != typeof(void))
            {
                statementSyntax = SyntaxFactory.ReturnStatement(expressionSyntax);
            }
            else
            {
                statementSyntax = SyntaxFactory.ExpressionStatement(expressionSyntax);
            }

            return methodDeclaration.WithBody(SyntaxFactory.Block(SyntaxFactory.SingletonList(statementSyntax)));
        }

19 View Source File : ConsulServiceDiscovery.cs
License : MIT License
Project Creator : 1100100

public async Task<IReadOnlyList<ServiceNodeInfo>> GetServiceNodes(string serviceName)
        {
            if (ServiceNodes.TryGetValue(serviceName, out var result))
                return result;
            var serviceNodes = await QueryServiceAsync(serviceName);
            if (!serviceNodes.Any())
            {
                return new List<ServiceNodeInfo>();
            }
            var nodes = serviceNodes.Select(p => new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta)).ToList();

            if (ServiceNodes.TryAdd(serviceName, nodes))
                return nodes;

            throw new InvalidOperationException($"Service {serviceName} not found.");
        }

19 View Source File : Check.cs
License : MIT License
Project Creator : 17MKH

public static void Collection<T>(IList<T> list, string parameterName)
    {
        NotNull(list, parameterName);

        if (!list.Any())
            throw new ArgumentException("集合不包含任何内容", parameterName);
    }

19 View Source File : RedisBloomCountMinSketch.cs
License : MIT License
Project Creator : 2881099

public string CmsMerge(string dest, long numKeys, string[] src, long[] weights) => Call("CMS.MERGE"
            .InputKey(dest, numKeys)
            .InputKey(src)
            .InputIf(weights?.Any() == true, "WEIGHTS", weights), rt => rt.ThrowOrValue<string>());

See More Examples