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

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

44249 Examples 7

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

public override T[] LoadRegistered<T>() {
            lock (GlobalLock) {
                return LoadRaw<Global>(GlobalPath).UIDs.Values.Select(uid => Load<T>(uid)).ToArray();
            }
        }

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

public override T[] LoadAll<T>() {
            lock (GlobalLock) {
                if (!Directory.Exists(UserRoot))
                    return Dummy<T>.EmptyArray;
                string name = GetDataFileName(typeof(T));
                return Directory.GetDirectories(UserRoot).Select(dir => LoadRaw<T>(Path.Combine(dir, name))).ToArray();
            }
        }

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

public override string[] GetAll()
            => !Directory.Exists(UserRoot) ? Dummy<string>.EmptyArray : Directory.GetDirectories(UserRoot).Select(name => Path.GetFileName(name)).ToArray();

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

[RCEndpoint(true, "/userinfos", "?from={first}&count={count}", "?from=0&count=100", "User Infos", "Get some basic information about ALL users.")]
        public static void UserInfos(Frontend f, HttpRequestEventArgs c) {
            using UserDataBatchContext ctx = f.Server.UserData.OpenBatch();

            string[] uids = f.Server.UserData.GetAll();

            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);
            if (!int.TryParse(args["from"], out int from) || from <= 0)
                from = 0;
            if (!int.TryParse(args["count"], out int count) || count <= 0)
                count = 100;
            if (from + count > uids.Length)
                count = uids.Length - from;

            f.RespondJSON(c, uids.Skip(from).Take(count).Select(uid => {
                BasicUserInfo info = f.Server.UserData.Load<BasicUserInfo>(uid);
                BanInfo ban = f.Server.UserData.Load<BanInfo>(uid);
                KickHistory kicks = f.Server.UserData.Load<KickHistory>(uid);
                return new {
                    UID = uid,
                    info.Name,
                    info.Discrim,
                    info.Tags,
                    Key = f.Server.UserData.GetKey(uid),
                    Ban = ban.Reason.IsNullOrEmpty() ? null : new {
                        ban.Name,
                        ban.Reason,
                        From = ban.From?.ToUnixTime() ?? 0,
                        To = ban.To?.ToUnixTime() ?? 0
                    },
                    Kicks = kicks.Log.Select(e => new {
                        e.Reason,
                        From = e.From?.ToUnixTime() ?? 0
                    }).ToArray()
                };
            }).ToArray());
        }

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

protected override void CreateModMenuSectionHeader(TextMenu menu, bool inGame, EventInstance snapshot) {
            base.CreateModMenuSectionHeader(menu, inGame, snapshot);

            CelesteNetModShareComponent sharer = Context?.Get<CelesteNetModShareComponent>();
            if (sharer != null && !inGame) {
                List<EverestModuleMetadata> requested;
                lock (sharer.Requested)
                    requested = new List<EverestModuleMetadata>(sharer.Requested);

                if (requested.Count != 0) {
                    TextMenu.Item item;
                    menu.Add(item = new TextMenu.Button("modoptions_celestenetclient_recommended".DialogClean()).Pressed(() => {
                        f_OuiDependencyDownloader_MissingDependencies.SetValue(null, requested);
                        m_Overworld_Goto_OuiDependencyDownloader.Invoke(Engine.Scene, Dummy<object>.EmptyArray);
                    }));

                    item.AddDescription(
                        menu,
                        "modoptions_celestenetclient_recommendedhint".DialogClean()
                        .Replace("((list))", string.Join(", ", requested.Select(r => r.DLL)))
                    );
                }
            }
        }

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

public static IEnumerable<MemberDeclarationSyntax> GenerateStaticFactory(SqModelMeta meta)
        {
            return ExtractTableRefs(meta).Select(tableRef => SyntaxFactory
                    .MethodDeclaration(SyntaxFactory.ParseTypeName(meta.Name), MethodNameRead)
                    .WithModifiers(Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                    .AddParameterListParameters(FuncParameter("record", nameof(ISqDataRecordReader)))
                    .AddParameterListParameters(FuncParameter("table", ExtractTableTypeName(meta, tableRef)))
                    .WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(
                        SyntaxFactory.ObjectCreationExpression(SyntaxFactory.Token(SyntaxKind.NewKeyword),
                            SyntaxFactory.ParseTypeName(meta.Name),
                            ArgumentList(meta.Properties.Select(p =>
                                {
                                    ExpressionSyntax invocation = MemberAccess("table", p.Column.First().ColumnName)
                                        .MemberAccess("Read")
                                        .Invoke(SyntaxFactory.ParseName("record"));

                                    if (p.CastType != null)
                                    {
                                        invocation = SyntaxFactory.CastExpression(SyntaxFactory.ParseTypeName(p.CastType), invocation);
                                    }
                                    return new NamedArgument(p.Name.FirstToLower(),
                                        invocation);
                                })
                                .ToArray()),
                            null)))));
        }

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

public static IEnumerable<MemberDeclarationSyntax> GenerateOrdinalStaticFactory(SqModelMeta meta)
        {
            return ExtractTableRefs(meta).Select(tableRef => SyntaxFactory
                    .MethodDeclaration(SyntaxFactory.ParseTypeName(meta.Name), MethodNameReadOrdinal)
                    .WithModifiers(Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                    .AddParameterListParameters(FuncParameter("record", nameof(ISqDataRecordReader)))
                    .AddParameterListParameters(FuncParameter("table", ExtractTableTypeName(meta, tableRef)))
                    .AddParameterListParameters(FuncParameter("offset", "int"))
                    .WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(
                        SyntaxFactory.ObjectCreationExpression(SyntaxFactory.Token(SyntaxKind.NewKeyword),
                            SyntaxFactory.ParseTypeName(meta.Name),
                            ArgumentList(meta.Properties.Select((p,index) =>
                                {
                                    ExpressionSyntax invocation = MemberAccess("table", p.Column.First().ColumnName)
                                        .MemberAccess("Read")
                                        .Invoke(
                                            SyntaxFactory.ParseName("record"),
                                            index == 0 
                                                ? SyntaxFactory.IdentifierName("offset")
                                                : SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, SyntaxFactory.IdentifierName("offset"), SyntaxFactory.LiteralExpression(SyntaxKind.NumerireplacederalExpression, SyntaxFactory.Literal(index))));

                                    if (p.CastType != null)
                                    {
                                        invocation = SyntaxFactory.CastExpression(SyntaxFactory.ParseTypeName(p.CastType), invocation);
                                    }
                                    return new NamedArgument(p.Name.FirstToLower(),
                                        invocation);
                                })
                                .ToArray()),
                            null)))));
        }

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

private static MemberDeclarationSyntax[] GenerateMethods(IReadOnlyList<TableModel> tables, string tablePrefix)
        {
            var result = new List<MemberDeclarationSyntax>(tables.Count*2 + 2);

            var identifierAliasType = SyntaxFactory.IdentifierName(nameof(Alias));

            var arrayItems = tables.Select(t=> SyntaxFactory.IdentifierName(GetMethodName(t,tablePrefix)).Invoke(identifierAliasType.MemberAccess(nameof(Alias.Empty))));
            var arrayType = SyntaxFactory.ArrayType(SyntaxFactory.IdentifierName(nameof(TableBase)),
                new SyntaxList<ArrayRankSpecifierSyntax>(new[]
                {
                    SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.Token(SyntaxKind.OpenBracketToken),
                        new SeparatedSyntaxList<ExpressionSyntax>(),
                        SyntaxFactory.Token(SyntaxKind.CloseBracketToken))
                }));
            var array = SyntaxFactory.ArrayCreationExpression(
                arrayType,
                SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression,
                    new SeparatedSyntaxList<ExpressionSyntax>().AddRange(arrayItems))
            );

            result.Add(
                SyntaxFactory.MethodDeclaration(arrayType, "BuildAllTableList")
                    .WithModifiers(SyntaxHelpers.Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                    .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(
                        array
                        ))
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

            foreach (var t in tables)
            {
                var aliasParamName = "alias";

                result.Add(SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(t.Name), GetMethodName(t, tablePrefix))
                    .WithModifiers(SyntaxHelpers.Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                    .AddParameterListParameters(SyntaxHelpers.FuncParameter(aliasParamName, nameof(Alias)))
                    .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(t.Name),
                            SyntaxHelpers.ArgumentList(SyntaxFactory.IdentifierName(aliasParamName)),
                            null)))
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));

                result.Add(SyntaxFactory.MethodDeclaration(SyntaxFactory.ParseTypeName(t.Name), GetMethodName(t, tablePrefix))
                    .WithModifiers(SyntaxHelpers.Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                    .WithExpressionBody(SyntaxFactory.ArrowExpressionClause(
                        SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(t.Name),
                            SyntaxHelpers.ArgumentList(identifierAliasType.MemberAccess(nameof(Alias.Auto))),
                            null)))
                    .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            return result.ToArray();

            static string GetMethodName(TableModel t, string tablePrefix)
            {
                var name = t.Name;
                if (!string.IsNullOrEmpty(tablePrefix))
                {
                    name = name.Substring(tablePrefix.Length);
                }

                return "Get" + name;
            }
        }

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

public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
        {
            List<NodeModel> result = new List<NodeModel>();
				
            var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);

            files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));

            var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
            var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);

            foreach (var tree in trees)
            {
                var semantic = cSharpCompilation.GetSemanticModel(tree);

                foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
                {
                    var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
                    
                    var isSuitable = clreplacedSymbol != null 
                                 && !clreplacedSymbol.IsAbstract 
                                 && clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
                                 && IsExpr(clreplacedSymbol) 
                                 && clreplacedSymbol.Name.StartsWith("Expr");
                        
                    if (!isSuitable)
                    {
                        continue;
                    }

                    var properties = GetProperties(clreplacedSymbol);

                    var subNodes = new List<SubNodeModel>();
                    var modelProps = new List<SubNodeModel>();

                    foreach (var constructor in clreplacedSymbol.Constructors)
                    {
                        foreach (var parameter in constructor.Parameters)
                        {
                            INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;

                            var correspondingProperty = properties.FirstOrDefault(prop =>
                                string.Equals(prop.Name,
                                    parameter.Name,
                                    StringComparison.CurrentCultureIgnoreCase));

                            if (correspondingProperty == null)
                            {
                                throw new Exception(
                                    $"Could not find a property for the constructor arg: '{parameter.Name}'");
                            }

                            var ta = replacedyzeSymbol(ref pType);

                            var subNodeModel = new SubNodeModel(correspondingProperty.Name,
                                parameter.Name,
                                pType.Name,
                                ta.ListName,
                                ta.IsNullable,
                                ta.HostTypeName);
                            if (ta.Expr)
                            {
                                subNodes.Add(subNodeModel);
                            }
                            else
                            {
                                modelProps.Add(subNodeModel);
                            }

                        }
                    }

                    result.Add(new NodeModel(clreplacedSymbol.Name,
                        modelProps.Count == 0 && subNodes.Count == 0,
                        subNodes,
                        modelProps));
                }
            }

            result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));

            return result;

            bool IsExpr(INamedTypeSymbol symbol)
            {
                if (symbol.Name == "IExpr")
                {
                    return true;
                }
                while (symbol != null)
                {
                    if (symbol.Interfaces.Any(HasA))
                    {
                        return true;
                    }
                    symbol = symbol.BaseType;
                }

                return false;


                bool HasA(INamedTypeSymbol iSym)
                {
                    if (iSym.Name == "IExpr")
                    {
                        return true;
                    }

                    return IsExpr(iSym);
                }
            }

            List<ISymbol> GetProperties(INamedTypeSymbol symbol)
            {
                List<ISymbol> result = new List<ISymbol>();
                while (symbol != null)
                {
                    result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
                    symbol = symbol.BaseType;
                }

                return result;
            }

            Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
            {
                string listName = null;
                string hostType = null;
                if (typeSymbol.ContainingType != null)
                {
                    var host = typeSymbol.ContainingType;
                    hostType = host.Name;
                }

                var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;

                if (nullable && typeSymbol.Name == "Nullable")
                {
                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                if (typeSymbol.IsGenericType)
                {
                    if (typeSymbol.Name.Contains("List"))
                    {
                        listName = typeSymbol.Name;
                    }

                    if (typeSymbol.Name == "Nullable")
                    {
                        nullable = true;
                    }

                    typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
                }

                return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
            }
        }

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

public async Task Exec(IScenarioContext context)
        {
            var tOrder = AllTables.GereplacedOrder();
            var tOrderSub2 = AllTables.GereplacedOrder();
            var vwCustomer = new CustomerName();

            var numbers = Values(Enumerable.Range(1, 10).Select(Literal).ToList()).AsColumns("Num");

            var getNum = numbers.Column(context.Dialect == SqlDialect.MySql ? "1" : "Num");
            await InsertInto(tOrder, tOrder.CustomerId, tOrder.Notes)
                .From(
                    Select(vwCustomer.CustomerId, ("Notes for " + vwCustomer.Name + " No:" + Cast(getNum, SqlType.String(5))).As("Notes"))
                        .From(vwCustomer)
                        .CrossJoin(numbers)
                        .OrderBy(vwCustomer.CustomerId, getNum)
                )
                .Exec(context.Database);

            var count = await Select(Count(1)).From(tOrder).QueryScalar(context.Database);

            context.WriteLine("Orders are inserted: " + count);

            //Delete % 7
            await Delete(tOrder)
                .Where(tOrder.OrderId.In(Select(tOrderSub2.OrderId)
                    .From(tOrderSub2)
                    .Where(tOrderSub2.OrderId % 7 == 0)))
                .Exec(context.Database);

            count = await Select(Count(1)).From(tOrder).QueryScalar(context.Database);
            context.WriteLine("Some Orders are deleted. Current count: " + count);

            //Delete JOIN
            await Delete(tOrder)
                .From(tOrder)
                .InnerJoin(vwCustomer, on: vwCustomer.CustomerId == tOrder.CustomerId)
                .Where(tOrder.CustomerId % 7 + 1 == 1)
                .Exec(context.Database);

            //For my SQL number is different since Auto Increment is not reset on delete (ItCustomer)

            count = await Select(Count(1)).From(tOrder).QueryScalar(context.Database);
            context.WriteLine("Some Orders are deleted. Current count: " + count);

            await Update(tOrder)
                .Set(tOrder.Notes, tOrder.Notes + " (Updated 17)")
                .Where(tOrder.OrderId % 17 == 0)
                .Exec(context.Database);

            await Update(tOrder)
                .Set(tOrder.Notes, tOrder.Notes + " (Updated 19)")
                .From(tOrder)
                .Where(tOrder.OrderId % 19 == 0)
                .Exec(context.Database);

            await Update(tOrder)
                .Set(tOrder.Notes, tOrder.Notes + " (Updated 23)")
                .From(tOrder)
                .InnerJoin(vwCustomer, on: vwCustomer.CustomerId == tOrder.CustomerId)
                .Where(tOrder.OrderId % 23 == 0)
                .Exec(context.Database);
        }

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

public async Task Exec(IScenarioContext context)
        {
            IReadOnlyList<TableBase> createList = AllTables.BuildAllTableList(context.Dialect == SqlDialect.PgSql);

            var dropping = createList.Reverse().Select(i => i.Script.DropIfExist()).Combine();
            await context.Database.Statement(dropping);

            var creating = createList.Select(i => i.Script.Create()).Combine();
            await context.Database.Statement(creating);
        }

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

public async Task Exec(IScenarioContext context)
        {
            string[] ids =
            {
                "admin'--",
                "10; DROP TABLE members /*",
                "Line1\r\n\tLine2\\%%\b",
                "--",
                "\'",
                "\\",
                "\\'",
                "\\\\",
                "`\"'",
                "``\\`\\\\`\"\\\"\\\\\"'\\'\\\\'",
                "\"\\\"'\'\\'*`\\`;"
            };

            var expr = Select(ids.Select(id => Literal(id).As(id)).ToList()).Done();
            var res = await expr.Query(context.Database, new List<string>(),
                (acc,r) =>
                {
                    foreach (var id in ids)
                    {
                        acc.Add(r.GetString(id));
                    }

                    return acc;
                });

            for (var index = 0; index < ids.Length; index++)
            {
                if (res[index] != ids[index])
                {
                    context.WriteLine(context.Dialect.GetExporter().ToSql(expr));
                    throw new Exception("Sql Injection!");
                }
            }
        }

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

private void EnsureTableNamesAreUnique(List<TableModel> result, string defaultSchema)
        {
            if (result.Count < 2)
            {
                return;
            }

            var dic = result
                .Select((table,origIndex)=>
                {
                    EnsureColumnNamesAreUnique(table);
                    return (table, origIndex);
                })
                //C# clreplaced names is case-sensitive but windows file system is not, so there might be clreplaced overwriting.
                .GroupBy(t => t.table.Name, StringComparer.InvariantCultureIgnoreCase)
                .ToDictionary(t => t.Key, t => t.ToList(), StringComparer.InvariantCultureIgnoreCase);

            foreach (var pair in dic.ToList())
            {
                while (pair.Value.Count > 1)
                {
                    var newName = pair.Key;

                    //Try add schema prefix
                    int? duplicateIndex = null;
                    for (int i = 0; i < pair.Value.Count; i++)
                    {
                        var next = pair.Value[i];
                        if (!string.Equals(next.table.DbName.Schema, defaultSchema, StringComparison.InvariantCultureIgnoreCase))
                        {
                            duplicateIndex = i;
                            break;
                        }
                    }
                    if (duplicateIndex != null)
                    {
                        var duplicate = pair.Value[duplicateIndex.Value];

                        var tableName = duplicate.table.Name;

                        if (!string.IsNullOrEmpty(this._options.TableClreplacedPrefix))
                        {
                            tableName = tableName.Substring(this._options.TableClreplacedPrefix.Length);
                        }

                        newName = this._options.TableClreplacedPrefix + StringHelper.DeSnake(duplicate.table.DbName.Schema) + tableName;
                    }

                    newName = StringHelper.AddNumberUntilUnique(newName, "No", nn => !dic.ContainsKey(nn));

                    duplicateIndex ??= 1;//Second

                    var duplicateRes = pair.Value[duplicateIndex.Value];

                    var newTable = duplicateRes.table.WithNewName(newName);

                    result[duplicateRes.origIndex] = newTable;

                    dic.Add(newTable.Name, new List<(TableModel table, int origIndex)>(1){(newTable, duplicateRes.origIndex)});

                    pair.Value.RemoveAt(duplicateIndex.Value);
                }
            }
        }

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

public static IEnumerable<MemberDeclarationSyntax> GenerateGetColumns(SqModelMeta meta)
        {
            return ExtractTableRefs(meta).Select(tableRef =>
                {
                    string columnTypeName = ExtractTableColumnTypeName(tableRef);
                    var arrayItems = meta.Properties.Select(p => p.Column.First())
                        .Select(p => SyntaxFactory.IdentifierName("table").MemberAccess(p.ColumnName));
                    var arrayType = SyntaxFactory.ArrayType(
                        SyntaxFactory.IdentifierName(columnTypeName),
                        new SyntaxList<ArrayRankSpecifierSyntax>(new[]
                        {
                            SyntaxFactory.ArrayRankSpecifier(SyntaxFactory.Token(SyntaxKind.OpenBracketToken),
                                new SeparatedSyntaxList<ExpressionSyntax>(),
                                SyntaxFactory.Token(SyntaxKind.CloseBracketToken))
                        }));
                    var array = SyntaxFactory.ArrayCreationExpression(
                        arrayType,
                        SyntaxFactory.InitializerExpression(SyntaxKind.ArrayInitializerExpression,
                            new SeparatedSyntaxList<ExpressionSyntax>().AddRange(arrayItems))
                    );

                    return SyntaxFactory
                        .MethodDeclaration(arrayType, MethodNameGetColumns)
                        .WithModifiers(Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                        .AddParameterListParameters(FuncParameter("table", ExtractTableTypeName(meta, tableRef)))
                        .WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(
                            array
                        )));

                });
        }

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

public static ArgumentListSyntax ArgumentList(params ExpressionSyntax[] arguments)
        {
            return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(SyntaxFactory.Argument)));
        }

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

public static ArgumentListSyntax ArgumentList(params NamedArgument[] arguments)
        {
            return SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(arguments.Select(a=>SyntaxFactory.Argument(SyntaxFactory.NameColon(a.Name), default, a.ArgumentValue))));
        }

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

private static string RowDataToString(IReadOnlyList<TestMergeDataRow> data)
            => string.Join(';', data.Select(d=>$"{d.Id},{d.Value},{d.Version}"));

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

[Test]
        public void CalcStringSize()
        {
            var data = new string[] { "123456789", "1234", "1234567" };

            var derivedTable = SqQueryBuilder.Values(data.Select(SqQueryBuilder.Literal).ToList()).AsColumns("Str");

            var tmpQuery = TempTableData.FromDerivedTableValuesInsert(derivedTable, new[] { derivedTable.Columns[0] }, out _, name: "tmpTable");

            var sql = tmpQuery.ToMySql();
            
            replacedert.AreEqual("CREATE TEMPORARY TABLE `tmpTable`(`Str` varchar(9) character set utf8,CONSTRAINT PRIMARY KEY (`Str`));INSERT INTO `tmpTable`(`Str`) VALUES ('123456789'),('1234'),('1234567')", sql);
        }

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

public static string Splice(this string sql, params Func<bool>[] conditions)
        {
            return sql.Splice(conditions.Select(p => p()).ToArray());
        }

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

private Func<object, object[], dynamic> BuildInvoker(MethodInfo methodInfo)
        {
            if (methodInfo == null)
                throw new ArgumentNullException(nameof(methodInfo), "MethodInfo cannot be null.");
            var instanceParameter = Expression.Parameter(typeof(object));
            var argsParameter = Expression.Parameter(typeof(object[]));

            var argsExpressions = methodInfo.GetParameters().Select((item, index) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(index)), item.ParameterType));

            var instanceObj = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.DeclaringType ?? throw new InvalidOperationException());
            var methodCaller = Expression.Call(instanceObj, methodInfo, argsExpressions);
            if (methodCaller.Type == typeof(Task))
            {
                var action = Expression.Lambda<Action<object, object[]>>(methodCaller, instanceParameter, argsParameter).Compile();
                return (instance, args) => { action(instance, args); return Task.CompletedTask; };
            }

            var instanceMethodCaller = Expression.Convert(methodCaller, methodInfo.ReturnType);
            return Expression.Lambda<Func<object, object[], object>>(instanceMethodCaller, instanceParameter, argsParameter).Compile();
        }

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

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

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

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

private async Task SubscribeNodes(string path, Watcher.Event.EventType eventType)
        {
            var children = await ZooKeeper.getChildrenAsync(path, true);
            switch (eventType)
            {
                case Watcher.Event.EventType.NodeChildrenChanged:
                    var serviceName = GetServiceNameFromPath(path);
                    if (children == null)
                    {
                        RefreshNodes(serviceName, new List<ServiceNodeInfo>());
                    }
                    else
                    {
                        var nodes = await QueryServiceAsync(serviceName);
                        RefreshNodes(serviceName, nodes.Select(p => new ServiceNodeInfo(p.ServiceId, p.Address, p.Port, p.Weight, p.EnableTls, p.Meta)).ToList());
                    }
                    break;

            }
        }

19 View Source File : Entry.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios

[HarmonyPostfix]
            public static void Postfix(ref Game __instance) {
                var ms = ScriptableObjectSingleton<GameData>._instance.mapSet.Maps.items;

                for (var i = 0; i < ms.Length; i++) {
                    ms[i].isDebug = ms[i].isBrowserOnly = false;
                }

                var impls = new MapImpl[] { BigFoot.VALUE, Daffodils.VALUE, Shipwreck.VALUE };

                ScriptableObjectSingleton<GameData>._instance.mapSet.Maps.items = ms.AddAll(impls.Select(impl => impl.GetCreated()).ToArray());
            }

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

public static IPAddress GetLocalInternetIp()
        {
            return NetworkInterface
                .GetAllNetworkInterfaces()
                .Select(p => p.GetIPProperties())
                .SelectMany(p =>
                    p.UnicastAddresses
                ).FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address) && InternalIp(p.Address))?.Address;
        }

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

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

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

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

19 View Source File : 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 : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

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

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

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

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

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

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

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

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


            ExpressionSyntax expressionSyntax;

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

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

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

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

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

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

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

private static QualifiedNameSyntax GenerateQualifiedNameSyntax(IEnumerable<string> names)
        {
            var identifierNames = names.Select(SyntaxFactory.IdentifierName).ToArray();

            QualifiedNameSyntax left = null;
            for (var i = 0; i < identifierNames.Length - 1; i++)
            {
                left = left == null
                    ? SyntaxFactory.QualifiedName(identifierNames[i], identifierNames[i + 1])
                    : SyntaxFactory.QualifiedName(left, identifierNames[i + 1]);
            }
            return left;
        }

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

private static MemoryStream CompileClientProxy(IEnumerable<SyntaxTree> trees, IEnumerable<MetadataReference> references)
        {
            var replacedemblies = new[]
            {
                "System.Runtime",
                "mscorlib",
                "System.Threading.Tasks",
                "System.Collections"
            };
            references = replacedemblies.Select(i => MetadataReference.CreateFromFile(replacedembly.Load(new replacedemblyName(i)).Location)).Concat(references);

            references = references.Concat(new[]
            {
                MetadataReference.CreateFromFile(typeof(Task).GetTypeInfo().replacedembly.Location),
                MetadataReference.CreateFromFile(typeof(DynamicProxyAbstract).GetTypeInfo().replacedembly.Location)
            });
            return Compile("Uragano.DynamicProxy.UraganoProxy", trees, references);
        }

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

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

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 : 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 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 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;
            }
        }

See More Examples