System.Collections.Generic.IEnumerable.Where(System.Func)

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

31569 Examples 7

19 View Source File : UIIconManager.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public void Tick() {
            var time = DateTime.Now;
            var millis = time.Second * 1000 + time.Millisecond;
            var percent = (float)(millis % MILLIS_LOOP) / MILLIS_LOOP;

            var hotbarData = UIHelper.GetHotbarUI();
            if (hotbarData == null) return;

            HashSet<UIIcon> foundIcons = new();
            HashSet<CreateIconStruct> createIcons = new();

            for (var hotbarIndex = 0; hotbarIndex < AllActionBars.Length; hotbarIndex++) {
                var actionBar = (AddonActionBarBase*)AtkStage.GetSingleton()->RaptureAtkUnitManager->GetAddonByName(AllActionBars[hotbarIndex]);
                if (actionBar == null || actionBar->ActionBarSlotsAction == null || actionBar->AtkUnitBase.IsVisible == false) continue;

                if (hotbarIndex == 10) { // cross
                    ProcessCrossHotbar(hotbarIndex, actionBar, hotbarData, foundIcons, createIcons, percent);
                }
                else if(hotbarIndex == 11) {
                    ProcessDoubleCrossHotbar(hotbarIndex, actionBar, UIHelper.GetLeftDoubleCrossBar(), true, hotbarData, foundIcons, createIcons, percent);
                }
                else if(hotbarIndex == 12) {
                    ProcessDoubleCrossHotbar(hotbarIndex, actionBar, UIHelper.GetRightDoubleCrossBar(), false, hotbarData, foundIcons, createIcons, percent);
                }
                else {
                    ProcessNormalHotbar(hotbarIndex, actionBar, hotbarData, foundIcons, createIcons, percent);
                }
            }

            // remove unused
            foreach (var icon in Icons.Where(x => !foundIcons.Contains(x))) {
                icon.Dispose();
            }
            Icons.RemoveAll(x => !foundIcons.Contains(x));

            // create new
            foreach (var create in createIcons) {
                UIIcon newIcon = create.Props.IsTimer ?
                    new UIIconTimer(create.Action, create.ActionId, create.HotBarIndex, create.SlotIndex, create.Component, create.Props) :
                    new UIIconBuff(create.Action, create.ActionId, create.HotBarIndex, create.SlotIndex, create.Component, create.Props);
                Icons.Add(newIcon);
            }
        }

19 View Source File : CelesteNetServer.cs
License : MIT License
Project Creator : 0x0ade

public void RegisterModule(string path) {
            ModuleWrappers.Add(new(this, path));

            Reload:
            foreach (CelesteNetServerModuleWrapper wrapper in ModuleWrappers) {
                if (wrapper.Module != null ||
                    !wrapper.References.All(ModuleWrappers.Where(other => other.Module != null).Select(other => other.ID).Contains))
                    continue;

                wrapper.Load();
                goto Reload;
            }
        }

19 View Source File : UIHelper.Status.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public static bool CheckForTriggers(Dictionary<Item, Status> buffDict, Item[] triggers, out Item newTrigger) {
            newTrigger = default;
            foreach (var trigger in triggers.Where(t => t.Type == ItemType.Buff)) {
                if (buffDict.ContainsKey(trigger) && buffDict[trigger].RemainingTime > 0) {
                    newTrigger = trigger;
                    return true;
                }
            }
            return false;
        }

19 View Source File : IconManager.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public void Tick() {
            if (!JobBars.Config.IconsEnabled) return;
            foreach (var icon in CurrentIcons.Where(i => i.Enabled)) {
                icon.Tick();
            }
            JobBars.IconBuilder.Tick();
        }

19 View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade

[RCEndpoint(false, "/channels", null, null, "Channel List", "Basic channel list.")]
        public static void Channels(Frontend f, HttpRequestEventArgs c) {
            IEnumerable<Channel> channels = f.Server.Channels.All;
            if (!f.IsAuthorized(c))
                channels = channels.Where(c => !c.IsPrivate);
            f.RespondJSON(c, channels.Select(c => new {
                c.ID, c.Name, c.IsPrivate,
                Players = c.Players.Select(p => p.ID).ToArray()
            }).ToArray());
        }

19 View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade

private static IEnumerable<Type> _GetTypes(replacedembly asm) {
            try {
                return asm.GetTypes();
            } catch (ReflectionTypeLoadException e) {
#pragma warning disable CS8619 // Compiler thinks this could be <Type?> even though we check for t != null
                return e.Types.Where(t => t != null);
#pragma warning restore CS8619
            }
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000

private static async Task RunGenModelsOptions(GenModelsOptions options)
        {
            ILogger logger = new DefaultLogger(Console.Out, options.Verbosity);

            logger.LogMinimal("Model clreplacedes generation is running...");

            string inDirectory = EnsureDirectory(options.InputDir, logger, "Input", false);
            string outDirectory = EnsureDirectory(options.OutputDir, logger, "Output", true);

            var replacedysis = ExistingCodeExplorer
                .EnumerateTableDescriptorsModelAttributes(inDirectory, DefaultFileSystem.Instance)
                .ParseAttribute(options.NullRefTypes)
                .Createreplacedysis();

            if (replacedysis.Count < 1)
            {
                logger.LogNormal("No model attributes detected in the input directory.");
            }
            else
            {
                logger.LogNormal($"Found {replacedysis.Count} models in the input directory.");
            }

            if (logger.IsDetailed)
            {
                foreach (var model in replacedysis)
                {
                    logger.LogDetailed(model.Name);
                    foreach (var property in model.Properties)
                    {
                        logger.LogDetailed(
                            $" -{property.Type} {property.Name}");
                        foreach (var col in property.Column)
                        {
                            logger.LogDetailed(
                                $"   ={(property.CastType != null ? $"({property.CastType})" : null)}{col.TableRef.TableTypeName}.{col.ColumnName}");
                        }
                    }
                }
            }

            logger.LogNormal("Code generation...");

            foreach (var meta in replacedysis)
            {
                string path = Path.Combine(outDirectory, $"{meta.Name}.cs");
                if (logger.IsDetailed) logger.LogDetailed(path);
                await File.WriteAllTextAsync(path, ModelClreplacedGenerator.Generate(meta, options.Namespace, path, options.RwClreplacedes, DefaultFileSystem.Instance, out var existing).ToFullString());
                if (logger.IsDetailed) logger.LogDetailed(existing ? "Existing file updated." : "New file created.");
            }

            if (options.CleanOutput)
            {
                var modelFiles = replacedysis.Select(meta => $"{meta.Name}.cs").ToHashSet(StringComparer.InvariantCultureIgnoreCase);

                var toRemove = Directory.EnumerateFiles(outDirectory).Where(p=> !modelFiles.Contains(Path.GetFileName(p))).ToList();

                foreach (var delPath in toRemove)
                {
                    File.Delete(delPath);
                    if(logger.IsNormalOrHigher) logger.LogNormal($"File {Path.GetFileName(delPath)} has been removed since it does not contain any model clreplaced");
                }

            }


            logger.LogMinimal("Model clreplacedes generation successfully completed!");
        }

19 View Source File : ColumnPropertyTypeParserTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public void Test()
        {
            var allTypes = typeof(TableColumn).replacedembly.GetTypes().Where(t => typeof(TableColumn).IsreplacedignableFrom(t)).ToList();

            foreach (var type in allTypes)
            {
                if (type.Name != nameof(TableColumn))
                {
                    replacedert.AreEqual("Success", ColumnPropertyTypeParser.Parse(type.Name, this, "Success"));
                }
            }
        }

19 View Source File : GameConversationsController.cs
License : MIT License
Project Creator : 0xbustos

public void AddConversation()
        {
            PendingStatus unlockedStatus = this.model.ConversationsToAdd[0];
            this.model.ConversationsToAdd.RemoveAt( 0 );
            Dictionary<string, List<PendingStatus>> conversations = this.model.PendingConversations;
            if (!conversations.ContainsKey( unlockedStatus.ConversationName ))
            {
                conversations[unlockedStatus.ConversationName] = new List<PendingStatus>();
            }

            List<PendingStatus> pending = conversations[unlockedStatus.ConversationName];
            PendingStatus match = pending.Where( status => status.ConversationName == unlockedStatus.StatusName ).FirstOrDefault();
            if (match == null)
            {
                pending.Add( unlockedStatus );
                pending.OrderBy( status => status.Importance );
            }
        }

19 View Source File : DbManager.cs
License : MIT License
Project Creator : 0x1000000

private static IReadOnlyList<TableRef> SortTablesByForeignKeys(Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>> acc)
        {
            var tableGraph = new Dictionary<TableRef, int>();
            var maxValue = 0;

            foreach (var pair in acc)
            {
                CountTable(pair.Key, pair.Value, 1);
            }

            return acc
                .Keys
                .OrderByDescending(k => tableGraph.TryGetValue(k, out var value) ? value : maxValue)
                .ThenBy(k => k)
                .ToList();

            void CountTable(TableRef table, Dictionary<ColumnRef, ColumnModel> columns, int value)
            {
                var parentTables = columns.Values
                    .Where(c => c.Fk != null)
                    .SelectMany(c => c.Fk!)
                    .Select(f => f.Table)
                    .Distinct()
                    .Where(pt => !pt.Equals(table))//Self ref
                    .ToList();

                bool hasParents = false;
                foreach (var parentTable in parentTables)
                {
                    if (tableGraph.TryGetValue(parentTable, out int oldValue))
                    {
                        if (value >= 1000)
                        {
                            throw new SqExpressCodeGenException("Cycle in tables");
                        }

                        if (oldValue < value)
                        {
                            tableGraph[parentTable] = value;
                        }
                    }
                    else
                    {
                        tableGraph.Add(parentTable, value);
                    }

                    if (maxValue < value)
                    {
                        maxValue = value;
                    }

                    CountTable(parentTable, acc[parentTable], value + 1);
                    hasParents = true;
                }

                if (hasParents && !tableGraph.ContainsKey(columns.Keys.First().Table))
                {
                    tableGraph.Add(table, 0);
                }
            }
        }

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

private static IEnumerable<PropertyInfo> GetProperties(object param)
        {
            return ParamProperties.GetOrAdd(param.GetType(), key =>
            {
                return key.GetProperties().Where(p => p.CanRead).ToList();
            });
        }

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 : ServiceBuilder.cs
License : MIT License
Project Creator : 1100100

public async Task StartAsync(CancellationToken cancellationToken)
        {
            UraganoSettings.ClientGlobalInterceptors.Reverse();
            UraganoSettings.ServerGlobalInterceptors.Reverse();

            var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
            var enableServer = UraganoSettings.ServerSettings != null;

            var types = ReflectHelper.GetDependencyTypes();
            var services = types.Where(t => t.IsInterface && typeof(IService).IsreplacedignableFrom(t)).Select(@interface => new
            {
                Interface = @interface,
                Implementation = types.FirstOrDefault(p => p.IsClreplaced && p.IsPublic && !p.IsAbstract && !p.Name.EndsWith("_____UraganoClientProxy") && @interface.IsreplacedignableFrom(p))
            }).ToList();

            foreach (var service in services)
            {
                var imp = service.Implementation;

                var routeAttr = service.Interface.GetCustomAttribute<ServiceRouteAttribute>();
                var routePrefix = routeAttr == null ? $"{service.Interface.Namespace}/{service.Interface.Name}" : routeAttr.Route;


                var interfaceMethods = service.Interface.GetMethods();

                List<MethodInfo> implementationMethods = null;
                if (enableServer && imp != null)
                    implementationMethods = imp.GetMethods().ToList();

                var disableClientIntercept = service.Interface.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                var clientClreplacedInterceptors = new List<Type>();
                if (!disableClientIntercept)
                    clientClreplacedInterceptors = service.Interface.GetCustomAttributes(true).Where(p => p is IInterceptor)
                    .Select(p => p.GetType()).ToList();

                var serverClreplacedInterceptors = new List<Type>();
                var disableServerIntercept = false;
                if (enableServer && imp != null)
                {
                    disableServerIntercept = imp.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                    if (!disableServerIntercept)
                        serverClreplacedInterceptors = imp.GetCustomAttributes(true).Where(p => p is IInterceptor)
                            .Select(p => p.GetType()).ToList();
                }

                foreach (var interfaceMethod in interfaceMethods)
                {
                    MethodInfo serverMethod = null;
                    var idAttr = interfaceMethod.GetCustomAttribute<ServiceRouteAttribute>();
                    var route = idAttr == null ? $"{routePrefix}/{interfaceMethod.Name}" : $"{routePrefix}/{idAttr.Route}";

                    var clientInterceptors = new List<Type>();
                    if (enableClient && !disableClientIntercept && interfaceMethod.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                    {
                        clientInterceptors.AddRange(UraganoSettings.ClientGlobalInterceptors);
                        clientInterceptors.AddRange(clientClreplacedInterceptors);
                        clientInterceptors.AddRange(interfaceMethod.GetCustomAttributes(true)
                            .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                        clientInterceptors.Reverse();
                    }


                    var serverInterceptors = new List<Type>();
                    if (enableServer && imp != null)
                    {
                        serverMethod = implementationMethods.First(p => IsImplementationMethod(interfaceMethod, p));
                        if (!disableServerIntercept && serverMethod?.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                        {
                            serverInterceptors.AddRange(UraganoSettings.ServerGlobalInterceptors);
                            serverInterceptors.AddRange(serverClreplacedInterceptors.ToList());
                            if (serverMethod != null)
                                serverInterceptors.AddRange(serverMethod.GetCustomAttributes(true)
                                    .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                            serverInterceptors.Reverse();
                        }
                    }

                    ServiceFactory.Create(route, serverMethod, interfaceMethod, serverInterceptors, clientInterceptors);
                }
            }

            await Task.CompletedTask;
        }

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

public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
        {
            outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
            string discSfbPath = null;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
                if (string.IsNullOrEmpty(inDir))
                {
                    foreach (var drive in drives)
                    {
                        discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
                        if (!File.Exists(discSfbPath))
                            continue;

                        input = drive.Name;
                        Drive = drive.Name[0];
                        break;
                    }
                }
                else
                {
                    discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
                    if (File.Exists(discSfbPath))
                    {
                        input = Path.GetPathRoot(discSfbPath);
                        Drive = discSfbPath[0];
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                if (string.IsNullOrEmpty(inDir))
                    inDir = "/media";
                discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
                if (!string.IsNullOrEmpty(discSfbPath))
                    input = Path.GetDirectoryName(discSfbPath);
            }
            else
                throw new NotImplementedException("Current OS is not supported");

            if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
                throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");

            Log.Info("Selected disc: " + input);
            discSfbData = File.ReadAllBytes(discSfbPath);
            var replacedleId = CheckDiscSfb(discSfbData);
            var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
            if (!File.Exists(paramSfoPath))
                throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");

            using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                ParamSfo = ParamSfo.ReadFrom(stream);
            CheckParamSfo(ParamSfo);
            if (replacedleId != ProductCode)
                Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");

            // todo: maybe use discutils instead to read TOC as one block
            var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
            DiscFilenames = new List<string>();
            var totalFilesize = 0L;
            var rootLength = input.Length;
            foreach (var f in files)
            {
                try { totalFilesize += new FileInfo(f).Length; } catch { }
                DiscFilenames.Add(f.Substring(rootLength));
            }
            TotalFileSize = totalFilesize;
            TotalFileCount = DiscFilenames.Count;

            OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
            Log.Debug($"Output: {OutputDir}");
        }

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 : Dumper.cs
License : MIT License
Project Creator : 13xforever

private List<DiscInfo.DiscInfo> GetValidationInfo()
        {
            var discInfoList = new List<DiscInfo.DiscInfo>();
            foreach (var discKeyInfo in allMatchingKeys.Where(ki => ki.KeyType == KeyType.Ird))
            {
                var ird = IrdParser.Parse(File.ReadAllBytes(discKeyInfo.FullPath));
                if (!DiscVersion.Equals(ird.GameVersion))
                    continue;

                discInfoList.Add(ird.ToDiscInfo());
            }
            return discInfoList;
        }

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 : 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 : 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 : Dumper.cs
License : MIT License
Project Creator : 13xforever

private List<string> EnumeratePhysicalDrivesLinux()
        {
            var cdInfo = "";
            try
            {
                cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
            }
            catch (Exception e)
            {
                Log.Debug(e, e.Message);
            }
            var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
            return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
                    .Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
                    .Distinct()
                    .ToList();

        }

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = [email protected]"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public ConstructorInfo FindConstructor(Type csharpType)
        {
            var constructor = csharpType.GetConstructor(Type.EmptyTypes);
            if (constructor == null)
            {
                var constructors = csharpType.GetConstructors();
                constructor = constructors.Where(a => a.GetParameters().Length == constructors.Max(s => s.GetParameters().Length)).FirstOrDefault();
            }
            return constructor;
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResovleInsert(bool idenreplacedy)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .Where(a => !a.IsComplexType)
                .Where(a => !a.IsDefault || (_parameters.ContainsKey(a.CsharpName) && _parameters[a.CsharpName] != null));//如果是默认字段
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            var parameterNames = string.Join(",", intcolumns.Select(s => $"@{s.CsharpName}"));
            var sql = $"INSERT INTO {table}({columnNames}) VALUES ({parameterNames})";
            if (idenreplacedy)
            {
                sql = $"{sql};SELECT @@IDENreplacedY";
            }
            return sql;
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResovleBatchInsert(IEnumerable<T> enreplacedys)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos()
                .Where(a => !a.IsComplexType).ToList();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .ToList();
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            if (_context.DbContextType == DbContextType.Mysql)
            {
                var buffer = new StringBuilder();
                buffer.Append($"INSERT INTO {table}({columnNames}) VALUES ");
                var serializer = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(typeof(T));
                var list = enreplacedys.ToList();
                for (var i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    var values = serializer(item);
                    buffer.Append("(");
                    for (var j = 0; j < intcolumns.Count; j++)
                    {
                        var column = intcolumns[j];
                        var value = values[column.CsharpName];
                        if (value == null)
                        {
                            buffer.Append(column.IsDefault ? "DEFAULT" : "NULL");
                        }
                        else if (column.CsharpType == typeof(bool) || column.CsharpType == typeof(bool?))
                        {
                            buffer.Append(Convert.ToBoolean(value) == true ? 1 : 0);
                        }
                        else if (column.CsharpType == typeof(DateTime) || column.CsharpType == typeof(DateTime?))
                        {
                            buffer.Append($"'{value}'");
                        }
                        else if (column.CsharpType.IsValueType || (Nullable.GetUnderlyingType(column.CsharpType)?.IsValueType == true))
                        {
                            buffer.Append(value);
                        }
                        else
                        {
                            var str = SqlEncoding(value.ToString());
                            buffer.Append($"'{str}'");
                        }
                        if (j + 1 < intcolumns.Count)
                        {
                            buffer.Append(",");
                        }
                    }
                    buffer.Append(")");
                    if (i + 1 < list.Count)
                    {
                        buffer.Append(",");
                    }
                }
                return buffer.Remove(buffer.Length - 1, 0).ToString();
            }
            throw new NotImplementedException();
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResolveUpdate()
        {
            var table = GetTableMetaInfo().TableName;
            var builder = new StringBuilder();
            if (_setExpressions.Count > 0)
            {
                var where = ResolveWhere();
                foreach (var item in _setExpressions)
                {
                    var column = new BooleanExpressionResovle(item.Column).Resovle();
                    var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
                    builder.Append($"{column} = {expression},");
                }
                var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
                return sql;
            }
            else
            {
                var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
                var where = ResolveWhere();
                var columns = GetColumnMetaInfos();
                var updcolumns = columns
                    .Where(a => !filters.Contains(a.ColumnName))
                    .Where(a => !a.IsComplexType)
                    .Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
                    .Where(a => !a.IsConcurrencyCheck)
                    .Select(s => $"{s.ColumnName} = @{s.CsharpName}");
                if (string.IsNullOrEmpty(where))
                {
                    var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
                        ?? columns.First();
                    where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
                    if (columns.Exists(a => a.IsConcurrencyCheck))
                    {
                        var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                        where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
                    }
                }
                var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
                if (columns.Exists(a => a.IsConcurrencyCheck))
                {
                    var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                    sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
                    if (checkColumn.CsharpType.IsValueType)
                    {
                        var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                    else
                    {
                        var version = Guid.NewGuid().ToString("N");
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                }
                sql += where;
                return sql;
            }
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResovleColumns()
        {
            if (_selectExpression == null)
            {
                var filters = new GroupExpressionResovle(_filterExpression)
                    .Resovle().Split(',');
                var columns = GetColumnMetaInfos()
                    .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped)
                    .Select(s => s.ColumnName != s.CsharpName ? $"{s.ColumnName} AS {s.CsharpName}" : s.CsharpName);
                return string.Join(",", columns);
            }
            else
            {
                return new SelectExpressionResovle(_selectExpression).Resovle();
            }
        }

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResolveGet()
        {
            var table = GetTableMetaInfo().TableName;
            var columns = GetColumnMetaInfos();
            var column = ResovleColumns();
            var where = $" WHERE {columns.Where(a => a.IsPrimaryKey == true).First().ColumnName}[email protected]";
            string sql;
            if (_context.DbContextType == DbContextType.SqlServer)
            {
                sql = $"SELECT TOP 1 {column} FROM {table}{where}";
            }
            else
            {
                sql = $"SELECT {column} FROM {table}{where} LIMIT 0,1";
            }
            return sql;
        }

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

private List<OptionResultModel> ResolveCascader(IList<DicreplacedemEnreplacedy> all, int parentId = 0)
    {
        return all.Where(m => m.ParentId == parentId).OrderBy(m => m.Sort).Select(m =>
        {
            var node = new OptionResultModel
            {
                Label = m.Name,
                Value = m.Value,
                Data = new
                {
                    m.Id,
                    m.Name,
                    m.Value,
                    m.Extend,
                    m.Icon,
                    m.Level
                },
                Children = ResolveCascader(all, m.Id)
            };

            if (!node.Children.Any())
            {
                node.Children = null;
            }
            return node;
        }).ToList();
    }

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

private void ResolveMenu(IList<MenuEnreplacedy> menus, IList<RoleButtonEnreplacedy> buttons, ProfileMenuVo parent)
    {
        parent.Children = new List<ProfileMenuVo>();
        var children = menus.Where(m => m.ParentId == parent.Id).ToList();
        foreach (var child in children)
        {
            var menuVo = _mapper.Map<ProfileMenuVo>(child);
            menuVo.Buttons = buttons.Where(m => m.MenuId == child.Id).Select(m => m.ButtonCode.ToLower()).ToList();

            parent.Children.Add(menuVo);

            ResolveMenu(menus, buttons, menuVo);
        }
    }

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

private void ResolveTree(IList<MenuEnreplacedy> all, TreeResultModel<MenuEnreplacedy> parent)
    {
        foreach (var menu in all.Where(m => m.ParentId == parent.Id).OrderBy(m => m.Sort))
        {
            var child = new TreeResultModel<MenuEnreplacedy>
            {
                Id = menu.Id,
                Label = menu.Name,
                Item = menu
            };

            child.Path.AddRange(parent.Path);
            child.Path.Add(child.Label);

            //只有节点菜单才有子级
            if (menu.Type == MenuType.Node)
            {
                ResolveTree(all, child);
            }

            parent.Children.Add(child);
        }
    }

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

public static OptionCollectionResultModel ToResult(this Enum value, bool ignoreUnKnown = false)
    {
        var enumType = value.GetType();

        if (!enumType.IsEnum)
            return null;

        var options = Enum.GetValues(enumType).Cast<Enum>()
            .Where(m => !ignoreUnKnown || !m.ToString().Equals("UnKnown"));

        return Options2Collection(options);
    }

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

public static OptionCollectionResultModel ToResult<T>(bool ignoreUnKnown = false)
    {
        var enumType = typeof(T);

        if (!enumType.IsEnum)
            return null;

        if (ignoreUnKnown)
        {
            #region ==忽略UnKnown属性==

            if (!ListCacheNoIgnore.TryGetValue(enumType.TypeHandle, out OptionCollectionResultModel list))
            {
                var options = Enum.GetValues(enumType).Cast<Enum>()
                    .Where(m => !m.ToString().Equals("UnKnown"));

                list = Options2Collection(options);

                ListCacheNoIgnore.TryAdd(enumType.TypeHandle, list);
            }

            return list;

            #endregion ==忽略UnKnown属性==
        }
        else
        {
            #region ==包含UnKnown选项==

            if (!ListCache.TryGetValue(enumType.TypeHandle, out OptionCollectionResultModel list))
            {
                var options = Enum.GetValues(enumType).Cast<Enum>();
                list = Options2Collection(options);
                ListCache.TryAdd(enumType.TypeHandle, list);
            }

            return list;

            #endregion ==包含UnKnown选项==
        }
    }

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

private void LoadRepositories()
    {
        if (_repositoryreplacedemblies.IsNullOrEmpty())
            return;

        foreach (var replacedembly in _repositoryreplacedemblies)
        {
            /*
             * 仓储约定:
             * 1、仓储统一放在Repositories目录中
             * 2、仓储默认使用SqlServer数据库,如果数据库之间有差异无法通过ORM规避时,采用以下方式解决:
             *    a)将对应的方法定义为虚函数
             *    b)假如当前方法在MySql中实现有差异,则在Repositories新建一个MySql目录
             *    c)在MySql目录中新建一个仓储(我称之为兼容仓储)并继承默认仓储
             *    d)在新建的兼容仓储中使用MySql语法重写对应的方法
             */

            var repositoryTypes = replacedembly.GetTypes()
                .Where(m => !m.IsInterface && typeof(IRepository).IsImplementType(m))
                //排除兼容仓储
                .Where(m => m.FullName!.Split('.')[^2].EqualsIgnoreCase("Repositories"))
                .ToList();

            //兼容仓储列表
            var compatibilityRepositoryTypes = replacedembly.GetTypes()
                .Where(m => !m.IsInterface && typeof(IRepository).IsImplementType(m))
                //根据数据库类型来过滤
                .Where(m => m.FullName!.Split('.')[^2].EqualsIgnoreCase(Options.Provider.ToString()))
                .ToList();

            foreach (var type in repositoryTypes)
            {
                //按照框架约定,仓储的第三个接口类型就是所需的仓储接口
                var interfaceType = type.GetInterfaces()[2];

                //按照约定,仓储接口的第一个接口的泛型参数即为对应实体类型
                var enreplacedyType = interfaceType.GetInterfaces()[0].GetGenericArguments()[0];
                //保存实体描述符
                DbContext.EnreplacedyDescriptors.Add(new EnreplacedyDescriptor(DbContext, enreplacedyType));

                //优先使用兼容仓储
                var implementationType = compatibilityRepositoryTypes.FirstOrDefault(m => m.Name == type.Name) ?? type;

                Services.AddScoped(interfaceType, sp =>
                {
                    var instance = Activator.CreateInstance(implementationType);
                    var initMethod = implementationType.GetMethod("Init", BindingFlags.Instance | BindingFlags.NonPublic);
                    initMethod!.Invoke(instance, new Object[] { DbContext });

                    //保存仓储实例
                    var manager = sp.GetService<IRepositoryManager>();
                    manager?.Add((IRepository)instance);

                    return instance;
                });

                //保存仓储描述符
                DbContext.RepositoryDescriptors.Add(new RepositoryDescriptor(enreplacedyType, interfaceType, implementationType));
            }
        }
    }

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

private void LoadEnums(ModuleDescriptor descriptor)
    {
        var layer = descriptor.Layerreplacedemblies;

        if (layer.Core == null)
            return;

        var enumTypes = layer.Core.GetTypes().Where(m => m.IsEnum);
        foreach (var enumType in enumTypes)
        {
            var enumDescriptor = new ModuleEnumDescriptor
            {
                Name = enumType.Name,
                Type = enumType,
                Options = Enum.GetValues(enumType).Cast<Enum>().Where(m => !m.ToString().EqualsIgnoreCase("UnKnown")).Select(x => new OptionResultModel
                {
                    Label = x.ToDescription(),
                    Value = x
                }).ToList()
            };

            descriptor.EnumDescriptors.Add(enumDescriptor);
        }
    }

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

public List<PermissionDescriptor> GetPermissions(string moduleCode)
    {
        return _descriptors.Where(m => m.ModuleCode.EqualsIgnoreCase(moduleCode)).ToList();
    }

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

public async Task RemoveByPrefix(string prefix)
    {
        if (prefix.IsNull())
            return;

        var keys = GetAllKeys().Where(m => m.StartsWith(prefix));
        foreach (var key in keys)
        {
            await Remove(key);
        }
    }

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 : DictService.cs
License : MIT License
Project Creator : 17MKH

private List<TreeResultModel<int, DicreplacedemTreeVo>> ResolveTree(IList<DicreplacedemEnreplacedy> all, int parentId = 0)
    {
        return all.Where(m => m.ParentId == parentId).OrderBy(m => m.Sort).Select(m =>
        {
            var node = new TreeResultModel<int, DicreplacedemTreeVo>
            {
                Id = m.Id,
                Label = m.Name,
                Value = m.Value,
                Item = _mapper.Map<DicreplacedemTreeVo>(m),
                Children = ResolveTree(all, m.Id)
            };

            return node;
        }).ToList();
    }

19 View Source File : NailsMap.cs
License : MIT License
Project Creator : 1upD

public NailsCube GetCube(int x, int y, int z)
        {
            // Return value
            NailsCube cube = null;
            
            // Use Linq to query the list
            var cubesList = NailsCubes.Where(i => i.X == x && i.Y == y && i.Z == z).ToList();

            // If there is a cube at this location, return it
            if (cubesList != null && cubesList.Count > 0)
            {
                cube = cubesList[0];
            }

            // If more than one cube is found, log an error
            if (cubesList.Count > 1)
            {
                log.Error(string.Format("NailsCube.GetCube(): Multiple cubes found at one location: x {0} y {1} z {2}", x.ToString(), y.ToString(), z.ToString()));
            }

            // If there is no cube at this location, return null
            return cube;
        }

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
            string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))

            {
                //X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);

                log.Info($"Got SMSID from registration of: {clientId}");

                // create base DDR Message
                ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
                {
                    // Add necessary discovery data
                    SmsId = clientId,
                    ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
                    SiteCode = SiteCode,
                    DomainName = domainName,
                    NetBiosName = clientName
                };

                ddrMessage.Discover();
                // Add our certificate for message signing
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
                ddrMessage.Settings.HostName = CMServerName;
                ddrMessage.Settings.Compression = MessageCompression.Zlib;
                ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
                if (enumerateAndAddCustomDdr)
                {
                    //see current value for the DDR message
                    var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");

                    ////retrieve actual setting
                    string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                                        select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();

                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();

                    ////retrieve reported value
                    xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());

                    ////Set OS to correct setting
                    xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";

                    ////Remove the instance
                    ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));

                    CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
                    {
                        PlatformId = osCaption
                    };
                    InventoryInstance instance = new InventoryInstance(FixedOSRecord);

                    ////Add new instance
                    ddrMessage.DdrInstances.Add(instance);
                }

                ddrMessage.SendMessage(Sender);

                ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
                hinvMessage.Settings.HostName = CMServerName;
                hinvMessage.SmsId = clientId;
                hinvMessage.Settings.Compression = MessageCompression.Zlib;
                hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                //hinvMessage.Settings.Security.EncryptMessage = true;
                hinvMessage.Discover();

                var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
                foreach (string Clreplaced in Clreplacedes)
                {
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
                foreach (string Clreplaced in SMSClreplacedes)
                {
                    log.Info($"---Adding clreplaced : [{Clreplaced}]");
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                hinvMessage.Validate(Sender);
                hinvMessage.SendMessage(Sender);
            };
        }

19 View Source File : NailsStyle.cs
License : MIT License
Project Creator : 1upD

public List<string> GetInstancePaths(string aInstanceName)
        {
            // Unreadable linq expression gets the filepath list from an instance by instance name
            var instances = Instances.Where(i => i.Name == aInstanceName).Select(i => i.Filepaths).ToList();
            if(instances == null || instances.Count < 1)
            {
                return null;
            }
            return instances[0];
        }

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static HashSet<string> GetValidClreplacedes(byte[] replacedembly)
        {
            replacedembly asm = replacedembly.Load(replacedembly);
            return new HashSet<string>(asm.GetTypes().Where(t => t.IsPublic && t.GetConstructor(new Type[0]) != null).Select(t => t.FullName));
        }

19 View Source File : NailsConfig.cs
License : MIT License
Project Creator : 1upD

public NailsStyle GetStyle(string aStyleName)
        {
            var styles = this.Styles.Where(t => t.Name == aStyleName).ToList();
            if (styles == null || styles.Count < 1)
            {
                return null;
            }

            return styles[0];            
        }

19 View Source File : JcApiHelper.cs
License : MIT License
Project Creator : 279328316

private static void InitController(IActionDescriptorCollectionProvider actionProvider)
        {
            lock (controllerList)
            {
                if (controllerList.Count > 0)
                {
                    return;
                }
                #region 获取Controller,Action,TypeModel信息
                List<ActionDescriptor> actionDescList = actionProvider.ActionDescriptors.Items.ToList();
                for (int i = 0; i < actionDescList.Count; i++)
                {
                    ControllerActionDescriptor actionDescriptor = actionDescList[i] as ControllerActionDescriptor;

                    ControllerModel controller = controllerList.Where(a =>
                        a.Id == TypeHelper.GetModuleMark(actionDescriptor.ControllerTypeInfo)).FirstOrDefault();
                    if (controller == null)
                    {
                        controller = GetControllerModel(actionDescriptor);
                        if (controller.ControllerName == "ApiHelper")
                        {
                            continue;
                        }
                        controllerList.Add(controller);
                    }
                    ActionModel action = GetActionModel(actionDescriptor);
                    controller.ActionList.Add(action);
                }
                #endregion

                #region Controller,Action 排序
                for (int i = 0; i < controllerList.Count; i++)
                {
                    controllerList[i].ActionList.Sort((a1, a2) =>
                    {
                        return a1.ActionName.CompareTo(a2.ActionName);
                    });
                }
                controllerList.Sort((a1, a2) =>
                {
                    return a1.ControllerName.CompareTo(a2.ControllerName);
                });
                #endregion
            }
        }

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : 279328316

public static void Serialize<T>(T dto, string xmlPathName) where T : clreplaced, new()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            Type modelType = typeof(T);
            XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(declaration);
            XmlElement root = xmlDoc.CreateElement(modelType.Name);
            xmlDoc.AppendChild(root);

            List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();

            foreach (PropertyInfo pi in piList)
            {
                object value = pi.GetValue(dto);
                if (value != null)
                {
                    var propertyNode = xmlDoc.CreateNode(XmlNodeType.Element, pi.Name, "");
                    propertyNode.InnerText = value.ToString();
                    root.AppendChild(propertyNode);
                }
            }
            xmlDoc.Save(xmlPathName);
        }

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 : JcApiHelper_InitParam.cs
License : MIT License
Project Creator : 279328316

private static List<ParamModel> GetEnumPiList(Type type)
        {
            List<ParamModel> list = new List<ParamModel>();

            List<MemberInfo> memberList = type.GetMembers().ToList();
            //去掉枚举value__属性
            List<FieldInfo> fieldList = memberList
                .Where(a => a.MemberType == MemberTypes.Field)
                .Where(a => a.Name!= "value__")
                .Select(a => a as FieldInfo).ToList();

            if (fieldList?.Count > 0)
            {
                for (int i = 0; i < fieldList.Count; i++)
                {
                    ParamModel param = GetParam(fieldList[i], i);
                    list.Add(param);
                }
            }
            return list;
        }

19 View Source File : JcApiHelper_InitParam.cs
License : MIT License
Project Creator : 279328316

private static List<ParamModel> GetClreplacedObjPiList(Type type)
        {
            List<ParamModel> list = new List<ParamModel>();

            if (type.GenericTypeArguments.Length > 0)
            {
                #region 处理GenericTypeArguments>0情况
                if (type.GenericTypeArguments.Length > 1)
                {   //字典类型
                    for (int i = 0; i < type.GenericTypeArguments.Length; i++)
                    {
                        ParamModel param = GetParam(type.GenericTypeArguments[i], i);
                        list.Add(param);
                    }
                    return list;
                }
                else if (type.GenericTypeArguments.Length == 1)
                {   //单属性时,使用普通方法处理 PageResult<T>等格式
                    List<PropertyInfo> piList = type.GetMembers()
                        .Where(a => a.MemberType == MemberTypes.Property)
                        .Select(a => a as PropertyInfo).ToList();

                    if (piList?.Count > 0)
                    {
                        for (int i = 0; i < piList.Count; i++)
                        {
                            ParamModel param = GetParam(piList[i], i);
                            list.Add(param);
                        }
                    }
                }
                #endregion
            }
            else
            {
                List<MemberInfo> memberList = type.GetMembers().ToList();
                List<PropertyInfo> piList = memberList
                    .Where(a => a.MemberType == MemberTypes.Property)
                    .Select(a => a as PropertyInfo).ToList();
                if (piList?.Count > 0)
                {
                    for (int i = 0; i < piList.Count; i++)
                    {
                        ParamModel param = GetParam(piList[i], i);
                        list.Add(param);
                    }
                }
            }
            return list;
        }

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

static Func<T, Dictionary<string, string>> CompilePropertySerializer()
        {
            var o_t = typeof(T);
            var o = Expression.Parameter(o_t, "o");

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Variable(d_t, "d");
            var d_init = Expression.MemberInit(Expression.New(d_t));
            var d_add = d_t.GetMethod("Add");
            var d_setters = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance) // build setters via Add(k,v)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var prop = Expression.Property(o, x.Name);
                    var prop_mi_to_string = x.PropertyType.GetMethod("ToString", new Type[0]);
                    var add_to_dict = Expression.Call(d, d_add, Expression.Constant(x.Name), Expression.Call(prop, prop_mi_to_string));

                    if (!x.PropertyType.IsByRef)
                        return (Expression)add_to_dict;
                    else
                        return (Expression)Expression.IfThen(
                            Expression.Not(Expression.Equal(prop, Expression.Constant(null))),
                            add_to_dict);
                });

            // run this
            var body = Expression.Block(new[] { d }, // scope variables
                Expression.replacedign(d, d_init), // initialize
                Expression.Block(d_setters), // set
                d); // return

            return Expression.Lambda<Func<T, Dictionary<string, string>>>(body, o)
                .Compile();
        }

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

[Fact]
		public void AclCat()
		{
			var replacedertList = new[] { "keyspace", "read", "write", "set", "sortedset", "list", "hash", "string", "bitmap", "hyperloglog", "geo", "stream", "pubsub", "admin", "fast", "slow", "blocking", "dangerous", "connection", "transaction", "scripting" };
			var rt = rds.AclCat();
			if (!rt.IsError) replacedertList.Where(a => rt.Value.Contains(a)).Count().replacedertEqual(replacedertList.Length);
			replacedertList = new[] { "flushdb", "lastsave", "info", "latency", "slowlog", "replconf", "slaveof", "acl", "flushall", "role", "pfdebug", "cluster", "shutdown", "restore-asking", "sort", "sync", "pfselftest", "restore", "swapdb", "config", "keys", "psync", "migrate", "bgsave", "monitor", "bgrewriteaof", "module", "debug", "save", "client", "replicaof" };
			rt = rds.AclCat("dangerous");
			if (!rt.IsError) replacedertList.Where(a => rt.Value.Contains(a)).Count().replacedertEqual(replacedertList.Length);
		}

See More Examples