System.Text.StringBuilder.AppendLine(string)

Here are the examples of the csharp api System.Text.StringBuilder.AppendLine(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

9950 Examples 7

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

private DataPlayerInfo ListPlayerUnderChannel(StringBuilder builder, DataPlayerInfo player) {
            if (player != null) {
                builder
                    .Append(player.DisplayName);

                if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
                    AppendState(builder, state);

                builder.AppendLine();
                return player;

            } else {
                builder.AppendLine("?");
                return null;
            }
        }

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

public void RebuildList() {
            if (MDraw.DefaultFont == null || Client == null || Channels == null)
                return;

            DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();

            List<Blob> list = new() {
                new Blob {
                    Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
                    Color = ColorCountHeader
                }
            };

            StringBuilder builder = new();


            switch (Mode) {
                case ListMode.Clreplacedic:
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        builder.Append(player.DisplayName);

                        DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
                        if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
                            builder
                                .Append(" #")
                                .Append(channel.Name);
                        }

                        if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
                            AppendState(builder, state);

                        builder.AppendLine();
                    }

                    list.Add(new() {
                        Text = builder.ToString().Trim(),
                        ScaleFactor = 1f
                    });
                    break;

                case ListMode.Channels:
                    HashSet<DataPlayerInfo> listed = new();

                    DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));

                    if (own != null) {
                        list.Add(new() {
                            Text = own.Name,
                            Color = ColorChannelHeaderOwn
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p))) 
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 0.5f
                        });
                    }

                    foreach (DataChannelList.Channel channel in Channels.List) {
                        if (channel == own)
                            continue;

                        list.Add(new() {
                            Text = channel.Name,
                            Color = ColorChannelHeader
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }

                    bool wrotePrivate = false;

                    builder.Clear();
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        if (!wrotePrivate) {
                            wrotePrivate = true;
                            list.Add(new() {
                                Text = "!<private>",
                                Color = ColorChannelHeaderPrivate
                            });
                        }

                        builder.AppendLine(player.DisplayName);
                    }

                    if (wrotePrivate) {
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }
                    break;
            }

            List = list;
        }

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

public static void WriteHTMLStart(HttpListenerContext c, StringBuilder builder) {
            builder.Append(
@"<!DOCTYPE html>
<html>
    <head>
        <meta charset=""utf-8"" />
        <meta name=""viewport"" content=""width=device-width, initial-scale=1, user-scalable=no"" />
        <replacedle>CelesteNet ClientRC</replacedle>
        <style>
@font-face {
    font-family: Renogare;
    src:
    url(""https://everestapi.github.io/fonts/Renogare-Regular.woff"") format(""woff""),
    url(""https://everestapi.github.io/fonts/Renogare-Regular.otf"") format(""opentype"");
}
body {
    color: rgba(0, 0, 0, 0.87);
    font-family: sans-serif;
    padding: 0;
    margin: 0;
    line-height: 1.5em;
}
header {
    background: #3b2d4a;
    color: white;
    font-family: Renogare, sans-serif;
    font-size: 32px;
    position: sticky;
    top: 0;
    left: 0;
    right: 0;
    height: 64px;
    line-height: 64px;
    padding: 8px 48px;
    z-index: 100;
}
#main {
    position: relative;
    margin: 8px;
    min-height: 100vh;
}
#endpoints li h3 {
    margin-bottom: 0;
}
#endpoints li p {
    margin-top: 0;
}
        </style>
    </head>
    <body>
"
            );

            builder.AppendLine(@"<header>CelesteNet ClientRC</header>");
            builder.AppendLine(@"<div id=""main"">");
        }

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

public static void WriteHTMLEnd(HttpListenerContext c, StringBuilder builder) {
            builder.AppendLine(@"</div>");

            builder.Append(
@"
    </body>
</html>
"
            );
        }

19 View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade

public static void SDL_Main()
		{
			if (string.IsNullOrEmpty(Instance.GamePath))
			{
				AlertDialog dialog = null;
				Instance.RunOnUiThread(() =>
				{
					using (AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Instance))
					{
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.Append("Game not found: ").AppendLine(Game);
						foreach (Java.IO.File root in Instance.GetExternalFilesDirs(null))
						{
							stringBuilder.AppendLine();
							stringBuilder.AppendLine(Path.Combine(root.AbsolutePath, Game));
						}

						dialogBuilder.SetMessage(stringBuilder.ToString());
						dialogBuilder.SetCancelable(false);
						dialog = dialogBuilder.Show();
					}
				});

				while (dialog == null || dialog.IsShowing)
				{
					System.Threading.Thread.Sleep(0);
				}
				dialog.Dispose();
				return;
			}

			// Replace the following with whatever was in your Program.Main method.

			/*/
			using (TestGame game = new TestGame())
			{
				game.Run();
			}
			/*/
			replacedembly.LoadFrom(Instance.GamePath).EntryPoint.Invoke(null, new object[] { new string[] { /*args*/ } });
			/**/
		}

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

public string Help_GetCommandSnippet(ChatCMDEnv env, ChatCMD cmd) {
            string prefix = Chat.Settings.CommandPrefix;
            StringBuilder builder = new();

            builder
                .Append(prefix)
                .Append(cmd.ID)
                .Append(" ")
                .Append(cmd.Args)
                .AppendLine()
                .AppendLine(cmd.Help);

            return builder.ToString().Trim();
        }

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

private static void Generate(string projDir, string relativePath, IReadOnlyList<NodeModel> model, Action<IReadOnlyList<NodeModel>, StringBuilder> generator)
        {
            var path = Path.Combine(projDir, relativePath);

            StringBuilder newContentBuilder = new StringBuilder();

            bool skip = false;
            foreach (var line in File.ReadLines(path))
            {
                if (line.Contains("//CodeGenEnd"))
                {
                    generator.Invoke(model, newContentBuilder);
                    skip = false;
                }

                if (!skip)
                {
                    newContentBuilder.AppendLine(line);
                }

                if (line.Contains("//CodeGenStart"))
                {
                    skip = true;
                }
            }

            File.WriteAllText(path, newContentBuilder.ToString());
        }

19 View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : 0x4F776C

private string RunCommand(string script)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(script);
            pipeline.Commands.Add("Out-String");

            Collection<PSObject> results = pipeline.Invoke();

            runspace.Close();

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject psObject in results)
                stringBuilder.AppendLine(psObject.ToString());
            return stringBuilder.ToString();
        }

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

public void AppendLine(string line)
        {
            this._builder.AppendLine(line);
        }

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

public void AppendLineStart(int tabs, string line)
        {
            this._builder.Append(' ', (this._indentTabs + tabs) * 4);
            this._builder.AppendLine(line);
        }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

public static string GenerateRoutes(IEnumerable<RouteInfo> infos)
        {
            StringBuilder sb = new StringBuilder();
            var group = infos.GroupBy(o => o.Namespace);
            sb.AppendLine($"using {typeof(object).Namespace};");
            sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");

            sb.AppendLine();
            for (int i = 0; i < group.Count(); i++)
            {
                sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
            }

            return sb.ToString();
        }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static StringBuilder GenerateNamespace(IGrouping<string, RouteInfo> namespaceGroup, bool isLast)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"namespace {GetConvertedNamespace(namespaceGroup.Key)}");
            sb.AppendLine("{");

            var group = namespaceGroup.GroupBy(o => o.ControllerName);
            for (int i = 0; i < group.Count(); i++)
            {
                sb.Append(GenerateClreplaced(group.ElementAt(i), i == (group.Count() - 1)));
            }

            sb.AppendLine("}");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static StringBuilder GenerateClreplaced(IGrouping<string, RouteInfo> group, bool isLast)
        {
            string clreplacedFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
            string crefNamespace = GetCrefNamespace(clreplacedFullName, GetConvertedNamespace(group.First().Namespace));
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"    /// <summary>");
            sb.AppendLine($"    /// <see cref=\"{crefNamespace}\"/>");
            sb.AppendLine($"    /// </summary>");
            sb.AppendLine($"    public clreplaced {group.Key}Route");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item = group.ElementAt(i);
                var renamedAction = RenameOverloadedAction(group, i);
                sb.AppendLine("        /// <summary>");
                sb.AppendLine($"        /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
                sb.AppendLine("        /// </summary>");
                sb.AppendLine($"        public const string {renamedAction} = \"{item.Path}\";");

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

private static StringBuilder GenerateClreplaced(IGrouping<string, RouteInfo> group, bool isLast)
        {
            string clreplacedFullName = $"{group.First().Namespace}.{group.First().ControllerName}Controller";
            string crefNamespace = GetCrefNamespace(clreplacedFullName, GetConvertedNamespace(group.First().Namespace));
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"    /// <summary>");
            sb.AppendLine($"    /// <see cref=\"{crefNamespace}\"/>");
            sb.AppendLine($"    /// </summary>");
            sb.AppendLine($"    public clreplaced {group.Key}Route");
            sb.AppendLine("    {");
            for (int i = 0; i < group.Count(); i++)
            {
                var item = group.ElementAt(i);
                var renamedAction = RenameOverloadedAction(group, i);
                sb.AppendLine("        /// <summary>");
                sb.AppendLine($"        /// <see cref=\"{crefNamespace}.{item.ActionName}\"/>");
                sb.AppendLine("        /// </summary>");
                sb.AppendLine($"        public const string {renamedAction} = \"{item.Path}\";");

                if (config != null && config.GenerateMethod)
                {
                    sb.AppendLine($"        public static async Task<T> {item.ActionName}Async<T>({GeneraParameters(item.Parameters, true, false)})");
                    sb.AppendLine("        {");
                    sb.AppendLine($"            var routeInfo = new {nameof(RouteInfo)}");
                    sb.AppendLine("            {");
                    sb.AppendLine($"                {nameof(RouteInfo.HttpMethods)} = \"{item.HttpMethods}\",");
                    sb.AppendLine($"                {nameof(RouteInfo.Path)} = {renamedAction},");
                    sb.Append(GenerateParameters(item.Parameters));
                    sb.AppendLine("            };");
                    sb.AppendLine($"            return await {nameof(HttpClientAsync)}.{nameof(HttpClientAsync.Async)}<T>(routeInfo{GeneraParameters(item.Parameters, false, true)});");
                    sb.AppendLine("        }");
                }

                if (i != group.Count() - 1)
                {
                    sb.AppendLine();
                }
            }

            sb.AppendLine("    }");
            if (!isLast)
            {
                sb.AppendLine();
            }

            return sb;
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

public static string GenerateRoutes(IList<RouteInfo> infos)
        {
            StringBuilder sb = new StringBuilder();
            var group = infos.GroupBy(o => o.Namespace);
            sb.AppendLine($"using {typeof(object).Namespace};");
            sb.AppendLine($"using {typeof(Dictionary<int, int>).Namespace};");
            sb.AppendLine($"using {typeof(Task).Namespace};");
            sb.AppendLine($"using {typeof(HttpClientAsync).Namespace};");

            sb.AppendLine();
            for (int i = 0; i < group.Count(); i++)
            {
                sb.Append(GenerateNamespace(group.ElementAt(i), i == (group.Count() - 1)));
            }

            return sb.ToString();
        }

19 View Source File : RouteGenerator.cs
License : MIT License
Project Creator : 188867052

private static string GenerateParameters(IList<ParameterInfo> parameters)
        {
            StringBuilder sb = new StringBuilder();
            if (parameters != null && parameters.Count > 0)
            {
                sb.AppendLine($"                {nameof(RouteInfo.Parameters)} = new List<{nameof(ParameterInfo)}>");
                sb.AppendLine("                {");
                foreach (var item in parameters)
                {
                    sb.AppendLine($"                    new {nameof(ParameterInfo)}() {{{nameof(item.Name)} = \"{item.Name}\", {nameof(item.Type)} = \"{item.Type}\"}},");
                }

                sb.AppendLine("                }");
            }

            return sb.ToString();
        }

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

public void compileToExe(String code, String decKey, String filePath, String Arch, string type="exe")
        {

            parameters.Outputreplacedembly = filePath;
            parameters.CompilerOptions = "/target:" + type + Arch;
            if (type != "exe") 
            {
                parameters.GenerateExecutable = false;
            }

            CompilerResults results = provider.CompilereplacedemblyFromSource(parameters, code);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
        }

19 View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(customShellListView.SelectedItems.Count > 0){
                ListViewItem item = customShellListView.SelectedItems[0];
                if(null != item){
                    CmdShell cmds = (CmdShell) item.Tag;
                    StringBuilder sb = new StringBuilder();
                    foreach (TaskShell task in cmds.ShellList)
                    {
                        if (cmds.TaskType == TaskType.Default)
                        {
                            sb.AppendLine(task.Shell);
                        }
                        else if (cmds.TaskType == TaskType.Timed)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                        else if (cmds.TaskType == TaskType.Condition)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", cmds.Condition, task.Shell));
                        }
                    }
                    shellView.Text = sb.ToString();
                    if(cmds.TaskType == TaskType.Default){
                        btn_run.Enabled = true;
                    }
                    return;
                }
            }
            btn_run.Enabled = false;
            shellView.Text = "";
        }

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

public static string GetScriptHeader(Boolean debug)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Sub DebugPrint(s)");
            if (debug) builder.AppendLine("    Debug.Print s");
            builder.AppendLine("End Sub");
            builder.AppendLine();

            return builder.ToString();
        }

19 View Source File : NginxMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (customShellListView.SelectedItems.Count > 0)
            {
                ListViewItem item = customShellListView.SelectedItems[0];
                if (null != item)
                {
                    CmdShell cmds = (CmdShell)item.Tag;
                    StringBuilder sb = new StringBuilder();
                    foreach (TaskShell task in cmds.ShellList)
                    {
                        if (cmds.TaskType == TaskType.Default)
                        {
                            sb.AppendLine(task.Shell);
                        }
                        else if (cmds.TaskType == TaskType.Timed)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                        else if (cmds.TaskType == TaskType.Condition)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                    }
                    shellView.Text = sb.ToString();
                    if (cmds.TaskType == TaskType.Default)
                    {
                        btn_run.Enabled = true;
                    }
                    return;
                }
            }
            btn_run.Enabled = false;
            shellView.Text = "";
        }

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

static string GetScriptHeader(RuntimeVersion version, bool enable_debug)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("function setversion() {");
            switch (version)
            {
                case RuntimeVersion.Auto:
                    builder.AppendLine(Global_Var.jscript_auto_version_script);
                    break;
                case RuntimeVersion.v2:
                    builder.AppendLine("new ActiveXObject('WScript.Shell').Environment('Process')('COMPLUS_Version') = 'v2.0.50727';");
                    break;
                case RuntimeVersion.v4:
                    builder.AppendLine("new ActiveXObject('WScript.Shell').Environment('Process')('COMPLUS_Version') = 'v4.0.30319';");
                    break;
            }
            builder.AppendLine("}");
            builder.Append("function debug(s) {");
            if (enable_debug)
            {
                builder.Append("WScript.Echo(s);");
            }
            builder.AppendLine("}");
            return builder.ToString();
        }

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

static string GetScriptHeader(RuntimeVersion version, bool enable_debug)
        {
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("function setversion() {");
            switch (version)
            {
                case RuntimeVersion.Auto:
                    builder.AppendLine(Global_Var.jscript_auto_version_script);
                    break;
                case RuntimeVersion.v2:
                    builder.AppendLine("new ActiveXObject('WScript.Shell').Environment('Process')('COMPLUS_Version') = 'v2.0.50727';");
                    break;
                case RuntimeVersion.v4:
                    builder.AppendLine("new ActiveXObject('WScript.Shell').Environment('Process')('COMPLUS_Version') = 'v4.0.30319';");
                    break;
            }
            builder.AppendLine("}");
            builder.Append("function debug(s) {");
            if (enable_debug)
            {
                builder.Append("WScript.Echo(s);");
            }
            builder.AppendLine("}");
            return builder.ToString();
        }

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

public static string GetScriptHeader(RuntimeVersion version, Boolean debug)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Sub DebugPrint(s)");
            if (debug) builder.AppendLine("    WScript.Echo s");
            builder.AppendLine("End Sub");
            builder.AppendLine();

            builder.AppendLine("Sub SetVersion");
            if (version != RuntimeVersion.None)
            {
                builder.AppendLine("Dim shell");
                builder.AppendLine("Set shell = CreateObject(\"WScript.Shell\")");
                switch (version)
                {
                    case RuntimeVersion.v2:
                        builder.AppendLine("shell.Environment(\"Process\").Item(\"COMPLUS_Version\") = \"v2.0.50727\"");
                        break;
                    case RuntimeVersion.v4:
                        builder.AppendLine("shell.Environment(\"Process\").Item(\"COMPLUS_Version\") = \"v4.0.30319\"");
                        break;
                    case RuntimeVersion.Auto:
                        builder.AppendLine(Global_Var.vb_multi_auto_version_script);
                        break;
                }
            }
            builder.AppendLine("End Sub");
            builder.AppendLine();
            return builder.ToString();
        }

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

public static string GetScriptHeader(RuntimeVersion version, Boolean debug)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Sub DebugPrint(s)");
            if (debug) builder.AppendLine("    WScript.Echo s");
            builder.AppendLine("End Sub");
            builder.AppendLine();

            builder.AppendLine("Sub SetVersion");
            if (version != RuntimeVersion.None)
            {
                builder.AppendLine("Dim shell");
                builder.AppendLine("Set shell = CreateObject(\"WScript.Shell\")");
                switch (version)
                {
                    case RuntimeVersion.v2:
                        builder.AppendLine("shell.Environment(\"Process\").Item(\"COMPLUS_Version\") = \"v2.0.50727\"");
                        break;
                    case RuntimeVersion.v4:
                        builder.AppendLine("shell.Environment(\"Process\").Item(\"COMPLUS_Version\") = \"v4.0.30319\"");
                        break;
                    case RuntimeVersion.Auto:
                        builder.AppendLine(Global_Var.vb_multi_auto_version_script);
                        break;
                }
            }
            builder.AppendLine("End Sub");
            builder.AppendLine();
            return builder.ToString();
        }

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

public void compileToExe(String code, String filePath, String Arch)
        {

            parameters.Outputreplacedembly = filePath;
            parameters.CompilerOptions = Arch;

            CompilerResults results = provider.CompilereplacedemblyFromSource(parameters, code);

            if (results.Errors.HasErrors)
            {
                StringBuilder sb = new StringBuilder();

                foreach (CompilerError error in results.Errors)
                {
                    sb.AppendLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText));
                }

                throw new InvalidOperationException(sb.ToString());
            }
        }

19 View Source File : IceMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(customShellListView.SelectedItems.Count > 0){
                ListViewItem item = customShellListView.SelectedItems[0];
                if(null != item){
                    CmdShell cmds = (CmdShell) item.Tag;
                    StringBuilder sb = new StringBuilder();
                    foreach (TaskShell task in cmds.ShellList)
                    {
                        if (cmds.TaskType == TaskType.Default)
                        {
                            sb.AppendLine(task.Shell);
                        }
                        else if (cmds.TaskType == TaskType.Timed)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                        else if (cmds.TaskType == TaskType.Condition)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", cmds.Condition, task.Shell));
                        }
                    }
                    shellView.Text = sb.ToString();
                    if(cmds.TaskType == TaskType.Default){
                        btn_run.Enabled = true;
                    }
                    return;
                }
            }
            btn_run.Enabled = false;
            shellView.Text = "";
        }

19 View Source File : NginxMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (customShellListView.SelectedItems.Count > 0)
            {
                ListViewItem item = customShellListView.SelectedItems[0];
                if (null != item)
                {
                    CmdShell cmds = (CmdShell)item.Tag;
                    StringBuilder sb = new StringBuilder();
                    foreach (TaskShell task in cmds.ShellList)
                    {
                        if (cmds.TaskType == TaskType.Default)
                        {
                            sb.AppendLine(task.Shell);
                        }
                        else if (cmds.TaskType == TaskType.Timed)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                        else if (cmds.TaskType == TaskType.Condition)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                    }
                    shellView.Text = sb.ToString();
                    if (cmds.TaskType == TaskType.Default)
                    {
                        btn_run.Enabled = true;
                    }
                    return;
                }
            }
            btn_run.Enabled = false;
            shellView.Text = "";
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : 214175590

static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】:" + ex.GetType().Name);
                sb.AppendLine("【异常信息】:" + ex.Message);
                sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】:" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }

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

private string GetTsServiceJcCode(ActionModel action)
        {
            StringBuilder strBuilder = new StringBuilder();
            string actionRouteName = (string.IsNullOrEmpty(action.AreaName) ? "" : $"{action.AreaName}/")
                                        + $"{action.ControllerName}/{action.ActionName}";
            string inputParamStr = "";
            string ajaxParamStr = "";
            string returnParamTypeStr = "";
            if (action.InputParameters != null && action.InputParameters.Count > 0)
            {
                if (action.InputParameters.Count == 1 && action.InputParameters[0].HasPiList == true)
                {
                    inputParamStr = $"{action.InputParameters[0].Name}:{GetTsType(action.InputParameters[0].PType)}";
                    ajaxParamStr = $",{action.InputParameters[0].Name}";
                }
                else if (action.InputParameters.Any(param=>param.Name.ToLower().Contains("index"))
                         && action.InputParameters.Any(param => param.Name.ToLower().Contains("size")))
                {   //处理分页查询方法
                    string queryObjTypeName = "PgQueryObj";
                    if (action.ReturnParameter.PType.PiList?.Count > 0)
                    {
                        for (int i = 0; i < action.ReturnParameter.PType.PiList.Count; i++)
                        {
                            if (action.ReturnParameter.PType.PiList[i].IsIEnumerable)
                            {
                                PTypeModel enumPType = JcApiHelper.GetPTypeModel(action.ReturnParameter.PType.PiList[i].EnumItemId);
                                queryObjTypeName = GetTsType(enumPType) + "QueryObj";
                                break;
                            }
                        }
                    }
                    inputParamStr = $"{FirstToLower(queryObjTypeName)}: {queryObjTypeName}";
                    ajaxParamStr = $",{FirstToLower(queryObjTypeName)}";
                }
                else
                {
                    ajaxParamStr = ",{";
                    for (int i = 0; i < action.InputParameters.Count; i++)
                    {
                        if (i > 0)
                        {
                            inputParamStr += ",";
                            ajaxParamStr += ",";
                        }
                        inputParamStr += $"{action.InputParameters[i].Name}: {GetTsType(action.InputParameters[i].PType)}";
                        ajaxParamStr += $"{action.InputParameters[i].Name}: {action.InputParameters[i].Name}";
                    }
                    ajaxParamStr += "}";
                }
            }
            returnParamTypeStr = GetTsType(action.ReturnParameter.PType);

            strBuilder.AppendLine($"  /*{(string.IsNullOrEmpty(action.Summary) ? action.ActionName : action.Summary)}*/");
            strBuilder.AppendLine($"  public { FirstToLower(action.ActionName)}({inputParamStr}): Observable<{returnParamTypeStr}>{{");
            strBuilder.AppendLine($"    return Util.ajax('{actionRouteName}'{ajaxParamStr});");
            strBuilder.AppendLine("  }");
            return strBuilder.ToString();
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (customShellListView.SelectedItems.Count > 0)
            {
                ListViewItem item = customShellListView.SelectedItems[0];
                if (null != item)
                {
                    CmdShell cmds = (CmdShell)item.Tag;
                    StringBuilder sb = new StringBuilder();
                    foreach (TaskShell task in cmds.ShellList)
                    {
                        if (cmds.TaskType == TaskType.Default)
                        {
                            sb.AppendLine(task.Shell);
                        }
                        else if (cmds.TaskType == TaskType.Timed)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                    }
                    shellView.Text = sb.ToString();
                    if (cmds.TaskType == TaskType.Default)
                    {
                        btn_run.Enabled = true;
                    }
                    return;
                }
            }
            btn_run.Enabled = false;
            shellView.Text = "";
        }

19 View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void customShellListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (customShellListView.SelectedItems.Count > 0)
            {
                ListViewItem item = customShellListView.SelectedItems[0];
                if (null != item)
                {
                    CmdShell cmds = (CmdShell)item.Tag;
                    StringBuilder sb = new StringBuilder();
                    foreach (TaskShell task in cmds.ShellList)
                    {
                        if (cmds.TaskType == TaskType.Default)
                        {
                            sb.AppendLine(task.Shell);
                        }
                        else if (cmds.TaskType == TaskType.Timed)
                        {
                            sb.AppendLine(string.Format("{0} - {1}", task.DateTime, task.Shell));
                        }
                    }
                    shellView.Text = sb.ToString();
                    if (cmds.TaskType == TaskType.Default)
                    {
                        btn_run.Enabled = true;
                    }
                    return;
                }
            }
            btn_run.Enabled = false;
            shellView.Text = "";
        }

19 View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void 校验ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                ListViewItem item = listView1.SelectedItems[0];

                string content = "";
                if (tabControl1.SelectedIndex == 0)
                {
                    string line = "";
                    StringBuilder sb = new StringBuilder();
                    foreach(TreeListViewItem treeNode in _treeView.Items){
                        line = treeNode.Text;
                        if(!line.TrimStart().StartsWith("#")){
                            line += ": " + treeNode.SubItems[0].Text;
                            line += treeNode.SubItems[2].Text;
                        }
                        sb.AppendLine(treeNode.Text);
                    }
                    content = sb.ToString();
                }
                else
                {
                    content = ymlEditor.Text;
                }

                Validate(item, content);
            }
            
        }

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

private string GetTsModelCode(PTypeModel ptype)
        {
            StringBuilder strBuilder = new StringBuilder();
            string tsType = GetTsType(ptype);
            strBuilder.AppendLine($"/*{(string.IsNullOrEmpty(ptype.Summary) ? tsType : ptype.Summary)}*/");
            strBuilder.AppendLine("export clreplaced " + tsType + " {");
            for (int i = 0; i < ptype.PiList.Count; i++)
            {
                strBuilder.AppendLine($"  { FirstToLower(ptype.PiList[i].Name)}: {GetTsType(ptype.PiList[i].PType)};   // " + ptype.PiList[i].Summary);
            }
            strBuilder.AppendLine("}");
            strBuilder.AppendLine();
            return strBuilder.ToString();
        }

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

private string GetTsModelCode(PTypeModel ptype)
        {
            StringBuilder strBuilder = new StringBuilder();
            string tsType = GetTsType(ptype);
            strBuilder.AppendLine($"/*{(string.IsNullOrEmpty(ptype.Summary) ? tsType : ptype.Summary)}*/");
            strBuilder.AppendLine("export clreplaced " + tsType + " {");
            for (int i = 0; i < ptype.PiList.Count; i++)
            {
                strBuilder.AppendLine($"  { FirstToLower(ptype.PiList[i].Name)}: {GetTsType(ptype.PiList[i].PType)};   // " + ptype.PiList[i].Summary);
            }
            strBuilder.AppendLine("}");
            strBuilder.AppendLine();
            return strBuilder.ToString();
        }

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

private string GetTsQueryModelCode(PTypeModel ptype)
        {
            if(ptype.IsEnum || ptype.IsGeneric)
            {   //排除枚举和泛型类型
                return "";
            }
            string tsType = GetTsType(ptype);
            StringBuilder strBuilder = new StringBuilder();
            strBuilder.AppendLine($"/*{(string.IsNullOrEmpty(ptype.Summary) ? tsType : ptype.Summary)} QueryObj 分页查询对象*/");
            strBuilder.AppendLine($"export clreplaced { tsType }QueryObj extends { tsType } implements IPage {{");
            strBuilder.AppendLine("  pageIndex: number;");
            strBuilder.AppendLine("  pageSize: number;");
            strBuilder.AppendLine("  sort: string;");
            strBuilder.AppendLine("  order: string;");
            strBuilder.AppendLine("  constructor() {");
            strBuilder.AppendLine("    super();");
            strBuilder.AppendLine("  }");
            strBuilder.AppendLine("}");
            strBuilder.AppendLine();
            return strBuilder.ToString();
        }

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

private TsServiceModel GetTsServiceModel(ControllerModel controller)
        {
            TsServiceModel tsService = new TsServiceModel();
            StringBuilder jcCodeBuilder = new StringBuilder();
            StringBuilder commonCodeBuilder = new StringBuilder();
            StringBuilder headerCodeBuilder = new StringBuilder();
            headerCodeBuilder.AppendLine("import {Injectable} from '@angular/core';");
            headerCodeBuilder.AppendLine("import {Observable} from 'rxjs/Observable';");
            headerCodeBuilder.AppendLine();

            jcCodeBuilder.AppendLine("import {Util} from '@core/util'");
            jcCodeBuilder.AppendLine();
            jcCodeBuilder.AppendLine("@Injectable()");
            jcCodeBuilder.AppendLine($"export clreplaced {controller.ControllerName}Service {{");
            jcCodeBuilder.AppendLine();

            commonCodeBuilder.AppendLine("import {HttpClient} from '@angular/common/http';");
            commonCodeBuilder.AppendLine();
            commonCodeBuilder.AppendLine("@Injectable()");
            commonCodeBuilder.AppendLine($"export clreplaced {controller.ControllerName} {{");
            commonCodeBuilder.AppendLine();
            commonCodeBuilder.AppendLine("  constructor(private http: HttpClient) {");
            commonCodeBuilder.AppendLine("  }");
            commonCodeBuilder.AppendLine();

            for (int i = 0; i < controller.ActionList.Count; i++)
            {
                ActionModel action = controller.ActionList[i];
                jcCodeBuilder.AppendLine(GetTsServiceJcCode(action));
                commonCodeBuilder.AppendLine(GetTsServiceCommonCode(action));
            }
            jcCodeBuilder.AppendLine("}");
            commonCodeBuilder.AppendLine("}");

            tsService.JcCode = headerCodeBuilder.ToString() + jcCodeBuilder.ToString();
            tsService.CommonCode = headerCodeBuilder.ToString() + commonCodeBuilder.ToString();
            return tsService;
        }

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

private string GetTsServiceCommonCode(ActionModel action)
        {
            StringBuilder strBuilder = new StringBuilder();
            string actionRouteName = (string.IsNullOrEmpty(action.AreaName) ? "" : $"{action.AreaName}/")
                                        + $"{action.ControllerName}/{action.ActionName}";
            string inputParamStr = "";
            string ajaxParamStr = "";
            string returnParamTypeStr = "";
            if (action.InputParameters != null && action.InputParameters.Count > 0)
            {
                if (action.InputParameters.Count == 1 && action.InputParameters[0].HasPiList == true)
                {
                    inputParamStr = $"{action.InputParameters[0].Name}:{GetTsType(action.InputParameters[0].PType)}";
                    ajaxParamStr = $",{action.InputParameters[0].Name}";
                }
                else if (action.InputParameters.Any(param => param.Name.ToLower().Contains("index"))
                         && action.InputParameters.Any(param => param.Name.ToLower().Contains("size")))
                {   //处理分页查询方法
                    string queryObjTypeName = "PgQueryObj";
                    if (action.ReturnParameter.PType.PiList?.Count > 0)
                    {
                        for (int i = 0; i < action.ReturnParameter.PType.PiList.Count; i++)
                        {
                            if (action.ReturnParameter.PType.PiList[i].IsIEnumerable)
                            {
                                PTypeModel enumPType = JcApiHelper.GetPTypeModel(action.ReturnParameter.PType.PiList[i].EnumItemId);
                                queryObjTypeName = GetTsType(enumPType) + "QueryObj";
                                break;
                            }
                        }
                    }
                    inputParamStr = $"{FirstToLower(queryObjTypeName)}: {queryObjTypeName}";
                    ajaxParamStr = $",{FirstToLower(queryObjTypeName)}";
                }
                else
                {
                    ajaxParamStr = ",{";
                    for (int i = 0; i < action.InputParameters.Count; i++)
                    {
                        if (i > 0)
                        {
                            inputParamStr += ",";
                            ajaxParamStr += ",";
                        }
                        inputParamStr += $"{action.InputParameters[i].Name}: {GetTsType(action.InputParameters[i].PType)}";
                        ajaxParamStr += $"{action.InputParameters[i].Name}: {action.InputParameters[i].Name}";
                    }
                    ajaxParamStr += "}";
                }
            }
            returnParamTypeStr = GetTsType(action.ReturnParameter.PType);

            strBuilder.AppendLine($"  /*{(string.IsNullOrEmpty(action.Summary) ? action.ActionName : action.Summary)}*/");
            strBuilder.AppendLine($"  public { FirstToLower(action.ActionName)}({inputParamStr}): Observable<{returnParamTypeStr}>{{");
            strBuilder.AppendLine($"    return this.http.post('{actionRouteName}'{ajaxParamStr});");
            strBuilder.AppendLine("  }");
            return strBuilder.ToString();
        }

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

public static string ToProxy(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            var isResult = false;

            if (isAsync)
            {
                sb.AppendLine($"            await _context.BeforeAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.Before(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isAsync)
            {
                sb.AppendLine($"            await _context.AfterAsync(typeof(RedisClient).GetMethod({method.Name}))");
            }
            else
            {
                sb.AppendLine($"            _context.After(typeof(RedisClient).GetMethod({method.Name}))");
            }

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

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

static void Update(StringBuilder sb, int forTime, int size) {
			Stopwatch sw = new Stopwatch();

			var songs = fsql.Select<Song>().Limit(size).ToList();
			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				fsql.Update<Song>().SetSource(songs).ExecuteAffrows();
			}
			sw.Stop();
			sb.AppendLine($"FreeSql Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			songs = sugar.Queryable<Song>().Take(size).ToList();
			sw.Restart();
			Exception sugarEx = null;
			try {
				for (var a = 0; a < forTime; a++)
					sugar.Updateable(songs).ExecuteCommand();
			} catch (Exception ex) {
				sugarEx = ex;
			}
			sw.Stop();
			sb.AppendLine($"SqlSugar Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));

			using (var db = new SongContext()) {
				songs = db.Songs.Take(size).AsNoTracking().ToList();
			}
			sw.Restart();
			for (var a = 0; a < forTime; a++) {

				using (var db = new SongContext()) {
					//db.Configuration.AutoDetectChangesEnabled = false;
					db.Songs.UpdateRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Update {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

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

public static IApplicationBuilder UseFreeAdminLtePreview(this IApplicationBuilder app, string requestPathBase, params Type[] enreplacedyTypes) {

			requestPathBase = requestPathBase.ToLower();
			if (requestPathBase.StartsWith("/") == false) requestPathBase = $"/{requestPathBase}";
			if (requestPathBase.EndsWith("/") == false) requestPathBase = $"{requestPathBase}/";
			var restfulRequestPath = $"{requestPathBase}restful-api";

			IFreeSql fsql = app.ApplicationServices.GetService(typeof(IFreeSql)) as IFreeSql;
			if (fsql == null) throw new Exception($"UseFreeAdminLtePreview 错误,找不到 IFreeSql,请提前注入");

			var dicEnreplacedyTypes = enreplacedyTypes.ToDictionary(a => a.Name);

			app.UseFreeAdminLteStaticFiles(requestPathBase);

			app.Use(async (context, next) => {

				var req = context.Request;
				var res = context.Response;
				var location = req.Path.Value;
				var is301 = false;

				if (location.EndsWith("/") == false) {
					is301 = true;
					location = $"{location}/";
				}

				var reqPath = location.ToLower();
				try {
					if (reqPath == requestPathBase) {
						if (is301) {
							res.StatusCode = 301;
							res.Headers["Location"] = location;
							return;
						}
						//首页
						var sb = new StringBuilder();
						sb.AppendLine(@"<ul clreplaced=""treeview-menu"">");
						foreach (var et in dicEnreplacedyTypes) {
							sb.AppendLine([email protected]"<li><a href=""{requestPathBase}{et.Key}/""><i clreplaced=""fa fa-circle-o""></i>{fsql.CodeFirst.GetTableByEnreplacedy(et.Value).Comment.IsNullOrEmtpty(et.Key)}</a></li>");
						}
						sb.AppendLine(@"</ul>");
						await res.WriteAsync(Views.Index.Replace(@"<ul clreplaced=""treeview-menu""></ul>", sb.ToString()));
						return;
					}
					else if (reqPath.StartsWith(restfulRequestPath)) {
						//动态接口
						if (await Restful.Use(context, fsql, restfulRequestPath, dicEnreplacedyTypes)) return;
					}
					else if (reqPath.StartsWith(requestPathBase)) {
						if (reqPath == "/favicon.ico/") return;
						//前端UI
						if (await Admin.Use(context, fsql, requestPathBase, dicEnreplacedyTypes)) return;
					}

				} catch (Exception ex) {
					await Utils.Jsonp(context, new { code = 500, message = ex.Message });
					return;
				}
				await next();
			});

			return app;
		}

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

static void Insert(StringBuilder sb, int forTime, int size) {
			var songs = Enumerable.Range(0, size).Select(a => new Song {
				Create_time = DateTime.Now,
				Is_deleted = false,
				replacedle = $"Insert_{a}",
				Url = $"Url_{a}"
			});

			//预热
			fsql.Insert(songs.First()).ExecuteAffrows();
			sugar.Insertable(songs.First()).ExecuteCommand();
			using (var db = new SongContext()) {
				//db.Configuration.AutoDetectChangesEnabled = false;
				db.Songs.AddRange(songs.First());
				db.SaveChanges();
			}
			Stopwatch sw = new Stopwatch();

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				fsql.Insert(songs).ExecuteAffrows();
			}
			sw.Stop();
			sb.AppendLine($"FreeSql Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				using (var db = new FreeSongContext()) {
					db.Songs.AddRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"FreeSql.DbContext Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			Exception sugarEx = null;
			try {
				for (var a = 0; a < forTime; a++)
					sugar.Insertable(songs.ToArray()).ExecuteCommand();
			} catch (Exception ex) {
				sugarEx = ex;
			}
			sw.Stop();
			sb.AppendLine($"SqlSugar Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms" + (sugarEx != null ? $"成绩无效,错误:{sugarEx.Message}" : ""));

			sw.Restart();
			for (var a = 0; a < forTime; a++) {

				using (var db = new SongContext()) {
					//db.Configuration.AutoDetectChangesEnabled = false;
					db.Songs.AddRange(songs.ToArray());
					db.SaveChanges();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Insert {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

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

public async Task<string> Setup(TaskBuild taskBuild, List<DbTableInfo> outputTables)
        {
            try
            {
                var paths = await Task.Run(() =>
                {
                    var config = new TemplateServiceConfiguration();
                    config.EncodedStringFactory = new RawStringFactory();
                    Engine.Razor = RazorEngineService.Create(config);

                    string path = string.Empty;


                    foreach (var templatesPath in taskBuild.Templates)
                    {
                        path = $"{taskBuild.GeneratePath}\\{taskBuild.DbName}\\{templatesPath.Replace(".tpl", "").Trim()}";
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

                        var razorId = Guid.NewGuid().ToString("N");
                        var html = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "Templates", templatesPath));
                        Engine.Razor.Compile(html, razorId);
                        //开始生成操作
                        foreach (var table in outputTables)
                        {
                            var sw = new StringWriter();
                            var model = new RazorModel(taskBuild, outputTables, table);
                            Engine.Razor.Run(razorId, sw, null, model);
                            StringBuilder plus = new StringBuilder();
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.AppendLine("// <auto-generated>");
                            plus.AppendLine("//     此代码由工具生成。");
                            plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                            plus.AppendLine("//     Website: http://www.freesql.net");
                            plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                            plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                            plus.AppendLine("// </auto-generated>");
                            plus.AppendLine("//------------------------------------------------------------------------------");
                            plus.Append(sw.ToString());
                            plus.AppendLine();
                            var outPath = $"{path}\\{taskBuild.FileName.Replace("{name}", model.GetCsName(table.Name))}";
                            if (!string.IsNullOrEmpty(taskBuild.RemoveStr))
                                outPath = outPath.Replace(taskBuild.RemoveStr, "").Trim();
                            File.WriteAllText(outPath, plus.ToString());
                        }
                    }
                    return path;
                });
                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成时发生异常,请检查模版代码: {ex.Message}.");
                return $"生成时发生异常,请检查模版代码: {ex.Message}.";
            }
        }

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

public async Task<string> Setup(TaskBuild taskBuild, string code, List<DbTableInfo> dbTables, DbTableInfo dbTableInfo)
        {
            StringBuilder plus = new StringBuilder();
            try
            {
                var config = new TemplateServiceConfiguration();
                config.EncodedStringFactory = new RawStringFactory();
                Engine.Razor = RazorEngineService.Create(config);
                var razorId = Guid.NewGuid().ToString("N");
                Engine.Razor.Compile(code, razorId);

                var sw = new StringWriter();
                var model = new RazorModel(taskBuild, dbTables, dbTableInfo);
                Engine.Razor.Run(razorId, sw, null, model);

                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.AppendLine("// <auto-generated>");
                plus.AppendLine("//     此代码由工具生成。");
                plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                plus.AppendLine("//     Website: http://www.freesql.net");
                plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                plus.AppendLine("// </auto-generated>");
                plus.AppendLine("//------------------------------------------------------------------------------");
                plus.Append(sw.ToString());
                plus.AppendLine();
                return await Task.FromResult(plus.ToString());
            }
            catch
            {
                return await Task.FromResult(plus.ToString());
            }
        }

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

static void Select(StringBuilder sb, int forTime, int size) {
			Stopwatch sw = new Stopwatch();
			sw.Restart();
			for (var a = 0; a < forTime; a++)
				fsql.Select<Song>().Limit(size).ToList();
			sw.Stop();
			sb.AppendLine($"FreeSql Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++)
				sugar.Queryable<Song>().Take(size).ToList();
			sw.Stop();
			sb.AppendLine($"SqlSugar Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms");

			sw.Restart();
			for (var a = 0; a < forTime; a++) {
				using (var db = new SongContext()) {
					db.Songs.Take(size).AsNoTracking().ToList();
				}
			}
			sw.Stop();
			sb.AppendLine($"EFCore Select {size}条数据,循环{forTime}次,耗时{sw.ElapsedMilliseconds}ms\r\n");
		}

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

public static string ToMethod(this MethodInfo method)
        {
            if (method == null) return null;
            var sb = new StringBuilder();
            sb.Append("        public static ");

            var returnType = method.ReturnType;
            var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
            var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
            var isAsync = isGenericAsync || isNoResultAsync;

            var isResult = false;

            if (isAsync)
                sb.Append("async ");

            var funcInfo = method.ToInterface(false);
            sb.AppendLine(funcInfo);
            sb.AppendLine("        {");

            if (isAsync)
            {
                if (isNoResultAsync)
                    sb.Append("            await _redisClient.").Append(method.Name);
                else
                {
                    isResult = true;
                    sb.Append("            var result = await _redisClient.").Append(method.Name);
                }
            }
            else
            {
                if (returnType == typeof(void))
                {
                    sb.Append("            _redisClient.").Append(method.Name);
                }
                else
                {
                    isResult = true;
                    sb.Append("            var result = _redisClient.").Append(method.Name);
                }
            }

            var genericParameters = method.GetGenericArguments();
            if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
            {
                var dic = genericParameters.ToDictionary(a => a.Name);
                foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
                    if (dic.ContainsKey(nestedGenericParameter.Name))
                        dic.Remove(nestedGenericParameter.Name);
                genericParameters = dic.Values.ToArray();
            }
            if (genericParameters.Any())
                sb.Append("<")
                    .Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
                    .Append(">");

            sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");

            if (isResult)
                sb.AppendLine("            return result;");

            sb.Append("        }\r\n\r\n");
            return sb.ToString();
        }

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

public async Task<string> Setup(Models.TaskBuild task)
        {



            try
            {
                var paths = await Task.Run(() =>
                 {

                     var config = new TemplateServiceConfiguration();
                     config.EncodedStringFactory = new RawStringFactory();
                     var service = RazorEngineService.Create(config);
                     Engine.Razor = service;


                     ///本次要操作的数据库
                     var dataBases = task.TaskBuildInfos.Where(a => a.Level == 1).ToList();

                     string path = string.Empty;

                     foreach (var db in dataBases)
                     {
                         //创建数据库连接
                         using (IFreeSql fsql = new FreeSql.FreeSqlBuilder()
                        .UseConnectionString(db.DataBaseConfig.DataType, db.DataBaseConfig.ConnectionStrings)
                        .Build())
                         {

                             //取指定数据库信息
                             var tables = fsql.DbFirst.GetTablesByDatabase(db.Name);
							 var outputTables = tables;

                             //是否有指定表
                             var uTables = task.TaskBuildInfos.Where(a => a.Level > 1).Select(a => a.Name).ToArray();
                             if (uTables.Length > 0)
                                 //过滤不要的表
                                 outputTables = outputTables.Where(a => uTables.Contains(a.Name)).ToList();

                             //根据用户设置组装生成路径并验证目录是否存在
                             path = $"{task.GeneratePath}\\{db.Name}";
                             if (!Directory.Exists(path))
                                 Directory.CreateDirectory(path);

							 var razorId = Guid.NewGuid().ToString("N");
							 Engine.Razor.Compile(task.Templates.Code, razorId);
                             //开始生成操作
                             foreach (var table in outputTables)
                             {
								 var sw = new StringWriter();
								 var model = new RazorModel(fsql, task, tables, table);
								 Engine.Razor.Run(razorId, sw, null, model);
 

                                 StringBuilder plus = new StringBuilder();
                                 plus.AppendLine("//------------------------------------------------------------------------------");
                                 plus.AppendLine("// <auto-generated>");
                                 plus.AppendLine("//     此代码由工具生成。");
                                 plus.AppendLine("//     运行时版本:" + Environment.Version.ToString());
                                 plus.AppendLine("//     Website: http://www.freesql.net");
                                 plus.AppendLine("//     对此文件的更改可能会导致不正确的行为,并且如果");
                                 plus.AppendLine("//     重新生成代码,这些更改将会丢失。");
                                 plus.AppendLine("// </auto-generated>");
                                 plus.AppendLine("//------------------------------------------------------------------------------");

                                 plus.Append(sw.ToString());

                                 plus.AppendLine();
                                 File.WriteAllText($"{path}\\{task.FileName.Replace("{name}", model.GetCsName(table.Name))}", plus.ToString());
                             }
                         }
                     }
                     return path;
                 });

                Process.Start(paths);
                return "生成成功";
            }
            catch (Exception ex)
            {
                return "生成时发生异常,请检查模版代码.";
            }


        }

19 View Source File : SysProxyHandle.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private static void ExecSysproxy(string arguments)
        {
            // using event to avoid hanging when redirect standard output/error
            // ref: https://stackoverflow.com/questions/139593/processstartinfo-hanging-on-waitforexit-why
            // and http://blog.csdn.net/zhangweixing0/article/details/7356841
            using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
            using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
            {
                using (Process process = new Process())
                {
                    // Configure the process using the StartInfo properties.
                    process.StartInfo.FileName = Utils.GetTempPath("sysproxy.exe");
                    process.StartInfo.Arguments = arguments;
                    process.StartInfo.WorkingDirectory = Utils.GetTempPath();
                    process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    process.StartInfo.UseShellExecute = false;
                    process.StartInfo.RedirectStandardError = true;
                    process.StartInfo.RedirectStandardOutput = true;

                    // Need to provide encoding info, or output/error strings we got will be wrong.
                    process.StartInfo.StandardOutputEncoding = Encoding.Unicode;
                    process.StartInfo.StandardErrorEncoding = Encoding.Unicode;

                    process.StartInfo.CreateNoWindow = true;

                    StringBuilder output = new StringBuilder();
                    StringBuilder error = new StringBuilder();

                    process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            output.AppendLine(e.Data);
                        }
                    };
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };
                    try
                    {
                        process.Start();

                        process.BeginErrorReadLine();
                        process.BeginOutputReadLine();

                        process.WaitForExit();
                    }
                    catch (System.ComponentModel.Win32Exception e)
                    {

                        // log the arguments
                        throw new Exception(process.StartInfo.Arguments);
                    }
                    string stderr = error.ToString();
                    string stdout = output.ToString();

                    int exitCode = process.ExitCode;
                    if (exitCode != (int)RET_ERRORS.RET_NO_ERROR)
                    {
                        throw new Exception(stderr);
                    }

                    //if (arguments == "query")
                    //{
                    //    if (stdout.IsNullOrWhiteSpace() || stdout.IsNullOrEmpty())
                    //    {
                    //        throw new Exception("failed to query wininet settings");
                    //    }
                    //    _queryStr = stdout;
                    //}
                }
            }
        }

19 View Source File : WExtensibilityGlobals.cs
License : MIT License
Project Creator : 3F

public override string Extract(object data)
        {
            if(items == null) {
                return String.Empty;
            }

            var sb = new StringBuilder();
            sb.AppendLine($"{SP}GlobalSection(ExtensibilityGlobals) = postSolution");

            items.ForEach(i =>
                sb.AppendLine($"{SP}{SP}{i.Key}" + (i.Value != null ? $" = {i.Value}" : String.Empty))
            );

            sb.Append($"{SP}EndGlobalSection");
            return sb.ToString();
        }

19 View Source File : WExtensibilityGlobals.cs
License : MIT License
Project Creator : 3F

public override string Extract(object data)
        {
            if(items == null) {
                return String.Empty;
            }

            var sb = new StringBuilder();
            sb.AppendLine($"{SP}GlobalSection(ExtensibilityGlobals) = postSolution");

            items.ForEach(i =>
                sb.AppendLine($"{SP}{SP}{i.Key}" + (i.Value != null ? $" = {i.Value}" : String.Empty))
            );

            sb.Append($"{SP}EndGlobalSection");
            return sb.ToString();
        }

19 View Source File : WNestedProjects.cs
License : MIT License
Project Creator : 3F

public override string Extract(object data)
        {
            var sb = new StringBuilder();

            sb.AppendLine($"{SP}GlobalSection(NestedProjects) = preSolution");
            bool hasDep = false;

            folders?.ForEach(p =>
            {
                if(p.header.parent?.Value != null)
                {
                    sb.AppendLine($"{SP}{SP}{p.header.pGuid} = {p.header.parent.Value?.header.pGuid}");
                    hasDep = true;
                }
            });

            pItems?.ForEach(p =>
            {
                if(p.parent?.Value != null)
                {
                    sb.AppendLine($"{SP}{SP}{p.pGuid} = {p.parent.Value?.header.pGuid}");
                    hasDep = true;
                }
            });

            if(!hasDep) {
                return String.Empty;
            }

            sb.Append($"{SP}EndGlobalSection");
            return sb.ToString();
        }

See More Examples