System.Collections.Generic.IEnumerable.ToList()

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

27178 Examples 7

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

public static void UpdatePartyMembers() {
            var order = GetPartyMemberOrder();
            var members = GetPartyMembers();
            PartyMembers = order.Select(objectId => objectId == 0 ? null : members.Find(member => member.ObjectId == objectId)).ToList();
        }

19 View Source File : Ribbon.cs
License : GNU General Public License v3.0
Project Creator : 0dteam

public String GetURLsAndAttachmentsInfo(MailItem mailItem)
        {
            string urls_and_attachments = "---------- URLs and Attachments ----------";

            var domainsInEmail = new List<string>();

            var emailHTML = mailItem.HTMLBody;
            var doc = new HtmlAgilityPack.HtmlDoreplacedent();
            doc.LoadHtml(emailHTML);

            // extracting all links
            var urlsText = "";
            var urlNodes = doc.DoreplacedentNode.SelectNodes("//a[@href]");
            if(urlNodes != null)
            {
                urlsText = "\n\n # of URLs: " + doc.DoreplacedentNode.SelectNodes("//a[@href]").Count;
                foreach (HtmlNode link in doc.DoreplacedentNode.SelectNodes("//a[@href]"))
                {
                    HtmlAttribute att = link.Attributes["href"];
                    if (att.Value.Contains("a"))
                    {
                        urlsText += "\n --> URL: " + att.Value.Replace(":", "[:]");
                        // Domain Extraction
                        try
                        {
                            domainsInEmail.Add(new Uri(att.Value).Host);
                        }
                        catch (UriFormatException)
                        {
                            // Try to process URL as email address. Example -> <a href="mailto:[email protected]">...etc
                            String emailAtChar = "@";
                            int ix = att.Value.IndexOf(emailAtChar);
                            if (ix != -1)
                            {
                                string emailDomain = att.Value.Substring(ix + emailAtChar.Length);
                                try
                                {
                                    domainsInEmail.Add(new Uri(emailDomain).Host);
                                }
                                catch (UriFormatException)
                                {
                                    // if it fails again, ignore domain extraction
                                    Console.WriteLine("Bad url: {0}", emailDomain);
                                }
                            }
                        }
                    }
                }
            }
            else
                urlsText = "\n\n # of URLs: 0";

            // Get domains
            domainsInEmail = domainsInEmail.Distinct().ToList();
            urls_and_attachments += "\n # of unique Domains: " + domainsInEmail.Count;
            foreach (string item in domainsInEmail)
            {
                urls_and_attachments += "\n --> Domain: " + item.Replace(":", "[:]");
            }

            // Add Urls
            urls_and_attachments += urlsText;

            urls_and_attachments += "\n\n # of Attachments: " + mailItem.Attachments.Count;
            foreach (Attachment a in mailItem.Attachments)
            {
                // Save attachment as txt file temporarily to get its hashes (saves under User's Temp folder)
                var filePath = Environment.ExpandEnvironmentVariables(@"%TEMP%\Outlook-Phishaddin-" + a.DisplayName + ".txt");
                a.SaveAsFile(filePath);

                string fileHash_md5 = "";
                string fileHash_sha256 = "";
                if (File.Exists(filePath))
                {
                    fileHash_md5 = CalculateMD5(filePath);
                    fileHash_sha256 = GetHashSha256(filePath);
                    // Delete file after getting the hashes
                    File.Delete(filePath);
                }
                urls_and_attachments += "\n --> Attachment: " + a.FileName + " (" + a.Size + " bytes)\n\t\tMD5: " + fileHash_md5 + "\n\t\tSha256: " + fileHash_sha256 + "\n";
            }
            return urls_and_attachments;
        }

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

[RCEndpoint(true, "/asms", null, null, "replacedembly List", "List of all loaded replacedemblies.")]
        public static void ASMs(Frontend f, HttpRequestEventArgs c) {
            f.RespondJSON(c, AppDomain.CurrentDomain.Getreplacedemblies().Select(asm => new {
                asm.GetName().Name,
                Version = asm.GetName().Version?.ToString() ?? "",
                Context =
#if NETCORE
                    (replacedemblyLoadContext.GetLoadContext(asm) ?? replacedemblyLoadContext.Default)?.Name ?? "Unknown",
#else
                    AppDomain.CurrentDomain.FriendlyName
#endif
            }).ToList());
        }

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

public static IReadOnlyList<SqModelMeta> Createreplacedysis(this IEnumerable<SqModelMetaRaw> rawModels)
        {
            var acc = new Dictionary<string, SqModelMeta>();

            foreach (var raw in rawModels)
            {
                var meta = GetFromAcc(raw);

                var property = meta.AddPropertyCheckExistence(new SqModelPropertyMeta(raw.FieldName, raw.FieldTypeName, raw.CastTypeName, raw.IsPrimaryKey, raw.IsIdenreplacedy));

                property.AddColumnCheckExistence(meta.Name, new SqModelPropertyTableColMeta(new SqModelTableRef(raw.TableName, raw.TableNamespace, raw.BaseTypeKindTag), raw.ColumnName));
            }

            var res =  acc.Values.OrderBy(v => v.Name).ToList();

            foreach (var model in res)
            {
                int? num = null;

                foreach (var p in model.Properties)
                {
                    if (num == null)
                    {
                        num = p.Column.Count;
                    }
                    else
                    {
                        if (num.Value != p.Column.Count)
                        {
                            throw new SqExpressCodeGenException($"{nameof(SqModelAttribute)} with name \"{model.Name}\" was declared in several table descriptors but numbers of properties do not match");
                        }
                    }
                }
            }


            return res;

            SqModelMeta GetFromAcc(SqModelMetaRaw raw)
            {
                if (acc.TryGetValue(raw.ModelName, out var result))
                {
                    return result;
                }

                var meta = new SqModelMeta(raw.ModelName);
                acc.Add(raw.ModelName, meta);
                return meta;
            }
            

        }

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 : 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 : Program.cs
License : MIT License
Project Creator : 0x1000000

private static void GenerateSyntaxModify(IReadOnlyList<NodeModel> models, StringBuilder stringBuilder)
        {
            CodeBuilder builder = new CodeBuilder(stringBuilder, 2);
            foreach (var nodeModel in models)
            {
                var subNodes = nodeModel.SubNodes.Concat(nodeModel.Properties).ToList();

                foreach (var subNode in subNodes)
                {
                    builder.AppendLineStart(0, $"public static {nodeModel.TypeName} With{subNode.PropertyName}(this {nodeModel.TypeName} original, {subNode.GetFullPropertyTypeName()} new{subNode.PropertyName}) ");
                    builder.AppendStart(1, $"=> new {nodeModel.TypeName}(");
                    for (var index = 0; index < subNodes.Count; index++)
                    {
                        var subNodeConst = subNodes[index];
                        if (index != 0)
                        {
                            builder.Append(", ");
                        }

                        builder.Append(subNodeConst == subNode
                            ? $"{subNode.ConstructorArgumentName}: new{subNode.PropertyName}"
                            : $"{subNodeConst.ConstructorArgumentName}: original.{subNodeConst.PropertyName}");
                    }

                    builder.AppendLine(");");
                    builder.AppendLine(null);
                }
            }
        }

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

public DataPage<TNext> Select<TNext>(Func<T, TNext> selector)
        {
            return new DataPage<TNext>(this.Items.Select(selector).ToList(), this.Offset, this.Total);
        }

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

public static IStatement Combine(this IEnumerable<IStatement> statements) =>
            StatementList.Combine(statements is IReadOnlyList<IStatement> l ? l : statements.ToList());

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

public async Task<IReadOnlyList<TableModel>> SelectTables()
        {
            var columnsRaw = await this.Database.LoadColumns();
            var indexes = await this.Database.LoadIndexes();
            var fk = await this.Database.LoadForeignKeys();

            var acc = new Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>>();

            foreach (var rawColumn in columnsRaw)
            {
                var table = rawColumn.DbName.Table;
                if (!acc.TryGetValue(table, out var colList))
                {
                    colList = new Dictionary<ColumnRef, ColumnModel>();
                    acc.Add(table, colList);
                }

                var colModel = BuildColumnModel(
                    rawColumn,
                    indexes.Pks.TryGetValue(table, out var pkCols) ? pkCols.Columns : null,
                    fk.TryGetValue(rawColumn.DbName, out var fkList) ? fkList : null);

                colList.Add(colModel.DbName, colModel);
            }

            var sortedTables = SortTablesByForeignKeys(acc: acc);

            var result = sortedTables.Select(t =>
                    new TableModel(
                        name: ToTableCrlName(tableRef: t),
                        dbName: t,
                        columns: acc[key: t]
                            .Select(p => p.Value)
                            .OrderBy(c => c.Pk?.Index ?? 10000)
                            .ThenBy(c => c.OrdinalPosition)
                            .ToList(),
                        indexes: indexes.Indexes.TryGetValue(key: t, value: out var tIndexes)
                            ? tIndexes
                            : new List<IndexModel>(capacity: 0)))
                .ToList();

            EnsureTableNamesAreUnique(result, this.Database.DefaultSchemaName);

            return result;

        }

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

public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
        {
            var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
            var nextLevel = new List<string>();
            var filePaths = new List<string>();
            var dirPaths = new List<string>();
            while (fsObjects.Any())
            {
                foreach (var path in fsObjects)
                {
                    if (reader.FileExists(path))
                        filePaths.Add(path);
                    else if (reader.DirectoryExists(path))
                    {
                        dirPaths.Add(path);
                        nextLevel.AddRange(reader.GetFileSystemEntries(path));
                    }
                    else
                        Log.Warn($"Unknown filesystem object: {path}");
                }
                (fsObjects, nextLevel) = (nextLevel, fsObjects);
                nextLevel.Clear();
            }
            
            var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
            var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
            var deepestDirnames = new List<string>();
            foreach (var dirname in dirnames)
            {
                var tmp = dirname + "\\";
                if (deepestDirnames.Any(n => n.StartsWith(tmp)))
                    continue;
                
                deepestDirnames.Add(dirname);
            }
            dirnames = deepestDirnames.OrderBy(n => n).ToList();
            var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
            var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();

            var fileList = new List<FileRecord>();
            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                if (filename.EndsWith("."))
                    Log.Warn($"Fixing potential mastering error in {filename}");
                fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            fileList = fileList.OrderBy(r => r.StartSector).ToList();
            return (files: fileList, dirs: emptydirs);
        }

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

public static List<Type> GenerateProxy(List<Type> interfaces)
        {
            if (interfaces.Any(p => !p.IsInterface && !typeof(IService).IsreplacedignableFrom(p)))
                throw new ArgumentException("The proxy object must be an interface and inherit IService.", nameof(interfaces));

            var replacedemblies = DependencyContext.Default.RuntimeLibraries.SelectMany(i => i.GetDefaultreplacedemblyNames(DependencyContext.Default).Select(z => replacedembly.Load(new replacedemblyName(z.Name)))).Where(i => !i.IsDynamic);

            var types = replacedemblies.Select(p => p.GetType()).Except(interfaces);
            replacedemblies = types.Aggregate(replacedemblies, (current, type) => current.Append(type.replacedembly));

            var trees = interfaces.Select(GenerateProxyTree).ToList();

            if (UraganoOptions.Output_DynamicProxy_SourceCode.Value)
            {
                for (var i = 0; i < trees.Count; i++)
                {
                    File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), $"{interfaces[i].Name}.Implement.cs"),
                        trees[i].ToString());
                }
            }

            using (var stream = CompileClientProxy(trees,
                replacedemblies.Select(x => MetadataReference.CreateFromFile(x.Location))
                    .Concat(new[]
                    {
                        MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location)
                    })))
            {
                var replacedembly = replacedemblyLoadContext.Default.LoadFromStream(stream);
                return replacedembly.GetExportedTypes().ToList();
            }
        }

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

private static MemberDeclarationSyntax[] GenerateMethods(Type type, string clreplacedName, string serviceName)
        {
            var typeAttr = type.GetCustomAttribute<ServiceRouteAttribute>();
            var routePrefix = typeAttr == null ? $"{type.Namespace}/{type.Name}" : typeAttr.Route;
            var methods = type.GetMethods().ToList();

            var s = methods.Select(p => GenerateMethod(routePrefix, p, serviceName)).ToList();
            s.Insert(0, GenerateConstructorDeclaration(clreplacedName));
            return s.ToArray();
        }

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

public List<T> GetAllNodes()
        {
            return Ring.Select(p => p.Value).Distinct().ToList();
        }

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

[Test, Explicit("Requires custom data")]
        public async Task TocSizeTest()
        {
            var path = @"E:\FakeCDs\PS3 Games\ird";
            var result = new List<(string filename, long size)>();
            foreach (var f in Directory.EnumerateFiles(path, "*.ird", SearchOption.TopDirectoryOnly))
            {
                var bytes = await File.ReadAllBytesAsync(f).ConfigureAwait(false);
                var ird = IrdParser.Parse(bytes);
                using (var header = GetDecompressHeader(ird))
                    result.Add((Path.GetFileName(f), header.Length));
            }
            replacedert.That(result.Count, Is.GreaterThan(0));

            var groupedStats = (from t in result
                    group t by t.size into g
                    select new {size = g.Key, count = g.Count()}
                ).OrderByDescending(i => i.count)
                .ThenByDescending(i => i.size)
                .ToList();

            var largest = groupedStats.Max(i => i.size);
            var largesreplacedem = result.First(i => i.size == largest);
            Console.WriteLine($"Largest TOC: {largesreplacedem.filename} ({largest.replacedtorageUnit()})");

            foreach (var s in groupedStats)
                Console.WriteLine($"{s.count} items of size {s.size}");

            replacedert.That(groupedStats.Count, Is.EqualTo(1));
        }

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

private IList<RedisKey> GetKeys(string prefix = null, int pageSize = 10, int pageOffset = 0)
    {
        var pat = prefix.IsNull() ? null : $"{GetKey(prefix)}*";
        var endPoints = _redis.GetEndPoints();
        if (endPoints.Length > 1)
        {
            var skipNum = pageOffset * pageSize;
            var leftNum = skipNum + pageSize;
            var keys = new List<RedisKey>();
            foreach (var endPoint in endPoints)
            {
                if (leftNum > 0)
                {
                    foreach (var key in _redis.GetServer(endPoint).Keys(_dbIndex, pat, pageSize: leftNum))
                    {
                        if (keys.Any(m => m == key))
                        {
                            continue;
                        }
                        keys.Add(key);
                        leftNum--;
                    }
                }
            }
            return keys.Skip(pageSize * pageOffset).Take(pageSize).ToList();
        }
        else
        {
            return _redis.GetServer(_redis.GetEndPoints().FirstOrDefault()).Keys(_dbIndex, pat, pageSize: pageSize, pageOffset: pageOffset).ToList();
        }
    }

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 : 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 : Server.cs
License : MIT License
Project Creator : 1ZouLTReX1

public void StartListening()
    {
        List<Socket> Inputs;
        List<Socket> Errors;

        Console.WriteLine("Main Loop Listening");
        InputsOG.Add(listenerSocket);

        isRunning = true;
        while (isRunning)
        {
            Inputs = InputsOG.ToList();
            Errors = InputsOG.ToList();

            Socket.Select(Inputs, null, Errors, -1);

            foreach (Socket sock in Inputs)
            {
                if (sock == listenerSocket)
                {
                    // If the sock is the server socket then we got a new player.
                    // So we need to Accept the socket and replacedign the socket an available new player ID and enreplacedy.
                    Socket newConnection = sock.Accept();

                    if (playerIdList.Count > 0)
                    {
                        OnUserConnect(newConnection);
                    } 
                    else
                    {
                        Debug.Log($"{newConnection.RemoteEndPoint} failed to connect: Server full!");
                        newConnection.Close();
                    }
                }
                else if (sock != null)
                {
                    if (!isRunning)
                        return;

                    try
                    {
                        User usr = clients[sock];
                        // Receive and process one message at a time.
                        bool result = usr.ReceiveOnce();

                        if (result == false)
                        {
                            OnUserDisconnect(sock);
                        }
                    }
                    catch { }
                }
            }

            foreach (Socket sock in Errors)
            {
                Console.WriteLine("Client Disconnected: Cause - Error");
                OnUserDisconnect(sock);
            }

            Errors.Clear();
        }

        Debug.Log("Stop Listening");
    }

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

private void OnItemsSourceChanged()
        {
            var itemsSource = ItemsSource;
            var items = itemsSource as IList;
            if (items == null && itemsSource is IEnumerable list)
                items = list.Cast<object>().ToList();

            if (items != null)
            {
                var textValues = items as IEnumerable<string>;
                if (textValues == null && items.Count > 0 && items[0] is string)
                    textValues = items.Cast<string>();

                if (textValues != null)
                {
                    Children = new List<SegmentedControlOption>(textValues.Select(child => new SegmentedControlOption {Text = child}));
                    OnSelectedItemChanged(true);
                }
                else
                {
                    var textPropertyName = TextPropertyName;
                    if (textPropertyName != null)
                    {
                        var newChildren = new List<SegmentedControlOption>();
                        foreach (var item in items)
                            newChildren.Add(new SegmentedControlOption { Item = item, TextPropertyName = textPropertyName });
                        Children = newChildren;
                        OnSelectedItemChanged(true);
                    }
                }
            }
        }

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

private void Start()
    {
        MaximumPlayers = ServerSettings.maxPlayerCount;
        playerIdList = Enumerable.Range(1, MaximumPlayers).Select(x => (ushort)x).ToList();

        serverLoop = new ServerLoop(playerPrefab);
        StartServer();
    }

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

private void Update()
    {
        // Network Tick.
        lock (instantiateJobs)
        {
            for (int i = 0; i < instantiateJobs.Count; i++)
            {
                (User user, ushort id) = instantiateJobs[i]; 

                var obj = Instantiate(playerPrefab, Vector3.zero, Quaternion.idenreplacedy);
                var tmpPlayer = obj.GetComponent<Player>();
                tmpPlayer.SetPlayerID(id);

                user.player = tmpPlayer;

                // Attach the Lag compensation module to the new instantiated player.
                obj.AddComponent<LagCompensationModule>().Init(user.player);
            }

            instantiateJobs.Clear();
        }

        
        lock (disconnectedClients)
        {

            foreach (var clientSock in clients.Keys)
            {
                if (clients[clientSock].player.playerContainer == null)
                {
                    OnUserDisconnect(clientSock);
                }
            }

            foreach (var disconnectedSock in disconnectedClients)
            {
                var playerId = clients[disconnectedSock].player.playerId;
                if (clients[disconnectedSock].player.playerContainer != null)
                {
                    GameObject.Destroy(clients[disconnectedSock].player.playerContainer);
                }

                lock (clients)
                {
                    clients.Remove(disconnectedSock);
                }

                lock (playerIdList)
                {
                    playerIdList.Add(playerId);
                    // return the id number to the id pool for new players to join in.
                    Console.WriteLine("Client Disconnected, Returned Player ID: " + playerId);
                    Console.WriteLine("Player Count: " + (MaximumPlayers - playerIdList.Count) + " / " + MaximumPlayers);
                }
            }

            disconnectedClients.Clear();
        }

        // Every tick we call update function which will process all the user commands and apply them to the physics world.
        serverLoop.Update(clients.Values.Select(x => x.player).ToList());

        WorldState snapshot = serverLoop.GetSnapshot();

        lock (OutputsOG)
        {
            for (int i = OutputsOG.Count - 1; i >= 0; i--)
            {
                var sock = OutputsOG[i];

                try
                {
                    SendSnapshot(sock, snapshot);
                }
                catch
                {
                    OnUserDisconnect(sock);
                }
            }
        }
    }

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

private void UpdateClientCount()
        {
            if (null == EndingNumber) { return; }
            if (null == NumberOfClients) { return; }
            if (StartingNumber.Text.Length.Equals(0) || EndingNumber.Text.Length.Equals(0))
            {
                return;
            }
            int StartingNo = Int32.Parse(StartingNumber.Text);
            int EndingNo = Int32.Parse(EndingNumber.Text);
            CalculatedClientsCount = Enumerable.Range(StartingNo, EndingNo).ToList().Count.ToString();

            NumberOfClients.Text = CalculatedClientsCount;

            Console.WriteLine("Generating " + CalculatedClientsCount + " new clients");
        }

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

private static void InitAllControllerNote()
        {
            List<replacedemblyNoteModel> noteList = new List<replacedemblyNoteModel>();

            #region 处理replacedemblyNote
            List<string> moduleList = controllerList.Select(controller => controller.ModuleName).Distinct().ToList();

            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo dirInfo = new DirectoryInfo(baseDir);
            for (int i = 0; i < moduleList.Count; i++)
            {
                string xmlNoteFileName = moduleList[i].Replace(".dll", ".xml");

                FileInfo fileInfo = dirInfo.GetFiles(xmlNoteFileName, SearchOption.AllDirectories).FirstOrDefault();
                if (fileInfo != null)
                {
                    replacedemblyNoteModel noteModel = replacedemblyHelper.GetreplacedemblyNote(fileInfo.FullName);
                    noteList.Add(noteModel);
                }
            }
            #endregion

            for (int i = 0; i < controllerList.Count; i++)
            {
                ControllerModel controller = controllerList[i];
                replacedemblyNoteModel noteModel = noteList.FirstOrDefault(note => note.ModuleName == controller.ModuleName);
                if (noteModel == null)
                {
                    continue;
                }
                //Controller 注释
                controller.NoteModel = noteModel.MemberList.FirstOrDefault(member => member.Name == controller.Id);
                foreach (ActionModel action in controller.ActionList)
                {   //Action注释
                    action.NoteModel = noteModel.MemberList.FirstOrDefault(member => member.Name == action.Id);

                    if (action.NoteModel != null)
                    {
                        foreach (ParamModel param in action.InputParameters)
                        {   //输入参数注释
                            if (action.NoteModel.ParamList.Keys.Contains(param.Name))
                            {
                                param.Summary = action.NoteModel.ParamList[param.Name];
                            }
                        }
                        //返回参数注释
                        action.ReturnParameter.Summary = action.NoteModel.Returns;
                    }
                }
            }
        }

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

private static CustomAttrModel GetCustomAttribute(CustomAttributeData customAttribute, int index = 0)
        {
            PTypeModel ptype = GetPType(customAttribute.AttributeType);
            CustomAttrModel model = new CustomAttrModel()
            {
                Name = ptype.TypeName.Replace("Attribute",""),
                PType = ptype,
                Position = index,
                ConstructorArgumentsList = customAttribute.ConstructorArguments.Select((a,i)=> { return GetParam(a, i); }).ToList(),
                NamedArgumentsList = customAttribute.NamedArguments.Select((a, i) => { return GetParam(a, i); }).ToList()
            };
            return model;
        }

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

private static ParamModel GetParam(ParameterInfo paramInfo)
        {
            PTypeModel ptype = GetPType(paramInfo.ParameterType);
            ParamModel param = new ParamModel()
            {
                Name = paramInfo.Name,
                PType = ptype,
                DefaultValue = paramInfo.DefaultValue?.ToString(),
                CustomAttrList = paramInfo.GetCustomAttributes().Select(a => GetCustomAttribute(a)).ToList(),
                Position = paramInfo.Position + 1
            };
            return param;
        }

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

public static List<int> OrderPaiLordWithColor(List<int> paiarr)
        {
            List<int> _tempList = new List<int>(paiarr);
            for (int i = 0; i < _tempList.Count; i++)
            {
                if (_tempList[i] > 100) _tempList[i] %= 100;
            }
            int[] temparr = _tempList.ToArray<int>();
            Array.Sort<int>(temparr);
            List<int> _ASCList = temparr.ToList<int>();
            _ASCList.Reverse();//默认是升序反转一下就降序了

            //带上花色,有点小复杂 
            Dictionary<int, int> _dicPoker2Count = GetPoker_Count(_ASCList);
            Dictionary<int, int> _dicPoker2CountUsed = new Dictionary<int, int>();
            for (int j = 0; j < _ASCList.Count; j++)
            {
                if (!_dicPoker2CountUsed.ContainsKey(_ASCList[j])) _dicPoker2CountUsed.Add(_ASCList[j], 1);

                for (int c = _dicPoker2CountUsed[_ASCList[j]]; c <= 4; c++)
                {
                    _dicPoker2CountUsed[_ASCList[j]]++;
                    if (paiarr.Contains(_ASCList[j] + 100 * c))
                    {
                        _ASCList[j] = _ASCList[j] + 100 * c;
                        break;
                    }
                }
            }
            return _ASCList;
        }

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 ParamModel GetParam(FieldInfo fi, int index = 0)
        {
            PTypeModel ptype = GetPType(fi.FieldType);
            int? value = null;
            if (fi.FieldType.IsEnum)
            {
                try
                {
                    value = Convert.ToInt32(Enum.Parse(fi.FieldType, fi.Name));
                }
                catch
                {   //如转换失败,忽略不做处理
                }
            }

            string fiId = null;
            if (fi.DeclaringType != null)
            {
                fiId = $"F:{fi.DeclaringType.ToString()}.{fi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = fi.Name,
                Id = fiId,
                PType = ptype,
                ParamValue = value,
                CustomAttrList = fi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };

            if (fi.CustomAttributes.Count() > 0)
            {

            }
            return param;
        }

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

private static ParamModel GetParam(PropertyInfo pi, int index = 0)
        {
            PTypeModel ptype = GetPType(pi.PropertyType);

            string piId = null;
            if (pi.DeclaringType != null)
            {
                string declaringTypeName = pi.DeclaringType.ToString();
                if (declaringTypeName.IndexOf("`") != -1)
                {   //泛型属性Id结构如下:P:Jc.Core.Robj`1.Result
                    declaringTypeName = declaringTypeName.Substring(0, declaringTypeName.IndexOf("`") + 2);
                }
                piId = $"P:{declaringTypeName}.{pi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = pi.Name,
                Id = piId,
                PType = ptype,
                CustomAttrList = pi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };
            if(pi.CustomAttributes.Count()>0)
            {

            }
            return param;
        }

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

private string GetTsType(string typeName)
        {
            string tsTypeStr = "";

            List<string> numberTypeList =
                ("int,int?,int16,int16?,int32,int32?,int64,int64?,decimal,decimal?," +
                "double,double?,byte,byte?,long,long?,single,single?").Split(',').ToList();
            
            List<string> boolTypeList = ("bool,bool?,boolean,boolean?").Split(',').ToList();
            List<string> stringTypeList =
                ("string,guid,guid?").Split(',').ToList();
            List<string> dateTimeTypeList =
                ("datetime,datetime?").Split(',').ToList();

            if (boolTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "boolean";
            }
            else if (stringTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "string";
            }
            else if (dateTimeTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "Date";
            }
            else if (numberTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "number";
            }
            else
            {
                tsTypeStr = typeName;
                #region 去掉Dto,Model命名
                if (tsTypeStr.EndsWith("Dto"))
                {   //参数类型名称 去掉末尾Dto,Model命名
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto"));
                }
                else if (tsTypeStr.EndsWith("Dto>"))
                {
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto")) + ">";
                }
                else if (tsTypeStr.EndsWith("Model"))
                {
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model"));
                }
                else if (tsTypeStr.EndsWith("Model>"))
                {
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model")) + ">";
                }
                #endregion
            }
            return tsTypeStr;
        }

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

public T DeserializeNode<T>(XmlNode node = null) where T : clreplaced, new()
        {
            T model = new T();
            XmlNode firstChild;
            if (node == null)
            {
                node = root;
            }
            firstChild = node.FirstChild;

            Dictionary<string, string> dict = new Dictionary<string, string>();

            XmlAttributeCollection xmlAttribute = node.Attributes;
            if (node.Attributes.Count > 0)
            {
                for (int i = 0; i < node.Attributes.Count; i++)
                {
                    if (!dict.Keys.Contains(node.Attributes[i].Name))
                    {
                        dict.Add(node.Attributes[i].Name, node.Attributes[i].Value);
                    }
                }
            }
            if (!dict.Keys.Contains(firstChild.Name))
            {
                dict.Add(firstChild.Name, firstChild.InnerText);
            }
            XmlNode next = firstChild.NextSibling;
            while (next != null)
            {
                if (!dict.Keys.Contains(next.Name))
                {
                    dict.Add(next.Name, next.InnerText);
                }
                else
                {
                    throw new Exception($"重复的属性Key:{next.Name}");
                }
                next = next.NextSibling;
            }


            #region 为对象赋值

            Type modelType = typeof(T);
            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)
            {
                string dictKey = dict.Keys.FirstOrDefault(key => key.ToLower() == pi.Name.ToLower());
                if (!string.IsNullOrEmpty(dictKey))
                {
                    string value = dict[dictKey];
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(pi.PropertyType);
                    if (typeConverter != null)
                    {
                        if (typeConverter.CanConvertFrom(typeof(string)))
                            pi.SetValue(model, typeConverter.ConvertFromString(value));
                        else
                        {
                            if (typeConverter.CanConvertTo(pi.PropertyType))
                                pi.SetValue(model, typeConverter.ConvertTo(value, pi.PropertyType));
                        }
                    }
                }
            }
            #endregion
            return model;
        }

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

internal static string GetMethodModuleMark(MethodInfo method)
        {
            string moduleMark = null;

            string controllerName = method.DeclaringType.FullName;
            string methodName = method.Name;

            string parametersName = "";
            List<ParameterInfo> parameters = method.GetParameters().ToList();
            if (parameters.Count > 0)
            {
                parametersName = "(";
                for (int i = 0; i < parameters.Count; i++)
                {
                    if (i > 0)
                    {
                        parametersName += ",";
                    }
                    parametersName += GetParameterTypeName(parameters[i].ParameterType);
                }
                parametersName += ")";
            }
            moduleMark = $"M:{controllerName}.{methodName}{parametersName}";
            return moduleMark;
        }

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

public static void SerializeCollection<T>(IEnumerable<T> list, string filePath) 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(string.Format("{0}List", 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 (T item in list)
            {
                XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.Element, modelType.Name, "");
                root.AppendChild(xmlNode);

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

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

[HttpPost]
        [AllowAnonymous]
        [Route("[action]")]
        public IActionResult GetApiVersion()
        {
            Robj<string> robj = new Robj<string>();
            List<replacedembly> replacedemblyList = AppDomain.CurrentDomain.Getreplacedemblies().ToList();
            AppDomain currentDomain = AppDomain.CurrentDomain;
            replacedembly replacedembly = replacedemblyList.FirstOrDefault(a=>a.GetName().Name==currentDomain.FriendlyName);
            if (replacedembly != null)
            {
                //replacedemblyFileVersionAttribute fileVersionAttr = replacedembly.GetCustomAttribute<replacedemblyFileVersionAttribute>();
                replacedemblyInformationalVersionAttribute versionAttr = replacedembly.GetCustomAttribute<replacedemblyInformationalVersionAttribute>();
                robj.Result = versionAttr?.InformationalVersion;
            }
            return new JsonResult(robj);
        }

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

public static List<int> OrderPaiLord(List<int> paiarr)
        {
            List<int> _tempList = new List<int>(paiarr);
            for (int i = 0; i < _tempList.Count; i++)
            {
                if (_tempList[i] > 100) _tempList[i] %= 100;
            }
            int[] temparr = _tempList.ToArray<int>();
            Array.Sort<int>(temparr);
            List<int> _ASCList = temparr.ToList<int>();
            _ASCList.Reverse();//默认是升序反转一下就降序了
            return _ASCList;
        }

19 View Source File : IdleBus`1.cs
License : MIT License
Project Creator : 2881099

public List<TValue> GetAll() => _dic.Keys.ToArray().Select(a => Get(a)).ToList();

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

[Fact]
        public void Command()
        {
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = cli.Command();
			//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
			var flags = new List<string>();
			var flags7 = new List<string>();
			var diccmd = new Dictionary<string, (string[], string[])>();

			var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
			{
				var a = a1 as object[];
				var cmd = a[0].ToString();
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());

				var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
				var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
				flags.AddRange(aflags);
				flags7.AddRange(fopts);

				diccmd.Add(cmd.ToUpper(), (aflags, fopts));

				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += $"string arg{x}, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey)
						{
							if (firstKey != lastKey) parms += "string[] keys, ";
							else parms += "string key, ";
						}
						else
						{
							if (firstKey != lastKey) parms += $"string[] arg{x}, ";
							else parms += $"string arg{x}, ";
						}
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}

				return [email protected]"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
			}));
			flags = flags.Distinct().ToList();
			flags7 = flags7.Distinct().ToList();


			var sboptions = new StringBuilder();
            foreach (var cmd in CommandSets._allCommands)
            {
                if (diccmd.TryGetValue(cmd, out var tryv))
                {
                    sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(");

                    for (var x = 0; x < tryv.Item1.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
                    }

                    sboptions.Append(", ");
                    for (var x = 0; x < tryv.Item2.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
                    }

                    sboptions.Append(", LocalStatus.none),");
                }
                else
                {
                    sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
                }
            }

            var optioncode = sboptions.ToString();
		}

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

async Task<int> DbContextBetchUpdatePrivAsync(EnreplacedyState[] ups, bool isLiveUpdate) {
			if (ups.Any() == false) return 0;
			var uplst1 = ups[ups.Length - 1];
			var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;

			if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
			var lstval2 = default(EnreplacedyState);
			if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");

			var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
			var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;

			List<EnreplacedyState> data = null;
			string[] cuig = null;
			if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
				//最后一个不保存
				data = ups.ToList();
				data.RemoveAt(ups.Length - 1);
				cuig = cuig2;
			} else if (isLiveUpdate) {
				//立即保存
				data = ups.ToList();
				cuig = cuig1;
			}

			if (data?.Count > 0) {

				if (cuig.Length == _table.Columns.Count)
					return ups.Length == data.Count ? -998 : -997;

				var updateSource = data.Select(a => a.Value).ToArray();
				var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);

				var affrows = await update.ExecuteAffrowsAsync();

				foreach (var newval in data) {
					if (_states.TryGetValue(newval.Key, out var tryold))
						_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
					if (newval.OldValue != null)
						_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
				}
				return affrows;
			}

			//等待下次对比再保存
			return 0;
		}

See More Examples